From wescpy at gmail.com Sun Feb 1 00:19:18 2009 From: wescpy at gmail.com (wesley chun) Date: Sat, 31 Jan 2009 15:19:18 -0800 Subject: [Tutor] string fomatting In-Reply-To: <4984BBE6.6050800@gmail.com> References: <498498A3.7030003@gmail.com> <4984BBE6.6050800@gmail.com> Message-ID: <78b3a9580901311519m18b59902x51f1b2c91f9a4153@mail.gmail.com> >> I want to search any characters in test after https://www.localhost.org/ >> and >> the search will end after it finds another / here's another solution that takes advantage of the 'maxsplit' parameter of the str.split() method... it requires more stitching to get the final output(s): >>> url = 'https://www.localhost.org/testmodule/dev/trunk/admin/sql/mytest.sql' >>> parts = url.split('/', 4) >>> print '%s//%s/' % (parts[0], parts[2]) https://www.localhost.org/ >>> print parts[3] testmodule >>> print '/%s' % parts[4] /dev/trunk/admin/sql/mytest.sql -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From mwalsh at mwalsh.org Sun Feb 1 04:36:35 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Sat, 31 Jan 2009 21:36:35 -0600 Subject: [Tutor] Want to write a Perl based IP to Domain Name converter. In-Reply-To: <78b3a9580901311442t791abf63vb034df85f8b3bddc@mail.gmail.com> References: <6410451598.20090131201141@gmail.com> <1c2a2c590901310544l7f261ef3xeceb2633030b7e05@mail.gmail.com> <23816288.20090131221128@gmail.com> <78b3a9580901311442t791abf63vb034df85f8b3bddc@mail.gmail.com> Message-ID: <498518C3.2040202@mwalsh.org> wesley chun wrote: >>>>> The script in the following can do the batch conversion from domain >>>>> name to IP: >>>> This is a Python list, not Perl! >>> OMG! It's my mistake, sorry for this. >> Lol..thats okay. Now that you are here and have seen what fun we have >> writing Python code - why not join the party? >> >> Don't be shy to join us :p - i bet you won't be sorry. > > > well, he had to join Tutor to post, unless a mod allowed his msg, so > there should be *some* interest in doing it in Python. after all, the > equivalent code is already slightly shorter and easier to read than > the Perl version... > > import socket > import sys > > for hp in sys.argv[1:]: > h, p = hp.strip().split(':') > print '%s -> %s:%s' % (hp, socket.gethostbyname(h), p) Here's my attempt, a few lines longer. The 'split /:/ or next' part confuses me a bit, though I suspect it's a bug ... 'cause I guess, as long as the line has value even if it doesn't match the host:port pattern, it won't be an exception, or undef, or false, or whatever you call it in perl. :D import socket import fileinput for line in fileinput.input(): line = line.rstrip('\n') # chomp try: # split /:/ host, port = line.split(':') except ValueError: continue # or next ip = socket.gethostbyname(host) print '%s -> %s:%s' % (line, ip, port) ... and the opposite ... for line in fileinput.input(): line = line.rstrip('\n') try: ip, port = line.split(':') except ValueError: continue host = socket.gethostbyaddr(ip)[0] print '%s -> %s:%s' % (line, host, port) HTH, Marty From ldl08 at gmx.net Sun Feb 1 09:34:10 2009 From: ldl08 at gmx.net (David) Date: Sun, 01 Feb 2009 16:34:10 +0800 Subject: [Tutor] confusion about cloning (graphics) Message-ID: <49855E82.2090503@gmx.net> Hello list, I continue my reading of Harrington. In section 2.4. he is making a point about the need to clone, as otherwise the object associated to parameter corner (the point (20, 50)) takes the same value as corner2. That is: corner2 changes corner, which in turn changes the point (20, 50). Here is the faulty code Harrington provides: '''Program: makeRectBad.py Attempt a function makeRect (incorrectly), which takes a takes a corner point and dimensions to construct a Rectangle. ''' from graphics import * # based on Zelle's graphics.py module def makeRect(corner, width, height): # Incorrect! '''Return a new Rectangle given one corner Point and the dimensions.''' corner2 = corner corner2.move(width, height) return Rectangle(corner, corner2) def main(): winWidth = 300 winHeight = 300 win = GraphWin('Draw a Rectangle (NOT!)', winWidth, winHeight) win.setCoords(0, 0, winWidth, winHeight) rect = makeRect(Point(20, 50), 250, 200) rect.draw(win) # Wait for another click to exit msg = Text(Point(winWidth/2, 20),'Click anywhere to quit.') msg.draw(win) win.getMouse() win.close() main() This behaviour stuns me, because I was always following the belief that when variable2 refers to another variable1, the value of variable1 would NOT change, even as I operate on variable2 - just like my little experiment at the promt: In [10]: x = 5 In [11]: y = x In [12]: y + 2 Out[12]: 7 In [13]: x Out[13]: 5 So here is my question: what have I failed to grasp? Are those different issues? If so, why? I'd appreciate it if you could give me a short comment, this one bothers me ;-) David From denis.spir at free.fr Sun Feb 1 10:51:55 2009 From: denis.spir at free.fr (spir) Date: Sun, 1 Feb 2009 10:51:55 +0100 Subject: [Tutor] Re : Is instance of what? In-Reply-To: <1c2a2c590901311200r84b674evca84c16e7a23507d@mail.gmail.com> References: <200901310757.44807.tim@johnsons-web.com> <6faf39c90901310939n789915aesbc6911b36f94cdca@mail.gmail.com> <6faf39c90901310939m768b6b18n2884bbf8ffc45469@mail.gmail.com> <200901310954.24588.tim@johnsons-web.com> <20090131204739.2eff54c0@o> <1c2a2c590901311200r84b674evca84c16e7a23507d@mail.gmail.com> Message-ID: <20090201105155.73524534@o> Le Sat, 31 Jan 2009 15:00:02 -0500, Kent Johnson a ?crit : > On Sat, Jan 31, 2009 at 2:47 PM, spir wrote: > > >> > o.__class__ (or rather o.__class__.__name__) will work. > >> Understood. Thank you. > >> tj > > > > type(a) has been changed (since 2.2?) to return the same value as a.__class__ > > I think you mean type(o) (type of the instance) rather than type(a) > (type of the class object). > type(o) == o.__class__ is only true if o is an instance of a new-style > class. Instances of oldstyle classes all have type 'instance'. > > Kent > You're right, Kent! I haven't paid enough attention to a/o. Thanks also for the precision about old style classes' instances. By the way, don't your fingers find "isinstance" difficult to type? Mine always write typos ;-) Denis ------ la vida e estranya From denis.spir at free.fr Sun Feb 1 12:45:08 2009 From: denis.spir at free.fr (spir) Date: Sun, 1 Feb 2009 12:45:08 +0100 Subject: [Tutor] confusion about cloning (graphics) In-Reply-To: <49855E82.2090503@gmx.net> References: <49855E82.2090503@gmx.net> Message-ID: <20090201124508.44f3d96e@o> Le Sun, 01 Feb 2009 16:34:10 +0800, David a ?crit : > Hello list, > > I continue my reading of Harrington. In section 2.4. he is making a > point about the need to clone, as otherwise the object associated to > parameter corner (the point (20, 50)) takes the same value as corner2. > That is: corner2 changes corner, which in turn changes the point (20, > 50). [...] (Both point happen to have the same coordinates, actually to *be* the same point, that's it?) > This behaviour stuns me, because I was always following the belief that > when variable2 refers to another variable1, the value of variable1 would > NOT change, even as I operate on variable2 - just like my little > experiment at the promt: > > In [10]: x = 5 > > In [11]: y = x > > In [12]: y + 2 > Out[12]: 7 > > In [13]: x > Out[13]: 5 > > So here is my question: what have I failed to grasp? Are those different > issues? If so, why? > > I'd appreciate it if you could give me a short comment, this one bothers > me ;-) > > David You are not the first one, you won't be the last one ;-) Actually, python does not make any difference between values and objects: all are objects. (Python distinguishes mutable and immutable types, see below about that). More precisely, at the conceptual level, there are kinds of data (or data constructs), like a "position", that are values, even when compound. For instance, a position may be made of x and y simple values. Let us say you create a custom type of objects such as: class Point(object): def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return "(x:%s y:%s)" %(self.x,self.y) Conceptually, this is in fact a compound value that should rather be called "Position". So that when you "copy" a point/position to create a new one, you expect each one to have its own value -- what won't happen: shift_x, shift_y = 20,30 p = Point(100,100) q = p # ... q.x += shift_x ; q.y += shift_y print p,q ==> (x:120 y:130) (x:120 y:130) This occurs because you make a confusion between what is for you a value (be it compound), or not, at the conceptual level ; and what it is for python: an object in both cases, that has an identity and a state. When "q = p" is executed an alias name "q" is bound to the same unique Point object that was already bound to the name 'p'. That's all what happens. When this object's state is further changed, then logically printing p or q outputs the same new state. The point is shared by p and q. The obvious remedy is to copy the point's state, meaning the values it holds, instead of copying the object itself: q = Point() q.x,q.y = p.x,p.y Another solution is to use tuples, which are the container type that python provides to hold compound values. If you represent points/positions by (x,y) tuples, then the program wil behave the way you intend it, meaning that p and q will have different positions and actually *be* distinct objects for python: shift_x, shift_y = 20,30 p = (100,100) q = p # ... q = (q[0]+shift_x, q[1]+shift_y) print p,q ==> (100, 100) (120, 130) The proper distinction here is that tuples are "immutable" objects. This means that one cannot change them directly (actually there is some more subtility) by writing e.g. q[0]=120. Concretely, for the programmer, it follows that tuples and all immutable objects (number,string,boolean) behave like we expect it from data that represent values in a program/model. [There some literature on the topic. And even a design pattern called "value object" that adresses the issue.] Denis ------ la vida e estranya From gslindstrom at gmail.com Sun Feb 1 04:05:35 2009 From: gslindstrom at gmail.com (gslindstrom at gmail.com) Date: Sun, 01 Feb 2009 03:05:35 +0000 Subject: [Tutor] Precision with Decimal Message-ID: <00221532cd043a4c7e0461d2b613@google.com> I am using the decimal module to work with money (US dollars and cents) and do not understand the precision. The documentation states: "The decimal module incorporates a notion of significant places so that 1.30 + 1.20 is 2.50. The trailing zero is kept to indicate significance. This is the customary presentation for monetary applications." But I get: >>> from decimal import Decimal >>> a = Decimal('1.25') >>> a Decimal('1.25') >>> b = Decimal('2.50') >>> b Decimal('2.50') >>> a+b Decimal('3.8') I expect (and would like) a+b to be '3.75'. I've read through the getcontext() section but must be missing something. Can you help? Thanks! --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Feb 1 13:35:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 1 Feb 2009 07:35:20 -0500 Subject: [Tutor] string fomatting In-Reply-To: References: <498498A3.7030003@gmail.com> Message-ID: <1c2a2c590902010435g420c055ak2c30c3736f4fef08@mail.gmail.com> On Sat, Jan 31, 2009 at 1:44 PM, Jay Jesus Amorin wrote: > Thanks bob. > > I want to search any characters in test after https://www.localhost.org/ and > the search will end after it finds another / > > and when i print it will display testmodule. If *all* you want is the first element of the path, you can get that simply by splitting the string on / and retrieving the correct piece: In [28]: test Out[28]: 'https://www.localhost.org/testmodule/dev/trunk/admin/sql/mytest.sql' In [29]: test.split('/') Out[29]: ['https:', '', 'www.localhost.org', 'testmodule', 'dev', 'trunk', 'admin', 'sql', 'mytest.sql'] In [30]: test.split('/')[3] Out[30]: 'testmodule' Kent From kent37 at tds.net Sun Feb 1 13:46:58 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 1 Feb 2009 07:46:58 -0500 Subject: [Tutor] confusion about cloning (graphics) In-Reply-To: <49855E82.2090503@gmx.net> References: <49855E82.2090503@gmx.net> Message-ID: <1c2a2c590902010446k41e44bdcjcfaaf2507af8227@mail.gmail.com> On Sun, Feb 1, 2009 at 3:34 AM, David wrote: > This behaviour stuns me, because I was always following the belief that when > variable2 refers to another variable1, the value of variable1 would NOT > change, even as I operate on variable2 > So here is my question: what have I failed to grasp? Are those different > issues? If so, why? My explanation is here: http://personalpages.tds.net/~kent37/kk/00012.html Harrington explains immediately after the program you cite; did you see his explanation? Kent From sander.sweers at gmail.com Sun Feb 1 14:04:43 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Sun, 1 Feb 2009 14:04:43 +0100 Subject: [Tutor] Precision with Decimal In-Reply-To: <00221532cd043a4c7e0461d2b613@google.com> References: <00221532cd043a4c7e0461d2b613@google.com> Message-ID: On Sun, Feb 1, 2009 at 04:05, wrote: > "The decimal module incorporates a notion of significant places so that 1.30 > + 1.20 is 2.50. The trailing zero is kept to indicate significance. This is > the customary presentation for monetary applications." > > But I get: >>>> from decimal import Decimal >>>> a = Decimal('1.25') >>>> a > Decimal('1.25') >>>> b = Decimal('2.50') >>>> b > Decimal('2.50') >>>> a+b > Decimal('3.8') > > I expect (and would like) a+b to be '3.75'. I've read through the > getcontext() section but must be missing something. Can you help? You probably set the precision to 2 via getcontext. example: >>> import decimal >>> a = decimal.Decimal('1.25') >>> b = decimal.Decimal('2.50') >>> a + b Decimal("3.75") >>> decimal.getcontext().prec = 2 >>> a + b Decimal("3.8") Greets Sander From kent37 at tds.net Sun Feb 1 14:16:28 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 1 Feb 2009 08:16:28 -0500 Subject: [Tutor] Precision with Decimal In-Reply-To: <00221532cd043a4c7e0461d2b613@google.com> References: <00221532cd043a4c7e0461d2b613@google.com> Message-ID: <1c2a2c590902010516ve3fd4ecub82dfb1bdee8256a@mail.gmail.com> On Sat, Jan 31, 2009 at 10:05 PM, wrote: > I am using the decimal module to work with money (US dollars and cents) and > do not understand the precision. The documentation states: > > "The decimal module incorporates a notion of significant places so that 1.30 > + 1.20 is 2.50. The trailing zero is kept to indicate significance. This is > the customary presentation for monetary applications." > > But I get: >>>> from decimal import Decimal >>>> a = Decimal('1.25') >>>> a > Decimal('1.25') >>>> b = Decimal('2.50') >>>> b > Decimal('2.50') >>>> a+b > Decimal('3.8') > > I expect (and would like) a+b to be '3.75'. I've read through the > getcontext() section but must be missing something. Can you help? I get a different result, are you sure you didn't set the precision before you did the above? In [31]: from decimal import * In [32]: a=Decimal('1.25') In [33]: b=Decimal('2.50') In [34]: a+b Out[34]: Decimal('3.75') The precision is the number of significant digits, not the number of decimal places: In [37]: getcontext().prec=1 In [38]: a+b Out[38]: Decimal('4') In [39]: getcontext().prec=2 In [40]: a+b Out[40]: Decimal('3.8') In [41]: a*Decimal('11111') Out[41]: Decimal('1.4E+4') The example is the docs is perhaps not the best one because 1.3 + 1.2 works correctly with normal floating point. 1.1 + 1.1 gives a different result with Decimal vs floating point: In [46]: 1.1 + 1.1 Out[46]: 2.2000000000000002 In [48]: Decimal('1.1') + Decimal('1.1') Out[48]: Decimal('2.2') Kent From kent37 at tds.net Sun Feb 1 14:29:16 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 1 Feb 2009 08:29:16 -0500 Subject: [Tutor] Python 3 tutorials Message-ID: <1c2a2c590902010529t3020888eldafcb72b81b1a193@mail.gmail.com> I added a page to the Python.org wiki to list tutorials that address Python 3: http://wiki.python.org/moin/Python3.0Tutorials Please add any I have missed. (Alan, that mean you - I couldn't find a link to your work-in-progress update.) Kent From ldl08 at gmx.net Sun Feb 1 14:53:01 2009 From: ldl08 at gmx.net (David) Date: Sun, 01 Feb 2009 21:53:01 +0800 Subject: [Tutor] confusion about cloning (graphics) In-Reply-To: <1c2a2c590902010446k41e44bdcjcfaaf2507af8227@mail.gmail.com> References: <49855E82.2090503@gmx.net> <1c2a2c590902010446k41e44bdcjcfaaf2507af8227@mail.gmail.com> Message-ID: <4985A93D.6010805@gmx.net> Dear list members, thanks for all your replies, following your comments and links I will do some more research into this issue! Kent Johnson wrote: > Harrington explains immediately after the program you cite; did you > see his explanation? Yes, though the explanation didn't give me enough depth. David From alan.gauld at btinternet.com Mon Feb 2 00:15:10 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 1 Feb 2009 23:15:10 -0000 Subject: [Tutor] IDLE vs PythonWin References: <49810945.8050402@sbcglobal.net> <49819EBA.3030208@sbcglobal.net> <589697.85007.qm@web86706.mail.ird.yahoo.com> <4981DB8D.5050108@sbcglobal.net> <4984641B.5010302@sbcglobal.net><333efb450901310741u62d08674u31597850be35244c@mail.gmail.com> <49847496.5060204@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Hi, sorry, but I have no idea what vim is, Yes, its just a text editor that runs in its own window. Its a very very powerful text editor, one of perhaps 3 or 4 that are universally used by professional programmers on any operating system they may need to work with, and specifically designed for writing programs. But you could substitute the name of any text editor. > I'd still like to know why pythonwin prints almost > completely blank pages. Me, too, I checked and it works fine for me. One option is to try a different print driver - it could be a bad interface between vim and the printer. But thats unlikely... > vim=vi(m), linux?? vim = vi improved. vi was developed by Bill Joy(founder of Sun Microsystems) while at university in the late 1970s or very early 80s. It was desuigned to make it easier to edit programs and take advantage of the brand new "glass teletypes" (ie video monitors) that weere becoming available. It ran on Unix and fast became the standard Unix editor. Emacs was being built at around the same time on Digital computers as a set of macros on top of the Teco editor (The name stands for Editining Macros) and when these became popular it was turned into a fully fledged editor. But because it came from a bunch of Lisp programmers it was almost immediately made cross platform and became popular across a whole bunch of programmers. And because it had a Lisp macro lamnguage it was easy to extend. (A lot more than vi!) Both vi and emacs are extremely popular but work in almost diametrically opposite ways and so polarise opinions. This regularly leads to "Editor wars" between programmers on Usenet :-) Personally I useed both on Unix and liked both. When I moved to Windows Emacs couldn't perform all its tricks, whereas vi just worked as usual so gradually I stopped using emacs. Thebn I found vim wjhich added a whole bunch of the "missing" features of vi plus full GUI support(mice etc) and vim is now my standard editor for serious programming whether it be in Lisp, C, Python or HTML. > I think you may have misunderstood Alan. Yes, the description below is correct. I have 3 separate windows open. I use Alt-Tab to cycle between them. In both the Python and OS windows I use up/down arrow to cycle between previous commands. > Then he saves his code in vim and runs the script in the > shell (in Ipython you'd use the magic function %run, In vim I could use the :! command to run it within vim, but I prefer to keep the errors etc plus the previous outputs all available in a separate window. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Mon Feb 2 01:27:31 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 2 Feb 2009 00:27:31 -0000 Subject: [Tutor] Python 3 tutorials References: <1c2a2c590902010529t3020888eldafcb72b81b1a193@mail.gmail.com> Message-ID: "Kent Johnson" wrote > Please add any I have missed. (Alan, that mean you - I couldn't find > a > link to your work-in-progress update.) I've literally just started last week so there's really nothing to note yet. It usually takes jme a week or two per topic to do a major update. So once I get a few topics done then I'll publish the new link and add it to my sig... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Mon Feb 2 01:35:30 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 2 Feb 2009 00:35:30 -0000 Subject: [Tutor] PyCon2009 Tutorial: An Introduction to Object-OrientedProgramming References: <18820.40697.568054.637852@Michael-Goldwassers-Computer.local> <78b3a9580901311449g62e267e5v5315c59ad6089385@mail.gmail.com> Message-ID: "wesley chun" wrote >> David Letscher and I will be leading a tutorial at this year's >> PyCon titled "An Introduction to Object-Oriented Programming." > > likewise, i'll be doing one on network programming, Such fun! I just wish I could afford the trip to the US! :-) Alan G. From wescpy at gmail.com Mon Feb 2 02:17:52 2009 From: wescpy at gmail.com (wesley chun) Date: Sun, 1 Feb 2009 17:17:52 -0800 Subject: [Tutor] PyCon2009 Tutorial: An Introduction to Object-OrientedProgramming In-Reply-To: References: <18820.40697.568054.637852@Michael-Goldwassers-Computer.local> <78b3a9580901311449g62e267e5v5315c59ad6089385@mail.gmail.com> Message-ID: <78b3a9580902011717i5169599p909ba957b4528769@mail.gmail.com> > Such fun! I just wish I could afford the trip to the US! :-) PyCons are such a great way to (re)connect with the community and so many opportunities to learn from the masters (and mistresses) of Python. the conferences are so incredible that once you go, you have to go every year thereafter. as far as costs go, alan and everyone else, even if you can't afford it, there's help: http://us.pycon.org/2009/registration/financial-aid/ hopefully this will help some of you out, especially this year! cheers, and hope to meet some of you in a few months! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From etrade.griffiths at dsl.pipex.com Mon Feb 2 12:31:40 2009 From: etrade.griffiths at dsl.pipex.com (etrade.griffiths at dsl.pipex.com) Date: Mon, 02 Feb 2009 11:31:40 +0000 Subject: [Tutor] reading binary files In-Reply-To: References: Message-ID: <1233574300.4986d99c336d1@netmail.pipex.net> Hi I am trying to read data from a file that has format item_name num_items item_type items .... eg TIME 1 0.0 DISTANCE 10 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 TIME 1 1.0 DISTANCE 10 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 I can read this if the data are in ASCII format using in_file = open("my_file.dat","r") data1 = in_file.read() tokens = data1.split() and then stepping through the resulting list but the data also appear in the same format in a binary file. I tried converting the binary file to an ASCII file using ifile = open("my_file.dat","rb") ofile = open("new_file.dat","w") base64.decode(ifile, ofile) but that gave the error "Error: Incorrect padding". I imagine that there is a straightforward way of doing this but haven't found it so far. Would be grateful for any suggestions! Thanks Alun Griffiths ------------------------------------------------- Visit Pipex Business: The homepage for UK Small Businesses Go to http://www.pipex.co.uk/business-services From jadrifter at gmail.com Mon Feb 2 14:24:57 2009 From: jadrifter at gmail.com (jadrifter) Date: Mon, 02 Feb 2009 05:24:57 -0800 Subject: [Tutor] reading binary files In-Reply-To: <1233574300.4986d99c336d1@netmail.pipex.net> References: <1233574300.4986d99c336d1@netmail.pipex.net> Message-ID: <1233581097.15652.1.camel@ltop> On Mon, 2009-02-02 at 11:31 +0000, etrade.griffiths at dsl.pipex.com wrote: > Hi > > I am trying to read data from a file that has format > > item_name num_items item_type items .... > > eg > > TIME 1 0.0 > DISTANCE 10 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 > TIME 1 1.0 > DISTANCE 10 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 > > I can read this if the data are in ASCII format using > > in_file = open("my_file.dat","r") > data1 = in_file.read() > tokens = data1.split() > > and then stepping through the resulting list but the data > also appear in the same format in a binary file. I tried > converting the binary file to an ASCII file using > > ifile = open("my_file.dat","rb") > ofile = open("new_file.dat","w") > base64.decode(ifile, ofile) > > but that gave the error "Error: Incorrect padding". I imagine > that there is a straightforward way of doing this but haven't > found it so far. Would be grateful for any suggestions! > > Thanks > > Alun Griffiths > Honestly I'm not sure what you're asking for but in general for reading binary data the I use the struct module. Check it out in the documentation. John Purser From alan.gauld at btinternet.com Mon Feb 2 14:38:46 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 2 Feb 2009 13:38:46 -0000 Subject: [Tutor] reading binary files References: <1233574300.4986d99c336d1@netmail.pipex.net> Message-ID: wrote> > I am trying to read data from a file that has format > item_name num_items item_type items .... > > eg > > TIME 1 0.0 > DISTANCE 10 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 Where is the item_type? > I can read this if the data are in ASCII format using > > in_file = open("my_file.dat","r") > data1 = in_file.read() > tokens = data1.split() It might be easier to process line by line using readline or readlines rather than read but otherwise, ok so far... > and then stepping through the resulting list but the data > also appear in the same format in a binary file. When you say a binary file do you mean an ASCII file encoded into binary using some standard algorithm? Or do you mean the data is binary so that, for example, the number 1 would appear as 4 bytes? If so do you know how strings (the name) are delimited? Also how many could be present - is length a single or multiple bytes? and are the reors fixed length or variable? If variable what is the field/record separator? You may need to load the file into a hex editor of debugger to determine the answers... Having done that the struct module will allow you to read the data. You can see a basic example of using struct in my tutorial topic about handling files. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From bernd at prager.ws Mon Feb 2 22:53:59 2009 From: bernd at prager.ws (Bernd Prager) Date: Mon, 02 Feb 2009 14:53:59 -0700 Subject: [Tutor] question about mpmath product expression Message-ID: Does anybody know if there is a precision difference when I use mpmath and take an expression: from mpmath import * mp.dps = 100 mu0 = [mpf('4') * pi * power(10, -7) rather then: mu0 = fprod([mpf('4'), pi, power(10, -7)]) ? Thanks, -- Bernd From berankin99 at yahoo.com Mon Feb 2 23:46:18 2009 From: berankin99 at yahoo.com (Bernard Rankin) Date: Mon, 2 Feb 2009 14:46:18 -0800 (PST) Subject: [Tutor] regex: not start with FOO Message-ID: <528538.84097.qm@web112218.mail.gq1.yahoo.com> Hello, I'd like to match any line that does not start with FOO. (Using just a reg-ex rule) 1) What is the effective difference between: (?!^FOO).* ^(?!FOO).* 2) Is there a better way to do this? Thanks, :) From wferguson1 at socal.rr.com Tue Feb 3 00:50:18 2009 From: wferguson1 at socal.rr.com (WM.) Date: Mon, 02 Feb 2009 15:50:18 -0800 Subject: [Tutor] newton's sqrt formula Message-ID: <498786BA.6090002@socal.rr.com> # program to find square root square = input ('Please enter a number to be rooted, ') square = square * 1.0 guess = input('Please guess at the root, ') guess = guess * 1.0 newguess = 0. while guess**2 != square: # Newton's formula newguess = guess - (guess * guess - square) / (guess * 2) guess = newguess guess**2 - square print print print guess, ' is the square root of ', square print print print 'bye' Last month there was a square root program discussed. I wondered if the tide of my ignorance had receded enough that I could take a whack at messing with it. I offer this rewrite for your critique. Can it be terser, faster, prettier? Thank you. From alan.gauld at btinternet.com Tue Feb 3 01:44:27 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Feb 2009 00:44:27 -0000 Subject: [Tutor] newton's sqrt formula References: <498786BA.6090002@socal.rr.com> Message-ID: "WM." wrote > square = input ('Please enter a number to be rooted, ') > square = square * 1.0 Use raw_input() instead of input() and don't multiply by 1.0 - instead convert to float using float(): square = float( raw_input ('Please enter a number to be rooted, ')) > guess = input('Please guess at the root, ') > guess = guess * 1.0 > newguess = 0. > > while guess**2 != square: > # Newton's formula > newguess = guess - (guess * guess - square) / (guess * 2) > guess = newguess You could just combine these two guess = guess - (guess * guess - square) / (guess * 2) > guess**2 - square That line does not do anything! > print > print > print guess, ' is the square root of ', square > print > print > print 'bye' Partly a style thing but I would prefer you either used triple quoted strings and format chars or inserted \n characters. ie either: > print """ %s is the square root of %s bye""" % (guess, square) OR print "\n\n\n",guess," is the square root of", square,"\n\n\nbye!" Or combine both: print "\n\n\n%s is the square root of %s\n\n\nbye!" % (guess, square) Actually, if it was me I'd use two prints: print "\n\n\n%s is the square root of %s" % (guess, square) print"\n\n\nbye!" > I offer this rewrite for your critique. Can it be terser, faster, > prettier? > Thank you. Not very critical but maybe it helps... Alan G. From jervisau at gmail.com Tue Feb 3 02:19:30 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Tue, 3 Feb 2009 12:19:30 +1100 Subject: [Tutor] regex: not start with FOO In-Reply-To: <528538.84097.qm@web112218.mail.gq1.yahoo.com> References: <528538.84097.qm@web112218.mail.gq1.yahoo.com> Message-ID: <8e63a5ce0902021719o317f362euc26c9a36ce4a77d@mail.gmail.com> On Tue, Feb 3, 2009 at 9:46 AM, Bernard Rankin wrote: > Hello, > > > I'd like to match any line that does not start with FOO. (Using just a reg-ex rule) > > 1) What is the effective difference between: > > (?!^FOO).* > > ^(?!FOO).* > > 2) Is there a better way to do this? > myline = 'FOO things in line' >>> myline.startswith('FOO') True Cheers, From tim at johnsons-web.com Tue Feb 3 02:36:58 2009 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 2 Feb 2009 16:36:58 -0900 Subject: [Tutor] Installing python via ftp in virtual domain Message-ID: <200902021636.58091.tim@johnsons-web.com> I have a client who is hosting under virtual domain services that do not provide python. He has unlimited disk space available ( or so the hoster says) and they would allow installation of binaries in the virtual domain via ftp. It's a linux 'box' with a /private folder under the domain root. given that I have python 2.5 installed on my own desktop, which is also linux, could I expect to be able to install python and all libraries via FTP? If so, I'd welcome pointers, caveats and potentially issues. If it does not appear workable, I have alternatives, but the client wants me to try this initially. Thanks tim From john at fouhy.net Tue Feb 3 03:14:48 2009 From: john at fouhy.net (John Fouhy) Date: Tue, 3 Feb 2009 15:14:48 +1300 Subject: [Tutor] Installing python via ftp in virtual domain In-Reply-To: <200902021636.58091.tim@johnsons-web.com> References: <200902021636.58091.tim@johnsons-web.com> Message-ID: <5e58f2e40902021814w50338b8crd9dae84370fce466@mail.gmail.com> 2009/2/3 Tim Johnson : > I have a client who is hosting under virtual domain services that do not > provide python. > He has unlimited disk space available ( or so the hoster says) and they > would allow installation of binaries in the virtual domain via ftp. > > It's a linux 'box' with a /private folder under the domain root. given > that I have python 2.5 installed on my own desktop, which is also linux, > could I expect to be able to install python and all libraries via FTP? I guess the issues you'd face are: - different architecture (could be 64bit?) - wrong libraries It might be easier if you can build a statically-linked version of python -- although it appears that can have issues: http://bytes.com/groups/python/23235-build-static-python-executable-linux Or upload the python sources and build it there (do they provide gcc?). -- John. From kent37 at tds.net Tue Feb 3 03:24:06 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 2 Feb 2009 21:24:06 -0500 Subject: [Tutor] newton's sqrt formula In-Reply-To: <498786BA.6090002@socal.rr.com> References: <498786BA.6090002@socal.rr.com> Message-ID: <1c2a2c590902021824j6d778c42n428669d11afb6568@mail.gmail.com> On Mon, Feb 2, 2009 at 6:50 PM, WM. wrote: > # Newton's formula > newguess = guess - (guess * guess - square) / (guess * 2) > guess = newguess or guess = (guess + square/guess)/2 Kent From tim at johnsons-web.com Tue Feb 3 03:43:24 2009 From: tim at johnsons-web.com (Tim Johnson) Date: Mon, 2 Feb 2009 17:43:24 -0900 Subject: [Tutor] Installing python via ftp in virtual domain In-Reply-To: <5e58f2e40902021814w50338b8crd9dae84370fce466@mail.gmail.com> References: <200902021636.58091.tim@johnsons-web.com> <5e58f2e40902021814w50338b8crd9dae84370fce466@mail.gmail.com> Message-ID: <200902021743.24208.tim@johnsons-web.com> On Monday 02 February 2009, John Fouhy wrote: > 2009/2/3 Tim Johnson : > > I have a client who is hosting under virtual domain services that do not > > provide python. > > He has unlimited disk space available ( or so the hoster says) and they > > would allow installation of binaries in the virtual domain via ftp. > > > > It's a linux 'box' with a /private folder under the domain root. given > > that I have python 2.5 installed on my own desktop, which is also linux, > > could I expect to be able to install python and all libraries via FTP? > > I guess the issues you'd face are: > - different architecture (could be 64bit?) Let's say that they are using 32-bit architecture, then > - wrong libraries how do we resolve paths to libraries? tim - :-) who has other alternatives. From john at fouhy.net Tue Feb 3 03:55:34 2009 From: john at fouhy.net (John Fouhy) Date: Tue, 3 Feb 2009 15:55:34 +1300 Subject: [Tutor] Installing python via ftp in virtual domain In-Reply-To: <200902021743.24208.tim@johnsons-web.com> References: <200902021636.58091.tim@johnsons-web.com> <5e58f2e40902021814w50338b8crd9dae84370fce466@mail.gmail.com> <200902021743.24208.tim@johnsons-web.com> Message-ID: <5e58f2e40902021855n40568c4ai779a39c94a3911fc@mail.gmail.com> 2009/2/3 Tim Johnson : >> - wrong libraries > how do we resolve paths to libraries? Well, like I suggested, you could try building a staticly-linked version. Then it doesn't matter. Otherwise, I'm not sure. Maybe you could figure out what libraries you need, upload them, and play around with LD_LIBRARY_PATH. This is really a linux question, rather than a python question, though, so this may not be the best place to ask. (but see: http://tldp.org/HOWTO/Program-Library-HOWTO/shared-libraries.html and http://blogs.sun.com/ali/entry/avoiding_ld_library_path_the ) -- John. From wferguson1 at socal.rr.com Tue Feb 3 03:59:55 2009 From: wferguson1 at socal.rr.com (WM.) Date: Mon, 02 Feb 2009 18:59:55 -0800 Subject: [Tutor] newton's square root formula Message-ID: <4987B32B.7090109@socal.rr.com> # program to find square root square = float(raw_input ("Please enter a number to be rooted, ")) guess = input("Please guess at the root, ") i = 0 while guess**2 != square: i+=1 # Newton's formula guess = guess - (guess * guess - square) / (guess * 2) print i print "\n\n\n%s is the square root of %s" % (guess, square) print "\n%s loops were run." % (i) print "\n\n\nbye" # Here is my program, enhanced by Alan's good advice. The reason I wanted to re-write the other program was, it had a limited number of loops and I felt accuracy should be the measure. So, just now, I added a loop counter here and found that the formula is a little buggy. Make 'square = 7' and you will be in the 'i = 500' area before you can find ControlC. From berankin99 at yahoo.com Tue Feb 3 02:25:10 2009 From: berankin99 at yahoo.com (Bernard Rankin) Date: Mon, 2 Feb 2009 17:25:10 -0800 (PST) Subject: [Tutor] regex: not start with FOO References: <528538.84097.qm@web112218.mail.gq1.yahoo.com> <8e63a5ce0902021719o317f362euc26c9a36ce4a77d@mail.gmail.com> Message-ID: <924430.3872.qm@web112203.mail.gq1.yahoo.com> > > I'd like to match any line that does not start with FOO. (Using just a reg-ex > rule) > > > > 1) What is the effective difference between: > > > > (?!^FOO).* > > > > ^(?!FOO).* > > > > 2) Is there a better way to do this? > > > > myline = 'FOO things in line' > > >>> myline.startswith('FOO') > True Right. However, I am trying to just do this in a general "does this match" regex environment. From david at abbottdavid.com Tue Feb 3 04:53:50 2009 From: david at abbottdavid.com (David) Date: Mon, 02 Feb 2009 22:53:50 -0500 Subject: [Tutor] Alarm Clock (suggestions please) Message-ID: <4987BFCE.3060308@abbottdavid.com> Hi All, As I am getting a little older, I sometimes take small naps to recharge my batteries:) Is this while loop OK? What kind of error checking should I use? thanks -david #!/usr/bin/python import time import subprocess import sys doit = 1 alarmhour = int(raw_input("Please enter the hour. (24h): ")) alarmmin = int(raw_input("Please enter the minute. (01-59) ")) while(doit): mytime = list(time.localtime()) hour = mytime[3] minute = mytime[4] if hour == alarmhour and minute == alarmmin: subprocess.call('mplayer -loop 9 ring.wav', shell=True) sys.exit() doit = 0 -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From john at fouhy.net Tue Feb 3 05:13:09 2009 From: john at fouhy.net (John Fouhy) Date: Tue, 3 Feb 2009 17:13:09 +1300 Subject: [Tutor] Alarm Clock (suggestions please) In-Reply-To: <4987BFCE.3060308@abbottdavid.com> References: <4987BFCE.3060308@abbottdavid.com> Message-ID: <5e58f2e40902022013v595503c5x17db54a660df63bd@mail.gmail.com> 2009/2/3 David : > while(doit): > mytime = list(time.localtime()) > hour = mytime[3] > minute = mytime[4] > if hour == alarmhour and minute == alarmmin: > subprocess.call('mplayer -loop 9 ring.wav', shell=True) > sys.exit() Hi David, What you've written here is called a Busy Wait -- essentially, your program will be checking the local time as fast as it possibly can, which could be hundreds or thousands of times per second. It will cause your CPU (or, at least, the core python is on) to run at 100%. I imagine you don't actually care if your alarm is a few milliseconds late, so you could add a call to time.sleep(1) to the body of the loop. This will cause python to sleep for one second every iteration, thus allowing other programs to get some CPU time, and saving your power bill. (in fact, since you're only specifying hour and minute for your alarm, you may as well sleep for 60 seconds each iteration) Also, you could just write while(True). Your control variable doit isn't actually doing anything in this program. Regarding error checking, you could do tests to make sure the hour and minutes are in-range. Perhaps you could add code to check whether the alarm time is more than a certain number of hours in the future. Depends how complex you want to make it. (you could also inspect sys.argv -- this would allow you to specify the time on the command line, rather than requiring user input) -- John. From andreengels at gmail.com Tue Feb 3 09:03:12 2009 From: andreengels at gmail.com (Andre Engels) Date: Tue, 3 Feb 2009 09:03:12 +0100 Subject: [Tutor] newton's square root formula In-Reply-To: <6faf39c90902030002r624d47c3xaecdc0810ef36f8a@mail.gmail.com> References: <4987B32B.7090109@socal.rr.com> <6faf39c90902030002r624d47c3xaecdc0810ef36f8a@mail.gmail.com> Message-ID: <6faf39c90902030003q203a7109ra8d70871c6bc9fe8@mail.gmail.com> On Tue, Feb 3, 2009 at 3:59 AM, WM. wrote: > # program to find square root > square = float(raw_input ("Please enter a number to be rooted, ")) > guess = input("Please guess at the root, ") > i = 0 > while guess**2 != square: > i+=1 > # Newton's formula > guess = guess - (guess * guess - square) / (guess * 2) > print i > print "\n\n\n%s is the square root of %s" % (guess, square) > print "\n%s loops were run." % (i) > print "\n\n\nbye" > # > > > Here is my program, enhanced by Alan's good advice. The reason I wanted to > re-write the other program was, it had a limited number of loops and I felt > accuracy should be the measure. So, just now, I added a loop counter here > and found that the formula is a little buggy. Make 'square = 7' and you will > be in the 'i = 500' area before you can find ControlC. The problem is the loop guard: while guess**2 != square There probably is no number guess for which Python has guess**2 == 7 exactly. You'll have to choose a certain precision, and look for a number for which this closer than your chosen precision rather than a number for which it is true exactly. Change the guard to: while abs(guess*guess-square) > 0.0000000000001: and (choosing 1 as my initial guess) I got an answer after 6 iterations. -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Tue Feb 3 09:39:15 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 3 Feb 2009 08:39:15 -0000 Subject: [Tutor] newton's square root formula References: <4987B32B.7090109@socal.rr.com> Message-ID: "WM." wrote ># program to find square root > square = float(raw_input ("Please enter a number to be rooted, ")) > guess = input("Please guess at the root, ") Actually, I meant you should use raw_input here too... input() is considered insecure and not recommended. (In Python v3 it has been removed from the language and raw_input renamed to input.) -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From prasadaraon50 at gmail.com Tue Feb 3 09:42:20 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Tue, 3 Feb 2009 14:12:20 +0530 Subject: [Tutor] Division problems Message-ID: <9e3fac840902030042v593648f3q2c0cfa126a43ed13@mail.gmail.com> HelloI wrote a function named vertical to print string .printable characters and ASCII values in a table. 1)It is swallowing some characters. 2)It output some characters 2 or 3 times. 3)It prints one column more than what I asked for. It may be a division problem(floating point). Its sibling called horizontal got no problems. please examine it and give suggestions and improvements to set it right. #!usr\\bin\\env python def horizontal(columns): import string n=0 v=string.printable v=v.replace('\n','') v=v.replace('\t','') while n From simon at sibass.co.uk Tue Feb 3 09:45:21 2009 From: simon at sibass.co.uk (ukapache) Date: Tue, 3 Feb 2009 00:45:21 -0800 (PST) Subject: [Tutor] Alarm Clock (suggestions please) Message-ID: <21805118.post@talk.nabble.com> John Fouhy wrote: > > 2009/2/3 David : >> while(doit): >> mytime = list(time.localtime()) >> hour = mytime[3] >> minute = mytime[4] >> if hour == alarmhour and minute == alarmmin: >> subprocess.call('mplayer -loop 9 ring.wav', shell=True) >> sys.exit() > > Hi David, > > What you've written here is called a Busy Wait -- essentially, your > program will be checking the local time as fast as it possibly can, > which could be hundreds or thousands of times per second. It will > cause your CPU (or, at least, the core python is on) to run at 100%. > > I imagine you don't actually care if your alarm is a few milliseconds > late, so you could add a call to time.sleep(1) to the body of the > loop. This will cause python to sleep for one second every iteration, > thus allowing other programs to get some CPU time, and saving your > power bill. > > (in fact, since you're only specifying hour and minute for your alarm, > you may as well sleep for 60 seconds each iteration) > > Also, you could just write while(True). Your control variable doit > isn't actually doing anything in this program. > > Regarding error checking, you could do tests to make sure the hour and > minutes are in-range. Perhaps you could add code to check whether the > alarm time is more than a certain number of hours in the future. > Depends how complex you want to make it. > > (you could also inspect sys.argv -- this would allow you to specify > the time on the command line, rather than requiring user input) > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Hi This is my first post so please be gentle, have been teaching myself python for the last two months.... If you know the current local time (time.localtime()) and the time you want to wake up.... why not when you submit the program work out the difference and make the alarm sleep for that time interval? Simon -- View this message in context: http://www.nabble.com/Alarm-Clock-%28suggestions-please%29-tp21803518p21805118.html Sent from the Python - tutor mailing list archive at Nabble.com. From etrade.griffiths at dsl.pipex.com Tue Feb 3 10:20:36 2009 From: etrade.griffiths at dsl.pipex.com (etrade.griffiths at dsl.pipex.com) Date: Tue, 03 Feb 2009 09:20:36 +0000 Subject: [Tutor] reading binary files In-Reply-To: References: Message-ID: <1233652836.49880c6411543@netmail.pipex.net> Sorry, still having problems .... > > I am trying to read data from a file that has format > > item_name num_items item_type items .... > > > > eg > > > > TIME 1 0.0 > > DISTANCE 10 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 > > Where is the item_type? Ooops, the data format should look like this: TIME 1 F 0.0 DISTANCE 10 F 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 F=float, D=double, L=logical, S=string etc > > > I can read this if the data are in ASCII format using > > > > in_file = open("my_file.dat","r") > > data1 = in_file.read() > > tokens = data1.split() > > It might be easier to process line by line using readline > or readlines rather than read but otherwise, ok so far... > > > and then stepping through the resulting list but the data > > also appear in the same format in a binary file. > > When you say a binary file do you mean an ASCII file > encoded into binary using some standard algorithm? > Or do you mean the data is binary so that, for example, > the number 1 would appear as 4 bytes? If so do you > know how strings (the name) are delimited? Also > how many could be present - is length a single or > multiple bytes? and are the reors fixed length or > variable? If variable what is the field/record separator? Sorry, no idea what the difference is. All I know is that the data were written by a FORTRAN program using the UNFORMATTED argument in the WRITE statement and that if they had been written FORMATTED then we would get afile that looks something like the example above > > You may need to load the file into a hex editor of debugger > to determine the answers... > > Having done that the struct module will allow you to read > the data. > > You can see a basic example of using struct in my > tutorial topic about handling files. The first part of the file should contain a string (eg "TIME"), an integer (1) and another string (eg "F") so I tried using import struct in_file = open(file_name+".dat","rb") data = in_file.read() items = struct.unpack('sds', data) Now I get the error error: unpack requires a string argument of length 17 which has left me completely baffled! > > > ------------------------------ > > Message: 4 > Date: Mon, 02 Feb 2009 14:53:59 -0700 > From: Bernd Prager > Subject: [Tutor] question about mpmath product expression > To: tutor at python.org > Message-ID: > Content-Type: text/plain; charset="UTF-8" > > Does anybody know if there is a precision difference when I use mpmath and > take an expression: > > from mpmath import * > mp.dps = 100 > mu0 = [mpf('4') * pi * power(10, -7) > > rather then: > > mu0 = fprod([mpf('4'), pi, power(10, -7)]) > > ? > > Thanks, > -- Bernd > > > ------------------------------ > > Message: 5 > Date: Mon, 2 Feb 2009 14:46:18 -0800 (PST) > From: Bernard Rankin > Subject: [Tutor] regex: not start with FOO > To: Tutor at python.org > Message-ID: <528538.84097.qm at web112218.mail.gq1.yahoo.com> > Content-Type: text/plain; charset=us-ascii > > Hello, > > > I'd like to match any line that does not start with FOO. (Using just a > reg-ex rule) > > 1) What is the effective difference between: > > (?!^FOO).* > > ^(?!FOO).* > > 2) Is there a better way to do this? > > > Thanks, > :) > > > > > > > > ------------------------------ > > Message: 6 > Date: Mon, 02 Feb 2009 15:50:18 -0800 > From: "WM." > Subject: [Tutor] newton's sqrt formula > To: tutor at python.org > Message-ID: <498786BA.6090002 at socal.rr.com> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > # program to find square root > square = input ('Please enter a number to be rooted, ') > square = square * 1.0 > guess = input('Please guess at the root, ') > guess = guess * 1.0 > newguess = 0. > > while guess**2 != square: > # Newton's formula > newguess = guess - (guess * guess - square) / (guess * 2) > guess = newguess > guess**2 - square > print > print > print guess, ' is the square root of ', square > print > print > print 'bye' > Last month there was a square root program discussed. I wondered if the > tide of my ignorance had receded enough that I could take a whack at > messing with it. > I offer this rewrite for your critique. Can it be terser, faster, prettier? > Thank you. > > > > > ------------------------------ > > Message: 7 > Date: Tue, 3 Feb 2009 00:44:27 -0000 > From: "Alan Gauld" > Subject: Re: [Tutor] newton's sqrt formula > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=response > > "WM." wrote > > > square = input ('Please enter a number to be rooted, ') > > square = square * 1.0 > > Use raw_input() instead of input() and don't multiply > by 1.0 - instead convert to float using float(): > > square = float( raw_input ('Please enter a number to be rooted, ')) > > > guess = input('Please guess at the root, ') > > guess = guess * 1.0 > > newguess = 0. > > > > while guess**2 != square: > > # Newton's formula > > newguess = guess - (guess * guess - square) / (guess * 2) > > guess = newguess > > You could just combine these two > > guess = guess - (guess * guess - square) / (guess * 2) > > > guess**2 - square > > That line does not do anything! > > > print > > print > > print guess, ' is the square root of ', square > > print > > print > > print 'bye' > > Partly a style thing but I would prefer you either used triple > quoted strings and format chars or inserted \n characters. > ie either: > > > print """ > > > %s is the square root of %s > > > > bye""" % (guess, square) > > OR > > print "\n\n\n",guess," is the square root of", square,"\n\n\nbye!" > > Or combine both: > > print "\n\n\n%s is the square root of %s\n\n\nbye!" % (guess, square) > > Actually, if it was me I'd use two prints: > > print "\n\n\n%s is the square root of %s" % (guess, square) > print"\n\n\nbye!" > > > I offer this rewrite for your critique. Can it be terser, faster, > > prettier? > > Thank you. > > Not very critical but maybe it helps... > > Alan G. > > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 60, Issue 5 > ************************************ > -- ------------------------------------------------- Visit Pipex Business: The homepage for UK Small Businesses Go to http://www.pipex.co.uk/business-services From prasadaraon50 at gmail.com Tue Feb 3 11:40:14 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Tue, 3 Feb 2009 16:10:14 +0530 Subject: [Tutor] weird bool Message-ID: <9e3fac840902030240y47297162x14f34a2af7c11c43@mail.gmail.com> hi >>> a=2.1 >>> a%1==True False >>> a%1==False False >>> b=3.8 >>> b%1==True False >>> b%1==False False If it gives correct bool, it could be put to good use. Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Tue Feb 3 11:50:57 2009 From: andreengels at gmail.com (Andre Engels) Date: Tue, 3 Feb 2009 11:50:57 +0100 Subject: [Tutor] weird bool In-Reply-To: <6faf39c90902030250g359963efs6c943094778b5700@mail.gmail.com> References: <9e3fac840902030240y47297162x14f34a2af7c11c43@mail.gmail.com> <6faf39c90902030250g359963efs6c943094778b5700@mail.gmail.com> Message-ID: <6faf39c90902030250lb6acbc3id713532a5bc38bc2@mail.gmail.com> On Tue, Feb 3, 2009 at 11:40 AM, prasad rao wrote: > hi >>>> a=2.1 >>>> a%1==True > False >>>> a%1==False > False >>>> b=3.8 >>>> b%1==True > False >>>> b%1==False > False > If it gives correct bool, it could be put to good use. == gives a high degree of equality. In your idea, it would not be a kind of equality at all, because you would have: >>> 1 == True True >>> 2 == True True >>> 1 == 2 False It would also be confusion as to when '==' would mean logical equality and when real equality: >>>> 1 == ((0 == 0) or not (0==0)) True >>>> 1 == ((0 + 0) * (0 + 0)) False >>>> True == 1 ??? Finally, it is rarely necessary: >>> a=2.1 >>> bool(a%1)==True True That's a few characters more, but to me that's more than compensated by the gains in clarity and consistency (== is an equivalence relationship, at least unless you have redefined it for your own class in a less practical way) -- Andr? Engels, andreengels at gmail.com From simon at sibass.co.uk Tue Feb 3 08:41:08 2009 From: simon at sibass.co.uk (ukapache) Date: Mon, 2 Feb 2009 23:41:08 -0800 (PST) Subject: [Tutor] Alarm Clock (suggestions please) In-Reply-To: <5e58f2e40902022013v595503c5x17db54a660df63bd@mail.gmail.com> References: <4987BFCE.3060308@abbottdavid.com> <5e58f2e40902022013v595503c5x17db54a660df63bd@mail.gmail.com> Message-ID: <21805118.post@talk.nabble.com> John Fouhy wrote: > > 2009/2/3 David : >> while(doit): >> mytime = list(time.localtime()) >> hour = mytime[3] >> minute = mytime[4] >> if hour == alarmhour and minute == alarmmin: >> subprocess.call('mplayer -loop 9 ring.wav', shell=True) >> sys.exit() > > Hi David, > > What you've written here is called a Busy Wait -- essentially, your > program will be checking the local time as fast as it possibly can, > which could be hundreds or thousands of times per second. It will > cause your CPU (or, at least, the core python is on) to run at 100%. > > I imagine you don't actually care if your alarm is a few milliseconds > late, so you could add a call to time.sleep(1) to the body of the > loop. This will cause python to sleep for one second every iteration, > thus allowing other programs to get some CPU time, and saving your > power bill. > > (in fact, since you're only specifying hour and minute for your alarm, > you may as well sleep for 60 seconds each iteration) > > Also, you could just write while(True). Your control variable doit > isn't actually doing anything in this program. > > Regarding error checking, you could do tests to make sure the hour and > minutes are in-range. Perhaps you could add code to check whether the > alarm time is more than a certain number of hours in the future. > Depends how complex you want to make it. > > (you could also inspect sys.argv -- this would allow you to specify > the time on the command line, rather than requiring user input) > > -- > John. > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Hi This is my first post so please be gentle, have been teaching myself python for the last two months.... If you know the current local time (time.localtime()) and the time you want to wake up.... why not when you submit the program work out the difference and make the alarm sleep for that time interval? Simon -- View this message in context: http://www.nabble.com/Alarm-Clock-%28suggestions-please%29-tp21803518p21805118.html Sent from the Python - tutor mailing list archive at Nabble.com. From kent37 at tds.net Tue Feb 3 12:40:59 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 3 Feb 2009 06:40:59 -0500 Subject: [Tutor] regex: not start with FOO In-Reply-To: <528538.84097.qm@web112218.mail.gq1.yahoo.com> References: <528538.84097.qm@web112218.mail.gq1.yahoo.com> Message-ID: <1c2a2c590902030340v18f6b9foac29526d0f72b775@mail.gmail.com> On Mon, Feb 2, 2009 at 5:46 PM, Bernard Rankin wrote: > Hello, > > > I'd like to match any line that does not start with FOO. (Using just a reg-ex rule) > > 1) What is the effective difference between: > > (?!^FOO).* > > ^(?!FOO).* One difference is that the first will match starting anywhere in a string, while the second will match only at the start. For this exact example I don't think it matters but if you replace .* with something else you can see a difference. For example: In [52]: re.findall('(?!^FOO) in', 'in in in') Out[52]: [' in', ' in'] In [53]: re.findall('^(?!FOO) in', 'in in in') Out[53]: [] I think I would use the second form, it seems to more directly express what you mean. Kent From kent37 at tds.net Tue Feb 3 12:56:06 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 3 Feb 2009 06:56:06 -0500 Subject: [Tutor] Division problems In-Reply-To: <9e3fac840902030042v593648f3q2c0cfa126a43ed13@mail.gmail.com> References: <9e3fac840902030042v593648f3q2c0cfa126a43ed13@mail.gmail.com> Message-ID: <1c2a2c590902030356h4873c4a3s6c6939bbfd21b63b@mail.gmail.com> On Tue, Feb 3, 2009 at 3:42 AM, prasad rao wrote: > Hello > I wrote a function named vertical to print string .printable characters and > ASCII values in a table. > 1)It is swallowing some characters. > 2)It output some characters 2 or 3 times. > 3)It prints one column more than what I asked for. > def vertical(columns): > import string > v=string.printable > v=v.replace('\n','') > v=v.replace('\t','') What is len(v) here? What is len(v)/columns? > for x in range((len(v))/columns): > for y in range(x,len(v),x+((len(v))/columns)): The third argument to range() is the step size. Do you want to use a different step size for each row? Kent From prasadaraon50 at gmail.com Tue Feb 3 14:24:16 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Tue, 3 Feb 2009 18:54:16 +0530 Subject: [Tutor] re division problem Message-ID: <9e3fac840902030524x669a9095tf89de468dd32b58@mail.gmail.com> > I wrote a function named vertical to print string .printable characters and .>> ASCII values in a table. >> 1)It is swallowing some characters. >> 2)It output some characters 2 or 3 times. >> 3)It prints one column more than what I asked for. >> def vertical(columns): >> import string >> v=string.printable >> v=v.replace('\n','') >> v=v.replace('\t','') >What is len(v) here? What is len(v)/columns? There are 100 characters in the string(string.printable) I deleted '\n\t'. So 98/say 4==24.5 So if there is a fraction I have to round it off to 1. So 24.5 should be rounded off to 25..But is there a better way to print it in given number of columns >> for x in range((len(v))/columns): >> for y in range(x,len(v),x+((len(v))/columns)): >The third argument to range() is the step size. Do you want to use a >different step size for each row? No. How can I ensure that every value is an integer but without missing in retrieving an element in the string. Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From prasadaraon50 at gmail.com Tue Feb 3 14:33:27 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Tue, 3 Feb 2009 19:03:27 +0530 Subject: [Tutor] re weird bool Message-ID: <9e3fac840902030533o4afc83c1s97831153b07c89be@mail.gmail.com> helloyes.you are right. >>> 2==True False It is an unexpected result to me. I thought any value other than 0 is True. And the solution provided by you(bool(a/1)) is useful to me. Thank you Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Feb 3 14:35:29 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 3 Feb 2009 08:35:29 -0500 Subject: [Tutor] re division problem In-Reply-To: <9e3fac840902030524x669a9095tf89de468dd32b58@mail.gmail.com> References: <9e3fac840902030524x669a9095tf89de468dd32b58@mail.gmail.com> Message-ID: <1c2a2c590902030535i22009a11sd36ede3e2aa4ddf@mail.gmail.com> On Tue, Feb 3, 2009 at 8:24 AM, prasad rao wrote: >> I wrote a function named vertical to print string .printable characters >> and > .>> ASCII values in a table. >>> 1)It is swallowing some characters. >>> 2)It output some characters 2 or 3 times. >>> 3)It prints one column more than what I asked for. > >>> def vertical(columns): >>> import string >>> v=string.printable >>> v=v.replace('\n','') >>> v=v.replace('\t','') > >>What is len(v) here? What is len(v)/columns? > There are 100 characters in the string(string.printable) > I deleted '\n\t'. So 98/say 4==24.5 So if there is a fraction > I have to round it off to 1. So 24.5 should be rounded off > to 25..But is there a better way to print it in given number > of columns Right. One way to do integer division that rounds up is like this: skip = (len(v) + columns - 1) / columns > >>> for x in range((len(v))/columns): >>> for y in range(x,len(v),x+((len(v))/columns)): > >>The third argument to range() is the step size. Do you want to use a >>different step size for each row? > No. How can I ensure that every value is an integer but without missing > in retrieving an element in the string. Not sure what you mean by that. How many elements do you need to skip to get to the next column? Right now you skip by x+((len(v))/columns) which will be different for each row. Kent From prasadaraon50 at gmail.com Tue Feb 3 14:46:05 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Tue, 3 Feb 2009 19:16:05 +0530 Subject: [Tutor] re division problem Message-ID: <9e3fac840902030546h6b807776hd97f351ce6df8495@mail.gmail.com> hi>Right now you skip by x+((len(v))/columns) >which will be different for each row. How is it possible. len(v)=98.A constant. Is it not. Does len(v) changes with each iteration? Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Tue Feb 3 14:59:25 2009 From: andreengels at gmail.com (Andre Engels) Date: Tue, 3 Feb 2009 14:59:25 +0100 Subject: [Tutor] re division problem In-Reply-To: <9e3fac840902030546h6b807776hd97f351ce6df8495@mail.gmail.com> References: <9e3fac840902030546h6b807776hd97f351ce6df8495@mail.gmail.com> Message-ID: <6faf39c90902030559g454a3c00i5ac549898082cdaa@mail.gmail.com> On Tue, Feb 3, 2009 at 2:46 PM, prasad rao wrote: > hi >>Right now you skip by x+((len(v))/columns) >>which will be different for each row. > How is it possible. len(v)=98.A constant. > Is it not. > Does len(v) changes with each iteration? No, but x does. -- Andr? Engels, andreengels at gmail.com From hgleroy at gmail.com Tue Feb 3 16:17:31 2009 From: hgleroy at gmail.com (H.G. le Roy) Date: Tue, 3 Feb 2009 16:17:31 +0100 Subject: [Tutor] transforming an integer to a list of integers Message-ID: <317299150902030717k54aecd8do256654a20e189eff@mail.gmail.com> Hi, recently I learned about Project Euler (http://projecteuler.net/) and now I'm trying to work me through. At the moment I'm thinking about http://projecteuler.net/index.php?section=problems&id=8 One step for my solution should be transforming this big integer to a list of integers. I did: import math bignr = 12345 bignrs =[] for i in xrange(math.ceil(math.log10(bignr)): rem = bignr % 10 bignrs.append(rem) bignr /= 10 However this "feels" a bit complicated, Do you know a better (more simple, nice etc.) way to do this? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From ksterling at mindspring.com Tue Feb 3 16:22:52 2009 From: ksterling at mindspring.com (Ken Oliver) Date: Tue, 3 Feb 2009 10:22:52 -0500 (EST) Subject: [Tutor] transforming an integer to a list of integers Message-ID: <2439240.1233674572763.JavaMail.root@elwamui-ovcar.atl.sa.earthlink.net> An HTML attachment was scrubbed... URL: From andreengels at gmail.com Tue Feb 3 16:24:53 2009 From: andreengels at gmail.com (Andre Engels) Date: Tue, 3 Feb 2009 16:24:53 +0100 Subject: [Tutor] transforming an integer to a list of integers In-Reply-To: <317299150902030717k54aecd8do256654a20e189eff@mail.gmail.com> References: <317299150902030717k54aecd8do256654a20e189eff@mail.gmail.com> Message-ID: <6faf39c90902030724y2888b285v3ca787c73473fcd2@mail.gmail.com> On Tue, Feb 3, 2009 at 4:17 PM, H.G. le Roy wrote: > Hi, > > recently I learned about Project Euler (http://projecteuler.net/) and now > I'm trying to work me through. At the moment I'm thinking about > http://projecteuler.net/index.php?section=problems&id=8 > > One step for my solution should be transforming this big integer to a list > of integers. I did: > > import math > > bignr = 12345 > bignrs =[] > > for i in xrange(math.ceil(math.log10(bignr)): > rem = bignr % 10 > bignrs.append(rem) > bignr /= 10 > > However this "feels" a bit complicated, Do you know a better (more simple, > nice etc.) way to do this? One way could be to represent the number as a string; a string can be treated as a list, so you get what you want quite quickly that way: bignr = 12345 bignrs =[] for char in str(bignr): bignrs.append(int(char)) -- Andr? Engels, andreengels at gmail.com From andreengels at gmail.com Tue Feb 3 16:25:44 2009 From: andreengels at gmail.com (Andre Engels) Date: Tue, 3 Feb 2009 16:25:44 +0100 Subject: [Tutor] transforming an integer to a list of integers In-Reply-To: <6faf39c90902030724y2888b285v3ca787c73473fcd2@mail.gmail.com> References: <317299150902030717k54aecd8do256654a20e189eff@mail.gmail.com> <6faf39c90902030724y2888b285v3ca787c73473fcd2@mail.gmail.com> Message-ID: <6faf39c90902030725y658d7a42l88e89913f05537b7@mail.gmail.com> On Tue, Feb 3, 2009 at 4:24 PM, Andre Engels wrote: > On Tue, Feb 3, 2009 at 4:17 PM, H.G. le Roy wrote: >> Hi, >> >> recently I learned about Project Euler (http://projecteuler.net/) and now >> I'm trying to work me through. At the moment I'm thinking about >> http://projecteuler.net/index.php?section=problems&id=8 >> >> One step for my solution should be transforming this big integer to a list >> of integers. I did: >> >> import math >> >> bignr = 12345 >> bignrs =[] >> >> for i in xrange(math.ceil(math.log10(bignr)): >> rem = bignr % 10 >> bignrs.append(rem) >> bignr /= 10 >> >> However this "feels" a bit complicated, Do you know a better (more simple, >> nice etc.) way to do this? > > One way could be to represent the number as a string; a string can be > treated as a list, so you get what you want quite quickly that way: > > bignr = 12345 > bignrs =[] > > for char in str(bignr): > bignrs.append(int(char)) Or as a one-liner: bignr = 12345 bignrs =[int(char) for char in str(bignr)] -- Andr? Engels, andreengels at gmail.com From kent37 at tds.net Tue Feb 3 17:06:00 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 3 Feb 2009 11:06:00 -0500 Subject: [Tutor] transforming an integer to a list of integers In-Reply-To: <317299150902030717k54aecd8do256654a20e189eff@mail.gmail.com> References: <317299150902030717k54aecd8do256654a20e189eff@mail.gmail.com> Message-ID: <1c2a2c590902030806l17231e93t82ec5abae2768091@mail.gmail.com> On Tue, Feb 3, 2009 at 10:17 AM, H.G. le Roy wrote: > One step for my solution should be transforming this big integer to a list > of integers. I did: > > import math > > bignr = 12345 > bignrs =[] > The suggestions with strings are fine, but you can simplify your approach as well: > for i in xrange(math.ceil(math.log10(bignr)): No need for the complicated range expression, just use while bignr > 0: > rem = bignr % 10 > bignrs.append(rem) > bignr /= 10 Using the divmod() function you can compute rem and the new value for bignr in one operation: bignr, rem = divmod(bignr, 10) Kent From berankin99 at yahoo.com Tue Feb 3 17:18:40 2009 From: berankin99 at yahoo.com (Bernard Rankin) Date: Tue, 3 Feb 2009 08:18:40 -0800 (PST) Subject: [Tutor] regex: not start with FOO References: <528538.84097.qm@web112218.mail.gq1.yahoo.com> <1c2a2c590902030340v18f6b9foac29526d0f72b775@mail.gmail.com> Message-ID: <895360.82262.qm@web112201.mail.gq1.yahoo.com> > > I'd like to match any line that does not start with FOO. (Using just a reg-ex > rule) > > > > 1) What is the effective difference between: > > > > (?!^FOO).* > > > > ^(?!FOO).* > > One difference is that the first will match starting anywhere in a > string, while the second will match only at the start. For this exact > example I don't think it matters but if you replace .* with something > else you can see a difference. For example: > In [52]: re.findall('(?!^FOO) in', 'in in in') > Out[52]: [' in', ' in'] > > In [53]: re.findall('^(?!FOO) in', 'in in in') > Out[53]: [] > > I think I would use the second form, it seems to more directly express > what you mean. > Hmm... In [30]: re.findall('(?!FOO)in', 'in FOOin in') Out[30]: ['in', 'in', 'in'] OK, now I am confused... . why am I getting 3 results? From berankin99 at yahoo.com Tue Feb 3 17:12:59 2009 From: berankin99 at yahoo.com (Bernard Rankin) Date: Tue, 3 Feb 2009 08:12:59 -0800 (PST) Subject: [Tutor] regex: not start with FOO References: <528538.84097.qm@web112218.mail.gq1.yahoo.com> <1c2a2c590902030340v18f6b9foac29526d0f72b775@mail.gmail.com> Message-ID: <682706.24984.qm@web112207.mail.gq1.yahoo.com> > > I'd like to match any line that does not start with FOO. (Using just a reg-ex > rule) > > > > 1) What is the effective difference between: > > > > (?!^FOO).* > > > > ^(?!FOO).* > > One difference is that the first will match starting anywhere in a > string, while the second will match only at the start. For this exact > example I don't think it matters but if you replace .* with something > else you can see a difference. For example: > In [52]: re.findall('(?!^FOO) in', 'in in in') > Out[52]: [' in', ' in'] > > In [53]: re.findall('^(?!FOO) in', 'in in in') > Out[53]: [] > > I think I would use the second form, it seems to more directly express > what you mean. > Thank you... that clarifies things greatly. Now, to change the example slightly: In [3]: re.findall('^(?!FOO)in', 'in in in') Out[3]: ['in'] In [4]: re.findall('(?!^FOO)in', 'in in in') Out[4]: ['in', 'in', 'in'] In [5]: re.findall('(?!FOO)in', 'in in in') Out[5]: ['in', 'in', 'in'] In [6]: re.findall('(?!FOO$)in', 'in in in') Out[6]: ['in', 'in', 'in'] In [7]: re.findall('(?!^FOO$)in', 'in in in') Out[7]: ['in', 'in', 'in'] What is the effective difference between numbers 4 thru 7? That is, what effect does a string position anchor have within the sub expression? Thank you, :) From kent37 at tds.net Tue Feb 3 18:00:50 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 3 Feb 2009 12:00:50 -0500 Subject: [Tutor] regex: not start with FOO In-Reply-To: <682706.24984.qm@web112207.mail.gq1.yahoo.com> References: <528538.84097.qm@web112218.mail.gq1.yahoo.com> <1c2a2c590902030340v18f6b9foac29526d0f72b775@mail.gmail.com> <682706.24984.qm@web112207.mail.gq1.yahoo.com> Message-ID: <1c2a2c590902030900p184e485h7cc490ce003e69bc@mail.gmail.com> On Tue, Feb 3, 2009 at 11:12 AM, Bernard Rankin wrote: > In [3]: re.findall('^(?!FOO)in', 'in in in') > Out[3]: ['in'] > > In [4]: re.findall('(?!^FOO)in', 'in in in') > Out[4]: ['in', 'in', 'in'] > > In [5]: re.findall('(?!FOO)in', 'in in in') > Out[5]: ['in', 'in', 'in'] > > In [6]: re.findall('(?!FOO$)in', 'in in in') > Out[6]: ['in', 'in', 'in'] > > In [7]: re.findall('(?!^FOO$)in', 'in in in') > Out[7]: ['in', 'in', 'in'] > > > What is the effective difference between numbers 4 thru 7? > > That is, what effect does a string position anchor have within the sub expression? 6 & 7 are meaningless; you can never have an end-of-line ($) followed by text. > Hmm... > > In [30]: re.findall('(?!FOO)in', 'in FOOin in') > Out[30]: ['in', 'in', 'in'] OK. (?!...) is a look *ahead* assertion - it requires that the current match not be followed by the given expression. It seems that this is meaningless at the start of a regex, since there is no current match. In other words, '(?!FOO)in' matches 'in FOOin in' at position 6 because starting at position 6 there is no FOO. You should use a look-behind assertion, or just put the ^ outside the assertion. In [2]: re.findall('(?!FOO)in', 'in FOOin in') Out[2]: ['in', 'in', 'in'] In [3]: re.findall('(? References: <497DC193.40301@gmail.com> Message-ID: <498885DB.8000701@gmail.com> Alan Gauld schreef: > Timo wrote > >> So my entry's look like this (more or less ;)): >> [person1] >> firstName = foo >> lastName = bar >> father = person2 >> mother = person3 > > And I assume you are reading these into a Person class and > storing these classes in a persons dictionary? Then to access > a father becomes: > > x = 'Person5' > print Persons[x].father.firstName > Can you explain this a little more for me please? The current way of reading the data is this: parser = ConfigParser.ConfigParser() parser.read(personFile) def get_info(person) infoDic = {} infoDic['first'] = parser.get(person, 'firstName') infoDic['last'] = parser.get(person, 'lastName') infoDic['father'] = parser.get(person, 'father') infoDic['mother'] = parser.get(person, 'mother') return infoDic But maybe it can be done better. Timo From bgailer at gmail.com Tue Feb 3 19:25:07 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 03 Feb 2009 13:25:07 -0500 Subject: [Tutor] struct question Message-ID: <49888C03.9060707@gmail.com> >>> struct.calcsize('s') 1 >>> struct.calcsize('d') 8 >>> struct.calcsize('sd') 16 Why? Should not that be 9? -- Bob Gailer Chapel Hill NC 919-636-4239 From srilyk at gmail.com Tue Feb 3 19:29:27 2009 From: srilyk at gmail.com (W W) Date: Tue, 3 Feb 2009 18:29:27 +0000 Subject: [Tutor] struct question In-Reply-To: <49888C03.9060707@gmail.com> References: <49888C03.9060707@gmail.com> Message-ID: <333efb450902031029v572c1522m6d561db36361013b@mail.gmail.com> On Tue, Feb 3, 2009 at 6:25 PM, bob gailer wrote: > >>> struct.calcsize('s') > 1 > >>> struct.calcsize('d') > 8 > >>> struct.calcsize('sd') > 16 > > Why? Should not that be 9? > >>> struct.calcsize('ds') 9 at least on the current box I'm running. It also gave me this: >>> struct.calcsize('sd') 12 so I must confess suspicion... HTH though, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From carroll at tjc.com Tue Feb 3 19:43:03 2009 From: carroll at tjc.com (Terry Carroll) Date: Tue, 3 Feb 2009 10:43:03 -0800 (PST) Subject: [Tutor] Parsing suggestion? (CUE file) Message-ID: I am parsing certai From marc.tompkins at gmail.com Tue Feb 3 20:03:38 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 3 Feb 2009 11:03:38 -0800 Subject: [Tutor] struct question In-Reply-To: <333efb450902031029v572c1522m6d561db36361013b@mail.gmail.com> References: <49888C03.9060707@gmail.com> <333efb450902031029v572c1522m6d561db36361013b@mail.gmail.com> Message-ID: <40af687b0902031103s676d91d2m2efe04769be2cb9f@mail.gmail.com> On Tue, Feb 3, 2009 at 10:29 AM, W W wrote: > > > On Tue, Feb 3, 2009 at 6:25 PM, bob gailer wrote: > >> >>> struct.calcsize('s') >> 1 >> >>> struct.calcsize('d') >> 8 >> >>> struct.calcsize('sd') >> 16 >> >> Why? Should not that be 9? >> > > >>> struct.calcsize('ds') > 9 > > at least on the current box I'm running. It also gave me this: > > >>> struct.calcsize('sd') > 12 > > so I must confess suspicion... > > HTH though, > Wayne > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > More results to chew on: >>> struct.calcsize('s') 1 >>> struct.calcsize('d') 8 >>> struct.calcsize('sd') 16 >>> struct.calcsize('ds') 9 >>> struct.calcsize('dss') 10 >>> struct.calcsize('dssssss') 14 >>> struct.calcsize('dsd') 24 I believe it's a matter of alignment: > Native size and alignment are determined using the C compiler's sizeofexpression. This is always combined with native byte order. > > Standard size and alignment are as follows: no alignment is required for > any type (so you have to use pad bytes); short is 2 bytes; int and longare 4 bytes; > long long (__int64 on Windows) is 8 bytes; float and double are 32-bit and > 64-bit IEEE floating point numbers, respectively. _Bool is 1 byte. > -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Feb 3 20:05:57 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 03 Feb 2009 14:05:57 -0500 Subject: [Tutor] struct question In-Reply-To: <333efb450902031029v572c1522m6d561db36361013b@mail.gmail.com> References: <49888C03.9060707@gmail.com> <333efb450902031029v572c1522m6d561db36361013b@mail.gmail.com> Message-ID: <49889595.70405@gmail.com> W W wrote: > > > On Tue, Feb 3, 2009 at 6:25 PM, bob gailer > wrote: > > >>> struct.calcsize('s') > 1 > >>> struct.calcsize('d') > 8 > >>> struct.calcsize('sd') > 16 > > Why? Should not that be 9? > > > >>> struct.calcsize('ds') > 9 > > at least on the current box I'm running. It also gave me this: > > >>> struct.calcsize('sd') > 12 > > so I must confess suspicion... I have submitted this as a bug. Same behavior with c instead of s. -- Bob Gailer Chapel Hill NC 919-636-4239 From marc.tompkins at gmail.com Tue Feb 3 20:14:37 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 3 Feb 2009 11:14:37 -0800 Subject: [Tutor] struct question In-Reply-To: <49889595.70405@gmail.com> References: <49888C03.9060707@gmail.com> <333efb450902031029v572c1522m6d561db36361013b@mail.gmail.com> <49889595.70405@gmail.com> Message-ID: <40af687b0902031114o7d897770m3d98f9db39132528@mail.gmail.com> On Tue, Feb 3, 2009 at 11:05 AM, bob gailer wrote: > I have submitted this as a bug. Same behavior with c instead of s. > I don't think it's a bug. Each double requires 8 bytes; that 8 bytes needs to start at an 8-byte boundary. If your struct starts with a 1-byte object, then some empty padding bytes need to be inserted. It's like loading the dishwasher. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Tue Feb 3 20:52:55 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 03 Feb 2009 14:52:55 -0500 Subject: [Tutor] reading binary files In-Reply-To: <1233652836.49880c6411543@netmail.pipex.net> References: <1233652836.49880c6411543@netmail.pipex.net> Message-ID: <4988A097.5070503@gmail.com> etrade.griffiths at dsl.pipex.com wrote: > Data format: > > TIME 1 F 0.0 > DISTANCE 10 F 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 > > F=float, D=double, L=logical, S=string etc > > > The first part of the file should contain a string (eg "TIME"), > an integer (1) and another string (eg "F") so I tried using > > import struct > in_file = open(file_name+".dat","rb") > data = in_file.read() > items = struct.unpack('sds', data) > > Now I get the error > > error: unpack requires a string argument of length 17 > > which has left me completely baffled! > > Did you open the file with mode 'b'? If not change that. You are passing the entire file to unpack when you should be giving it only the first "line". That's why is is complaining about the length. We need to figure out the lengths of the lines. Consider the first "line" TIME 1 F 0.0 There were (I assume) 4 FORTRAN variables written here: character integer character float. Without knowing the lengths of the character variables we are at a loss as to what the struct format should be. Do you know their lengths? Is the last float or double? Try this: print data[:40] You should see something like: TIME...\x01\x00\x00\x00...F...\x00\x00\x00\x00...DISTANCE...\n\x00\x00\x00 where ... means 0 or more intervening stuff. It might be that the \x01 and the \n are in other places, as we also have to deal with "byte order" issues. Please do this and report back your results. And also the FORTRAN variable types if you have access to them. -- Bob Gailer Chapel Hill NC 919-636-4239 From carroll at tjc.com Tue Feb 3 20:55:59 2009 From: carroll at tjc.com (Terry Carroll) Date: Tue, 3 Feb 2009 11:55:59 -0800 (PST) Subject: [Tutor] Parsing suggestion? (CUE file) In-Reply-To: Message-ID: On Tue, 3 Feb 2009, Terry Carroll wrote: > I am parsing certai Sorry about that. I was composing this message last night when my Internet connection went down. When I logged on this morning, I had a partial message. I meant to cancel but unfortunately, in pine, the SEND key (CTRL-X) is adjacent to the CANCEL key (CTRL-C), and I hit the wrong one. The silver cloud to my temporary Internet outage was that I was able to solve my problem, in the process discovering that the csv module can parse a CUE file[1] quite nicely if you set up an appropriate csv.Dialect class. "Comma Separated Values"; it's not just for commas any more. [1] http://en.wikipedia.org/wiki/Cue_file From kent37 at tds.net Tue Feb 3 20:57:46 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 3 Feb 2009 14:57:46 -0500 Subject: [Tutor] struct question In-Reply-To: <40af687b0902031103s676d91d2m2efe04769be2cb9f@mail.gmail.com> References: <49888C03.9060707@gmail.com> <333efb450902031029v572c1522m6d561db36361013b@mail.gmail.com> <40af687b0902031103s676d91d2m2efe04769be2cb9f@mail.gmail.com> Message-ID: <1c2a2c590902031157t62ce85f2n571d3cda5c5f1994@mail.gmail.com> On Tue, Feb 3, 2009 at 2:03 PM, Marc Tompkins wrote: > More results to chew on: > >>>> struct.calcsize('s') > 1 >>>> struct.calcsize('d') > 8 >>>> struct.calcsize('sd') > 16 >>>> struct.calcsize('ds') > 9 >>>> struct.calcsize('dss') > 10 >>>> struct.calcsize('dssssss') > 14 >>>> struct.calcsize('dsd') > 24 > > I believe it's a matter of alignment: Right. The struct module uses native alignment unless you tell it otherwise. Native alignment is the same as if you defined a C struct for the given items. In this case the double must start on an 8-byte boundary. If you don't want padding, use 'standard' alignment by specifying one of the modifier prefixes, e.g. '!s!d' Kent From kent37 at tds.net Tue Feb 3 21:08:11 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 3 Feb 2009 15:08:11 -0500 Subject: [Tutor] Parsing suggestion? (CUE file) In-Reply-To: References: Message-ID: <1c2a2c590902031208l5830bc62ja63a77acc5ec32af@mail.gmail.com> On Tue, Feb 3, 2009 at 2:55 PM, Terry Carroll wrote: > The silver cloud to my temporary Internet outage was that I was able to > solve my problem, in the process discovering that the csv module can parse > a CUE file[1] quite nicely if you set up an appropriate csv.Dialect class. > > "Comma Separated Values"; it's not just for commas any more. > > [1] http://en.wikipedia.org/wiki/Cue_file What is the dialect? That sounds like a useful trick. Kent From carroll at tjc.com Tue Feb 3 21:26:22 2009 From: carroll at tjc.com (Terry Carroll) Date: Tue, 3 Feb 2009 12:26:22 -0800 (PST) Subject: [Tutor] Parsing suggestion? (CUE file) In-Reply-To: <1c2a2c590902031208l5830bc62ja63a77acc5ec32af@mail.gmail.com> Message-ID: On Tue, 3 Feb 2009, Kent Johnson wrote: > On Tue, Feb 3, 2009 at 2:55 PM, Terry Carroll wrote: > > > The silver cloud to my temporary Internet outage was that I was able to > > solve my problem, in the process discovering that the csv module can parse > > a CUE file[1] quite nicely if you set up an appropriate csv.Dialect class. > > > > [1] http://en.wikipedia.org/wiki/Cue_file > > What is the dialect? That sounds like a useful trick. This seems to be working for me, at least with the sample CUE files I've tested with so far: ############################################################### import csv class cue(csv.Dialect): """Describe the usual properties of CUE files.""" delimiter = ' ' quotechar = '"' doublequote = True skipinitialspace = True lineterminator = '\r\n' quoting = csv.QUOTE_MINIMAL csv.register_dialect("cue", cue) f = open("test.cue", "r") reader = csv.reader(f,dialect="cue") for row in reader: print row ############################################################### The dialect is the same as the standard excel dialect, which I cribbed out of csv.py, except for delimiter and skipinitialspace. My project is to write a program to convert a CUE file into a list of labels that can be imported into Audacity; and perhaps a file of ID3 info that can be imported into MP3 tagging software. If I had to parse the blank-separated fields of quoted text that included blanks, I don't know how long this would have taken me. From etrade.griffiths at dsl.pipex.com Tue Feb 3 21:37:01 2009 From: etrade.griffiths at dsl.pipex.com (eShopping) Date: Tue, 03 Feb 2009 20:37:01 +0000 Subject: [Tutor] reading binary files In-Reply-To: <4988A097.5070503@gmail.com> References: <1233652836.49880c6411543@netmail.pipex.net> <4988A097.5070503@gmail.com> Message-ID: <72ladt$6evkv9@smtp.pipex.tiscali.co.uk> Bob At 19:52 03/02/2009, you wrote: >etrade.griffiths at dsl.pipex.com wrote: >>Data format: >> >>TIME 1 F 0.0 >>DISTANCE 10 F 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 >> >>F=float, D=double, L=logical, S=string etc >> >> >>The first part of the file should contain a string (eg "TIME"), >>an integer (1) and another string (eg "F") so I tried using >> >>import struct >>in_file = open(file_name+".dat","rb") >>data = in_file.read() >>items = struct.unpack('sds', data) >> >>Now I get the error >> >>error: unpack requires a string argument of length 17 >> >>which has left me completely baffled! >> > >Did you open the file with mode 'b'? If not change that. > >You are passing the entire file to unpack when you should be giving >it only the first "line". That's why is is complaining about the >length. We need to figure out the lengths of the lines. > >Consider the first "line" > >TIME 1 F 0.0 > >There were (I assume) 4 FORTRAN variables written here: character >integer character float. Without knowing the lengths of the >character variables we are at a loss as to what the struct format >should be. Do you know their lengths? Is the last float or double? > >Try this: print data[:40] You should see something like: > >TIME...\x01\x00\x00\x00...F...\x00\x00\x00\x00...DISTANCE...\n\x00\x00\x00 > >where ... means 0 or more intervening stuff. It might be that the >\x01 and the \n are in other places, as we also have to deal with >"byte order" issues. > >Please do this and report back your results. And also the FORTRAN >variable types if you have access to them. Apologies if this is getting a bit messy but the files are at a remote location and I forgot to bring copies home. I don't have access to the original FORTRAN program so I tried to emulate the reading the data using the Python script below. AFAIK the FORTRAN format line for the header is (1X, 1X, A8, 1X, 1X, I6, 1X, 1X, A1). If the data following is a float it is written using n(1X, F6.2) where n is the number of records picked up from the preceding header. # test program to read binary data import struct # create dummy data data = [] for i in range(0,10): data.append(float(i)) # write data to binary file b_file = open("test.bin","wb") b_file.write(" %8s %6d %1s\n" % ("DISTANCE", len(data), "F")) for x in data: b_file.write(" %6.2f" % x) b_file.close() # read back data from file c_file = open("test.bin","rb") data = c_file.read() start, stop = 0, struct.calcsize("2s8s2si2s1s") items = struct.unpack("2s8s2si2s1s",data[start:stop]) print items print data[:40] I'm pretty sure that when I tried this at the other PC there were a bunch of \x00\x00 characters in the file but they don't appear in NotePad ... anyway, I thought the Python above would unpack the data but items appears as (' ', 'DISTANCE', ' ', 538976288, '10', ' ') which seems to be contain an extra item (538976288) Alun Griffiths From bgailer at gmail.com Tue Feb 3 22:41:35 2009 From: bgailer at gmail.com (bob gailer) Date: Tue, 03 Feb 2009 16:41:35 -0500 Subject: [Tutor] reading binary files In-Reply-To: <72ladt$6evkv9@smtp.pipex.tiscali.co.uk> References: <1233652836.49880c6411543@netmail.pipex.net> <4988A097.5070503@gmail.com> <72ladt$6evkv9@smtp.pipex.tiscali.co.uk> Message-ID: <4988BA0F.8040502@gmail.com> First question: are you trying to work with the file written UNFORMATTED? If so read on. If you are working with a file formatted (1X, 1X, A8, 1X, 1X, I6, 1X, 1X, A1) then we have a completely different issue to deal with. Do not read on, instead let us know. eShopping wrote: >>> Data format: >>> >>> TIME 1 F 0.0 >>> DISTANCE 10 F 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 >>> >>> F=float, D=double, L=logical, S=string etc >>> >>> >>> The first part of the file should contain a string (eg "TIME"), >>> an integer (1) and another string (eg "F") so I tried using >>> >>> import struct >>> in_file = open(file_name+".dat","rb") >>> data = in_file.read() >>> items = struct.unpack('sds', data) >>> >>> Now I get the error >>> >>> error: unpack requires a string argument of length 17 >>> >>> which has left me completely baffled! >>> >> >> Did you open the file with mode 'b'? If not change that. >> >> You are passing the entire file to unpack when you should be giving >> it only the first "line". That's why is is complaining about the >> length. We need to figure out the lengths of the lines. >> >> Consider the first "line" >> >> TIME 1 F 0.0 >> >> There were (I assume) 4 FORTRAN variables written here: character >> integer character float. Without knowing the lengths of the character >> variables we are at a loss as to what the struct format should be. Do >> you know their lengths? Is the last float or double? >> >> Try this: print data[:40] You should see something like: >> >> TIME...\x01\x00\x00\x00...F...\x00\x00\x00\x00...DISTANCE...\n\x00\x00\x00 >> >> >> where ... means 0 or more intervening stuff. It might be that the >> \x01 and the \n are in other places, as we also have to deal with >> "byte order" issues. >> >> Please do this and report back your results. And also the FORTRAN >> variable types if you have access to them. > > Apologies if this is getting a bit messy but the files are at a remote > location and I forgot to bring copies home. I don't have access to > the original FORTRAN program so I tried to emulate the reading the > data using the Python script below. AFAIK the FORTRAN format line for > the header is (1X, 1X, A8, 1X, 1X, I6, 1X, 1X, A1). If the data > following is a float it is written using n(1X, F6.2) where n is the > number of records picked up from the preceding header. > > # test program to read binary data > > import struct > > # create dummy data > > data = [] > for i in range(0,10): > data.append(float(i)) > > # write data to binary file > > b_file = open("test.bin","wb") > > b_file.write(" %8s %6d %1s\n" % ("DISTANCE", len(data), "F")) > for x in data: > b_file.write(" %6.2f" % x) You are still confusing text vs binary. The above writes text regardless of the file mode. If the FORTRAN file was written UNFORMATTED then you are NOT emulating that with the above program. The character data is read back in just fine, since there is no translation involved in the writing nor in the reading. The integer len(data) is being written as its text (character) representation (translating binary to text) but being read back in without translation. Also all the floating point data is going out as text. The file looks like (where b = blank) (how it would look in notepad): bbDISTANCEbbbbbb10bFbbb0.00bbb1.00bbb2.00 If you analyze this with 2s8s2si2s1s you will see 2s matches bb, 8s matches DISTANCE, 2s matches bb, i matches bbbb. (\x40\x40\x40\x40). The i tells unpack to shove those 4 bytes unaltered into a Python integer, resulting in 538976288. You can verify that: >>> struct.unpack('i', ' ') (538976288,) Please either assure me you understand or are prepared for a more in depth tutorial. > b_file.close() > > # read back data from file > > c_file = open("test.bin","rb") > > data = c_file.read() > start, stop = 0, struct.calcsize("2s8s2si2s1s") > > items = struct.unpack("2s8s2si2s1s",data[start:stop]) > print items > print data[:40] > > I'm pretty sure that when I tried this at the other PC there were a > bunch of \x00\x00 characters in the file but they don't appear in > NotePad ... anyway, I thought the Python above would unpack the data > but items appears as > > (' ', 'DISTANCE', ' ', 538976288, '10', ' ') > > which seems to be contain an extra item (538976288) > > Alun Griffiths > -- Bob Gailer Chapel Hill NC 919-636-4239 From kent37 at tds.net Tue Feb 3 22:58:46 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 3 Feb 2009 16:58:46 -0500 Subject: [Tutor] Parsing suggestion? (CUE file) In-Reply-To: References: <1c2a2c590902031208l5830bc62ja63a77acc5ec32af@mail.gmail.com> Message-ID: <1c2a2c590902031358m35b399f2q6708efdff2e0c5ca@mail.gmail.com> On Tue, Feb 3, 2009 at 3:26 PM, Terry Carroll wrote: > On Tue, 3 Feb 2009, Kent Johnson wrote: > >> On Tue, Feb 3, 2009 at 2:55 PM, Terry Carroll wrote: >> >> > The silver cloud to my temporary Internet outage was that I was able to >> > solve my problem, in the process discovering that the csv module can parse >> > a CUE file[1] quite nicely if you set up an appropriate csv.Dialect class. >> > >> > [1] http://en.wikipedia.org/wiki/Cue_file >> >> What is the dialect? That sounds like a useful trick. > > This seems to be working for me, at least with the sample CUE files I've > tested with so far: > > ############################################################### > import csv > > class cue(csv.Dialect): > """Describe the usual properties of CUE files.""" > delimiter = ' ' > quotechar = '"' > doublequote = True > skipinitialspace = True > lineterminator = '\r\n' > quoting = csv.QUOTE_MINIMAL > csv.register_dialect("cue", cue) > > f = open("test.cue", "r") > reader = csv.reader(f,dialect="cue") > for row in reader: > print row > ############################################################### > > The dialect is the same as the standard excel dialect, which I cribbed out > of csv.py, except for delimiter and skipinitialspace. Ah, I see. I imagined something more ambitious, that treated the lines as fields. You are using csv to do kind of a smart split() function. > My project is to write a program to convert a CUE file into a list of > labels that can be imported into Audacity; and perhaps a file of ID3 info > that can be imported into MP3 tagging software. If I had to parse the > blank-separated fields of quoted text that included blanks, I don't know > how long this would have taken me. I would look at pyparsing for that, and make sure cuetools won't do what you want. Kent From carroll at tjc.com Tue Feb 3 23:17:51 2009 From: carroll at tjc.com (Terry Carroll) Date: Tue, 3 Feb 2009 14:17:51 -0800 (PST) Subject: [Tutor] Parsing suggestion? (CUE file) In-Reply-To: <1c2a2c590902031358m35b399f2q6708efdff2e0c5ca@mail.gmail.com> Message-ID: On Tue, 3 Feb 2009, Kent Johnson wrote: > Ah, I see. I imagined something more ambitious, that treated the lines > as fields. I find that the more ambitious my projects become, the less likely I am to complete them! With two toddlers, on a good day, I get 30 to 60 minutes of discretionary time, some of which I can do some coding! > You are using csv to do kind of a smart split() function. That's an excellent summary. > I would look at pyparsing for that, and make sure cuetools won't do > what you want. csv seems to be working well for me, and it's a standard piece of Python, which I prefer to use. I don't think I'm twisting it out of its intended useh: despite its name, it's really about splitting up uniform delimited input lines. The ability to use other delimeters and to trim the left-padding seems consistent with my use of it. The time it took between thinking of using CSV and getting it to actually work was probably a lot less time than I would have spend downloading and installing pyparsing, and figuring out how it worked. Thanks for the cuetools tip. I hadn't heard of it before. I spent some time looking for tools related to Audacity and CUE files, and couldn't find much (apart from one forum posting pointing out that Audacity didn't support CUE files, but it would be pretty easy to convert a CUE file to an Audacity label file). From kent37 at tds.net Tue Feb 3 23:36:41 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 3 Feb 2009 17:36:41 -0500 Subject: [Tutor] Parsing suggestion? (CUE file) In-Reply-To: References: <1c2a2c590902031358m35b399f2q6708efdff2e0c5ca@mail.gmail.com> Message-ID: <1c2a2c590902031436n255aa08fl52555ba55071afef@mail.gmail.com> On Tue, Feb 3, 2009 at 5:17 PM, Terry Carroll wrote: > On Tue, 3 Feb 2009, Kent Johnson wrote: > >> I would look at pyparsing for that, and make sure cuetools won't do >> what you want. > > csv seems to be working well for me, and it's a standard piece of Python, > which I prefer to use. I don't think I'm twisting it out of its intended > useh: despite its name, it's really about splitting up uniform delimited > input lines. The ability to use other delimeters and to trim the > left-padding seems consistent with my use of it. I think your use of the csv module is fine. What I really meant to say was more like, I would have looked to pyparsing to solve the same problem, and if you want a parser that parses the file into meaningful records, then it might still be worth a look. If we talk about it enough, maybe Paul McGuire will contribute the parser :-) Kent From pyprog05 at gmail.com Wed Feb 4 00:39:09 2009 From: pyprog05 at gmail.com (PyProg PyProg) Date: Wed, 4 Feb 2009 00:39:09 +0100 Subject: [Tutor] Can you help me with subprocess module ?. Message-ID: Hello everyone, I have a problem with the subprocess module. In fact I wish that when I run the command with subprocess I can retrieve the data immediately without waiting for the end of the command. I tried this way but ordering must end so that I can recover the data: import subprocess, os, sys # Commande FFmpeg com_1 = 'ffmpeg -i /home/user/path/in.avi -s 160x120 -ac 1 -ar 22050 -qmin 3 -qmax 3 -y /home/user/path/out.avi' p = [subprocess.Popen(com_1, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True).communicate()[0]] for toto in p: ---->if '\r' in toto: -------->tampon = str(toto).split(' ') --------># ..., 'time=151.6', ... -------->for vb in tampon: ------------>if 'time' in vb: ---------------->tempsEcoule = vb[5:] ---------------->print u'Temps ?coul?', tempsEcoule My version of Python: Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Can you help me?. Excuse me in advance for my bad English. a + -- http://ekd.tuxfamily.org From alan.gauld at btinternet.com Wed Feb 4 02:00:09 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Feb 2009 01:00:09 -0000 Subject: [Tutor] re weird bool References: <9e3fac840902030533o4afc83c1s97831153b07c89be@mail.gmail.com> Message-ID: "prasad rao" wrote >>>> 2==True > False > > It is an unexpected result to me. > I thought any value other than 0 is True. Any value of non zero is treated as True in a boolean context. But aq test of equality with a boolean value is not a boolean context. For equiality you have to compare like with like, and you do that by taking the boolean value of the number using bool() So: if 2: print 'True' else: print 'False' will print true but if 2 == True: print 'True' else: print 'False' will print False. The two tests are not identical. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Feb 4 02:02:58 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Feb 2009 01:02:58 -0000 Subject: [Tutor] struct question References: <49888C03.9060707@gmail.com> Message-ID: "bob gailer" wrote > >>> struct.calcsize('s') > 1 > >>> struct.calcsize('d') > 8 > >>> struct.calcsize('sd') > 16 > > Why? Should not that be 9? Numbers always start on word boundaries. >>> struct.calcsize('ds') 9 Alan G. From alan.gauld at btinternet.com Wed Feb 4 02:16:17 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Wed, 4 Feb 2009 01:16:17 +0000 (GMT) Subject: [Tutor] Sort of database & "family tree" question References: <497DC193.40301@gmail.com> <498885DB.8000701@gmail.com> Message-ID: <38224.28235.qm@web86708.mail.ird.yahoo.com> > > And I assume you are reading these into a Person class and > > storing these classes in a persons dictionary? > Can you explain this a little more for me please? Sure. (I didn't notice this on gmane so apologies if others already answered) > The current way of reading the data is this: > > parser = ConfigParser.ConfigParser() > parser.read(personFile) > > def get_info(person) > infoDic = {} > infoDic['first'] = parser.get(person, 'firstName') > infoDic['last'] = parser.get(person, 'lastName') > infoDic['father'] = parser.get(person, 'father') > infoDic['mother'] = parser.get(person, 'mother') > return infoDic TYhis is almost the same but you are using a dict. A sligtly more readable version is to define a class Person: class Person: def __init__(self, parser): self.first = parser.get(person, 'firstName') self.last = parser.get(person, 'lastName') self.father = parser.get(person, 'father') self.mother = parser.get(person, 'mother') Now you can create your person records with: parser = ConfigParser.ConfifgParser() parser.read(personFile) people = {} # some kind of loop here? # for record in parser... p = Person(parser) people[p.first,p.last] = p Now you will have a dictionary full of persons and you can access them by the first,last tuple of their name. BUT how is father/mother stored? Is it a first/last tuple or some ID number? If an ID you need to add that to your Person definition and use it as the people key. Does that help? Alan G. From Larry at Riedel.org Wed Feb 4 02:54:24 2009 From: Larry at Riedel.org (Larry Riedel) Date: Tue, 3 Feb 2009 17:54:24 -0800 Subject: [Tutor] Can you help me with subprocess module ?. In-Reply-To: References: Message-ID: <7c64c2920902031754o564c135x9997fa0b1604eff1@mail.gmail.com> > I have a problem with the subprocess module. In fact I wish > that when I run the command with subprocess I can retrieve the > data immediately without waiting for the end of the command. > > import subprocess, os, sys > # Commande FFmpeg > com_1 = 'ffmpeg -i /home/user/path/in.avi -s 160x120 -ac 1 > -ar 22050 -qmin 3 -qmax 3 -y /home/user/path/out.avi' > p = [subprocess.Popen(com_1, stderr=subprocess.STDOUT, > stdout=subprocess.PIPE, shell=True).communicate()[0]] The "communicate" method waits for the process to exit. Maybe look farther down the page for "Replacing os.popen" http://docs.python.org/library/subprocess.html Larry From etrade.griffiths at dsl.pipex.com Wed Feb 4 07:58:32 2009 From: etrade.griffiths at dsl.pipex.com (eShopping) Date: Wed, 04 Feb 2009 06:58:32 +0000 Subject: [Tutor] reading binary files In-Reply-To: <4988BA0F.8040502@gmail.com> References: <1233652836.49880c6411543@netmail.pipex.net> <4988A097.5070503@gmail.com> <72ladt$6evkv9@smtp.pipex.tiscali.co.uk> <4988BA0F.8040502@gmail.com> Message-ID: <7jhnpr$3qvetm@smtp.pipex.tiscali.co.uk> Bob I am trying to read UNFORMATTED files. The files also occur as formatted files and the format string I provided is the string used to write the formatted version. I can read the formatted version OK. I (naively) assumed that the same format string was used for both files, the only differences being whether the FORTRAN WRITE statement indicated unformatted or formatted. Best regards Alun Griffiths At 21:41 03/02/2009, bob gailer wrote: >First question: are you trying to work with the file written >UNFORMATTED? If so read on. > >If you are working with a file formatted (1X, 1X, A8, 1X, 1X, I6, >1X, 1X, A1) then we have a completely different issue to deal with. >Do not read on, instead let us know. > >eShopping wrote: > >>>>Data format: >>>> >>>>TIME 1 F 0.0 >>>>DISTANCE 10 F 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 >>>> >>>>F=float, D=double, L=logical, S=string etc >>>> >>>> >>>>The first part of the file should contain a string (eg "TIME"), >>>>an integer (1) and another string (eg "F") so I tried using >>>> >>>>import struct >>>>in_file = open(file_name+".dat","rb") >>>>data = in_file.read() >>>>items = struct.unpack('sds', data) >>>> >>>>Now I get the error >>>> >>>>error: unpack requires a string argument of length 17 >>>> >>>>which has left me completely baffled! >>> >>>Did you open the file with mode 'b'? If not change that. >>> >>>You are passing the entire file to unpack when you should be >>>giving it only the first "line". That's why is is complaining >>>about the length. We need to figure out the lengths of the lines. >>> >>>Consider the first "line" >>> >>>TIME 1 F 0.0 >>> >>>There were (I assume) 4 FORTRAN variables written here: character >>>integer character float. Without knowing the lengths of the >>>character variables we are at a loss as to what the struct format >>>should be. Do you know their lengths? Is the last float or double? >>> >>>Try this: print data[:40] You should see something like: >>> >>>TIME...\x01\x00\x00\x00...F...\x00\x00\x00\x00...DISTANCE...\n\x00\x00\x00 >>> >>>where ... means 0 or more intervening stuff. It might be that the >>>\x01 and the \n are in other places, as we also have to deal with >>>"byte order" issues. >>> >>>Please do this and report back your results. And also the FORTRAN >>>variable types if you have access to them. >> >>Apologies if this is getting a bit messy but the files are at a >>remote location and I forgot to bring copies home. I don't have >>access to the original FORTRAN program so I tried to emulate the >>reading the data using the Python script below. AFAIK the FORTRAN >>format line for the header is (1X, 1X, A8, 1X, 1X, I6, 1X, 1X, >>A1). If the data following is a float it is written using n(1X, >>F6.2) where n is the number of records picked up from the preceding header. >> >># test program to read binary data >> >>import struct >> >># create dummy data >> >>data = [] >>for i in range(0,10): >> data.append(float(i)) >> >># write data to binary file >> >>b_file = open("test.bin","wb") >> >>b_file.write(" %8s %6d %1s\n" % ("DISTANCE", len(data), "F")) >>for x in data: >> b_file.write(" %6.2f" % x) > >You are still confusing text vs binary. The above writes text >regardless of the file mode. If the FORTRAN file was written >UNFORMATTED then you are NOT emulating that with the above program. >The character data is read back in just fine, since there is no >translation involved in the writing nor in the reading. The integer >len(data) is being written as its text (character) representation >(translating binary to text) but being read back in without >translation. Also all the floating point data is going out as text. > >The file looks like (where b = blank) (how it would look in notepad): > >bbDISTANCEbbbbbb10bFbbb0.00bbb1.00bbb2.00 If you analyze this with 2s8s2si2s1s >you will see 2s matches bb, 8s matches DISTANCE, 2s matches bb, i >matches bbbb. (\x40\x40\x40\x40). The i tells unpack to shove those >4 bytes unaltered into a Python integer, resulting in 538976288. You >can verify that: > > >>> struct.unpack('i', ' ') >(538976288,) > >Please either assure me you understand or are prepared for a more in >depth tutorial. >>b_file.close() >> >># read back data from file >> >>c_file = open("test.bin","rb") >> >>data = c_file.read() >>start, stop = 0, struct.calcsize("2s8s2si2s1s") >> >>items = struct.unpack("2s8s2si2s1s",data[start:stop]) >>print items >>print data[:40] >> >>I'm pretty sure that when I tried this at the other PC there were a >>bunch of \x00\x00 characters in the file but they don't appear in >>NotePad ... anyway, I thought the Python above would unpack the >>data but items appears as >> >>(' ', 'DISTANCE', ' ', 538976288, '10', ' ') >> >>which seems to be contain an extra item (538976288) >> >>Alun Griffiths > > >-- >Bob Gailer >Chapel Hill NC >919-636-4239 From denis.spir at free.fr Wed Feb 4 09:08:27 2009 From: denis.spir at free.fr (spir) Date: Wed, 4 Feb 2009 09:08:27 +0100 Subject: [Tutor] Parsing suggestion? (CUE file) -- identify result In-Reply-To: <1c2a2c590902031436n255aa08fl52555ba55071afef@mail.gmail.com> References: <1c2a2c590902031358m35b399f2q6708efdff2e0c5ca@mail.gmail.com> <1c2a2c590902031436n255aa08fl52555ba55071afef@mail.gmail.com> Message-ID: <20090204090827.1a828325@o> Le Tue, 3 Feb 2009 17:36:41 -0500, Kent Johnson a ?crit : > I think your use of the csv module is fine. What I really meant to say > was more like, I would have looked to pyparsing to solve the same > problem, and if you want a parser that parses the file into meaningful > records, then it might still be worth a look. This would require heavy use of the setResultsName() method to attach "semantic tags" to the parse results; so that when you dig into them you know what each snippet is -- without the need of partial reparsing ;-) The point can be illustrated with the simple case of parsing arithmetic operations. Imagine each operand of a '+' can be a (litteral) number, a symbol (name), a grouped (parenthesized) sub-operation, an operation of higher priority. The result beeing of the form [op1, '+', op2] There is no other way to know what kind of thing op1 and op2 are, if they don't themselves carry the information, than re-examining them. Which has already beeing done while parsing. (The information needed is the name of the parsing rule used to yield the result.) Denis > > Kent ------ la vida e estranya From s4027340 at student.uq.edu.au Wed Feb 4 09:18:47 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Wed, 04 Feb 2009 18:18:47 +1000 Subject: [Tutor] VPython and Tkinter Message-ID: Is there a way to make separate VPython and Tkinter windows run simultaneously from the one program? Or to have the VPython window run inside a Tkinter toplevel? If I have a program that uses both, it seems that one window has to close before the other will start running. From denis.spir at free.fr Wed Feb 4 09:27:24 2009 From: denis.spir at free.fr (spir) Date: Wed, 4 Feb 2009 09:27:24 +0100 Subject: [Tutor] Sort of database & "family tree" question In-Reply-To: <38224.28235.qm@web86708.mail.ird.yahoo.com> References: <497DC193.40301@gmail.com> <498885DB.8000701@gmail.com> <38224.28235.qm@web86708.mail.ird.yahoo.com> Message-ID: <20090204092724.6105e831@o> Le Wed, 4 Feb 2009 01:16:17 +0000 (GMT), ALAN GAULD a ?crit : > > > And I assume you are reading these into a Person class and > > > storing these classes in a persons dictionary? > > > > Can you explain this a little more for me please? > > > Sure. > (I didn't notice this on gmane so apologies if others already answered) > > > The current way of reading the data is this: > > > > parser = ConfigParser.ConfigParser() > > parser.read(personFile) > > > > def get_info(person) > > infoDic = {} > > infoDic['first'] = parser.get(person, 'firstName') > > infoDic['last'] = parser.get(person, 'lastName') > > infoDic['father'] = parser.get(person, 'father') > > infoDic['mother'] = parser.get(person, 'mother') > > return infoDic > > TYhis is almost the same but you are using a dict. A sligtly more readable version is to define a class Person: > > class Person: > def __init__(self, parser): > self.first = parser.get(person, 'firstName') > self.last = parser.get(person, 'lastName') > self.father = parser.get(person, 'father') > self.mother = parser.get(person, 'mother') > Maybe I don't get the point, but I find it strange to make Person dependant not only of the data storage format, but also of the parsing technique. I would have written __init__ as usual so as to require the parser to deliver proper information -- not the contrary: class Person: def __init__(self, first, last, father, mother): self.first = first self.last = last self.father = father self.mother = mother If the format evoluates --> adapt the parser If the parser changes --> adapt it to Person's interface But the Person model has its own meaning. It should change only if the application's specification evoluates. Denis ------ la vida e estranya From alan.gauld at btinternet.com Wed Feb 4 09:47:59 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Feb 2009 08:47:59 -0000 Subject: [Tutor] Sort of database & "family tree" question References: <497DC193.40301@gmail.com> <498885DB.8000701@gmail.com><38224.28235.qm@web86708.mail.ird.yahoo.com> <20090204092724.6105e831@o> Message-ID: "spir" wrote >> > The current way of reading the data is this: >> > >> > def get_info(person) >> > infoDic = {} >> > infoDic['first'] = parser.get(person, 'firstName') >> > infoDic['last'] = parser.get(person, 'lastName') >> > infoDic['father'] = parser.get(person, 'father') >> > infoDic['mother'] = parser.get(person, 'mother') >> > return infoDic >> >> TYhis is almost the same but you are using a dict. >> A sligtly more readable version is to define a class Person: >> >> class Person: >> def __init__(self, parser): >> self.first = parser.get(person, 'firstName') > > Maybe I don't get the point, but I find it strange to make Person > dependant not only of the data storage format, but also of the > parsing technique. Yes, its not normal and the class probably should be called ParsedPerson or somesuch. I ws trying to mimic the current code style as much as possible, that was the reason for the decision. Normally I would agree with you and use: > class Person: > def __init__(self, first, last, father, mother): > self.first = first > self.last = last > self.father = father > self.mother = mother > Alan G. From timomlists at gmail.com Wed Feb 4 12:34:19 2009 From: timomlists at gmail.com (Timo) Date: Wed, 04 Feb 2009 12:34:19 +0100 Subject: [Tutor] Sort of database & "family tree" question In-Reply-To: References: <497DC193.40301@gmail.com> <498885DB.8000701@gmail.com><38224.28235.qm@web86708.mail.ird.yahoo.com> <20090204092724.6105e831@o> Message-ID: <49897D3B.2070500@gmail.com> Alan Gauld schreef: > "spir" wrote > >>> > The current way of reading the data is this: >>> > > def get_info(person) >>> > infoDic = {} >>> > infoDic['first'] = parser.get(person, 'firstName') >>> > infoDic['last'] = parser.get(person, 'lastName') >>> > infoDic['father'] = parser.get(person, 'father') >>> > infoDic['mother'] = parser.get(person, 'mother') >>> > return infoDic >>> >>> TYhis is almost the same but you are using a dict. A sligtly more >>> readable version is to define a class Person: >>> >>> class Person: >>> def __init__(self, parser): >>> self.first = parser.get(person, 'firstName') Hey Alan, thanks for that explanation! But the class you gave, does almost the same thing as my function. We both store the info in a dic, so to retrieve info for a certain person, we both have to do the same thing. Or am I missing something here? If so, I would love to hear it! Because I have to admit that when I program, I rarely use classes. > > Yes, its not normal and the class probably should be called > ParsedPerson or somesuch. I ws trying to mimic the current code style > as much as possible, that was the reason for the > decision. Normally I would agree with you and use: > >> class Person: >> def __init__(self, first, last, father, mother): >> self.first = first >> self.last = last >> self.father = father >> self.mother = mother >> If I do it like this, I will have to parse all the data from the file and then send them to this class and then call this class again to retrieve it. Then I like my function better. But again, I would love to hear if I'm wrong. Timo From denis.spir at free.fr Wed Feb 4 14:27:17 2009 From: denis.spir at free.fr (spir) Date: Wed, 4 Feb 2009 14:27:17 +0100 Subject: [Tutor] inheriting different builtin types Message-ID: <20090204142717.7f811746@o> Hello, I have a strange problem and cannot see a clear method to solve it. I would like to build a custom type that is able to add some informational attributes and a bunch attribute to a main "value". The outline is then: class Custom(X): def __init__(self, value, more): X.__init__(self) The base class is here to inherit value's behaviour and to avoid writing obj.value all the time. For this type will be heavily used by client code. The point is, this value may actually be of several builtin types. Logically, X is value.__class__. I imagine there are solutions using a factory, or __new__, or maybe metaclass (never done yet)? I cannot find a working method myself. Denis ------ la vida e estranya From prasadaraon50 at gmail.com Wed Feb 4 15:00:50 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Wed, 4 Feb 2009 19:30:50 +0530 Subject: [Tutor] re division problem Message-ID: <9e3fac840902040600p24ee52d7l95f469170d4a52b@mail.gmail.com> hi I modified my function ' vertical' by adding a few characters to eliminate the division problem. def vertical(columns): if columns>7: columns=7 import string v=string.printable v=v.replace('\n','') v=v.replace('\t','') if len(v)%columns !=0: v=v+ v[:columns-(len(v)%columns)] for x in range(len(v)/columns): for y in range(x,len(v),len(v)/columns): print v[y],'=','%3d'%ord(v[y]),' '*3, print Thank you Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldl08 at gmx.net Wed Feb 4 15:30:34 2009 From: ldl08 at gmx.net (David) Date: Wed, 04 Feb 2009 22:30:34 +0800 Subject: [Tutor] reading file, adding to each line, writing file Message-ID: <4989A68A.80802@gmx.net> Hello everybody, I have easily spent some four hours on this problem, and I am now asking for rescue. Here is what I am trying to do: I have a file ("step2", with some 30 or so lines. To each line I would like to add " -d" at the end. Finally, I want to save the file under another name ("pyout". So far I have managed to read the file, line by line, and save it under another name: # add " -d" to each line of a textfile infile = open("step2", 'r') # open file for appending outfile = open("pyout","a") # open file for appending line = infile.readline() # Invokes readline() method on file while line: outfile.write(line), # trailing ',' omits newline character line = infile.readline() infile.close() outfile.close() As I said, before writing to file "pyout" I would like to append the string " -d" to each line. But how, where? I can't append to strings (which the lines gained with infile.readline() seem be), and my trial and error approach has brought me nothing but a headache. Thanks for your help! David From a.t.hofkamp at tue.nl Wed Feb 4 15:43:47 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Wed, 04 Feb 2009 15:43:47 +0100 Subject: [Tutor] reading file, adding to each line, writing file In-Reply-To: <4989A68A.80802@gmx.net> References: <4989A68A.80802@gmx.net> Message-ID: <4989A9A3.7030209@tue.nl> David wrote: > line = infile.readline() # Invokes readline() method on file > while line: > outfile.write(line), # trailing ',' omits newline character > line = infile.readline() The 'while' loop can be replaced by a 'for' loop, like for line in infile: outfile.write(line) > > infile.close() > outfile.close() > > > > As I said, before writing to file "pyout" I would like to append the > string " -d" to each line. But how, where? I can't append to strings > (which the lines gained with infile.readline() seem be), and my trial > and error approach has brought me nothing but a headache. readline() literally reads a line, including the terminating \n at the end. (the end-of-file indication uses the empty string. By returning the terminating \n as well, an empty line becomes a "\n" string, so you can distinguish between both cases). The simplest solution would be to construct a new line from the old one directly below the 'while', for example line2 = line[:-1] + " -d\n" followed by writing line2 to disk. The question that arises however is, what should be done with a line like "bla bla \n" Do you want "bla bla -d\n" or do you want "bla bla -d\n" here? If the latter, you may want to use str.rstrip() that deletes all white-space from the end of the line, like line2 = line.rstrip() + " -d\n" Sincerely, Albert From Bruce_Sherwood at ncsu.edu Wed Feb 4 15:19:24 2009 From: Bruce_Sherwood at ncsu.edu (Bruce Sherwood) Date: Wed, 04 Feb 2009 09:19:24 -0500 Subject: [Tutor] [Visualpython-users] VPython and Tkinter In-Reply-To: References: Message-ID: <4989A3EC.9030403@ncsu.edu> In Visual 3, there is an example program (Tk-visual.py, if I remember correctly) which shows a Tk window controlling actions in a separate Visual window. In Visual 5, I believe that this program would still work on Windows and Linux, but because there seems to be no way to make this work in the Carbon-based Mac version, the application was removed from the set of examples, which are platform-independent. Bruce Sherwood Mr Gerard Kelly wrote: > Is there a way to make separate VPython and Tkinter windows run > simultaneously from the one program? Or to have the VPython window run > inside a Tkinter toplevel? > > If I have a program that uses both, it seems that one window has to > close before the other will start running. > > > From ldl08 at gmx.net Wed Feb 4 15:50:47 2009 From: ldl08 at gmx.net (David) Date: Wed, 04 Feb 2009 22:50:47 +0800 Subject: [Tutor] reading file, adding to each line, writing file In-Reply-To: <4989A9A3.7030209@tue.nl> References: <4989A68A.80802@gmx.net> <4989A9A3.7030209@tue.nl> Message-ID: <4989AB47.1030402@gmx.net> Hello Albert, thanks for your answer! A.T.Hofkamp wrote: > > The 'while' loop can be replaced by a 'for' loop, like > > for line in infile: > outfile.write(line) I first was thinking of/experimenting with a 'for' loop, but what I originally had in mind was to combine the 'for' loop with readline() -- which Python disallows. So I changed to a 'while' loop. > The simplest solution would be to construct a new line from the old > one directly below the 'while', for example > > line2 = line[:-1] + " -d\n" > > followed by writing line2 to disk. > > > The question that arises however is, what should be done with a line like > > "bla bla \n" > > Do you want > > "bla bla -d\n" > > or do you want > > "bla bla -d\n" > > here? I want "bla bla" -d\n ;-) Let me try your suggestions out! Cheers, David From andreengels at gmail.com Wed Feb 4 15:54:04 2009 From: andreengels at gmail.com (Andre Engels) Date: Wed, 4 Feb 2009 15:54:04 +0100 Subject: [Tutor] reading file, adding to each line, writing file In-Reply-To: <6faf39c90902040653h38be2989n92f4c1a557154c88@mail.gmail.com> References: <4989A68A.80802@gmx.net> <6faf39c90902040653h38be2989n92f4c1a557154c88@mail.gmail.com> Message-ID: <6faf39c90902040654u550bd3a3x432615687185076@mail.gmail.com> On Wed, Feb 4, 2009 at 3:30 PM, David wrote: > Hello everybody, > > I have easily spent some four hours on this problem, and I am now asking for > rescue. > > Here is what I am trying to do: I have a file ("step2", with some 30 or so > lines. To each line I would like to add " -d" at the end. Finally, I want to > save the file under another name ("pyout". > So far I have managed to read the file, line by line, and save it under > another name: > > > > # add " -d" to each line of a textfile > > infile = open("step2", 'r') # open file for appending > outfile = open("pyout","a") # open file for appending > > line = infile.readline() # Invokes readline() method on file > while line: > outfile.write(line), # trailing ',' omits newline character > line = infile.readline() > > infile.close() > outfile.close() > > > > As I said, before writing to file "pyout" I would like to append the string > " -d" to each line. But how, where? I can't append to strings (which the > lines gained with infile.readline() seem be), and my trial and error > approach has brought me nothing but a headache. You cannot append to strings, but you can add to them! So the first step would be: > # add " -d" to each line of a textfile infile = open("step2", 'r') # open file for reading outfile = open("pyout","a") # open file for appending line = infile.readline() # Invokes readline() method on file while line: outfile.write(line+" -d"), # trailing ',' omits newline character line = infile.readline() infile.close() outfile.close() However, that doesn't work fine, because the newline is at the end of the line, and thus the -d is coming at the beginning. To work that out, we use string.strip() which allows us to remove certain characters from the beginning and end of a string: # add " -d" to each line of a textfile infile = open("step2", 'r') # open file for reading outfile = open("pyout","a") # open file for appending line = infile.readline() # Invokes readline() method on file while line: outfile.write(line.strip("\n")+" -d\n") line = infile.readline() infile.close() outfile.close() By the way, a somewhat more elegant method (in my opinion at least) is to use readlines(), which gives a generator of the lines in a file, rather than readline(): # add " -d" to each line of a textfile infile = open("step2", 'r') # open file for appending outfile = open("pyout","a") # open file for appending for line in infile.readlines(): outfile.write(line.strip("\n")+" -k\n") infile.close() outfile.close() Yet another method would be a combination of read and replace: # add " -d" to each line of a textfile infile = open("step2", 'r') # open file for appending outfile = open("pyout","a") # open file for appending outfile.write(infile.read().replace("\n"," -d\n")) infile.close() outfile.close() However, this is sensitive to the presence or absence of a newline after the last line. -- Andr? Engels, andreengels at gmail.com From zebra05 at gmail.com Wed Feb 4 16:16:23 2009 From: zebra05 at gmail.com (OkaMthembo) Date: Wed, 4 Feb 2009 17:16:23 +0200 Subject: [Tutor] reading file, adding to each line, writing file In-Reply-To: <4989A68A.80802@gmx.net> References: <4989A68A.80802@gmx.net> Message-ID: The following is adapted from my humble text processing script that i use at work for a recurring task of mine. Any excuse not to use Java all day :) file_1 = open('step2', 'r+') lines = file_1.readlines() sentences = [] for line in lines: if line: sentences.insert(line + '-d') file_1.close() file_2 = open('pyout', 'w+') if len(sentences) > 0: for sentence in sentences: file_2.write(sentence) file_2.close() On Wed, Feb 4, 2009 at 4:30 PM, David wrote: > Hello everybody, > > I have easily spent some four hours on this problem, and I am now asking > for rescue. > > Here is what I am trying to do: I have a file ("step2", with some 30 or so > lines. To each line I would like to add " -d" at the end. Finally, I want to > save the file under another name ("pyout". > So far I have managed to read the file, line by line, and save it under > another name: > > > > # add " -d" to each line of a textfile > > infile = open("step2", 'r') # open file for appending > outfile = open("pyout","a") # open file for appending > > line = infile.readline() # Invokes readline() method on file > while line: > outfile.write(line), # trailing ',' omits newline character > line = infile.readline() > > infile.close() > outfile.close() > > > > As I said, before writing to file "pyout" I would like to append the string > " -d" to each line. But how, where? I can't append to strings (which the > lines gained with infile.readline() seem be), and my trial and error > approach has brought me nothing but a headache. > > Thanks for your help! > > David > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From zebra05 at gmail.com Wed Feb 4 16:18:13 2009 From: zebra05 at gmail.com (OkaMthembo) Date: Wed, 4 Feb 2009 17:18:13 +0200 Subject: [Tutor] reading file, adding to each line, writing file In-Reply-To: <4989A68A.80802@gmx.net> References: <4989A68A.80802@gmx.net> Message-ID: The following is adapted from my humble text processing script that i use at work for a recurring task of mine. Any excuse not to use Java all day :) There was an error with my other posts. Pardon the triple posting - won't happen again soon. file_1 = open('step2', 'r+') lines = file_1.readlines() sentences = [] for line in lines: if line: sentences.insert(len(sentences), line + '-d') file_1.close() file_2 = open('pyout', 'w+') if len(sentences) > 0: for sentence in sentences: file_2.write(sentence) file_2.close() On Wed, Feb 4, 2009 at 4:30 PM, David wrote: > Hello everybody, > > I have easily spent some four hours on this problem, and I am now asking > for rescue. > > Here is what I am trying to do: I have a file ("step2", with some 30 or so > lines. To each line I would like to add " -d" at the end. Finally, I want to > save the file under another name ("pyout". > So far I have managed to read the file, line by line, and save it under > another name: > > > > # add " -d" to each line of a textfile > > infile = open("step2", 'r') # open file for appending > outfile = open("pyout","a") # open file for appending > > line = infile.readline() # Invokes readline() method on file > while line: > outfile.write(line), # trailing ',' omits newline character > line = infile.readline() > > infile.close() > outfile.close() > > > > As I said, before writing to file "pyout" I would like to append the string > " -d" to each line. But how, where? I can't append to strings (which the > lines gained with infile.readline() seem be), and my trial and error > approach has brought me nothing but a headache. > > Thanks for your help! > > David > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Feb 4 16:42:49 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 4 Feb 2009 10:42:49 -0500 Subject: [Tutor] reading file, adding to each line, writing file In-Reply-To: References: <4989A68A.80802@gmx.net> Message-ID: <1c2a2c590902040742hec2d6b3j7f4d078c2eb1204c@mail.gmail.com> On Wed, Feb 4, 2009 at 10:18 AM, OkaMthembo wrote: > The following is adapted from my humble text processing script that i use at > work for a recurring task of mine. Any excuse not to use Java all day :) > > There was an error with my other posts. Pardon the triple posting - won't > happen again soon. > > > > file_1 = open('step2', 'r+') > lines = file_1.readlines() > sentences = [] > for line in lines: > if line: I don't think line will ever be empty, so this test is not needed. > sentences.insert(len(sentences), line + '-d') sentences.append(line + '-d') is simpler. Note this appends after the newline so it is not really what the OP wants. > file_1.close() > file_2 = open('pyout', 'w+') > if len(sentences) > 0: This test is not needed, if sentences is empty the for statement won't do anything. > for sentence in sentences: > file_2.write(sentence) The loop could be replaced with file_2.writelines(sentences) Kent From ldl08 at gmx.net Wed Feb 4 17:11:41 2009 From: ldl08 at gmx.net (David) Date: Thu, 05 Feb 2009 00:11:41 +0800 Subject: [Tutor] reading file, adding to each line, writing file In-Reply-To: <4989A9A3.7030209@tue.nl> References: <4989A68A.80802@gmx.net> <4989A9A3.7030209@tue.nl> Message-ID: <4989BE3D.3080204@gmx.net> Hello Arthur, not there yet.... A.T.Hofkamp wrote: > > The simplest solution would be to construct a new line from the old > one directly below the 'while', for example > > line2 = line[:-1] + " -d\n" > > followed by writing line2 to disk. Actually, I don't quite understand. You want me to put line2 = line[:-1] + " -d\n" right beneath the 'while', that is, without indenting it?? Never seen that before... Here is my latest try, which works: # add " -d" to each line of a textfile infile = open("step3", 'r') # open file for appending -- returns a file object outfile = open("pyout","a") # open file for appending -- returns a file object line = infile.readline() # Invokes readline() method on file for i in line: line2 = line[:-1] + " -d\n" outfile.write(line2), # trailing ',' omits newline character line = infile.readline() infile.close() outfile.close() print "done!" But I clearly still don't understand my own code. In particular I don't understand why I have to use infile.readline() twice, once before the for loop, and once inside it. Finally: changing the line "for i in line:" for "while line:" will freeze the machine, filling my hard disk. Any ideas? David From zebra05 at gmail.com Wed Feb 4 17:13:07 2009 From: zebra05 at gmail.com (OkaMthembo) Date: Wed, 4 Feb 2009 18:13:07 +0200 Subject: [Tutor] reading file, adding to each line, writing file In-Reply-To: <1c2a2c590902040742hec2d6b3j7f4d078c2eb1204c@mail.gmail.com> References: <4989A68A.80802@gmx.net> <1c2a2c590902040742hec2d6b3j7f4d078c2eb1204c@mail.gmail.com> Message-ID: Hmm...thanks Kent. Could use such information myself. I did feel that my code was bloated or could be tweaked somehow. Ha...there i double posted again :( Am having trouble paying attention today. On Wed, Feb 4, 2009 at 5:42 PM, Kent Johnson wrote: > On Wed, Feb 4, 2009 at 10:18 AM, OkaMthembo wrote: > > The following is adapted from my humble text processing script that i use > at > > work for a recurring task of mine. Any excuse not to use Java all day :) > > > > There was an error with my other posts. Pardon the triple posting - won't > > happen again soon. > > > > > > > > file_1 = open('step2', 'r+') > > lines = file_1.readlines() > > sentences = [] > > for line in lines: > > if line: > > I don't think line will ever be empty, so this test is not needed. > > > sentences.insert(len(sentences), line + '-d') > > sentences.append(line + '-d') is simpler. Note this appends after the > newline so it is not really what the OP wants. > > > file_1.close() > > file_2 = open('pyout', 'w+') > > if len(sentences) > 0: > > This test is not needed, if sentences is empty the for statement won't > do anything. > > > for sentence in sentences: > > file_2.write(sentence) > > The loop could be replaced with > file_2.writelines(sentences) > > Kent > -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Wed Feb 4 19:15:35 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 04 Feb 2009 13:15:35 -0500 Subject: [Tutor] reading binary files In-Reply-To: <7jhnpr$3qvetm@smtp.pipex.tiscali.co.uk> References: <1233652836.49880c6411543@netmail.pipex.net> <4988A097.5070503@gmail.com> <72ladt$6evkv9@smtp.pipex.tiscali.co.uk> <4988BA0F.8040502@gmail.com> <7jhnpr$3qvetm@smtp.pipex.tiscali.co.uk> Message-ID: <4989DB47.9060705@gmail.com> eShopping wrote: > Bob > > I am trying to read UNFORMATTED files. The files also occur as > formatted files and the format string I provided is the string used to > write the formatted version. I can read the formatted version OK. I > (naively) assumed that the same format string was used for both files, > the only differences being whether the FORTRAN WRITE statement > indicated unformatted or formatted. WRITE UNFORMATTED dump memory to disk with no formatting. That is why we must do some analysis of the file to see where the data has been placed, how long the floats are, and what "endian" is being used. I'd like to examine the file myself. We might save a lot of time and energy that way. If it is not very large would you attach it to your reply. If it is very large you could either copy just the first 1000 or so bytes, or send the whole thing thru www.yousendit.com. > > At 21:41 03/02/2009, bob gailer wrote: >> First question: are you trying to work with the file written >> UNFORMATTED? If so read on. Well, did you read on? What reactions do you have? >> eShopping wrote: >> >>>>> Data format: >>>>> >>>>> TIME 1 F 0.0 >>>>> DISTANCE 10 F 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 >>>>> >>>>> F=float, D=double, L=logical, S=string etc >>>>> >>>>> >>>>> The first part of the file should contain a string (eg "TIME"), >>>>> an integer (1) and another string (eg "F") so I tried using >>>>> >>>>> import struct >>>>> in_file = open(file_name+".dat","rb") >>>>> data = in_file.read() >>>>> items = struct.unpack('sds', data) >>>>> >>>>> Now I get the error >>>>> >>>>> error: unpack requires a string argument of length 17 >>>>> >>>>> which has left me completely baffled! >>>> >>>> Did you open the file with mode 'b'? If not change that. >>>> >>>> You are passing the entire file to unpack when you should be giving >>>> it only the first "line". That's why is is complaining about the >>>> length. We need to figure out the lengths of the lines. >>>> >>>> Consider the first "line" >>>> >>>> TIME 1 F 0.0 >>>> >>>> There were (I assume) 4 FORTRAN variables written here: character >>>> integer character float. Without knowing the lengths of the >>>> character variables we are at a loss as to what the struct format >>>> should be. Do you know their lengths? Is the last float or double? >>>> >>>> Try this: print data[:40] You should see something like: >>>> >>>> TIME...\x01\x00\x00\x00...F...\x00\x00\x00\x00...DISTANCE...\n\x00\x00\x00 >>>> >>>> >>>> where ... means 0 or more intervening stuff. It might be that the >>>> \x01 and the \n are in other places, as we also have to deal with >>>> "byte order" issues. >>>> >>>> Please do this and report back your results. And also the FORTRAN >>>> variable types if you have access to them. >>> >>> Apologies if this is getting a bit messy but the files are at a >>> remote location and I forgot to bring copies home. I don't have >>> access to the original FORTRAN program so I tried to emulate the >>> reading the data using the Python script below. AFAIK the FORTRAN >>> format line for the header is (1X, 1X, A8, 1X, 1X, I6, 1X, 1X, >>> A1). If the data following is a float it is written using n(1X, >>> F6.2) where n is the number of records picked up from the preceding >>> header. >>> >>> # test program to read binary data >>> >>> import struct >>> >>> # create dummy data >>> >>> data = [] >>> for i in range(0,10): >>> data.append(float(i)) >>> >>> # write data to binary file >>> >>> b_file = open("test.bin","wb") >>> >>> b_file.write(" %8s %6d %1s\n" % ("DISTANCE", len(data), "F")) >>> for x in data: >>> b_file.write(" %6.2f" % x) >> >> You are still confusing text vs binary. The above writes text >> regardless of the file mode. If the FORTRAN file was written >> UNFORMATTED then you are NOT emulating that with the above program. >> The character data is read back in just fine, since there is no >> translation involved in the writing nor in the reading. The integer >> len(data) is being written as its text (character) representation >> (translating binary to text) but being read back in without >> translation. Also all the floating point data is going out as text. >> >> The file looks like (where b = blank) (how it would look in notepad): >> >> bbDISTANCEbbbbbb10bFbbb0.00bbb1.00bbb2.00 If you analyze this with >> 2s8s2si2s1s >> you will see 2s matches bb, 8s matches DISTANCE, 2s matches bb, i >> matches bbbb. (\x40\x40\x40\x40). The i tells unpack to shove those 4 >> bytes unaltered into a Python integer, resulting in 538976288. You >> can verify that: >> >> >>> struct.unpack('i', ' ') >> (538976288,) >> >> Please either assure me you understand or are prepared for a more in >> depth tutorial. >>> b_file.close() >>> >>> # read back data from file >>> >>> c_file = open("test.bin","rb") >>> >>> data = c_file.read() >>> start, stop = 0, struct.calcsize("2s8s2si2s1s") >>> >>> items = struct.unpack("2s8s2si2s1s",data[start:stop]) >>> print items >>> print data[:40] >>> >>> I'm pretty sure that when I tried this at the other PC there were a >>> bunch of \x00\x00 characters in the file but they don't appear in >>> NotePad ... anyway, I thought the Python above would unpack the >>> data but items appears as >>> >>> (' ', 'DISTANCE', ' ', 538976288, '10', ' ') >>> >>> which seems to be contain an extra item (538976288) >>> >>> Alun Griffiths >> >> >> -- >> Bob Gailer >> Chapel Hill NC >> 919-636-4239 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer Chapel Hill NC 919-636-4239 From dineshbvadhia at hotmail.com Wed Feb 4 19:57:48 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Wed, 4 Feb 2009 10:57:48 -0800 Subject: [Tutor] Eliminating options Message-ID: Hi! I'm using 32-bit Python on Windows 64-bit Vista (instead of 64-bit Python because I also use Numpy/Scipy which doesn't offer 64-bit versions yet). I'm doing some very simple text processing ie. given a string s, find a subtring using s.find(). But, the program doesn't find all instances of the substring specified in s.find(). I ran the program on a Windows 32-bit XP and the program works perfectly. Intuition says this should work on the 64-bit box but since it doesn't is it possible there is something bizarre going on with 32-bit Python running on a 64-bit OS? Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From etrade.griffiths at dsl.pipex.com Wed Feb 4 21:04:09 2009 From: etrade.griffiths at dsl.pipex.com (eShopping) Date: Wed, 04 Feb 2009 20:04:09 +0000 Subject: [Tutor] reading binary files In-Reply-To: <4989DB47.9060705@gmail.com> References: <1233652836.49880c6411543@netmail.pipex.net> <4988A097.5070503@gmail.com> <72ladt$6evkv9@smtp.pipex.tiscali.co.uk> <4988BA0F.8040502@gmail.com> <7jhnpr$3qvetm@smtp.pipex.tiscali.co.uk> <4989DB47.9060705@gmail.com> Message-ID: <7jhs5f$6f9joe@smtp.pipex.tiscali.co.uk> Bob sorry, I misread your email and thought it said "read on" if the file was FORMATTED. It wasn't so I didn't (but should have). I read the complete thread and it is getting a little messy so I have extracted your questions and added some answers. >I'd like to examine the file myself. We might save a lot of time and >energy that way. If it is not very large would you attach it to your >reply. If it is very large you could either copy just the first 1000 >or so bytes, or send the whole thing thru www.yousendit.com. The file is around 800 Mb but I can't get hold of it until next week so suggest starting a new topic once I have a cut-down copy. >Well, did you read on? What reactions do you have? I did (finally) read on and I am still a little confused, though less than before. I guess the word UNFORMATTED means that the file has no format .... though it presumably has some structure? One major hurdle is that I am not really sure about the difference between a Python binary file and a FORTRAN UNFORMATTED file so any pointers would be gratefully received >The file looks like (where b = blank) (how it would look in notepad): >bbDISTANCEbbbbbb10bFbbb0.00bbb1.00bbb2.00 If you analyze this with 2s8s2si2s1s >you will see 2s matches bb, 8s matches DISTANCE, 2s matches bb, i >matches bbbb. (\x40\x40\x40\x40). The i tells unpack to shove those >4 bytes unaltered into a Python integer, resulting in 538976288. You >can verify that: > > >>> struct.unpack('i', ' ') >(538976288,) > >Please either assure me you understand or are prepared for a more in >depth tutorial. I now understand why Python gave me the results it did ... it looks like reading the FORTRAN file will be a non-trivial task so probably best to wait until I can post a copy of it. Thanks for your help Alun Griffiths From alan.gauld at btinternet.com Wed Feb 4 22:36:20 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Feb 2009 21:36:20 -0000 Subject: [Tutor] reading binary files References: <1233652836.49880c6411543@netmail.pipex.net><4988A097.5070503@gmail.com><72ladt$6evkv9@smtp.pipex.tiscali.co.uk><4988BA0F.8040502@gmail.com><7jhnpr$3qvetm@smtp.pipex.tiscali.co.uk><4989DB47.9060705@gmail.com> <7jhs5f$6f9joe@smtp.pipex.tiscali.co.uk> Message-ID: "eShopping" wrote > I now understand why Python gave me the results it did ... it looks > like reading the FORTRAN file will be a non-trivial task so probably > best to wait until I can post a copy of it. You don't say which OS you are on but you can read the binary file into a hex editor and see the structure. If you are on *nix you can use od -x and if on Windows run debug and use the d command to display the file as hex Using that you should be able to determine whether fields are fixed length or delimited by a particular character or tagged with a length prefix etc. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Wed Feb 4 22:51:27 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Feb 2009 21:51:27 -0000 Subject: [Tutor] reading file, adding to each line, writing file References: <4989A68A.80802@gmx.net> <4989A9A3.7030209@tue.nl> <4989BE3D.3080204@gmx.net> Message-ID: "David" wrote > Here is my latest try, which works: > > # add " -d" to each line of a textfile > > infile = open("step3", 'r') > outfile = open("pyout","a") > > line = infile.readline() # Invokes readline() method on file line is now a string representing a line in the file. > for i in line: You are now iterating over every character in line > line2 = line[:-1] + " -d\n" So you repeat this assignment for every character. No harm done its the same every time. Just very inefficient! > outfile.write(line2), # trailing ',' omits newline character But you are writing the same line for every character - did you find lots of duplicate lines in the output? > line = infile.readline() And now you reset line to the next line so invalidating some of what I njust said. I doubt this actually works properly although it may appear to! The use of the for loop is much simpler, avoiding all the readline confusion: infile = open("step3", 'r') outfile = open("pyout","a") for line in infile: # no need for readline outfile.write(line.rstrip() + " -d\n") infile.close() outfile.close() print "done!" That's all you need! for loops reading direct from the file are ideally suited to this kind of program and indeed any situation where you are handling a fixed size input. while loops are better for when you don't know where the end will be or even if there will be an end! HTH, Alan G. From bgailer at gmail.com Wed Feb 4 23:01:31 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 04 Feb 2009 17:01:31 -0500 Subject: [Tutor] reading binary files In-Reply-To: <7jhs5f$6f9joe@smtp.pipex.tiscali.co.uk> References: <1233652836.49880c6411543@netmail.pipex.net> <4988A097.5070503@gmail.com> <72ladt$6evkv9@smtp.pipex.tiscali.co.uk> <4988BA0F.8040502@gmail.com> <7jhnpr$3qvetm@smtp.pipex.tiscali.co.uk> <4989DB47.9060705@gmail.com> <7jhs5f$6f9joe@smtp.pipex.tiscali.co.uk> Message-ID: <498A103B.4020007@gmail.com> eShopping wrote: > > The file is around 800 Mb but I can't get hold of it until next week > so suggest starting a new topic once I have a cut-down copy. OK will wait with bated breath. > >> Well, did you read on? What reactions do you have? > > I did (finally) read on and I am still a little confused, though less > than before. I guess the word UNFORMATTED means that the file has no > format Depends on what you mean by format. When you use % formatting in Python it is the same thing as a FORMATTED WRITE in FORTRAN - a set of directives that direct the translation of data to human readable text. Files per se are a sequence of bytes. As such they have no "format". When we examine a file we attempt to make sense of the bytes. Some of the bytes may represent ASCII printable characters - other not.The body of this email is a sequence of ASCII printable characters that make sense to you when you read them. The file written UNFORMATTED has some ASCII printable characters that you can read (e.g. DISTANCE), some that you can recognize as letters, numbers, etc but are not English words, and non-printable characters that show up as "garbage" symbols or not at all. Those that are not "readable" are the internal representation of numbers. > .... though it presumably has some structure? One major hurdle is > that I am not really sure about the difference between a Python binary > file and a FORTRAN UNFORMATTED file so any pointers would be > gratefully received There is no such thing as a "Python binary file". When you open a file with mode 'b' you are asking the file system to ignore line-ends. If you do not specify 'b' then the file system "translates" line-ends into \n when reading and translates \n back to line-ends. The reason for this is that different OS file systems use different codes for line-ends. By translating them to and from \n the Python program becomes OS independent. Windows uses ctrl-M ctrl-J (carriage return - line feed; \x0d\x0a). Linux/Unix uses ctrl-J (line feed; \x0a). Mac uses ctrl-M (carriage return; \x0d). Python uniformly translates these to \n (x0a) When processing files written without line-ends (e.g. UNFORMATTED) there may be line-end characters or sequences that must NOT be treated as line-ends. Hence mode 'b' Example: >>> x=open('x','w') # write "normal" allowing \n to be translated to the OS line end. >>> x.write("Hello\n") >>> x=open('x','rb') # read binary, avoiding translation. >>> x.read() 'Hello\r\n' where \r = \x0d -- Bob Gailer Chapel Hill NC 919-636-4239 From alan.gauld at btinternet.com Wed Feb 4 23:33:45 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 4 Feb 2009 22:33:45 -0000 Subject: [Tutor] Sort of database & "family tree" question References: <497DC193.40301@gmail.com> <498885DB.8000701@gmail.com><38224.28235.qm@web86708.mail.ird.yahoo.com> <20090204092724.6105e831@o> <49897D3B.2070500@gmail.com> Message-ID: "Timo" wrote >>>> class Person: >>>> def __init__(self, parser): >>>> self.first = parser.get(person, 'firstName') > > Hey Alan, thanks for that explanation! > > But the class you gave, does almost the same thing as my function. That was my point. Its just a prettier way of handling it and slightly easier to use sionce you don;t need to quote the field names, just use the dot notation. > both store the info in a dic, so to retrieve info for a certain > person, we both have to do the same thing. Or am I missing something > here? The class is less typing. Youcreate a dictionary of dictionaries, I create a dictionary of objects - which are easier to access. However the class can also have methods added to do searches, follow the tree etc. You could also add the people dictionary as a class variable which would add to the conceptual consistency of the solution.. But you are right, classes are pretty much fancy dictionaries and you could write the "methods" as standalone functions operating on the dictionaries. Either way the biggest issue I see is the lack of a unique key for your dictionary. Using names as a key is a bad idea especially in familiies where the same names tend to get used over and over. You really should consider adding a unique ID field and use that to populate the father/mother fields. >> decision. Normally I would agree with you and use: >> >>> class Person: >>> def __init__(self, first, last, father, mother): >>> self.first = first >>> self.last = last >>> self.father = father >>> self.mother = mother I would definitely use this one and then you can instantiate it with: p = Person(parser.get(person,'ID', parser.get(person,'firstname', parser.get(person,'lastname', parser.get(person,'father', parser.get(person,'mother',) people[p.ID] = p print people[id].first > If I do it like this, I will have to parse all the data from the > file and then send them to this class and then call this class again > to retrieve it. You can store it in the class as you parse the file just as you did with your dictionary. You don't call the class again you use the people dictionary: A big bit of the advantage of OOP is not that it allows you to do stuff you couldn't do without it (although occasionaly this is true) but rather that it makes the code look cleaner, more readable. > Then I like my function better. But again, I would love to hear if > I'm wrong. Its not a metter of "wrong" its a matter of style. Using classes usually produces more readable code, with less typing. You can also add methods to prettty print a person (by implementing the __str__ method), search the people dictionary for a person (by implementing comparison methods) You then wind up writing code that looks like this: # imagine you have a person object p1... for p in people: if p1.ID == p.father: print "The father is', p Using dictionaries you get someting like: for p in people: if p1['ID'] == p['father']: print "The father is", p['first'], p['last'] Or if you write a print function: for p in people: if p1['ID'] == p['father']: print "The father is", printPerson(p) I think the first version is easier to read. But it is admittedly doing the same thing. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From s4027340 at student.uq.edu.au Thu Feb 5 02:21:43 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Thu, 05 Feb 2009 11:21:43 +1000 Subject: [Tutor] tkinter and visual with objects Message-ID: I'm trying to make this very simple program, where the idea is that you click a tkinter button named "Ball" and then a ball will appear in the visual window. Problem is that the window itself doesn't pop up until the button is pressed and the ball is created. I would like it to start out blank, and then have the ball appear in it when the button is pressed. I thought that having "self.display=display()" in the __init__ of the Application would do this, but it doesn't seem to. What do I need to add to this code to make it start out with a blank window? from visual import * from Tkinter import * import sys class Ball: def __init__(self): sphere(pos=(0,0,0)) class Application: def __init__(self, root): self.frame = Frame(root) self.frame.pack() self.display=display() self.button=Button(self.frame, text="Ball", command=self.ball) self.button.pack() def ball(self): self.ball=Ball() root=Tk() app=Application(root) root.mainloop() From icebergwtf at gmail.com Thu Feb 5 05:16:41 2009 From: icebergwtf at gmail.com (tiefeng wu) Date: Thu, 5 Feb 2009 12:16:41 +0800 Subject: [Tutor] reading file, adding to each line, writing file Message-ID: <4314c1f70902042016p3923d529uced8f441a601a7aa@mail.gmail.com> > Hello everybody, > > I have easily spent some four hours on this problem, and I am now asking > for rescue. > > Here is what I am trying to do: I have a file ("step2", with some 30 or > so lines. To each line I would like to add " -d" at the end. Finally, I > want to save the file under another name ("pyout". > So far I have managed to read the file, line by line, and save it under > another name: > > > > # add " -d" to each line of a textfile > > infile = open("step2", 'r') # open file for appending > outfile = open("pyout","a") # open file for appending > > line = infile.readline() # Invokes readline() method on file > while line: > outfile.write(line), # trailing ',' omits newline character > line = infile.readline() > > infile.close() > outfile.close() > > > > As I said, before writing to file "pyout" I would like to append the > string " -d" to each line. But how, where? I can't append to strings > (which the lines gained with infile.readline() seem be), and my trial > and error approach has brought me nothing but a headache. > > Thanks for your help! > > David > Hi David! My solution of your problem would be the following: >>> infile = open('step2', 'r') >>> str = infile.read() >>> infile.close() >>> outfile = open('pyout', 'a') >>> outfile.write(str.replace('\n', ' -d\n')) >>> outfile.close() hope helped cheers! Tiefeng Wu -------------- next part -------------- An HTML attachment was scrubbed... URL: From amit.pureenergy at gmail.com Thu Feb 5 09:07:16 2009 From: amit.pureenergy at gmail.com (amit sethi) Date: Thu, 5 Feb 2009 13:37:16 +0530 Subject: [Tutor] passing unknown no of arguments Message-ID: How do you pass arguments of unknown no. of arguments to a function. Also how can i run my python scripts in a web browser. -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From w.richert at gmx.net Thu Feb 5 09:24:50 2009 From: w.richert at gmx.net (Willi Richert) Date: Thu, 5 Feb 2009 09:24:50 +0100 Subject: [Tutor] inheriting different builtin types In-Reply-To: <20090204142717.7f811746@o> References: <20090204142717.7f811746@o> Message-ID: <200902050924.50528.w.richert@gmx.net> Hi, http://objectmix.com/python/710201-dynamically-changing-base-class.html may be of interest. wr On Mittwoch, 4. Februar 2009 14:27:17 spir wrote: > Hello, > > I have a strange problem and cannot see a clear method to solve it. > I would like to build a custom type that is able to add some informational > attributes and a bunch attribute to a main "value". The outline is then: > > class Custom(X): > def __init__(self, value, more): > X.__init__(self) > > > > The base class is here to inherit value's behaviour and to avoid writing > obj.value all the time. For this type will be heavily used by client code. > The point is, this value may actually be of several builtin types. > Logically, X is value.__class__. I imagine there are solutions using a > factory, or __new__, or maybe metaclass (never done yet)? I cannot find a > working method myself. > > Denis > > ------ > la vida e estranya > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From orsenthil at gmail.com Thu Feb 5 09:57:01 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Thu, 5 Feb 2009 14:27:01 +0530 Subject: [Tutor] passing unknown no of arguments In-Reply-To: References: Message-ID: <7c42eba10902050057o1f105c2dqd4de8f50bb3759fb@mail.gmail.com> On Thu, Feb 5, 2009 at 1:37 PM, amit sethi wrote: > How do you pass arguments of unknown no. of arguments to a function. You use * operator ( indirection) in the function definition for arguments and you pass the variable number of number arguments as a list. For e.g. >>> def foo(*args): ... print args ... >>> foo(1,2,3,4,5,6) (1, 2, 3, 4, 5, 6) >>> foo(1,2,3) (1, 2, 3) >>> > Also how can i run my python scripts in a web browser. What you are asking for is Python CGI programming. Look out for chapters for Alan's book. I think he has covered from the basics. Or just start here: pytute.blogspot.com/2007/05/python-cgi-howto.html You will write a simple script like #!/usr/bin/env python print "Content-Type: text/html\n" print "Hello, World" Give permissions chmod +rw to the script and put it in your web-server's cgi-bin/ directory and invoke the python file. The result will be displayed in the browser. -- Senthil http://uthcode.sarovar.org From alan.gauld at btinternet.com Thu Feb 5 09:57:15 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Feb 2009 08:57:15 -0000 Subject: [Tutor] passing unknown no of arguments References: Message-ID: "amit sethi" wrote > How do you pass arguments of unknown no. of arguments to a function. search the docs for *args and *kwargs > Also how can i run my python scripts in a web browser. In general you can't. You would need to have a Python interpreter in your browser. The only reliable way to run code in a browser is to use JavaScript. That having been said there are some options. The pythonwin extensions include a script to enable Python as an ActiveScripting language and in that case you can run Python inside IE on a PC with WSH enabled. Also there are some tools around that will embed an interpreter into a web page. But in my experience they are not suitable for running any significant amount of code they are really intended for tutorial type applications. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From orsenthil at gmail.com Thu Feb 5 10:33:13 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Thu, 5 Feb 2009 15:03:13 +0530 Subject: [Tutor] passing unknown no of arguments In-Reply-To: References: Message-ID: <7c42eba10902050133s691c76c2k7105cff00ff70a3c@mail.gmail.com> On Thu, Feb 5, 2009 at 2:27 PM, Alan Gauld wrote: > In general you can't. You would need to have a Python interpreter > in your browser. Alan, I think he was referring to CGI programming. Given the nature of his first question. Well continuing the discussion further, I saw a post by Bret Cannon on the possibility of Firefox 4 supporting Python. -- Senthil From alan.gauld at btinternet.com Thu Feb 5 10:42:16 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Feb 2009 09:42:16 -0000 Subject: [Tutor] passing unknown no of arguments References: <7c42eba10902050057o1f105c2dqd4de8f50bb3759fb@mail.gmail.com> Message-ID: "Senthil Kumaran" wrote >> Also how can i run my python scripts in a web browser. > > What you are asking for is Python CGI programming. > Look out for chapters for Alan's book. I think he has covered from > the basics. If you mean how do you write dynamic web pages using Python then indeed it is CGI or some other web framework (Django, TurboGears, Pylons etc). If you mean running a python script actually in the browser itself then see my previous mail. Sadly my tutor does not contain stuff on web programming because freenet removed update access as I was writing that topic. That will be fixed after I finish the update of the tutor to v3 on my new web site -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From denis.spir at free.fr Thu Feb 5 11:09:53 2009 From: denis.spir at free.fr (spir) Date: Thu, 5 Feb 2009 11:09:53 +0100 Subject: [Tutor] named list Message-ID: <20090205110953.7a729f4a@o> Hello, python world! I'm looking for a way to implement a kind of "named" list, or named tree, with the following requirements: * Each item is named (or key-ed), like in a dict. * Each item (node) can be either a terminal item (leaf) or a sub-list (branch). * There may be items with the same name, unlike in a dict. * The item entering order is preserved, unlike in a dict. * A non-requirement: may be useful that items can be retrieved by name (in case several items have the same name, it's allright to return first one -- it's up to the client code to manage that) A structural representation of such an object looks like that: obj n1:val n2:val n3 n31:val n32 n321:val n322:val n33 n4 Which is exactly the same as for a list, except that each item gets a name in addition to its value. I ask for advices before doing bull**** as I suspect there may be a data structure in language theory that matches that needs. Some questions: * Do you know of such a structure? * What is the difference between a tree and a python list? a tree and an array that allows nesting? * Are items in a tree, as defined in theory, supposed to be of homogeneous type? I cannot implement that simply by giving items an additional attribute, for items can be of an type and can even change. They also need a whole bunch of custom methods. This would require sub-typing averu possible type, including custom ones (this was the cause of a previous, in which I asked if it was possible to sub-type at a type known at runtime). So I plan instead to implement the whole load of necessary behaviour in a container, thus letting the items unchanged. A possible design (?) would be to subtype list in order to add such a container object a parallel list of names. So that direct access still directly reaches values, while matching names are accessed by indexing a parallel list: obj[n] <-- item obj.names[n] <-- name And maybe: obj.link[n] <-- (name,item) obj[name] <-- item obj.name(item) <-- name Denis ------ la vida e estranya From Bruce_Sherwood at ncsu.edu Thu Feb 5 03:57:25 2009 From: Bruce_Sherwood at ncsu.edu (Bruce Sherwood) Date: Wed, 04 Feb 2009 21:57:25 -0500 Subject: [Tutor] [Visualpython-users] tkinter and visual with objects In-Reply-To: References: Message-ID: <498A5595.6030102@ncsu.edu> The following works to produce a window with nothing displayed in it: ball = sphere() ball.visible = 0 Another scheme would be this: scene.range = 1 ball = sphere(radius=1e-6) The point is that Visual doesn't create a window unless there is something to display. Bruce Sherwood Mr Gerard Kelly wrote: > I'm trying to make this very simple program, where the idea is that you > click a tkinter button named "Ball" and then a ball will appear in the > visual window. > > Problem is that the window itself doesn't pop up until the button is > pressed and the ball is created. I would like it to start out blank, and > then have the ball appear in it when the button is pressed. > > I thought that having "self.display=display()" in the __init__ of the > Application would do this, but it doesn't seem to. > > What do I need to add to this code to make it start out with a blank window? > > > from visual import * > from Tkinter import * > import sys > > > class Ball: > def __init__(self): > sphere(pos=(0,0,0)) > > class Application: > def __init__(self, root): > > self.frame = Frame(root) > self.frame.pack() > > self.display=display() > > self.button=Button(self.frame, text="Ball", command=self.ball) > self.button.pack() > > def ball(self): > self.ball=Ball() > > root=Tk() > app=Application(root) > > root.mainloop() > > ------------------------------------------------------------------------------ > Create and Deploy Rich Internet Apps outside the browser with Adobe(R)AIR(TM) > software. With Adobe AIR, Ajax developers can use existing skills and code to > build responsive, highly engaging applications that combine the power of local > resources and data with the reach of the web. Download the Adobe AIR SDK and > Ajax docs to start building applications today-http://p.sf.net/sfu/adobe-com > _______________________________________________ > Visualpython-users mailing list > Visualpython-users at lists.sourceforge.net > https://lists.sourceforge.net/lists/listinfo/visualpython-users From kent37 at tds.net Thu Feb 5 12:55:40 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 5 Feb 2009 06:55:40 -0500 Subject: [Tutor] inheriting different builtin types In-Reply-To: <20090204142717.7f811746@o> References: <20090204142717.7f811746@o> Message-ID: <1c2a2c590902050355m4cfaf792xda85a5271aaf9032@mail.gmail.com> On Wed, Feb 4, 2009 at 8:27 AM, spir wrote: > Hello, > > I have a strange problem and cannot see a clear method to solve it. > I would like to build a custom type that is able to add some informational attributes and a bunch attribute to a main "value". The outline is then: > > class Custom(X): > def __init__(self, value, more): > X.__init__(self) > > > > The base class is here to inherit value's behaviour and to avoid writing obj.value all the time. For this type will be heavily used by client code. > The point is, this value may actually be of several builtin types. Logically, X is value.__class__. I imagine there are solutions using a factory, or __new__, or maybe metaclass (never done yet)? I cannot find a working method myself. If I understand correctly, you have two problems: - creating a class with a dynamic base type - creating a subclass of a built-in value type such as int The first is easily solved with a factory method to create the classes: def make_value_class(base_): class Derived(base_): # etc return Derived IntValue = make_value_class(int) Subclassing builtin types is tricky because the value has to be assigned in the __new__() method, not in __init__(). See for example http://www.python.org/download/releases/2.2.3/descrintro/#__new__ or search the tutor archives for __new__. Note that subclasses of builtin types are not as useful as you might hope because they are not preserved by binary operations. For example given a working IntValue class, if you did x = IntValue(3) y = IntValue(5) z = x+y type(z) is int, not IntValue, so all the special sauce is lost. From kent37 at tds.net Thu Feb 5 13:06:15 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 5 Feb 2009 07:06:15 -0500 Subject: [Tutor] passing unknown no of arguments In-Reply-To: References: Message-ID: <1c2a2c590902050406q5bad7fcam1b963698291d0a39@mail.gmail.com> On Thu, Feb 5, 2009 at 3:57 AM, Alan Gauld wrote: > In general you can't. You would need to have a Python interpreter > in your browser. The only reliable way to run code in a browser is > to use JavaScript. AFAIK MS Silverlight allows you to run .NET languages in your browser, including IronPython. Flash runs ActionScript. Kent From kent37 at tds.net Thu Feb 5 13:15:16 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 5 Feb 2009 07:15:16 -0500 Subject: [Tutor] named list In-Reply-To: <20090205110953.7a729f4a@o> References: <20090205110953.7a729f4a@o> Message-ID: <1c2a2c590902050415l74e2c4fete5c102bcaacdbc16@mail.gmail.com> On Thu, Feb 5, 2009 at 5:09 AM, spir wrote: > Hello, python world! > > I'm looking for a way to implement a kind of "named" list, or named tree, with the following requirements: > > * Each item is named (or key-ed), like in a dict. > * Each item (node) can be either a terminal item (leaf) or a sub-list (branch). > * There may be items with the same name, unlike in a dict. > * The item entering order is preserved, unlike in a dict. > > * A non-requirement: may be useful that items can be retrieved by name (in case several items have the same name, it's allright to return first one -- it's up to the client code to manage that) > > A structural representation of such an object looks like that: > > obj > n1:val > n2:val > n3 > n31:val > n32 > n321:val > n322:val > n33 > n4 > > Which is exactly the same as for a list, except that each item gets a name in addition to its value. > I ask for advices before doing bull**** as I suspect there may be a data structure in language theory that matches that needs. Some questions: > > * Do you know of such a structure? > * What is the difference between a tree and a python list? a tree and an array that allows nesting? > * Are items in a tree, as defined in theory, supposed to be of homogeneous type? > > I cannot implement that simply by giving items an additional attribute, for items can be of an type and can even change. They also need a whole bunch of custom methods. This would require sub-typing averu possible type, including custom ones (this was the cause of a previous, in which I asked if it was possible to sub-type at a type known at runtime). So I plan instead to implement the whole load of necessary behaviour in a container, thus letting the items unchanged. > A possible design (?) would be to subtype list in order to add such a container object a parallel list of names. So that direct access still directly reaches values, while matching names are accessed by indexing a parallel list: > > obj[n] <-- item > obj.names[n] <-- name > > And maybe: > > obj.link[n] <-- (name,item) > obj[name] <-- item > obj.name(item) <-- name Perhaps a list of (name, value) pairs, where the value could be a leaf node or another list? Or the nodes could be instances of namedtuple, so they have .name and .value attributes. You could subclass list or UserList. UserList gives you bottleneck methods which make it easy to customize all behaviour. You could also make your own wrapper class which would implement the above API. Kent From michael at arpsorensen.dk Thu Feb 5 13:26:52 2009 From: michael at arpsorensen.dk (=?UTF-8?Q?Michael_Bernhard_Arp_S=C3=B8rensen?=) Date: Thu, 5 Feb 2009 13:26:52 +0100 Subject: [Tutor] Killing a socketserver Message-ID: <1618520902050426u81f8d89kf24517b09fe4a3b1@mail.gmail.com> Geeting, my masters. How do I kill/shutdown a socket server running in its own thread either from handle() or from outside of the tread? Any thing will do. It's python version 2.5.2, so the newer shutdown method in version 2.6 does not work here. Thanks in advance. -- Med venlig hilsen/Kind regards Michael B. Arp S?rensen Programmer / BOFH -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Thu Feb 5 14:54:49 2009 From: denis.spir at free.fr (spir) Date: Thu, 5 Feb 2009 14:54:49 +0100 Subject: [Tutor] Sort of database & "family tree" question In-Reply-To: References: <497DC193.40301@gmail.com> <498885DB.8000701@gmail.com> <38224.28235.qm@web86708.mail.ird.yahoo.com> <20090204092724.6105e831@o> <49897D3B.2070500@gmail.com> Message-ID: <20090205145449.711c3434@o> Le Wed, 4 Feb 2009 22:33:45 -0000, "Alan Gauld" a ?crit : > > "Timo" wrote > > >>>> class Person: > >>>> def __init__(self, parser): > >>>> self.first = parser.get(person, 'firstName') > > > > Hey Alan, thanks for that explanation! > > > > But the class you gave, does almost the same thing as my function. > > That was my point. Its just a prettier way of handling it and slightly > easier to use sionce you don;t need to quote the field names, > just use the dot notation. > > > both store the info in a dic, so to retrieve info for a certain > > person, we both have to do the same thing. Or am I missing something > > here? > > The class is less typing. Youcreate a dictionary of dictionaries, > I create a dictionary of objects - which are easier to access. > However the class can also have methods added to do searches, > follow the tree etc. You could also add the people dictionary as a > class variable which would add to the conceptual consistency of > the solution.. [... lots of sensible words comparing dict way to object way ...] A note on implementing all the features needed for actual use (at least, a nice output format): using a dict of dicts will tend mixing up things related to persons with other, indirectly related things. Unless you keep a very strict design and coding discipline. Many things get uselessly dependant so that minor changes become difficult. Using objects does not guarantee preventing that (especially in python where it is always possible to access any object attribute from anywhere), but it helps much. Actually, it helps both at design and coding levels. But you are still free to write an unreadable mess... Denis ------ la vida e estranya From denis.spir at free.fr Thu Feb 5 15:02:58 2009 From: denis.spir at free.fr (spir) Date: Thu, 5 Feb 2009 15:02:58 +0100 Subject: [Tutor] passing unknown no of arguments In-Reply-To: References: Message-ID: <20090205150258.1f8c7d99@o> Le Thu, 5 Feb 2009 08:57:15 -0000, "Alan Gauld" a ?crit : > > "amit sethi" wrote > > > How do you pass arguments of unknown no. of arguments to a function. > > search the docs for *args and *kwargs > Or simply pass a tuple: def myPrint(thing): print thing thing_of_things = (1,'a',[True]) myPrint(thing_of_things) ==> (1,'a',[True]) Denis ------ la vida e estranya From dave at field15.com Thu Feb 5 15:19:54 2009 From: dave at field15.com (Dave Rankin) Date: Thu, 5 Feb 2009 09:19:54 -0500 Subject: [Tutor] passing unknown no of arguments In-Reply-To: References: Message-ID: <200902050919.54634.dave@field15.com> On Thu, Feb 5, 2009 at 3:57 AM, Alan Gauld wrote: > > In general you can't. You would need to have a Python interpreter > > in your browser. The only reliable way to run code in a browser is > > to use JavaScript. I'm very new to Python, but I've also been wondering about this. It would seem to me that with Jython you could write Python code that you convert to Java applets to run in the web browser. After a little bit of googling around, it seems that it all comes down to importing Applet from java.applet and then, of course, learning the applet interface. I didn't immediately see anything about performance issues, reliability, gotchas, or any other significant drawbacks, but if the original poster really did mean Python code that runs in the browser instead of on the server, maybe this approach would help them. -Dave From cclpianos at comcast.net Thu Feb 5 18:06:21 2009 From: cclpianos at comcast.net (cclpianos at comcast.net) Date: Thu, 5 Feb 2009 10:06:21 -0700 Subject: [Tutor] Install/upgrade question Message-ID: Hello, I am very new to programming and have been using Python on my Mac mini 1.66. I'm a bit confused by the install procedure as I have two different versions on my machine. I didn't know that it came pre-installed on my mac (version 2.3) and went to the DL site for 2.61. Well it downloaded just fine but I seem to have a few situations. My main question is "How do I get the downloaded version to replace what's on my system? As it is, I can open the IDLE and it verifies I have installed version 2.61. But when I run a dir() request it spouts the version is 2.3. Confusing... Further I DL'ed the .tar which decompressed to a .dmg file. The 2.61 folder is currently on my Desktop, where I process most of my downloads. Thanks! And finally, this is amazing stuff. I've dreamed about being able to write software for years and feel I have found something quite useful. From kent37 at tds.net Thu Feb 5 18:48:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 5 Feb 2009 12:48:05 -0500 Subject: [Tutor] Install/upgrade question In-Reply-To: References: Message-ID: <1c2a2c590902050948l2dce2b2cxf7ab6d7700044f71@mail.gmail.com> On Thu, Feb 5, 2009 at 12:06 PM, wrote: > My main question is "How do I get the downloaded version to replace what's > on my system? Don't; leave the system copy alone, there are system components that use it. > As it is, I can open the IDLE and it verifies I have installed version 2.61. > But when I run a dir() request it spouts the version is 2.3. Confusing... I don't understand that; what is a dir() request? What is spouting? Please be more specific and show the actual text. > Further I DL'ed the .tar which decompressed to a .dmg file. The 2.61 folder > is currently on my Desktop, where I process most of my downloads. Do you mean the installed Python in on your desktop, or the .dmg file, or what? It should not install to the desktop. > And finally, this is amazing stuff. Yes :-) Kent From alan.gauld at btinternet.com Thu Feb 5 19:02:44 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Feb 2009 18:02:44 -0000 Subject: [Tutor] passing unknown no of arguments References: <1c2a2c590902050406q5bad7fcam1b963698291d0a39@mail.gmail.com> Message-ID: "Kent Johnson" wrote >> in your browser. The only reliable way to run code in a browser is >> to use JavaScript. > > AFAIK MS Silverlight allows you to run .NET languages in your > browser, But how many browsers currently support Silverlight? After all IE supports VBScript too but its the only one. Eventually Silverlight may become ubiquitous but for now the only *reliable* way to write client code is JavaScript. > Flash runs ActionScript. Flash is a valid point although somewhat limited in practice - I wouldn't want to write a general purpose app in Actionscript! Also the point made about a Jython applet is good too. That might in fact be the best route to Python in a browser. Although Java applets seem to have fallen out of favour lately... -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Feb 5 19:07:28 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Feb 2009 18:07:28 -0000 Subject: [Tutor] Killing a socketserver References: <1618520902050426u81f8d89kf24517b09fe4a3b1@mail.gmail.com> Message-ID: "Michael Bernhard Arp S?rensen" wrote > How do I kill/shutdown a socket server running in its own thread > either from > handle() or from outside of the tread? Any thing will do. kill -9 pid if you are on *nix? Or do you need to do it from code? Or is it only the thread you want to kill? Are you killing from inside the same process? Or from an external process? Alan G From kent37 at tds.net Thu Feb 5 19:23:39 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 5 Feb 2009 13:23:39 -0500 Subject: [Tutor] passing unknown no of arguments In-Reply-To: References: <1c2a2c590902050406q5bad7fcam1b963698291d0a39@mail.gmail.com> Message-ID: <1c2a2c590902051023n21841e7ax7e5b3712f7534b83@mail.gmail.com> On Thu, Feb 5, 2009 at 1:02 PM, Alan Gauld wrote: > > "Kent Johnson" wrote >> AFAIK MS Silverlight allows you to run .NET languages in your browser, > > But how many browsers currently support Silverlight? >From the Silverlight FAQ: Silverlight will support all major browsers on both Mac OS X, Linux and on Windows. Particular care is being taken to account for differences in platform and browser capabilities to ensure a consistent experience including experiences on Firefox, Safari, and Internet Explorer. Kent From kent37 at tds.net Thu Feb 5 19:33:02 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 5 Feb 2009 13:33:02 -0500 Subject: [Tutor] Killing a socketserver In-Reply-To: <1618520902050426u81f8d89kf24517b09fe4a3b1@mail.gmail.com> References: <1618520902050426u81f8d89kf24517b09fe4a3b1@mail.gmail.com> Message-ID: <1c2a2c590902051033w1b8a67c5i94d53714d974d2d@mail.gmail.com> On Thu, Feb 5, 2009 at 7:26 AM, Michael Bernhard Arp S?rensen wrote: > Geeting, my masters. > > How do I kill/shutdown a socket server running in its own thread either from > handle() or from outside of the tread? Any thing will do. > > It's python version 2.5.2, so the newer shutdown method in version 2.6 does > not work here. > Subclass the server class adding shutdown() and supporting infrastructure from 2.6. Kent From alan.gauld at btinternet.com Thu Feb 5 20:00:22 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 5 Feb 2009 19:00:22 -0000 Subject: [Tutor] passing unknown no of arguments References: <1c2a2c590902050406q5bad7fcam1b963698291d0a39@mail.gmail.com> <1c2a2c590902051023n21841e7ax7e5b3712f7534b83@mail.gmail.com> Message-ID: "Kent Johnson" wrote > >>From the Silverlight FAQ: > Silverlight will support all major browsers on both Mac OS X, Linux > and on Windows. I briefly tried and failed to get it working on MacOS X and lost interest. Looks like I might be a bit premature in ignoring it. I'll have another go... Alan G. From emadnawfal at gmail.com Fri Feb 6 01:13:09 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Thu, 5 Feb 2009 19:13:09 -0500 Subject: [Tutor] confusing enumerate behavior Message-ID: <652641e90902051613l62c88ca0ha77a7ed841db2d@mail.gmail.com> Hi Tutors, I'm a little, actually a lot confused by the behavior of the enumerate function here. I have a text and I want to get each word within the context of the three preceding and the three following words. I tried this: #BEGIN my_input = "one two three four five six seven eight nine ten" text = my_input.split() for i,v in enumerate(text): line = text[i-3], text[i-2], text[i-1], v, text[i+1], text[i+2], text[i+3] print line # END The ouput was not as I expected. It did not start from the beginning (actually I had expected it to throw and exception immediately) ('eight', 'nine', 'ten', 'one', 'two', 'three', 'four') ('nine', 'ten', 'one', 'two', 'three', 'four', 'five') ('ten', 'one', 'two', 'three', 'four', 'five', 'six') ('one', 'two', 'three', 'four', 'five', 'six', 'seven') ('two', 'three', 'four', 'five', 'six', 'seven', 'eight') ('three', 'four', 'five', 'six', 'seven', 'eight', 'nine') ('four', 'five', 'six', 'seven', 'eight', 'nine', 'ten') Traceback (most recent call last): File "enumerate.py", line 13, in line = text[i-3], text[i-2], text[i-1], v, text[i+1], text[i+2], text[i+3] IndexError: list index out of range emad at emad-laptop:~/Desktop$ I then though of adding dummy words to the beginning and the end and exclude them later like this: #BEGIN my_input = "one two three four five six seven eight nine ten" text2 = " nothing " *6 + my_input + " nothing "* 6 text2 = text2.split() for i,v in enumerate(text2[6:-6]): line = text2[i-3], text2[i-2], text2[i-1], v, text2[i+1], text2[i+2], text2[i+3] print line #END The output this time was even more confusing: emad at emad-laptop:~/Desktop$ python enumerate.py ('nothing', 'nothing', 'nothing', 'one', 'nothing', 'nothing', 'nothing') ('nothing', 'nothing', 'nothing', 'two', 'nothing', 'nothing', 'nothing') ('nothing', 'nothing', 'nothing', 'three', 'nothing', 'nothing', 'nothing') ('nothing', 'nothing', 'nothing', 'four', 'nothing', 'nothing', 'one') ('nothing', 'nothing', 'nothing', 'five', 'nothing', 'one', 'two') ('nothing', 'nothing', 'nothing', 'six', 'one', 'two', 'three') ('nothing', 'nothing', 'nothing', 'seven', 'two', 'three', 'four') ('nothing', 'nothing', 'one', 'eight', 'three', 'four', 'five') ('nothing', 'one', 'two', 'nine', 'four', 'five', 'six') ('one', 'two', 'three', 'ten', 'five', 'six', 'seven') Can somebody please explain what is going on here? Have I done something wrong? How can this be fixed? Thanks in anticipation, Emad -------------- next part -------------- An HTML attachment was scrubbed... URL: From dorseye at gmail.com Fri Feb 6 02:24:07 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Thu, 5 Feb 2009 18:24:07 -0700 Subject: [Tutor] Python 2.6.1 + Linux Ubuntu (Gutsy Gibbon) Message-ID: I am trying to teach myself Linux, and so I'm running Ubuntu (Gutsy Gibbon) as a virtual machine. I went to terminal, started up Python and realized it was version 2.5 so I thought I'd just upgrade to 2.6.1 After doing some Googling around, it seems that Ubuntu is highly reliant on Python 2.5, so upgrading isn't so simple after all. Is this just Ubuntu that is so integrated with Python, or all flavors of Linux? Doesn't this hinder developers who use Ubuntu (and Linux?) as their primary OS when new versions of Python come out? I have been using Windows forever, but everyone says Linux is the development environment. Thoughts? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Feb 6 02:40:27 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 6 Feb 2009 01:40:27 -0000 Subject: [Tutor] confusing enumerate behavior References: <652641e90902051613l62c88ca0ha77a7ed841db2d@mail.gmail.com> Message-ID: "Emad Nawfal (???? ????)" wrote > I'm a little, actually a lot confused by the behavior of the > enumerate Its not enumerate thats confusing you its indexing. > my_input = "one two three four five six seven eight nine ten" > text = my_input.split() > for i,v in enumerate(text): > line = text[i-3], text[i-2], text[i-1], v, text[i+1], text[i+2], for i=0 the first index is -3 but an index of -3 in Python is the third item from the end. Its a little bit like the list was circular, so, instead of falling off the end with -1, you wrap around to the last item. > ('eight', 'nine', 'ten', 'one', 'two', 'three', 'four') So eight is text[-3] because its 3 from the end. > I then though of adding dummy words > text2 = " nothing " *6 + my_input + " nothing "* 6 > text2 = text2.split() > for i,v in enumerate(text2[6:-6]): > line = text2[i-3], text2[i-2], text2[i-1], v, text2[i+1], > text2[i+2], by using the slice you extracted your old list and got the same set of indexes! Instead of subtracting 3 you would need to add six minus the offset: line = text2[i+6-3], text2[i+6-2].... by the way doesn't this look like it could be in a loop? The other way is to simply test the index and if its beyond the range of your list add 'nothing'. Something like: my_input = "one two three four five six seven eight nine ten" text = my_input.split() for i,v in enumerate(text): for n in range(3,0,-1) if i-n < 0: print 'nothing', print text[i], for n in range(1,4) if i+n >= len(text) print 'nothing, Its late and this is untested but it should give a starting point. My brain is saying something about list comprehensions but I'm too tired to care :-) Or another waty might be to use your text2 approach and just print using indexes starting at the offset of your frst entry. Actually that sounds like it might be the best way... text2 = 'nil'*3+text+'niil*3 for i in range(3,len(text)): print text2[i-3:i+3] or somesuch... HTH Alan G. Zzzzzzzzzzzzzzzzzzzzzzzzzz.... From emadnawfal at gmail.com Fri Feb 6 03:54:04 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Thu, 5 Feb 2009 21:54:04 -0500 Subject: [Tutor] Python 2.6.1 + Linux Ubuntu (Gutsy Gibbon) In-Reply-To: References: Message-ID: <652641e90902051854m7ed3d8cj589263098f3e8ed3@mail.gmail.com> On Thu, Feb 5, 2009 at 8:24 PM, Eric Dorsey wrote: > I am trying to teach myself Linux, and so I'm running Ubuntu (Gutsy Gibbon) > as a virtual machine. I went to terminal, started up Python and realized it > was version 2.5 so I thought I'd just upgrade to 2.6.1 After doing some > Googling around, it seems that Ubuntu is highly reliant on Python 2.5, so > upgrading isn't so simple after all. > Is this just Ubuntu that is so integrated with Python, or all flavors of > Linux? Doesn't this hinder developers who use Ubuntu (and Linux?) as their > primary OS when new versions of Python come out? > > I have been using Windows forever, but everyone says Linux is the > development environment. Thoughts? > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > Just a quick reply until you get a better answer: I'm using Ubuntu Linux and I have Python 2.5.2 is the default version. I have recently downloaded and installed python3.0 without any problems. All I have to do is to specify that I want to use python3.0 >From the terminal type python and you get python2.5 Type python3.0 and you get python3.0. You can have multiple python versions on your machine. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Feb 6 04:36:07 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 5 Feb 2009 22:36:07 -0500 Subject: [Tutor] Install/upgrade question In-Reply-To: <44E609C5-4943-4270-BF4D-2227FF428164@comcast.net> References: <1c2a2c590902050948l2dce2b2cxf7ab6d7700044f71@mail.gmail.com> <44E609C5-4943-4270-BF4D-2227FF428164@comcast.net> Message-ID: <1c2a2c590902051936i2d81c5ebl85676ecf13b2cad0@mail.gmail.com> On Thu, Feb 5, 2009 at 9:29 PM, wrote: > Hi Kent, > Thanks for your very quick reply. I'll be as succinct as possible. > On Feb 5, 2009, at 10:48 AM, Kent Johnson wrote: > Last login: Thu Feb 5 18:55:15 on console > Welcome to Darwin! > p-ws-computer:~ pw$ python > Python 2.3.5 (#1, Nov 26 2007, 09:16:55) > [GCC 4.0.1 (Apple Computer, Inc. build 5363) (+4864187)] on darwin > Using IDLE I get a different version listing: > Python 2.6.1 (r261:67515, Dec 6 2008, 16:42:21) > [GCC 4.0.1 (Apple Computer, Inc. build 5370)] on darwin OK, so IDLE is using the 2.6.1 you installed but the command line still sees 2.3. > Further I DL'ed the .tar which decompressed to a .dmg file. The 2.61 folder > is currently on my Desktop, where I process most of my downloads. > > Do you mean the installed Python in on your desktop, or the .dmg file, > or what? It should not install to the desktop. > > This is what happened. I have 2.61 on the desktop. Before I move it I wanted > to be sure of several other things: > 1. You already answered that Q, "don't remove the older version 2.35." > 2. Is there a hack to get my 2.61 off the desktop and into the System? I > still have the .tar file. I'm still confused by this. The download from Python.org is a dmg file, not a tar file. The standard installers don't install to the desktop, and they put the new Python into your path. Where did you get your installer? Maybe you should just install the version from Python.org. What is the console output of these commands? echo $PATH which python which python2.6 python2.6 Kent From sierra_mtnview at sbcglobal.net Fri Feb 6 04:38:28 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 05 Feb 2009 19:38:28 -0800 Subject: [Tutor] Designing a Dialog in Python Message-ID: <498BB0B4.8030409@sbcglobal.net> An HTML attachment was scrubbed... URL: From jitu.icfai at gmail.com Fri Feb 6 08:00:31 2009 From: jitu.icfai at gmail.com (jitendra gupta) Date: Fri, 6 Feb 2009 12:30:31 +0530 Subject: [Tutor] confusing enumerate behavior In-Reply-To: <652641e90902051613l62c88ca0ha77a7ed841db2d@mail.gmail.com> References: <652641e90902051613l62c88ca0ha77a7ed841db2d@mail.gmail.com> Message-ID: On Fri, Feb 6, 2009 at 5:43 AM, Emad Nawfal (???? ????) wrote: > Hi Tutors, > I'm a little, actually a lot confused by the behavior of the enumerate > function here. I have a text and I want to get each word within the context > of the three preceding and the three following words. I tried this: > #BEGIN > my_input = "one two three four five six seven eight nine ten" > text = my_input.split() > for i,v in enumerate(text): > line = text[i-3], text[i-2], text[i-1], v, text[i+1], text[i+2], > text[i+3] > print line > # END > The ouput was not as I expected. It did not start from the beginning > (actually I had expected it to throw and exception immediately) > ('eight', 'nine', 'ten', 'one', 'two', 'three', 'four') > ('nine', 'ten', 'one', 'two', 'three', 'four', 'five') > ('ten', 'one', 'two', 'three', 'four', 'five', 'six') > ('one', 'two', 'three', 'four', 'five', 'six', 'seven') > ('two', 'three', 'four', 'five', 'six', 'seven', 'eight') > ('three', 'four', 'five', 'six', 'seven', 'eight', 'nine') > ('four', 'five', 'six', 'seven', 'eight', 'nine', 'ten') > Traceback (most recent call last): > File "enumerate.py", line 13, in > line = text[i-3], text[i-2], text[i-1], v, text[i+1], text[i+2], > text[i+3] > IndexError: list index out of range > emad at emad-laptop:~/Desktop$ > > I then though of adding dummy words to the beginning and the end and exclude > them later like this: > #BEGIN > my_input = "one two three four five six seven eight nine ten" > > text2 = " nothing " *6 + my_input + " nothing "* 6 > > text2 = text2.split() > for i,v in enumerate(text2[6:-6]): > line = text2[i-3], text2[i-2], text2[i-1], v, text2[i+1], text2[i+2], > text2[i+3] > print line > #END > > The output this time was even more confusing: > emad at emad-laptop:~/Desktop$ python enumerate.py > ('nothing', 'nothing', 'nothing', 'one', 'nothing', 'nothing', 'nothing') > ('nothing', 'nothing', 'nothing', 'two', 'nothing', 'nothing', 'nothing') > ('nothing', 'nothing', 'nothing', 'three', 'nothing', 'nothing', 'nothing') > ('nothing', 'nothing', 'nothing', 'four', 'nothing', 'nothing', 'one') > ('nothing', 'nothing', 'nothing', 'five', 'nothing', 'one', 'two') > ('nothing', 'nothing', 'nothing', 'six', 'one', 'two', 'three') > ('nothing', 'nothing', 'nothing', 'seven', 'two', 'three', 'four') > ('nothing', 'nothing', 'one', 'eight', 'three', 'four', 'five') > ('nothing', 'one', 'two', 'nine', 'four', 'five', 'six') > ('one', 'two', 'three', 'ten', 'five', 'six', 'seven') > > Can somebody please explain what is going on here? Have I done something > wrong? How can this be fixed? > > Thanks in anticipation, > Emad > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > hello Emad Try this if u r looking for this kind of solution >>>my_input = "one two three four five six seven eight nine ten" >>>text = my_input.split() >>>for i in range(len(text)): if i+3>=len(text): print text[i-3:len(text):1] elif i<=2: print text[0:i+4] else: print text[i-3:i+4] Output is....... ['one', 'two', 'three', 'four'] ['one', 'two', 'three', 'four', 'five'] ['one', 'two', 'three', 'four', 'five', 'six'] ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] ['two', 'three', 'four', 'five', 'six', 'seven', 'eight'] ['three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] ['four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'] ['five', 'six', 'seven', 'eight', 'nine', 'ten'] ['six', 'seven', 'eight', 'nine', 'ten'] ['seven', 'eight', 'nine', 'ten'] Jitendra Kumar Hyderabad From s4027340 at student.uq.edu.au Fri Feb 6 09:37:38 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Fri, 06 Feb 2009 18:37:38 +1000 Subject: [Tutor] 'sphere' object is unindexable Message-ID: I am trying to get around the problem of sphere object being unindexable. I need to make spheres appear, positioned according to some list, for example: for i in [0,1]: sphere(pos=(0,i,0), radius=0.1) Is there any way of making these different spheres behave differently without using indexing? For example, I would like to be able to make the lower sphere go red when it is clicked on, using this fragment of code: while True: if scene.mouse.events: m = scene.mouse.getevent() if m.pick is ball[0]: ball[0].color = color.red But obviously it won't work because I haven't named it ball[0]. I can't figure out a way to name the objects based on their position without using indexing. Is there any way to do this? Thank you. From amit.pureenergy at gmail.com Fri Feb 6 09:43:42 2009 From: amit.pureenergy at gmail.com (amit sethi) Date: Fri, 6 Feb 2009 14:13:42 +0530 Subject: [Tutor] passing unknown no of arguments In-Reply-To: References: <1c2a2c590902050406q5bad7fcam1b963698291d0a39@mail.gmail.com> <1c2a2c590902051023n21841e7ax7e5b3712f7534b83@mail.gmail.com> Message-ID: >> AFAIK MS Silverlight allows you to run .NET languages in your browser, so for that i guess i would have to use ironpython and not Cpython which is what i normally use . Are there any big problems porting the code from one to other that i need to be worried about. On Fri, Feb 6, 2009 at 12:30 AM, Alan Gauld wrote: > > "Kent Johnson" wrote > >> >> From the Silverlight FAQ: >>> >> Silverlight will support all major browsers on both Mac OS X, Linux >> and on Windows. >> > > I briefly tried and failed to get it working on MacOS X and lost interest. > Looks like I might be a bit premature in ignoring it. I'll have another > go... > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- A-M-I-T S|S -------------- next part -------------- An HTML attachment was scrubbed... URL: From dave6502 at googlemail.com Fri Feb 6 10:06:58 2009 From: dave6502 at googlemail.com (dave selby) Date: Fri, 6 Feb 2009 09:06:58 +0000 Subject: [Tutor] totally stumped on signal code, wont work in this instance Message-ID: Hi, I have been hitting my head on a brick wall on a bit of code that refuses to work. I have similar code in other scripts that works AOK I have commented out all functionality except the core problem ... import sys, threading, time, os.path, urllib, time, signal, ConfigParser, logger .... def main(): #logger.log('daemon starting ...', 'CRIT') #read_config() #thread1 = Thread1_PTZ() #thread1.setDaemon(True) #thread1.start() #thread2 = Thread2_PTZ_Park() #thread2.setDaemon(True) #thread2.start() #thread3 = Thread3_PTZ_Preset() #thread3.setDaemon(True) #thread3.start() while True: # sleep to keep daemons alive :) time.sleep(60 * 60 * 24) def signal_hup(signum, frame): """ SIGHUP, unlike all other daemons SIGHUP causes this daemon to exit killing all its daemon threads. This is a workaround. Because 'kmotion_ptzd' is threaded the only way to get the threads to reliably reload their config is to kill and restart else they languish in a sleep state for ? secs. args : discarded excepts : return : none """ print 'sighup :)' #logger.log('signal SIGHUP detected, shutting down due to threading', 'CRIT') #sys.exit() ... main() So main just sits there AOK. I send a sighup to the script with pkill -SIGHUP -f python.+kmotion_ptzd.py and I get ... dave at main-system:~/kmotion2/core$ ./kmotion_ptzd.py Hangup dave at main-system:~/kmotion2/core$ OK so I would have expected signal_hup to have intercepted the signal and printed 'sighup :)' and also not have exited in this case. Any ideas, I can solve most of my python probs but this one has me stumped. Cheers Dave -- Please avoid sending me Word or PowerPoint attachments. See http://www.gnu.org/philosophy/no-word-attachments.html From daniel.chaowang at gmail.com Fri Feb 6 10:11:08 2009 From: daniel.chaowang at gmail.com (Daniel) Date: Fri, 6 Feb 2009 17:11:08 +0800 Subject: [Tutor] any best practice on how to glue tiny tools together Message-ID: <57fe16f60902060111w7f783439weed58725206fad96@mail.gmail.com> Hi Tutors, I want to use python to finish some routine data processing tasks automatically (on Windows). The main task could be split to sub small tasks. Each can be done by executing some small tools like "awk" or by some other python scripts. One example of such task is conducting a data processing job, including: 1. use tool-A to produce some patterns. 2. feed tool-B with these patterns to mine more related data 3. repeat these tasks circularly until meeting some conditions. The real task includes more tools which run in parallel or sequential manner. I know how to do this with modules like subprocess, but the final python program looks somewhat messy and hard to adapt for changes. Do you have any best practices on this? Thanks a lot, Danny -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Feb 6 10:12:53 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 6 Feb 2009 09:12:53 -0000 Subject: [Tutor] Designing a Dialog in Python References: <498BB0B4.8030409@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Signature.htmlWhen I used VBasic many years ago, > it had the ability to design a dialog and then attach it > to the code. Is there something like this available for Python? What I think you are looking for is a GUI design tool. There are several for Python, some commercial some free. In my experience none of them are anywhere near as good as the VB or Delphi ones. However SPE worked, and I know some folks have gotten Glade to work. I think dabo might work too. And if you are on a Mac you can use the standard XCode development tools to build a GUI and connect Python via the PyObjC bridge. The bigger issue is that all of these tools are tied to GUI frameworks so you need to learn how to program using the framework first. wxPython or PyQt seem to be the most popular for GUI bulders but a few have modified the underlying framework to produce their own dialect. (I think dabo is an example) However most Python programmers still seem to build their GUIs using vanilla code rather than a visual editor. If you don't need the visual design tools then you can design dialogs etc in your favourite editor and for that Tkinter/Tix come as standard. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Fri Feb 6 10:22:25 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 6 Feb 2009 09:22:25 -0000 Subject: [Tutor] 'sphere' object is unindexable References: Message-ID: "Mr Gerard Kelly" wrote >I am trying to get around the problem of sphere object being >unindexable. Can you give some background? Where are you getting these spheres? Is this a graphics program or a tookit of some kind? > I need to make spheres appear, positioned according to some list, > for > example: > > for i in [0,1]: > sphere(pos=(0,i,0), radius=0.1) And does this work? Or do you get an error? If so what? > Is there any way of making these different spheres behave > differently > without using indexing? Where is the indexing issue? Are you trying to store the spheres in a list and index the list to access a sphere or are you trying to use an index to access some aspect of the sphere? Show us the code that sdoesn't work and the error message. Don't just describe it. Show us. Don't assume we know what you are trying to do - we are not psychic. > For example, I would like to be able to make the lower sphere go red > when it is clicked on, using this fragment of code: > > while True: > if scene.mouse.events: > m = scene.mouse.getevent() > if m.pick is ball[0]: > ball[0].color = color.red > > But obviously it won't work because I haven't named it ball[0]. So why don't you name it ball? and what is m.pick supposed to be? Some attribute of a muse event based on your code but I have no idea what it might be! > figure out a way to name the objects based on their position without > using indexing. Is there any way to do this? A standard list should work and so provided you stored your spheres in a list when you created them you should be able to access them via an index. But without real code and a real error trace we can't help very much other than by making speculative guesses. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From s4027340 at student.uq.edu.au Fri Feb 6 11:38:55 2009 From: s4027340 at student.uq.edu.au (Mr Gerard Kelly) Date: Fri, 06 Feb 2009 20:38:55 +1000 Subject: [Tutor] 'sphere' object is unindexable Message-ID: Sorry, I do see that I wrote that question in a confusing way, but I've worked out where I was going wrong now. Thanks for taking a look. ----- Original Message ----- From: Alan Gauld Date: Friday, February 6, 2009 7:22 pm Subject: Re: [Tutor] 'sphere' object is unindexable > "Mr Gerard Kelly" wrote > > >I am trying to get around the problem of sphere object being > >unindexable. > > Can you give some background? Where are you getting these spheres? > Is this a graphics program or a tookit of some kind? > > > I need to make spheres appear, positioned according to some list, > > for > > example: > > > > for i in [0,1]: > > sphere(pos=(0,i,0), radius=0.1) > > And does this work? Or do you get an error? If so what? > > > Is there any way of making these different spheres behave > > differently > > without using indexing? > > Where is the indexing issue? > Are you trying to store the spheres in a list and index the list > to access a sphere or are you trying to use an index to access > some aspect of the sphere? > > Show us the code that sdoesn't work and the error message. > Don't just describe it. Show us. Don't assume we know what > you are trying to do - we are not psychic. > > > For example, I would like to be able to make the lower sphere go red > > when it is clicked on, using this fragment of code: > > > > while True: > > if scene.mouse.events: > > m = scene.mouse.getevent() > > if m.pick is ball[0]: > > ball[0].color = color.red > > > > But obviously it won't work because I haven't named it ball[0]. > > So why don't you name it ball? and what is m.pick supposed to be? > Some attribute of a muse event based on your code but I have > no idea what it might be! > > > figure out a way to name the objects based on their position without > > using indexing. Is there any way to do this? > > A standard list should work and so provided you stored your > spheres in a list when you created them you should be able to > access them via an index. But without real code and a real > error trace we can't help very much other than by making > speculative guesses. > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From denis.spir at free.fr Fri Feb 6 12:00:31 2009 From: denis.spir at free.fr (spir) Date: Fri, 6 Feb 2009 12:00:31 +0100 Subject: [Tutor] confusing enumerate behavior In-Reply-To: References: <652641e90902051613l62c88ca0ha77a7ed841db2d@mail.gmail.com> Message-ID: <20090206120031.6e2596d1@o> Le Fri, 6 Feb 2009 12:30:31 +0530, jitendra gupta a ?crit : > > #BEGIN > > my_input = "one two three four five six seven eight nine ten" > > text = my_input.split() > > for i,v in enumerate(text): > > line = text[i-3], text[i-2], text[i-1], v, text[i+1], text[i+2], > > text[i+3] > > print line > > # END You do not need enumerate in that case: offset = 3 # constant my_input = "one two three four five six seven eight nine ten" words = my_input.split() for i in range(offset, len(words)-offset): # beware of right-open range: slice = [word for word in words[i-offset : i+offset+1]] print i,slice ==> 3 ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] 4 ['two', 'three', 'four', 'five', 'six', 'seven', 'eight'] 5 ['three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] 6 ['four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'] Adapt using a 'guard' based on offset's value if you actually want all lines. Denis ------ la vida e estranya From kent37 at tds.net Fri Feb 6 12:29:18 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Feb 2009 06:29:18 -0500 Subject: [Tutor] passing unknown no of arguments In-Reply-To: References: <1c2a2c590902050406q5bad7fcam1b963698291d0a39@mail.gmail.com> <1c2a2c590902051023n21841e7ax7e5b3712f7534b83@mail.gmail.com> Message-ID: <1c2a2c590902060329u7c47dccfse37ab68354b36c60@mail.gmail.com> On Fri, Feb 6, 2009 at 3:43 AM, amit sethi wrote: >>> AFAIK MS Silverlight allows you to run .NET languages in your browser, > > so for that i guess i would have to use ironpython and not Cpython which is > what i normally use . Are there any big problems porting the code from one > to other that i need to be worried about. http://www.codeplex.com/IronPython/Wiki/View.aspx?title=Differences&referringTitle=Home Kent From kent37 at tds.net Fri Feb 6 12:33:00 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Feb 2009 06:33:00 -0500 Subject: [Tutor] totally stumped on signal code, wont work in this instance In-Reply-To: References: Message-ID: <1c2a2c590902060333x7bf411daw3ccd00a9c482d836@mail.gmail.com> On Fri, Feb 6, 2009 at 4:06 AM, dave selby wrote: > import sys, threading, time, os.path, urllib, time, signal, ConfigParser, logger > .... > > def main(): > > while True: # sleep to keep daemons alive :) > time.sleep(60 * 60 * 24) > > > def signal_hup(signum, frame): > """ > SIGHUP, unlike all other daemons SIGHUP causes this daemon to exit killing > all its daemon threads. This is a workaround. Because 'kmotion_ptzd' is > threaded the only way to get the threads to reliably reload their config > is to kill and restart else they languish in a sleep state for ? secs. > > args : discarded > excepts : > return : none > """ > > print 'sighup :)' > #logger.log('signal SIGHUP detected, shutting down due to > threading', 'CRIT') > #sys.exit() > > ... > main() Don't you have to register your handler with something like signal.signal(signal.SIGHUP, signal_hup) ? Kent From kent37 at tds.net Fri Feb 6 12:44:11 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Feb 2009 06:44:11 -0500 Subject: [Tutor] any best practice on how to glue tiny tools together In-Reply-To: <57fe16f60902060111w7f783439weed58725206fad96@mail.gmail.com> References: <57fe16f60902060111w7f783439weed58725206fad96@mail.gmail.com> Message-ID: <1c2a2c590902060344w639e9e58iafeeaeb9d22c7bf9@mail.gmail.com> On Fri, Feb 6, 2009 at 4:11 AM, Daniel wrote: > Hi Tutors, > > I want to use python to finish some routine data processing tasks > automatically (on Windows). > > The main task could be split to sub small tasks. Each can be done by > executing some small tools like "awk" or by some other python scripts. > One example of such task is conducting a data processing job, including: > > use tool-A to produce some patterns. > feed tool-B with these patterns to mine more related data > repeat these tasks circularly until meeting some conditions. > > The real task includes more tools which run in parallel or sequential > manner. > > I know how to do this with modules like subprocess, but the final python > program looks somewhat messy and hard to adapt for changes. > > Do you have any best practices on this? My first thought was, use shell pipelines and bash. Then I remembered, David Beazley shows how to use generators to implement a processing pipeline in Python: http://www.dabeaz.com/generators-uk/ It's a fascinating read, it might take a couple of times to get it but it might fit your needs quite well. You would write a generator that wraps a subprocess call and use that to access external tools; other pieces and the control logic would be in Python. Kent From kent37 at tds.net Fri Feb 6 12:54:49 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Feb 2009 06:54:49 -0500 Subject: [Tutor] confusing enumerate behavior In-Reply-To: References: <652641e90902051613l62c88ca0ha77a7ed841db2d@mail.gmail.com> Message-ID: <1c2a2c590902060354l7a71f1d1tac18069bce603bc1@mail.gmail.com> 2009/2/6 jitendra gupta : > Try this if u r looking for this kind of solution >>>>my_input = "one two three four five six seven eight nine ten" >>>>text = my_input.split() >>>>for i in range(len(text)): > if i+3>=len(text): > print text[i-3:len(text):1] > elif i<=2: > print text[0:i+4] > else: > print text[i-3:i+4] You can simplify this using the min() and max() functions: for i in range(len(text)): print text[max(0, i-3):min(i+3, len(text))] Kent From denis.spir at free.fr Fri Feb 6 13:21:41 2009 From: denis.spir at free.fr (spir) Date: Fri, 6 Feb 2009 13:21:41 +0100 Subject: [Tutor] any best practice on how to glue tiny tools together In-Reply-To: <1c2a2c590902060344w639e9e58iafeeaeb9d22c7bf9@mail.gmail.com> References: <57fe16f60902060111w7f783439weed58725206fad96@mail.gmail.com> <1c2a2c590902060344w639e9e58iafeeaeb9d22c7bf9@mail.gmail.com> Message-ID: <20090206132141.6dfd7dba@o> Le Fri, 6 Feb 2009 06:44:11 -0500, Kent Johnson a ?crit : > My first thought was, use shell pipelines and bash. Then I remembered, > David Beazley shows how to use generators to implement a processing > pipeline in Python: > http://www.dabeaz.com/generators-uk/ see also http://en.wikipedia.org/wiki/Python_Pipelines ------ la vida e estranya From kent37 at tds.net Fri Feb 6 13:55:42 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Feb 2009 07:55:42 -0500 Subject: [Tutor] any best practice on how to glue tiny tools together In-Reply-To: <20090206132141.6dfd7dba@o> References: <57fe16f60902060111w7f783439weed58725206fad96@mail.gmail.com> <1c2a2c590902060344w639e9e58iafeeaeb9d22c7bf9@mail.gmail.com> <20090206132141.6dfd7dba@o> Message-ID: <1c2a2c590902060455p56ef1bfege875e2e5b0c7eb23@mail.gmail.com> On Fri, Feb 6, 2009 at 7:21 AM, spir wrote: > see also > http://en.wikipedia.org/wiki/Python_Pipelines That looks pretty dead, or at least unpublished. The google code project is almost two years old but it contains no code. Kent From emadnawfal at gmail.com Fri Feb 6 14:52:52 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Fri, 6 Feb 2009 08:52:52 -0500 Subject: [Tutor] confusing enumerate behavior In-Reply-To: <1c2a2c590902060354l7a71f1d1tac18069bce603bc1@mail.gmail.com> References: <652641e90902051613l62c88ca0ha77a7ed841db2d@mail.gmail.com> <1c2a2c590902060354l7a71f1d1tac18069bce603bc1@mail.gmail.com> Message-ID: <652641e90902060552w6c3a14fbwc51f68537b285dd9@mail.gmail.com> On Fri, Feb 6, 2009 at 6:54 AM, Kent Johnson wrote: > 2009/2/6 jitendra gupta : > > > Try this if u r looking for this kind of solution > >>>>my_input = "one two three four five six seven eight nine ten" > >>>>text = my_input.split() > >>>>for i in range(len(text)): > > if i+3>=len(text): > > print text[i-3:len(text):1] > > elif i<=2: > > print text[0:i+4] > > else: > > print text[i-3:i+4] > > You can simplify this using the min() and max() functions: > for i in range(len(text)): > print text[max(0, i-3):min(i+3, len(text))] > > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Thank you all for the great solutions. I'm really grateful, but also still confused about indexing now. Why is it that if i = 0 indexing starts with -3. I never read this before, and I thus assume it is an advanced thing, or why is it not in elementary to intermediate resources ( The ones I used at least). Can somebody please suggest an accessible tutorial on this? -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From emmanix2002 at yahoo.com Fri Feb 6 15:08:10 2009 From: emmanix2002 at yahoo.com (Okeke emmanuel) Date: Fri, 6 Feb 2009 06:08:10 -0800 (PST) Subject: [Tutor] (no subject) Message-ID: <385876.32637.qm@web58407.mail.re3.yahoo.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: From jecarnell at saintfrancis.com Fri Feb 6 15:11:14 2009 From: jecarnell at saintfrancis.com (Carnell, James E) Date: Fri, 6 Feb 2009 08:11:14 -0600 Subject: [Tutor] 'sphere' object is unindexable In-Reply-To: Message-ID: Sorry, I do see that I wrote that question in a confusing way, but I've worked out where I was going wrong now. Thanks for taking a look. > > m.pick = ["stab","stab","stab","..."] From bgailer at gmail.com Fri Feb 6 16:08:52 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 06 Feb 2009 10:08:52 -0500 Subject: [Tutor] (no subject) In-Reply-To: <385876.32637.qm@web58407.mail.re3.yahoo.com> References: <385876.32637.qm@web58407.mail.re3.yahoo.com> Message-ID: <498C5284.1050404@gmail.com> Okeke emmanuel wrote: > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > At least the subject is accurate! -- Bob Gailer Chapel Hill NC 919-636-4239 From bgailer at gmail.com Fri Feb 6 16:11:09 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 06 Feb 2009 10:11:09 -0500 Subject: [Tutor] any best practice on how to glue tiny tools together In-Reply-To: <20090206132141.6dfd7dba@o> References: <57fe16f60902060111w7f783439weed58725206fad96@mail.gmail.com> <1c2a2c590902060344w639e9e58iafeeaeb9d22c7bf9@mail.gmail.com> <20090206132141.6dfd7dba@o> Message-ID: <498C530D.1050100@gmail.com> spir wrote: > Le Fri, 6 Feb 2009 06:44:11 -0500, > Kent Johnson a ?crit : > > >> My first thought was, use shell pipelines and bash. Then I remembered, >> David Beazley shows how to use generators to implement a processing >> pipeline in Python: >> http://www.dabeaz.com/generators-uk/ >> > > see also > http://en.wikipedia.org/wiki/Python_Pipelines > Thank you for the plug! The code is currently in flux so not available. I hope to have an alpha version out soon. -- Bob Gailer Chapel Hill NC 919-636-4239 From bgailer at gmail.com Fri Feb 6 16:15:05 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 06 Feb 2009 10:15:05 -0500 Subject: [Tutor] any best practice on how to glue tiny tools together In-Reply-To: <1c2a2c590902060455p56ef1bfege875e2e5b0c7eb23@mail.gmail.com> References: <57fe16f60902060111w7f783439weed58725206fad96@mail.gmail.com> <1c2a2c590902060344w639e9e58iafeeaeb9d22c7bf9@mail.gmail.com> <20090206132141.6dfd7dba@o> <1c2a2c590902060455p56ef1bfege875e2e5b0c7eb23@mail.gmail.com> Message-ID: <498C53F9.7000805@gmail.com> Kent Johnson wrote: > On Fri, Feb 6, 2009 at 7:21 AM, spir wrote: > > >> see also >> http://en.wikipedia.org/wiki/Python_Pipelines >> > > That looks pretty dead, or at least unpublished. The google code > project is almost two years old but it contains no code. > It is sluggish but not dead. The code is on my PC - not ready to release. I started the google code to help establish the project. Since development is voluntary right now it is slow. Keep tuned... FWIW I was on target for an alpha version when I got sidetracked by writing a "universal parser" which I am now "finalizing". Assistants are always welcome. -- Bob Gailer Chapel Hill NC 919-636-4239 From zebra05 at gmail.com Fri Feb 6 16:40:18 2009 From: zebra05 at gmail.com (OkaMthembo) Date: Fri, 6 Feb 2009 17:40:18 +0200 Subject: [Tutor] (no subject) In-Reply-To: <498C5284.1050404@gmail.com> References: <385876.32637.qm@web58407.mail.re3.yahoo.com> <498C5284.1050404@gmail.com> Message-ID: Lol..indeed [?] On Fri, Feb 6, 2009 at 5:08 PM, bob gailer wrote: > Okeke emmanuel wrote: > >> >> >> ------------------------------------------------------------------------ >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > At least the subject is accurate! > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Lloyd Dube -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/png Size: 645 bytes Desc: not available URL: From optomatic at rogers.com Fri Feb 6 19:09:24 2009 From: optomatic at rogers.com (Patrick) Date: Fri, 06 Feb 2009 13:09:24 -0500 Subject: [Tutor] parallel port help Message-ID: <498C7CD4.1030803@rogers.com> Hi Everyone I would like to write a Python program to control the data lines of a parallel port. PyParallel seems buggy, even the install script has one and it has practically no documentation. Portio also failed to install for me. Is there any other library you could point me too, or do you have any other advice? Is there someway to control individual data lines from bash? Thanks in advance-Patrick From xchimeras at gmail.com Fri Feb 6 21:52:03 2009 From: xchimeras at gmail.com (Tom Green) Date: Fri, 6 Feb 2009 15:52:03 -0500 Subject: [Tutor] WINSOCK stdin question Message-ID: Hello Python group, I need some advice on a problem I am facing. Basically I have a binary that sends out a reverse shell (CMD prompt). I have a listening Python socket and I would like to know how I can redirect the CMD prompt to stdin, so I can interact with the host that is sending the shell. Basically this is a reverse shell. Any tips is much appreciated. Thank you, Tom -------------- next part -------------- An HTML attachment was scrubbed... URL: From hgleroy at gmail.com Fri Feb 6 22:19:36 2009 From: hgleroy at gmail.com (H.G. le Roy) Date: Fri, 6 Feb 2009 22:19:36 +0100 Subject: [Tutor] improving the speed of prime number code Message-ID: <317299150902061319q7c240e79s471a7e7fd502c4c5@mail.gmail.com> Hi, I'm stuck with Problem 10 ( http://projecteuler.net/index.php?section=problems&id=10) :-) A part of my code deals with the calculation of prime numbers. However it is really slow. Hopefully you have some ideas how to make it faster. pz = [2] # only iterate over odd numbers for i in xrange(3,2000000,2): remprod = 1 # product of remainders for j in xrange(len(pz)): remprod *= (i % pz[j]) if remprod == 0: # if a number is divisible wo remainder its not prime break if remprod > 0: pz.append(i) -------------- next part -------------- An HTML attachment was scrubbed... URL: From taserian at gmail.com Fri Feb 6 22:30:16 2009 From: taserian at gmail.com (taserian) Date: Fri, 6 Feb 2009 16:30:16 -0500 Subject: [Tutor] improving the speed of prime number code In-Reply-To: <317299150902061319q7c240e79s471a7e7fd502c4c5@mail.gmail.com> References: <317299150902061319q7c240e79s471a7e7fd502c4c5@mail.gmail.com> Message-ID: <70dbc4d40902061330g1823aec0x20770ce0cc5a9c2e@mail.gmail.com> One potential way to speed up is not to divide by every prime in your pz list, but only up to the square root of i. For example, to test if 37 is prime, you would only need to look at primes less than or equal to int(sqrt(37)) = 6.08. . . Tony R. On Fri, Feb 6, 2009 at 4:19 PM, H.G. le Roy wrote: > Hi, > > I'm stuck with Problem 10 ( > http://projecteuler.net/index.php?section=problems&id=10) :-) > > A part of my code deals with the calculation of prime numbers. However it > is really slow. Hopefully you have some ideas how to make it faster. > > pz = [2] > # only iterate over odd numbers > for i in xrange(3,2000000,2): > remprod = 1 # product of remainders > for j in xrange(len(pz)): > remprod *= (i % pz[j]) > if remprod == 0: # if a number is divisible wo remainder its not prime > break > if remprod > 0: > pz.append(i) > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Feb 6 22:34:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Feb 2009 16:34:20 -0500 Subject: [Tutor] improving the speed of prime number code In-Reply-To: <317299150902061319q7c240e79s471a7e7fd502c4c5@mail.gmail.com> References: <317299150902061319q7c240e79s471a7e7fd502c4c5@mail.gmail.com> Message-ID: <1c2a2c590902061334g62081bdvb262b173e4677e34@mail.gmail.com> On Fri, Feb 6, 2009 at 4:19 PM, H.G. le Roy wrote: > A part of my code deals with the calculation of prime numbers. However it is > really slow. Hopefully you have some ideas how to make it faster. > > pz = [2] > # only iterate over odd numbers > for i in xrange(3,2000000,2): > remprod = 1 # product of remainders Not sure why you accumulate the products, just keep a flag or use an else clause on the for loop. > for j in xrange(len(pz)): for p in pz: > remprod *= (i % pz[j]) > if remprod == 0: # if a number is divisible wo remainder its not prime > break > if remprod > 0: > pz.append(i) You inner loop could be (not tested) for p in pz: if i % p == 0: break else: pz.append(i) You might search the archives for more ideas, this is a popular question. There is a very slick Python implementation of the Sieve of Eratosthenes that uses slice assignment to mark off the non-primes. Kent From bgailer at gmail.com Fri Feb 6 22:46:17 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 06 Feb 2009 16:46:17 -0500 Subject: [Tutor] improving the speed of prime number code In-Reply-To: <317299150902061319q7c240e79s471a7e7fd502c4c5@mail.gmail.com> References: <317299150902061319q7c240e79s471a7e7fd502c4c5@mail.gmail.com> Message-ID: <498CAFA9.4090101@gmail.com> H.G. le Roy wrote: > Hi, > > I'm stuck with Problem 10 > (http://projecteuler.net/index.php?section=problems&id=10 > ) :-) > > A part of my code deals with the calculation of prime numbers. However > it is really slow. Hopefully you have some ideas how to make it faster. > > pz = [2] > # only iterate over odd numbers > for i in xrange(3,2000000,2): > remprod = 1 # product of remainders > for j in xrange(len(pz)): > remprod *= (i % pz[j]) > if remprod == 0: # if a number is divisible wo remainder its not > prime > break > if remprod > 0: > pz.append(i) > I know prime # algorithms have been discussed on at least one of the Python lists, and are also found in various internet resources. Without consulting them let me offer: - odd prime numbers are = 6x-1 or 6x+1 where x is integer. That reduces the # of candidates. - the highest candidate you need to test is <= the square root of the candidate. That reduces cycles of the inner for loop - there is no need to initialize remprod - you can use "for j in pz:" to access successive pz's in which case you'd write i % j - there is no need to multiply remprod by the remainders as you don't use that result later. -- Bob Gailer Chapel Hill NC 919-636-4239 From sierra_mtnview at sbcglobal.net Sat Feb 7 00:53:27 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 06 Feb 2009 15:53:27 -0800 Subject: [Tutor] Closing and Open File--TkFileDialogs Message-ID: <498CCD77.7030701@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Feb 7 00:53:33 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 6 Feb 2009 23:53:33 -0000 Subject: [Tutor] WINSOCK stdin question References: Message-ID: "Tom Green" wrote > I need some advice on a problem I am facing. Basically I have a > binary that > sends out a reverse shell (CMD prompt). OK, You lost me right here. What is a reverse shell? That's a new one for me? (I tried wikipedia but drew a blank) > I have a listening Python socket and I would like to know how I can > redirect the CMD prompt to stdin, It might be useful to know what OS you are on and how you are running this application. Also is the listening socket on the same computer as the "reverse shell"? > can interact with the host that is sending the shell. The fact you mention host suggests its a separate box, but I'm not sure. Curious, Alan G From juryef at yahoo.com Sat Feb 7 01:58:50 2009 From: juryef at yahoo.com (Judith Flores) Date: Fri, 6 Feb 2009 16:58:50 -0800 (PST) Subject: [Tutor] How to avoid error message: "_csv.Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?" Message-ID: <303999.84984.qm@web34708.mail.mud.yahoo.com> Hello, I get the error message above quite often when trying to open some csv files. I noticed that if I open the csv file in excel and delete the "empty" columns at the right end of my data, the error message doesn't appear. My code looks like this: myfile=open(csvfile) reader=csv.reader(myfile) header=reader.next() Thank you, Judith Let me know if you would like to have some of my csv files. From kent37 at tds.net Sat Feb 7 03:17:24 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Feb 2009 21:17:24 -0500 Subject: [Tutor] Closing and Open File--TkFileDialogs In-Reply-To: <498CCD77.7030701@sbcglobal.net> References: <498CCD77.7030701@sbcglobal.net> Message-ID: <1c2a2c590902061817pbf1946fva9643a0b4983bbc5@mail.gmail.com> On Fri, Feb 6, 2009 at 6:53 PM, Wayne Watson wrote: > I'm using asksaveasfilename, and, as I understand it, it returns the file > name to me in write mode. I don't recall that there's a way to reference the > file with only the filename. That is, there's no filename.write(). Comments? I think you are confused between askopenfile() and askopenfilename(). The first opens the file and returns a file object, the second returns just the file name and you open the file yourself. > While I'm at it, I have found a good example program for TkFileDialog > methods, but the description of them on the internet is pretty shallow. For > example, An Intro to Tkinter, Lundh's Tkinter pages, NM Tech pdf files and > Python docs have little to say. This is helpful: http://tkinter.unpythonic.net/wiki/tkFileDialog Kent From kent37 at tds.net Sat Feb 7 03:19:22 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 6 Feb 2009 21:19:22 -0500 Subject: [Tutor] WINSOCK stdin question In-Reply-To: References: Message-ID: <1c2a2c590902061819s78ba5f9csc97afa6fadd30e7e@mail.gmail.com> On Fri, Feb 6, 2009 at 3:52 PM, Tom Green wrote: > Hello Python group, > > I need some advice on a problem I am facing. Basically I have a binary that > sends out a reverse shell (CMD prompt). I have a listening Python socket > and I would like to know how I can redirect the CMD prompt to stdin, so I > can interact with the host that is sending the shell. Basically this is a > reverse shell. Any tips is much appreciated. Like Alan, I never heard of reverse shell before. With a little googling I think I understand it but I don't understand your question. Is the python program on the client (user) side or the server side? Kent From xchimeras at gmail.com Sat Feb 7 03:35:34 2009 From: xchimeras at gmail.com (Tom Green) Date: Fri, 6 Feb 2009 21:35:34 -0500 Subject: [Tutor] WINSOCK stdin question In-Reply-To: <1c2a2c590902061819s78ba5f9csc97afa6fadd30e7e@mail.gmail.com> References: <1c2a2c590902061819s78ba5f9csc97afa6fadd30e7e@mail.gmail.com> Message-ID: The Python app is on the Server side. Sorry, I don't mean to cause hassle for anyone. I appreciate everyone's assistance. I am trying to reproduce what Netcat does. Thanks, Mike On Fri, Feb 6, 2009 at 9:19 PM, Kent Johnson wrote: > On Fri, Feb 6, 2009 at 3:52 PM, Tom Green wrote: > > Hello Python group, > > > > I need some advice on a problem I am facing. Basically I have a binary > that > > sends out a reverse shell (CMD prompt). I have a listening Python socket > > and I would like to know how I can redirect the CMD prompt to stdin, so I > > can interact with the host that is sending the shell. Basically this is > a > > reverse shell. Any tips is much appreciated. > > Like Alan, I never heard of reverse shell before. With a little > googling I think I understand it but I don't understand your question. > Is the python program on the client (user) side or the server side? > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Sat Feb 7 04:49:43 2009 From: srilyk at gmail.com (W W) Date: Fri, 6 Feb 2009 21:49:43 -0600 Subject: [Tutor] Designing a Dialog in Python In-Reply-To: References: <498BB0B4.8030409@sbcglobal.net> Message-ID: <333efb450902061949u6f907150x10675b014f773ee7@mail.gmail.com> On Fri, Feb 6, 2009 at 3:12 AM, Alan Gauld wrote: > "Wayne Watson" wrote > >> Signature.htmlWhen I used VBasic many years ago, it had the ability to >> design a dialog and then attach it to the code. Is there something like this >> available for Python? >> > > However most Python programmers still seem to build their GUIs using > vanilla code rather than a visual editor. > If you don't need the visual design tools then you can design dialogs etc > in your favourite editor and for that Tkinter/Tix come as standard. I'm aware of a visual design tool for Tkinter. I tried it (nowhere near as polished as delphi/VB of course) for about 30 seconds before deciding I didn't need the visual design tool. I forget what the editor was called though >.< doh! Of course you could always roll your own in Tkinter ;) -the other Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From daniel.chaowang at gmail.com Sat Feb 7 06:08:06 2009 From: daniel.chaowang at gmail.com (Daniel) Date: Sat, 7 Feb 2009 13:08:06 +0800 Subject: [Tutor] any best practice on how to glue tiny tools together In-Reply-To: <1c2a2c590902060344w639e9e58iafeeaeb9d22c7bf9@mail.gmail.com> References: <57fe16f60902060111w7f783439weed58725206fad96@mail.gmail.com> <1c2a2c590902060344w639e9e58iafeeaeb9d22c7bf9@mail.gmail.com> Message-ID: <57fe16f60902062108k1478601etf8a0a39c739099b0@mail.gmail.com> These are really valuable info. I will try. Thanks a lot. On Fri, Feb 6, 2009 at 7:44 PM, Kent Johnson wrote: > On Fri, Feb 6, 2009 at 4:11 AM, Daniel wrote: > > Hi Tutors, > > > > I want to use python to finish some routine data processing tasks > > automatically (on Windows). > > > > The main task could be split to sub small tasks. Each can be done by > > executing some small tools like "awk" or by some other python scripts. > > One example of such task is conducting a data processing job, including: > > > > use tool-A to produce some patterns. > > feed tool-B with these patterns to mine more related data > > repeat these tasks circularly until meeting some conditions. > > > > The real task includes more tools which run in parallel or sequential > > manner. > > > > I know how to do this with modules like subprocess, but the final python > > program looks somewhat messy and hard to adapt for changes. > > > > Do you have any best practices on this? > > My first thought was, use shell pipelines and bash. Then I remembered, > David Beazley shows how to use generators to implement a processing > pipeline in Python: > http://www.dabeaz.com/generators-uk/ > > It's a fascinating read, it might take a couple of times to get it but > it might fit your needs quite well. You would write a generator that > wraps a subprocess call and use that to access external tools; other > pieces and the control logic would be in Python. > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dineshbvadhia at hotmail.com Sat Feb 7 07:11:14 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 6 Feb 2009 22:11:14 -0800 Subject: [Tutor] Picking up citations Message-ID: Hi! I want to process text that contains citations, in this case in legal documents, and pull-out each individual citation. Here is a sample text: text = "Page 500 Carter v. Jury Commission of Greene County, 396 U.S. 320, 90 S.Ct. 518, 24 L.Ed.2d 549 (1970); Lathe Turner v. Fouche, 396 U.S. 346, 90 S.Ct. 532, 24 L.Ed.2d 567 (1970); White v. Crook, 251 F.Supp. 401 (DCMD Ala.1966). Moreover, the Court has also recognized that the exclusion of a discernible class from jury service injures not only those defendants who belong to the excluded class, but other defendants as well, in that it destroys the possibility that the jury will reflect a representative cross section of the community. In John Doggone Williams v. Florida, 399 U.S. 78, 90 S.Ct. 1893, 234, 26 L.Ed.2d 446 (1970), we sought to delineate some of the essential features of the jury that is guaranteed, in certain circumstances, by the Sixth Amendment. We concluded that it comprehends, inter alia, 'a fair possibility for obtaining a representative cross-section of the community.' 399 U.S., at 100, 90 S.Ct., at 1906.9 Thus if the Sixth Amendment were applicable here, and petitioner were challenging a post-Duncan petit jury, he would clearly have standing to challenge the systematic exclusion of any identifiable group from jury service." The results required are: Carter v. Jury Commission of Greene County, 396 U.S. 320 (1970) Carter v. Jury Commission of Greene County, 90 S.Ct. 518 (1970) Carter v. Jury Commission of Greene County, 24 L.Ed.2d 549 (1970) Lathe Turner v. Fouche, 396 U.S. 346 (1970) Lathe Turner v. Fouche, 90 S.Ct. 532 (1970) Lathe Turner v. Fouche, 24 L.Ed.2d 567 (1970) White v. Crook, 251 F.Supp. 401 (DCMD Ala.1966) John Doggone Williams v. Florida, 399 U.S. 78 (1970) John Doggone Williams v. Florida, 90 S.Ct. 1893, 234 (1970) John Doggone Williams v. Florida, 26 L.Ed.2d 446 (1970) Before attempting to solve this problem I thought I'd first ask if anyone has seen a solution before? If not, I'll follow-up with some rules and an initial attempt. Thanks Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From noufal at nibrahim.net.in Sat Feb 7 09:28:37 2009 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Sat, 07 Feb 2009 13:58:37 +0530 Subject: [Tutor] Python 2.6.1 + Linux Ubuntu (Gutsy Gibbon) In-Reply-To: References: Message-ID: <498D4635.4090606@nibrahim.net.in> Eric Dorsey wrote: > I am trying to teach myself Linux, and so I'm running Ubuntu (Gutsy > Gibbon) as a virtual machine. I went to terminal, started up Python and > realized it was version 2.5 so I thought I'd just upgrade to 2.6.1 After > doing some Googling around, it seems that Ubuntu is highly reliant on > Python 2.5, so upgrading isn't so simple after all. > > Is this just Ubuntu that is so integrated with Python, or all flavors of > Linux? Doesn't this hinder developers who use Ubuntu (and Linux?) as > their primary OS when new versions of Python come out? It's not 'tightly' integrated per se. If you're familiar with Debian/Ubuntu, you can add deb http://ppa.launchpad.net/doko/ubuntu/ gutsy to your /etc/apt/sources.list file and then fetch python2.6 from there. You'll have to invoke it as python2.6. The default /usr/bin/python will still link to python2.5 -- ~noufal http://nibrahim.net.in/ From alan.gauld at btinternet.com Sat Feb 7 10:20:59 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 7 Feb 2009 09:20:59 +0000 (GMT) Subject: [Tutor] Designing a Dialog in Python References: <498BB0B4.8030409@sbcglobal.net> <333efb450902061949u6f907150x10675b014f773ee7@mail.gmail.com> Message-ID: <475179.67297.qm@web86710.mail.ird.yahoo.com> > I'm aware of a visual design tool for Tkinter. There are a couple, none of them great. I use PySpecTcl for a while which, as you might guess, is a Python version of the Tcl tool SpecTcl. The latter was developed by Sun when they were sponsoring Tcl - just before they became obsessed with Java... Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Feb 7 10:27:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 Feb 2009 09:27:39 -0000 Subject: [Tutor] WINSOCK stdin question References: <1c2a2c590902061819s78ba5f9csc97afa6fadd30e7e@mail.gmail.com> Message-ID: "Tom Green" wrote > I am trying to reproduce what Netcat does. >> > sends out a reverse shell (CMD prompt). I have a listening >> > Python socket >> > and I would like to know how I can redirect the CMD prompt to >> > stdin, so I >> > can interact with the host that is sending the shell. Basically >> > this is OK, I think what you want is a python program that will capture the output from your application over a socket and display it as a prompt on the remote host. It will then take input from the user (or maybe just from processing data?) and push it back to your application as input. Is that it? So the python user thinks he has a CMD shell on his local machine but it is really running on the other machine? Almost like ssh but without the encryption and other safety/security features?? Is that what you want? Alan G From alan.gauld at btinternet.com Sat Feb 7 10:38:10 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 7 Feb 2009 09:38:10 -0000 Subject: [Tutor] Closing and Open File--TkFileDialogs References: <498CCD77.7030701@sbcglobal.net> Message-ID: "Wayne Watson" wrote > I'm using asksaveasfilename, and, as I understand it, it returns > the file name to me in write mode. No it retuirns the filename. It is a string. Exactly like you would get from raw_input() in a command line application. It has no "mode", it is just a string. It is up to you to open the file in whatever mode you require. > While I'm at it, I have found a good example program for > TkFileDialog methods, but the description of them on the > internet is pretty shallow. Thats because their functionality is pretty shallow. They open a dialog box and return a filename, directory name or an open file depending on which function you call and which button you press. There is not much you can do with them other than specify the starting folder and the title of the dialog! > For example, An Intro to Tkinter, Lundh's Tkinter pages, Lundh has a couple of pages on them. http://www.pythonware.com/library/tkinter/introduction/standard-dialogs.htm And the Tk man pages give the official documentation but in native Tcl.- but its not hard to translate if you've read Lundh's intro. http://www.tcl.tk/man/tcl8.5/TkCmd/getOpenFile.htm HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sierra_mtnview at sbcglobal.net Sat Feb 7 12:07:11 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 07 Feb 2009 03:07:11 -0800 Subject: [Tutor] Closing and Open File--TkFileDialogs In-Reply-To: <1c2a2c590902061817pbf1946fva9643a0b4983bbc5@mail.gmail.com> References: <498CCD77.7030701@sbcglobal.net> <1c2a2c590902061817pbf1946fva9643a0b4983bbc5@mail.gmail.com> Message-ID: <498D6B5F.10203@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Feb 7 13:51:03 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 7 Feb 2009 07:51:03 -0500 Subject: [Tutor] Closing and Open File--TkFileDialogs In-Reply-To: <498CF920.7000602@sbcglobal.net> References: <498CCD77.7030701@sbcglobal.net> <1c2a2c590902061817pbf1946fva9643a0b4983bbc5@mail.gmail.com> <498CF920.7000602@sbcglobal.net> Message-ID: <1c2a2c590902070451s2e9d6f15r2cd0fc6ee4581c30@mail.gmail.com> On Fri, Feb 6, 2009 at 9:59 PM, Wayne Watson wrote: > Yes, I probably confused the two. The link you mentioned is the one I found > most helpful of the ones I mentioned. Note that his descriptions here, like > others, and to me at least, are minimal. I think, as Alan says, there just is not much to say, and that you are missing, or misinterpreting, what is there. Are you familiar with basic file operations in Python (open, read, write)? > First, > > 60 def asksaveasfile(self): > 61 > 62 """Returns an opened file in write mode.""" > 63 > 64 return tkFileDialog.asksaveasfile(mode='w', **self.file_opt) > > Although, his description in the table doesn't mention the return type, it > would seem like it should be the file name. However, the comment says the > file is open. OK, how do you write on it? Where's the object? OK, I see you > say it is an object. I'm sure you're right, but how do you know? When you call f = open('myfile.txt', 'w') the returned value is a file object representing an opened file in write mode. You write to it by calling the write() method: f.write('some text') The value returned from asksaveasfile() is the same - an object representing an opened file. > > BTW, I printed out the return from line 64 and got: > > > I may be misinterpreting this, but I took it as a file name, while it really > may be the representation for an object. Yes, it is the representation of a file object. Many objects are represented similarly if they don't have a reasonable literal representation. > Next consider: > > 66 def asksaveasfilename(self): > 67 > 68 """Returns an opened file in write mode. > 69 This time the dialog just returns a filename and the file is opened > by your own code. > 70 """ > 71 > 72 # get filename > 73 filename = tkFileDialog.asksaveasfilename(**self.file_opt) > 74 > 75 # open file on your own > 76 if filename: > 77 return open(filename, 'w') > > Here, the file is not opened, and one is on their own. So > output=open(filename,'w') will open it for writing. No difficulty here. Yes, and notice that the description of the returned object is identical to that for asksaveasfile(). Kent From denis.spir at free.fr Sat Feb 7 13:59:31 2009 From: denis.spir at free.fr (spir) Date: Sat, 7 Feb 2009 13:59:31 +0100 Subject: [Tutor] Picking up citations In-Reply-To: References: Message-ID: <20090207135931.42f4d1e7@o> Le Fri, 6 Feb 2009 22:11:14 -0800, "Dinesh B Vadhia" a ?crit : > Hi! I want to process text that contains citations, in this case in legal documents, and pull-out each individual citation. Here is a sample text: > > text = "Page 500 Carter v. Jury Commission of Greene County, 396 U.S. 320, 90 S.Ct. 518, 24 L.Ed.2d 549 (1970); Lathe Turner v. Fouche, 396 U.S. 346, 90 S.Ct. 532, 24 L.Ed.2d 567 (1970); White v. Crook, 251 F.Supp. 401 (DCMD Ala.1966). Moreover, the Court has also recognized that the exclusion of a discernible class from jury service injures not only those defendants who belong to the excluded class, but other defendants as well, in that it destroys the possibility that the jury will reflect a representative cross section of the community. In John Doggone Williams v. Florida, 399 U.S. 78, 90 S.Ct. 1893, 234, 26 L.Ed.2d 446 (1970), we sought to delineate some of the essential features of the jury that is guaranteed, in certain circumstances, by the Sixth Amendment. We concluded that it comprehends, inter alia, 'a fair possibility for obtaining a representative cross-section of the community.' 399 U.S., at 100, 90 S.Ct., at 1906.9 Thus if the Sixth Amendment were applicable here, and petitioner were challenging a post-Duncan petit jury, he would clearly have standing to challenge the systematic exclusion of any identifiable group from jury service." > > The results required are: > > Carter v. Jury Commission of Greene County, 396 U.S. 320 (1970) > Carter v. Jury Commission of Greene County, 90 S.Ct. 518 (1970) > Carter v. Jury Commission of Greene County, 24 L.Ed.2d 549 (1970) > > Lathe Turner v. Fouche, 396 U.S. 346 (1970) > Lathe Turner v. Fouche, 90 S.Ct. 532 (1970) > Lathe Turner v. Fouche, 24 L.Ed.2d 567 (1970) > > White v. Crook, 251 F.Supp. 401 (DCMD Ala.1966) > > John Doggone Williams v. Florida, 399 U.S. 78 (1970) > John Doggone Williams v. Florida, 90 S.Ct. 1893, 234 (1970) > John Doggone Williams v. Florida, 26 L.Ed.2d 446 (1970) > > Before attempting to solve this problem I thought I'd first ask if anyone has seen a solution before? I do not really understand how you could extract *all* of those results from the source text. Anyway, you need a good parsing tool for this. Regexes would probably be rather complicated. I would recommend pyparsing, but probably personal taste... Denis > If not, I'll follow-up with some rules and an initial attempt. > > Thanks > > Dinesh > > ------ la vida e estranya From kent37 at tds.net Sat Feb 7 14:09:24 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 7 Feb 2009 08:09:24 -0500 Subject: [Tutor] Picking up citations In-Reply-To: References: Message-ID: <1c2a2c590902070509j7ed3ddcalf8f7d5b070f73c7e@mail.gmail.com> On Sat, Feb 7, 2009 at 1:11 AM, Dinesh B Vadhia wrote: > Hi! I want to process text that contains citations, in this case in legal > documents, and pull-out each individual citation. > Before attempting to solve this problem I thought I'd first ask if anyone > has seen a solution before? This guy claims to have done it, the link is broken but it might be worth emailing him: http://www.loyalty.org/~schoen/resume-long.html Kent From alan.gauld at btinternet.com Sat Feb 7 15:14:41 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sat, 7 Feb 2009 14:14:41 +0000 (GMT) Subject: [Tutor] WINSOCK stdin question References: <1c2a2c590902061819s78ba5f9csc97afa6fadd30e7e@mail.gmail.com> Message-ID: <137588.99205.qm@web86707.mail.ird.yahoo.com> CCing the list... Please use ReplyAll when replying to tutor mail. ________________________________ From: Tom Green To: Alan Gauld Sent: Saturday, 7 February, 2009 11:42:23 AM Subject: Re: [Tutor] WINSOCK stdin question Yes, this is exactly what I am looking to accomplish. On one host I have an application that is sending cmd.exe to a second host. I want to do like you said, but I can't figure it out. Here is an example of Netcat. http://www.plenz.com/reverseshell Thank you. On Sat, Feb 7, 2009 at 4:27 AM, Alan Gauld wrote: "Tom Green" wrote I am trying to reproduce what Netcat does. > sends out a reverse shell (CMD prompt). I have a listening > Python socket > and I would like to know how I can redirect the CMD prompt to > stdin, so I > can interact with the host that is sending the shell. Basically > this is OK, I think what you want is a python program that will capture the output from your application over a socket and display it as a prompt on the remote host. It will then take input from the user (or maybe just from processing data?) and push it back to your application as input. Is that it? So the python user thinks he has a CMD shell on his local machine but it is really running on the other machine? Almost like ssh but without the encryption and other safety/security features?? Is that what you want? Alan G _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Feb 7 15:21:24 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 7 Feb 2009 09:21:24 -0500 Subject: [Tutor] Picking up citations In-Reply-To: References: Message-ID: <1c2a2c590902070621p19162d25jeb5b3676904ef2ad@mail.gmail.com> On Sat, Feb 7, 2009 at 1:11 AM, Dinesh B Vadhia wrote: > Hi! I want to process text that contains citations, in this case in legal > documents, and pull-out each individual citation. Here is a sample text: > The results required are: > > Carter v. Jury Commission of Greene County, 396 U.S. 320 (1970) > Carter v. Jury Commission of Greene County, 90 S.Ct. 518 (1970) > Carter v. Jury Commission of Greene County, 24 L.Ed.2d 549 (1970) > > Lathe Turner v. Fouche, 396 U.S. 346 (1970) > Lathe Turner v. Fouche, 90 S.Ct. 532 (1970) > Lathe Turner v. Fouche, 24 L.Ed.2d 567 (1970) > > White v. Crook, 251 F.Supp. 401 (DCMD Ala.1966) > > John Doggone Williams v. Florida, 399 U.S. 78 (1970) > John Doggone Williams v. Florida, 90 S.Ct. 1893, 234 (1970) > John Doggone Williams v. Florida, 26 L.Ed.2d 446 (1970) Here is a close solution using pyparsing. It only gets the last word of the first name, and it doesn't handle multiple page numbers so it missing J. D. Williams entirely. The name is hard - how do you know that "Page 500" is not part of "Carter" and "In" is not part of "John Doggone Williams"? The page numbers seem possible in theory but I don't know how to get pyparsing to do it. from pprint import pprint as pp from pyparsing import * text = "" # your text Name1 = Word(alphas).setResultsName('name1') Name2 = Combine(OneOrMore(Word(alphas)), joinString=' ', adjacent=False).setResultsName('name2') Volume = Word(nums).setResultsName('volume') Reporter = Word(alphas, alphanums+".").setResultsName('reporter') Page = Word(nums).setResultsName('page') VolumeCitation = (Volume + Reporter + Page).setResultsName('volume_citation', listAllMatches=True) VolumeCitations = delimitedList(VolumeCitation) Date = (Suppress('(') + Combine(CharsNotIn(')')).setResultsName('date') + Suppress(')')) FullCitation = Name1 + Suppress('v.') + Name2 + Suppress(',') + VolumeCitations + Date for item in FullCitation.scanString(text): fc = item[0] # Uncomment the following to see the raw parse results # pp(fc) # print # print fc.name1 # print fc.name2 # for vc in fc.volume_citation: # pp(vc) for vc in fc.volume_citation: print '%s v. %s, %s %s %s (%s)' % (fc.name1, fc.name2, vc.volume, vc.reporter, vc.page, fc.date) print The output is: Carter v. Jury Commission of Greene County, 396 U.S. 320 (1970) Carter v. Jury Commission of Greene County, 90 S.Ct. 518 (1970) Carter v. Jury Commission of Greene County, 24 L.Ed.2d 549 (1970) Turner v. Fouche, 396 U.S. 346 (1970) Turner v. Fouche, 90 S.Ct. 532 (1970) Turner v. Fouche, 24 L.Ed.2d 567 (1970) White v. Crook, 251 F.Supp. 401 (DCMD Ala.1966) Kent From gslindstrom at gmail.com Sat Feb 7 13:56:22 2009 From: gslindstrom at gmail.com (gslindstrom) Date: Sat, 7 Feb 2009 06:56:22 -0600 Subject: [Tutor] PyCon 2009 Tutorial Days Message-ID: Registration for PyCon 2009 (US) is open. Because of the popularity of the tutorials in years past, this year features 2 days of tutorials (32 total class on Wednesday, March 25 and Thursday, March 26) including: - 2 tracks on Introduciton to Python - Working with Excel spreadsheets - GIS with Python - Django - Concurrency and Kamaelia - Testing - SQLAlchemy - Advanced topics - much, much more These classes are being presented by some of the smartest cookies in the Python community and are 3-hours each (with break). You get to rub shoulders with other Python programmers who share your interests and all sessions have time for you to ask questions. There is a (modest) cost to attend, but you will get great training as well as class notes. We even feed you lunch and provide snacks during the breaks. Click http://us.pycon.org/2009/about/ for more information. Questions? Email us at pycon-tutorials at python.org. Greg Lindstrom Tutorial Coordinator -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sat Feb 7 16:09:33 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 07 Feb 2009 07:09:33 -0800 Subject: [Tutor] Closing and Open File--TkFileDialogs In-Reply-To: <1c2a2c590902070451s2e9d6f15r2cd0fc6ee4581c30@mail.gmail.com> References: <498CCD77.7030701@sbcglobal.net> <1c2a2c590902061817pbf1946fva9643a0b4983bbc5@mail.gmail.com> <498CF920.7000602@sbcglobal.net> <1c2a2c590902070451s2e9d6f15r2cd0fc6ee4581c30@mail.gmail.com> Message-ID: <498DA42D.8040306@sbcglobal.net> An HTML attachment was scrubbed... URL: From srilyk at gmail.com Sat Feb 7 16:23:30 2009 From: srilyk at gmail.com (W W) Date: Sat, 7 Feb 2009 09:23:30 -0600 Subject: [Tutor] Closing and Open File--TkFileDialogs In-Reply-To: <498DA42D.8040306@sbcglobal.net> References: <498CCD77.7030701@sbcglobal.net> <1c2a2c590902061817pbf1946fva9643a0b4983bbc5@mail.gmail.com> <498CF920.7000602@sbcglobal.net> <1c2a2c590902070451s2e9d6f15r2cd0fc6ee4581c30@mail.gmail.com> <498DA42D.8040306@sbcglobal.net> Message-ID: <333efb450902070723x295e21c9r7d861a37c7e94981@mail.gmail.com> On Sat, Feb 7, 2009 at 9:09 AM, Wayne Watson wrote: > Yes, amazingly enough, I'm quite familiar with basic file operations. :-) > I'm certainly no expert at all variations of it. > > Now for a related question. I'm using Win XP. One of the arguments is the > default_path. I would like it to be the same folder the program is in. How > do I do that? "c:/.", "./", or some variation? > IIRC you would use "." In [4]: import os In [5]: os.curdir Out[5]: '.' or of course, os.curdir would probably be more portable. And just a little tidbit I discovered while working with a program that would change directories, but I was running from inside Ipython, if you add this to the beginning of your file: import os startpath = os.path.abspath(os.curdir) and then this to the end: os.chdir(startpath) then it will keep your ipython environment in the directory you run the file from. HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From dineshbvadhia at hotmail.com Sat Feb 7 17:53:55 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 7 Feb 2009 08:53:55 -0800 Subject: [Tutor] Picking up citations In-Reply-To: <1c2a2c590902070621p19162d25jeb5b3676904ef2ad@mail.gmail.com> References: <1c2a2c590902070621p19162d25jeb5b3676904ef2ad@mail.gmail.com> Message-ID: Wow Kent, what a great start! I found this http://mail.python.org/pipermail/python-list/2006-April/376149.html which lays out some patterns of legal citations ie. 1. Two names, consisting of one or more words, separated by a "v." 2. One, two, or three citations, each of which has a volume number ("90") followed by a Reporter name ("U.S." or "S.Ct." or "L.Ed."), which consists of one or two words always ending with a ".", followed by a page number ("1893") 3. Each citation may contain a comma and a second page number (", 234 ") 4. Optionally, a parenthesized year ("(1970)") or optional information in parentheses ("(DCMD Ala.1966)") 5. An ending "." Some things I've noticed include: * A sequence of DIFFERENT citations are separated by a ';' as in Carter v. Jury Commission of Greene County, 396 U.S. 320, 90 S.Ct. 518, 24 L.Ed.2d 549 (1970); Lathe Turner v. Fouche, 396 U.S. 346, 90 S.Ct. 532, 24 L.Ed.2d 567 (1970); White v. Crook, 251 F.Supp. 401 (DCMD Ala.1966) with the first separation containing the names (separated by a v.) * A sequence of SIMILAR citations are separated by a ',' as in John Doggone Williams v. Florida, 399 U.S. 78, 90 S.Ct. 1893, 234, 26 L.Ed.2d 446 (1970) with the first separation containing the names (separated by a v.) I was pondering the same issue about names ie. how do you know that "Page 500" is not part of "Carter". My thought was to start from the "v.", step backwards a word at a time, assume that the first name is valid, for all subsequent words check if the last character of a word contained the digits [0-9] or these punctuation marks [.,:;], if so, then it was unlikely to be part of the name. I've changed the sample text to include examples of multiple page references: text = "Page 500 Carter v. Jury Commission of Greene County, 396 U.S. 320 876, 90 S.Ct. 518, 24 L.Ed.2d 549 (1970); Lathe Turner v. Fouche, 396 U.S. 346, 90 S.Ct. 532, 24 L.Ed.2d 567 (1970); White v. Crook, 251 F.Supp. 401 (DCMD Ala.1966). Moreover, the Court has also recognized that the exclusion of a discernible class from jury service injures not only those defendants who belong to the excluded class, but other defendants as well, in that it destroys the possibility that the jury will reflect a representative cross section of the community. In John Doggone Williams v. Florida, 399 U.S. 78, 90 S.Ct. 1893, 234, 26 L.Ed.2d 446 159-60 (1970), we sought to delineate some of the essential features of the jury that is guaranteed, in certain circumstances, by the Sixth Amendment. We concluded that it comprehends, inter alia, 'a fair possibility for obtaining a representative cross-section of the community.' 399 U.S., at 100, 90 S.Ct., at 1906.9 Thus if the Sixth Amendment were applicable here, and petitioner were challenging a post-Duncan petit jury, he would clearly have standing to challenge the systematic exclusion of any identifiable group from jury service." Okay, I'd better get to grips with pyparsing! Dinesh From: Kent Johnson Sent: Saturday, February 07, 2009 6:21 AM To: Dinesh B Vadhia Cc: tutor at python.org Subject: Re: [Tutor] Picking up citations On Sat, Feb 7, 2009 at 1:11 AM, Dinesh B Vadhia wrote: > Hi! I want to process text that contains citations, in this case in legal > documents, and pull-out each individual citation. Here is a sample text: > The results required are: > > Carter v. Jury Commission of Greene County, 396 U.S. 320 (1970) > Carter v. Jury Commission of Greene County, 90 S.Ct. 518 (1970) > Carter v. Jury Commission of Greene County, 24 L.Ed.2d 549 (1970) > > Lathe Turner v. Fouche, 396 U.S. 346 (1970) > Lathe Turner v. Fouche, 90 S.Ct. 532 (1970) > Lathe Turner v. Fouche, 24 L.Ed.2d 567 (1970) > > White v. Crook, 251 F.Supp. 401 (DCMD Ala.1966) > > John Doggone Williams v. Florida, 399 U.S. 78 (1970) > John Doggone Williams v. Florida, 90 S.Ct. 1893, 234 (1970) > John Doggone Williams v. Florida, 26 L.Ed.2d 446 (1970) Here is a close solution using pyparsing. It only gets the last word of the first name, and it doesn't handle multiple page numbers so it missing J. D. Williams entirely. The name is hard - how do you know that "Page 500" is not part of "Carter" and "In" is not part of "John Doggone Williams"? The page numbers seem possible in theory but I don't know how to get pyparsing to do it. from pprint import pprint as pp from pyparsing import * text = "" # your text Name1 = Word(alphas).setResultsName('name1') Name2 = Combine(OneOrMore(Word(alphas)), joinString=' ', adjacent=False).setResultsName('name2') Volume = Word(nums).setResultsName('volume') Reporter = Word(alphas, alphanums+".").setResultsName('reporter') Page = Word(nums).setResultsName('page') VolumeCitation = (Volume + Reporter + Page).setResultsName('volume_citation', listAllMatches=True) VolumeCitations = delimitedList(VolumeCitation) Date = (Suppress('(') + Combine(CharsNotIn(')')).setResultsName('date') + Suppress(')')) FullCitation = Name1 + Suppress('v.') + Name2 + Suppress(',') + VolumeCitations + Date for item in FullCitation.scanString(text): fc = item[0] # Uncomment the following to see the raw parse results # pp(fc) # print # print fc.name1 # print fc.name2 # for vc in fc.volume_citation: # pp(vc) for vc in fc.volume_citation: print '%s v. %s, %s %s %s (%s)' % (fc.name1, fc.name2, vc.volume, vc.reporter, vc.page, fc.date) print The output is: Carter v. Jury Commission of Greene County, 396 U.S. 320 (1970) Carter v. Jury Commission of Greene County, 90 S.Ct. 518 (1970) Carter v. Jury Commission of Greene County, 24 L.Ed.2d 549 (1970) Turner v. Fouche, 396 U.S. 346 (1970) Turner v. Fouche, 90 S.Ct. 532 (1970) Turner v. Fouche, 24 L.Ed.2d 567 (1970) White v. Crook, 251 F.Supp. 401 (DCMD Ala.1966) Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Feb 7 18:01:34 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 7 Feb 2009 12:01:34 -0500 Subject: [Tutor] Closing and Open File--TkFileDialogs In-Reply-To: <498DA42D.8040306@sbcglobal.net> References: <498CCD77.7030701@sbcglobal.net> <1c2a2c590902061817pbf1946fva9643a0b4983bbc5@mail.gmail.com> <498CF920.7000602@sbcglobal.net> <1c2a2c590902070451s2e9d6f15r2cd0fc6ee4581c30@mail.gmail.com> <498DA42D.8040306@sbcglobal.net> Message-ID: <1c2a2c590902070901ra0d1af4pf853fe550fc9599f@mail.gmail.com> On Sat, Feb 7, 2009 at 10:09 AM, Wayne Watson wrote: > I may be mistaken, but I do not think any of the documentation I've seen on > these two methods states what type of result is produced. That is really my > point. I had to find out the hard way by printing out the result. I'm mystified. "Returns an opened file in read mode." seems clear and explicit to me, as is "You also have two variants of the function, one to get an opened file which you can use to save your data and another to get a file name in order to open the file on your own." Kent From sierra_mtnview at sbcglobal.net Sat Feb 7 18:31:25 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 07 Feb 2009 09:31:25 -0800 Subject: [Tutor] Closing and Open File--TkFileDialogs In-Reply-To: <1c2a2c590902070901ra0d1af4pf853fe550fc9599f@mail.gmail.com> References: <498CCD77.7030701@sbcglobal.net> <1c2a2c590902061817pbf1946fva9643a0b4983bbc5@mail.gmail.com> <498CF920.7000602@sbcglobal.net> <1c2a2c590902070451s2e9d6f15r2cd0fc6ee4581c30@mail.gmail.com> <498DA42D.8040306@sbcglobal.net> <1c2a2c590902070901ra0d1af4pf853fe550fc9599f@mail.gmail.com> Message-ID: <498DC56D.7070706@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Feb 7 18:43:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 7 Feb 2009 12:43:05 -0500 Subject: [Tutor] Picking up citations In-Reply-To: References: <1c2a2c590902070621p19162d25jeb5b3676904ef2ad@mail.gmail.com> Message-ID: <1c2a2c590902070943n38e6f538l6007769edc86f8df@mail.gmail.com> On Sat, Feb 7, 2009 at 11:53 AM, Dinesh B Vadhia wrote: > Wow Kent, what a great start! > > I found this > http://mail.python.org/pipermail/python-list/2006-April/376149.html which > lays out some patterns of legal citations ie. Here is another good reference: http://philip.greenspun.com/politics/litigation/reading-cites.html > 1. Two names, consisting of one or more words, separated by a "v." > 2. One, two, or three citations, each of which has a volume number ("90") > followed by a Reporter name ("U.S." or "S.Ct." or "L.Ed."), which consists > of one or two words always ending with a ".", followed by a page number > ("1893") According to the reference I cite above, the Reporter name does not have to include periods, his examples include US and Tenn as reporters. > 3. Each citation may contain a comma and a second page number (", 234 ") > 4. Optionally, a parenthesized year ("(1970)") or optional information in > parentheses ("(DCMD Ala.1966)") > 5. An ending "." Or comma; this seems to be a grammatical element of the enclosing sentence rather than part of the citation. > I was pondering the same issue about names ie. how do you know that "Page > 500" is not part of "Carter". My thought was to start from the "v.", step > backwards a word at a time, assume that the first name is valid, for all > subsequent words check if the last character of a word contained the digits > [0-9] or these punctuation marks [.,:;], if so, then it was unlikely to be > part of the name. That won't help with "In John Doggone Williams". I can imagine a name with punctuation, also, e.g. St. John's Lumber. > > I've changed the sample text to include examples of multiple page > references: Actually you had one already. > Okay, I'd better get to grips with pyparsing! Pyparsing won't backtrack which may be a disadvantage here in parsing the extra page numbers. Here is some comment: http://mail.python.org/pipermail/python-list/2007-November/464726.html Kent From sierra_mtnview at sbcglobal.net Sat Feb 7 21:20:34 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 07 Feb 2009 12:20:34 -0800 Subject: [Tutor] Exec(uting) Code in a Dictionary? Message-ID: <498DED12.3090001@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Feb 7 21:40:43 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 7 Feb 2009 15:40:43 -0500 Subject: [Tutor] Exec(uting) Code in a Dictionary? In-Reply-To: <498DED12.3090001@sbcglobal.net> References: <498DED12.3090001@sbcglobal.net> Message-ID: <1c2a2c590902071240y36f3d1c3i942364bfebe0cd1b@mail.gmail.com> On Sat, Feb 7, 2009 at 3:20 PM, Wayne Watson wrote: > Is it possible to do some thing like this with exec: > > dcon0 = {'long':120.00, 'lat': 39.00, 'year': 2009} > > Can I use exec or eval simply on this to get: > long = 120.00 > lat = 39.00 > year = 2009 > > That is, initialize each of these three variables. Yes, without exec: long = dcon0['long'] etc. but why? If you know the keys, you can hard-code the assignments as above. If you don't know the keys, you are probably better off leaving the values in the dict. Kent From kent37 at tds.net Sat Feb 7 22:19:14 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 7 Feb 2009 16:19:14 -0500 Subject: [Tutor] Picking up citations In-Reply-To: <1c2a2c590902070943n38e6f538l6007769edc86f8df@mail.gmail.com> References: <1c2a2c590902070621p19162d25jeb5b3676904ef2ad@mail.gmail.com> <1c2a2c590902070943n38e6f538l6007769edc86f8df@mail.gmail.com> Message-ID: <1c2a2c590902071319u5e984d5dpf2a140b654c03e2f@mail.gmail.com> It turns out you can use Or expressions to cause a kind of backtracking in Pyparsing. This is very close to what you want: Name1 = Forward() Name1 << Combine(Word(alphas) + Name1 | Word(alphas) + Suppress('v.'), joinString=' ', adjacent=False).setResultsName('name1') Name2 = Combine(OneOrMore(Word(alphas)), joinString=' ', adjacent=False).setResultsName('name2') Volume = Word(nums).setResultsName('volume') Reporter = Word(alphas, alphanums+".").setResultsName('reporter') Page = Word(nums).setResultsName('page') Page2 = (',' + Word(nums)).setResultsName('page2') VolumeCitation = (Volume + Reporter + Page).setResultsName('volume_citation', listAllMatches=True) VolumeCitations = Forward() VolumeCitations << ( Combine(VolumeCitation + Page2, joinString=' ', adjacent=False).setResultsName('volume_citation2') + Suppress(',') + VolumeCitations | VolumeCitation + Suppress(',') + VolumeCitations | Combine(VolumeCitation + Page2, joinString=' ', adjacent=False).setResultsName('volume_citation2') | VolumeCitation ) Date = (Suppress('(') + Combine(CharsNotIn(')')).setResultsName('date') + Suppress(')')) FullCitation = Name1 + Name2 + Suppress(',') + VolumeCitations + Date for item in FullCitation.scanString(text): fc = item[0] # Uncomment the following to see the raw parse results # pp(fc) # print # print fc.name1 # print fc.name2 # for vc in fc.volume_citation: # pp(vc) # If name1 is multiple words it is enclosed in a ParseResults name1 = fc.name1 if isinstance(name1, ParseResults): name1 = name1[0] for vc in fc.volume_citation: print '%s v. %s, %s %s %s (%s)' % (name1, fc.name2, vc.volume, vc.reporter, vc.page, fc.date) for vc2 in fc.volume_citation2: print '%s v. %s, %s (%s)' % (name1, fc.name2, vc2, fc.date) print Output: Carter v. Jury Commission of Greene County, 396 U.S. 320 (1970) Carter v. Jury Commission of Greene County, 90 S.Ct. 518 (1970) Carter v. Jury Commission of Greene County, 24 L.Ed.2d 549 (1970) Lathe Turner v. Fouche, 396 U.S. 346 (1970) Lathe Turner v. Fouche, 90 S.Ct. 532 (1970) Lathe Turner v. Fouche, 24 L.Ed.2d 567 (1970) White v. Crook, 251 F.Supp. 401 (DCMD Ala.1966) In John Doggone Williams v. Florida, 399 U.S. 78 (1970) In John Doggone Williams v. Florida, 26 L.Ed.2d 446 (1970) In John Doggone Williams v. Florida, 90 S.Ct. 1893 , 234 (1970) It is correct except for the inclusion of "In" in the name and the extra space before the comma separating the page numbers in the last citation. Don't ask me why I did this :-) Kent From sierra_mtnview at sbcglobal.net Sat Feb 7 22:21:38 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 07 Feb 2009 13:21:38 -0800 Subject: [Tutor] Exec(uting) Code in a Dictionary? In-Reply-To: <1c2a2c590902071240y36f3d1c3i942364bfebe0cd1b@mail.gmail.com> References: <498DED12.3090001@sbcglobal.net> <1c2a2c590902071240y36f3d1c3i942364bfebe0cd1b@mail.gmail.com> Message-ID: <498DFB62.6090606@sbcglobal.net> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Sat Feb 7 22:37:04 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sat, 7 Feb 2009 13:37:04 -0800 Subject: [Tutor] Picking up citations In-Reply-To: <1c2a2c590902071319u5e984d5dpf2a140b654c03e2f@mail.gmail.com> References: <1c2a2c590902070621p19162d25jeb5b3676904ef2ad@mail.gmail.com> <1c2a2c590902070943n38e6f538l6007769edc86f8df@mail.gmail.com> <1c2a2c590902071319u5e984d5dpf2a140b654c03e2f@mail.gmail.com> Message-ID: <40af687b0902071337i645998ej4f85cd4e384754fb@mail.gmail.com> On Sat, Feb 7, 2009 at 1:19 PM, Kent Johnson wrote: > > It is correct except for the inclusion of "In" in the name and the > extra space before the comma separating the page numbers in the last > citation. > As I've been reading along, I've been thinking that the word "In" qualifies as a "magic word" - it's extremely unlikely to be part of a name, but also extremely likely to occur just before a citation, so maybe it deserves a rule of its own. I know we don't like magic numbers, and magic words aren't much better - but this seems like a good place to make an exception. Maybe, to make it more palatable, create a list of "magic words" (initially, "In" would be the only member)? -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Feb 7 22:42:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 7 Feb 2009 16:42:05 -0500 Subject: [Tutor] Exec(uting) Code in a Dictionary? In-Reply-To: <498DFB62.6090606@sbcglobal.net> References: <498DED12.3090001@sbcglobal.net> <1c2a2c590902071240y36f3d1c3i942364bfebe0cd1b@mail.gmail.com> <498DFB62.6090606@sbcglobal.net> Message-ID: <1c2a2c590902071342k366a9dcai419f6ffd989a13b1@mail.gmail.com> On Sat, Feb 7, 2009 at 4:21 PM, Wayne Watson wrote: > Here's more detail. What I was hoping for was something like: > > exec "=" dcon > > This is fictitious of course, but would mean assign the values in [1] to > [0]. > Yes, it would be easy to loop and assemble elements into a string that would > be executed by exec (or eval), or use some assignment line like your > example. > > I have 30 or more of such assignments, and I would prefer not to have to > write them as assignments. The end purpose here is to produce a config file, > assign initial values, and change values. For example, the (text) file might > look initially like: > long 120.00 > lat 39.00 > year 2009 Do you know about the ConfigParser module? http://docs.python.org/library/configparser.html > These would be written to the file by looping through dcon. Another time, I > might want to initialize these variables within the program, in the form > self.long = 120.00, etc., Ok, that is different than long = 120.00 because the variable is an attribute of self. Try this, it will take all the items in dcon and set them as attributes of self: for key, value in dcon: setattr(self, key, value) Kent From sierra_mtnview at sbcglobal.net Sat Feb 7 22:50:01 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 07 Feb 2009 13:50:01 -0800 Subject: [Tutor] Exec(uting) Code in a Dictionary? In-Reply-To: <1c2a2c590902071342k366a9dcai419f6ffd989a13b1@mail.gmail.com> References: <498DED12.3090001@sbcglobal.net> <1c2a2c590902071240y36f3d1c3i942364bfebe0cd1b@mail.gmail.com> <498DFB62.6090606@sbcglobal.net> <1c2a2c590902071342k366a9dcai419f6ffd989a13b1@mail.gmail.com> Message-ID: <498E0209.7080202@sbcglobal.net> An HTML attachment was scrubbed... URL: From dineshbvadhia at hotmail.com Sun Feb 8 00:15:47 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Sat, 7 Feb 2009 15:15:47 -0800 Subject: [Tutor] Picking up citations In-Reply-To: <1c2a2c590902070621p19162d25jeb5b3676904ef2ad@mail.gmail.com> <1c2a2c590902070943n38e6f538l6007769edc86f8df@mail.gmail.com> <1c2a2c590902071319u5e984d5dpf2a140b654c03e2f@mail.gmail.com> References: <1c2a2c590902070621p19162d25jeb5b3676904ef2ad@mail.gmail.com> <1c2a2c590902070943n38e6f538l6007769edc86f8df@mail.gmail.com> <1c2a2c590902071319u5e984d5dpf2a140b654c03e2f@mail.gmail.com> Message-ID: Kent I've just thought that as an initial attempt, the last name (of the name before the v.) is sufficient ie. "Turner v. Fouche, 396 U.S. 346 (1970)" instead of "Lathe Turner v. Fouche, 396 U.S. 346 (1970)" as we are only using the citations internally and not displaying publicly. That solves the first name problem. The remaining problem is picking up multiple pages in a citation ie. "John Doggone Williams v. Florida, 399 U.S. 78, 90 S.Ct. 1893, 234, 26 L.Ed.2d 446 (1970)" ... and a variation of this is: "John Doe Agency v. John Doe Corp., 493 U.S. 146, 159-60 (1934)" I didn't know about pyparsing which appears to be very powerful and have joined their list. Thank-you for your help. Dinesh From: Kent Johnson Sent: Saturday, February 07, 2009 1:19 PM To: Dinesh B Vadhia Cc: tutor at python.org Subject: Re: [Tutor] Picking up citations It turns out you can use Or expressions to cause a kind of backtracking in Pyparsing. This is very close to what you want: Name1 = Forward() Name1 << Combine(Word(alphas) + Name1 | Word(alphas) + Suppress('v.'), joinString=' ', adjacent=False).setResultsName('name1') Name2 = Combine(OneOrMore(Word(alphas)), joinString=' ', adjacent=False).setResultsName('name2') Volume = Word(nums).setResultsName('volume') Reporter = Word(alphas, alphanums+".").setResultsName('reporter') Page = Word(nums).setResultsName('page') Page2 = (',' + Word(nums)).setResultsName('page2') VolumeCitation = (Volume + Reporter + Page).setResultsName('volume_citation', listAllMatches=True) VolumeCitations = Forward() VolumeCitations << ( Combine(VolumeCitation + Page2, joinString=' ', adjacent=False).setResultsName('volume_citation2') + Suppress(',') + VolumeCitations | VolumeCitation + Suppress(',') + VolumeCitations | Combine(VolumeCitation + Page2, joinString=' ', adjacent=False).setResultsName('volume_citation2') | VolumeCitation ) Date = (Suppress('(') + Combine(CharsNotIn(')')).setResultsName('date') + Suppress(')')) FullCitation = Name1 + Name2 + Suppress(',') + VolumeCitations + Date for item in FullCitation.scanString(text): fc = item[0] # Uncomment the following to see the raw parse results # pp(fc) # print # print fc.name1 # print fc.name2 # for vc in fc.volume_citation: # pp(vc) # If name1 is multiple words it is enclosed in a ParseResults name1 = fc.name1 if isinstance(name1, ParseResults): name1 = name1[0] for vc in fc.volume_citation: print '%s v. %s, %s %s %s (%s)' % (name1, fc.name2, vc.volume, vc.reporter, vc.page, fc.date) for vc2 in fc.volume_citation2: print '%s v. %s, %s (%s)' % (name1, fc.name2, vc2, fc.date) print Output: Carter v. Jury Commission of Greene County, 396 U.S. 320 (1970) Carter v. Jury Commission of Greene County, 90 S.Ct. 518 (1970) Carter v. Jury Commission of Greene County, 24 L.Ed.2d 549 (1970) Lathe Turner v. Fouche, 396 U.S. 346 (1970) Lathe Turner v. Fouche, 90 S.Ct. 532 (1970) Lathe Turner v. Fouche, 24 L.Ed.2d 567 (1970) White v. Crook, 251 F.Supp. 401 (DCMD Ala.1966) In John Doggone Williams v. Florida, 399 U.S. 78 (1970) In John Doggone Williams v. Florida, 26 L.Ed.2d 446 (1970) In John Doggone Williams v. Florida, 90 S.Ct. 1893 , 234 (1970) It is correct except for the inclusion of "In" in the name and the extra space before the comma separating the page numbers in the last citation. Don't ask me why I did this :-) Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From cclpianos at comcast.net Sun Feb 8 04:45:25 2009 From: cclpianos at comcast.net (cclpianos at comcast.net) Date: Sat, 7 Feb 2009 20:45:25 -0700 Subject: [Tutor] Completed project. Is this correct? Can I simplify my formulas? Message-ID: <4070A0F9-63DC-4BBF-80FA-6D369B65672D@comcast.net> Hello, I've enclosed a completed project (my first!) and would like to know of it's accuracy. Also, what I could do to simplify the language. Thanks, Pat -------------- next part -------------- A non-text attachment was scrubbed... Name: Grant.py Type: text/x-python-script Size: 2935 bytes Desc: not available URL: From cclpianos at comcast.net Sun Feb 8 05:02:21 2009 From: cclpianos at comcast.net (cclpianos at comcast.net) Date: Sat, 7 Feb 2009 21:02:21 -0700 Subject: [Tutor] Oops! I just corrected my file:RE Completed project is this correct? Message-ID: <47B95607-D82C-4C70-B16B-D4BE610BF633@comcast.net> Forget the first, this is the corrected version. Thanks, Pat -------------- next part -------------- A non-text attachment was scrubbed... Name: Grant.py Type: text/x-python-script Size: 2901 bytes Desc: not available URL: From haztang17 at gmail.com Sun Feb 8 07:09:04 2009 From: haztang17 at gmail.com (Hi) Date: Sat, 7 Feb 2009 22:09:04 -0800 Subject: [Tutor] Question on how to open other programs and files Message-ID: I have a question regarding how to open other programs and files in Python code. I am creating a simple interface and I want it to be able to open other files, such as a text file or a pdf file. However, those files are usually associated with other programs - for instance, gedit for text and document viewer for pdf (I am using Ubuntu 8.10). What syntax or commands do I need in order to do so. I've used os.popen in Windows XP and it works fine, but the same code does not work in Ubuntu. This is the part of my code that deals with opening files/programs: def openfile(self, event): result = os.popen("home/user/textfile.txt") In the terminal it simply says, sh: home/user/textfile.txt: not found. And I have already set permissions via chmod +x on the files of my choosing. Any help would be greatly appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Sun Feb 8 09:56:03 2009 From: denis.spir at free.fr (spir) Date: Sun, 8 Feb 2009 09:56:03 +0100 Subject: [Tutor] Exec(uting) Code in a Dictionary? In-Reply-To: <498E0209.7080202@sbcglobal.net> References: <498DED12.3090001@sbcglobal.net> <1c2a2c590902071240y36f3d1c3i942364bfebe0cd1b@mail.gmail.com> <498DFB62.6090606@sbcglobal.net> <1c2a2c590902071342k366a9dcai419f6ffd989a13b1@mail.gmail.com> <498E0209.7080202@sbcglobal.net> Message-ID: <20090208095603.70a1f24e@o> Le Sat, 07 Feb 2009 13:50:01 -0800, Wayne Watson a ?crit : > That's something for me to ponder, setattr. I'd rather not go off and pick up on something like ConfigParser at this stage. I'd like to keep this code somewhat simple and easy to understand, but yet have some flexibility for changes. Dicts are very handy because they are still starightforwardly usable when a name/key is unknown at design time, in addition to the value: d["foo"] = val d[name] = val A typical use is precisely reading data from a config file where both names and values are data, meaning defined by the user. So that you cannot directly store them in a custom config object writing: config.name = val Setattr addresses this need: setattr(config,name,val) So that finally using an object or a dict are more or less equivalent, rather a programmer choice. * dict is slightly easier * object allows slightly lighter code (obj.name vs obj["name"]) and a syntax better consistent with the rest of python * additionnal data attibutes, custom behaviour Denis ------ la vida e estranya From alan.gauld at btinternet.com Sun Feb 8 10:03:07 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 8 Feb 2009 09:03:07 -0000 Subject: [Tutor] Question on how to open other programs and files References: Message-ID: "Hi" wrote >I have a question regarding how to open other programs and files in >Python > code. I am creating a simple interface and I want it to be able to > open > other files, such as a text file or a pdf file. OK, lets clarify something first. When you say open do you mean you want to open the file in Python such that you can read the data into your python program? Or do you mean you want to open the file in the default application on your computer. In other words for a pdf file do you want to read the data in the file or do you want to launch Acrobat on the file? > usually associated with other programs - for instance, gedit for > text and > document viewer for pdf (I am using Ubuntu 8.10). What syntax or > commands do > I need in order to do so. The "official" approach to laumnching applications is to use the subprocess module. This replaces several other mechanisms which are now considred obsolete. > I've used os.popen in Windows XP and it works > fine, but the same code does not work in Ubuntu. It should work but subprocess replaces popen. > def openfile(self, event): > result = os.popen("home/user/textfile.txt") > > In the terminal it simply says, sh: home/user/textfile.txt: not > found. I suspect your path is wrong. Notice you are not using an absolute path but a relative path, so unless you have a directory called home in your current directory it will fail. But this is not opening the text file this is trying to execute the text file and that is unlikely to work on Ubuntu. (In Windows it will launch the default app - probably Notepad) So back to the original question: do you want to open the t5extfile in Python or do you want to launch gedit from Python? Untiol you resolve that conundrum we can't really help much more. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sun Feb 8 10:08:09 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 8 Feb 2009 09:08:09 -0000 Subject: [Tutor] WINSOCK stdin question References: <1c2a2c590902061819s78ba5f9csc97afa6fadd30e7e@mail.gmail.com> <137588.99205.qm@web86707.mail.ird.yahoo.com> Message-ID: > Yes, this is exactly what I am looking to accomplish. > On one host I have an application that is sending > cmd.exe to a second host. OK, how is that application doing that? What port is it sending the output to on the remote host? You say CMD.exe but that is the windows shell. There is no way to direct it to another host directly so how is this application redirecting cmd.exe? Does it have a name? You might need to write two programs, one on the host computer to run and redirect cmd.exe to the remote PC and then relay the returned data as input to CMD.exe as well as another app on the remote PC to pick up the incoming data and relay the user input back down the socket. We need to know a lot more about how this thing is glued together. Alan G. From cclpianos at comcast.net Sun Feb 8 16:24:06 2009 From: cclpianos at comcast.net (cclpianos at comcast.net) Date: Sun, 8 Feb 2009 08:24:06 -0700 Subject: [Tutor] Is this correct? Message-ID: HI, I just realized that I shouldn't enclose my project in an attachment. This is my first attempt to string together py-code. Is this correct? And how would a pro word this? It seems like an awful lot of code for such a small task. Thanks in advance, Pat ///////////////////////////////////////////////////////////// # Problem Set 1 # Name P Wethington # Collaborators :None # Time #1:00 # This is a program intended to compute the number of students who will benefit from a grant, also what # amount the last student will receive. One grant is given every other year until the funds run out. principal = 500000 # Starting fund amount. balance = principal interestRate = .05 # Interest rate added to the principal annaully. tuition = -34986 # Starting tuition fee tuitionInc = .041# The annual increase applied to the tuition. count = 0 # keeps me informed on the number of students benefitting from this grant. if count == 0: print principal, "Is the starting principal" # This is to show the starting balance. print -tuition, "Is the starting tuition." print principal + tuition," the amount remaining after first tuition deduction. " balance = principal + tuition count = count + 1 if count ==1: newPrincipal = (balance * interestRate) # calculates the amount added to the fund print newPrincipal," Interest added to fund for one year. " print balance + newPrincipal, "is the new balance." count = count + 1 newBalance = balance + newPrincipal while principal > 0 + -tuition: if count > 1: newTuition = (tuition * tuitionInc) #calculates the rising cost of tuition. tuition = tuition + newTuition if newBalance < -tuition: print newBalance + newPrincipal newBalance = principal print principal," is the new balance. " newPrincipal = (principal * interestRate) print newPrincipal," is the new interest on the principal. " print principal + newPrincipal,"is the new principal. " balance = principal + newPrincipal newTuition = (tuition * tuitionInc) #calculates the rising cost of tuition. tuition = tuition + newTuition print -tuition," is the new cost of tuition. " principal = newBalance + tuition print principal," is the new balance. " newPrincipal = (principal * interestRate) print newPrincipal," is the new interest on the principal. " print principal + newPrincipal,"is the new principal. " balance = principal + newPrincipal count = count + 1 if -tuition > principal: print principal + newPrincipal, "was available for the last student." if count > 10: print count, "Students used this grant." From kent37 at tds.net Sun Feb 8 16:25:24 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 8 Feb 2009 10:25:24 -0500 Subject: [Tutor] Oops! I just corrected my file:RE Completed project is this correct? In-Reply-To: <47B95607-D82C-4C70-B16B-D4BE610BF633@comcast.net> References: <47B95607-D82C-4C70-B16B-D4BE610BF633@comcast.net> Message-ID: <1c2a2c590902080725t6ec5f12diec07c1e6be1b33f5@mail.gmail.com> I guess this is homework so I will keep my comments fairly general. You have a lot of tests on count. Are they all needed? The code might be clearer if tuition was a positive number. newPrincipal and newTuition could have better names I don't think you need so many variables, balance, newBalance and principal all represent the same thing. Kent On Sat, Feb 7, 2009 at 11:02 PM, wrote: > Forget the first, this is the corrected version. > > Thanks, > > Pat > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Sun Feb 8 19:02:22 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 8 Feb 2009 13:02:22 -0500 Subject: [Tutor] Fwd: Oops! I just corrected my file:RE Completed project is this correct? In-Reply-To: References: <47B95607-D82C-4C70-B16B-D4BE610BF633@comcast.net> <1c2a2c590902080725t6ec5f12diec07c1e6be1b33f5@mail.gmail.com> Message-ID: <1c2a2c590902081002p1817f639vf75e70b4114f6ea@mail.gmail.com> ---------- Forwarded message ---------- From: Date: Sun, Feb 8, 2009 at 11:32 AM Subject: Re: [Tutor] Oops! I just corrected my file:RE Completed project is this correct? To: Kent Johnson Oh one thing, I'm not a student at a university. But I am completing the assignments "as a student". The first project is from a downloaded MIT CompSci 101 course. If it takes me several weeks to do a project I don't mind. I'm actually 56 yrs old and run my own business. Eventually, I hope to write several programs to control external hardware. Thanks again, Pat On Feb 8, 2009, at 8:25 AM, Kent Johnson wrote: > I guess this is homework so I will keep my comments fairly general. > > You have a lot of tests on count. Are they all needed? > The code might be clearer if tuition was a positive number. > newPrincipal and newTuition could have better names > I don't think you need so many variables, balance, newBalance and > principal all represent the same thing. > > Kent > > On Sat, Feb 7, 2009 at 11:02 PM, wrote: >> >> Forget the first, this is the corrected version. >> >> Thanks, >> >> Pat >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> From kent37 at tds.net Sun Feb 8 19:04:47 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 8 Feb 2009 13:04:47 -0500 Subject: [Tutor] Picking up citations In-Reply-To: References: <1c2a2c590902070621p19162d25jeb5b3676904ef2ad@mail.gmail.com> <1c2a2c590902070943n38e6f538l6007769edc86f8df@mail.gmail.com> <1c2a2c590902071319u5e984d5dpf2a140b654c03e2f@mail.gmail.com> Message-ID: <1c2a2c590902081004l102d0194vf3488214684dc646@mail.gmail.com> I guess I'm in the mood for a parsing challenge this weekend, I wrote a PLY version of the citation parser, see attached. It generates exactly the output you asked for except for the inclusion of "In" in the name. Kent -------------- next part -------------- A non-text attachment was scrubbed... Name: ParseCitationPLY.py Type: text/x-python Size: 3627 bytes Desc: not available URL: From bgailer at gmail.com Sun Feb 8 19:10:19 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 08 Feb 2009 13:10:19 -0500 Subject: [Tutor] Is this correct? In-Reply-To: References: Message-ID: <498F200B.6070501@gmail.com> cclpianos at comcast.net wrote: > HI, > > I just realized that I shouldn't enclose my project in an attachment. > > This is my first attempt to string together py-code. Is this correct? > And how would a pro word this? It seems like an awful lot of code for > such a small task. I think we should start with the fundamental algorithm which I believe is: set the starting principal and tuition set the interest rates each year: increase the principal by its interest increase the tuition by its interest if principle > tuition increment student count decrement principal Is this correct? -- Bob Gailer Chapel Hill NC 919-636-4239 From berankin99 at yahoo.com Sun Feb 8 20:40:58 2009 From: berankin99 at yahoo.com (Bernard Rankin) Date: Sun, 8 Feb 2009 11:40:58 -0800 (PST) Subject: [Tutor] calling other process? Message-ID: <830940.23977.qm@web112212.mail.gq1.yahoo.com> Hello, I've been reading the Python docs on how to call a 2nd program and getting it's output, and would up here: http://docs.python.org/library/subprocess.html Is: from subprocess import Popen output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] Really the replacement for: output = `mycmd myarg` Is there a less verbose, yet still official supported, way to capture STDOUT from a different program? Thank you, :) From bgailer at gmail.com Sun Feb 8 23:11:40 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 08 Feb 2009 17:11:40 -0500 Subject: [Tutor] Is this correct? In-Reply-To: References: Message-ID: <498F589C.4020308@gmail.com> For what its worth - here is my revision of your program. I did not send it earlier because I kept finding things that led me to want to see and verify the fundamental algorithm. But now I think my observations could also be useful. My changes: Changed indentation from 8 to 2. For me this is much more readable and helps when there are several levels of indentation. Others prefer 4 Removed all blank lines Removed unnecessary if statements and started with count == 2 Changed sign of tuition (makes it a LOT easier to follow arithmetic) Calcuate balance then use in print statement avoiding duplicate calculation Removed unnecessary () Used *= where appropriate Used multiple assignment where appropriate Changed tuitionInc to 1.041 thus simplifying calculation of new tuition interest is misleading - it is the interest! Questions: Why calculate tuition increase twice? Next has no explanatory text - what is it for? print newBalance + interest I wonder about if newBalance < tuition: With the starting values you provided that case is never true If it were true, principal = newBalance - tuition should be under an else clause! principal = balance = 500000 # Starting fund amount. interestRate = .05 # Interest rate added to the principal annually. tuition = 34986 # Starting tuition fee tuitionInc = 1.041 # The annual increase applied to the tuition. print principal, "Is the starting principal" # This is to show the starting balance. print tuition, "Is the starting tuition." balance = principal - tuition print balance," the amount remaining after first tuition deduction. " interest = balance * interestRate # calculates the amount added to the fund print interest, " Interest added to fund for one year. " newBalance = balance + interest print newBalance, "is the new balance." count = 2 # keeps me informed on the number of students benefitting from this grant. while principal > tuition: tuition *= tuitionInc # calculates the rising cost of tuition. if newBalance < tuition: print newBalance + interest newBalance = principal print principal," is the new balance. " interest = principal * interestRate print interest," is the new interest on the principal. " balance = principal + interest print balance,"is the new principal. " tuition *= tuitionInc # calculates the rising cost of tuition. print tuition," is the new cost of tuition. " principal = newBalance - tuition print principal," is the new balance. " interest = principal * interestRate print interest," is the new interest on the principal. " balance = principal + interest print balance, "is the new principal. " count = count + 1 if tuition > principal: print principal + interest, "was available for the last student." if count > 10: print count, "Students used this grant." -- Bob Gailer Chapel Hill NC 919-636-4239 From emmanuel.ruellan at gmail.com Sun Feb 8 23:53:39 2009 From: emmanuel.ruellan at gmail.com (Emmanuel Ruellan) Date: Sun, 8 Feb 2009 23:53:39 +0100 Subject: [Tutor] Picking up citations Message-ID: <7296745c0902081453g70a3aeb2ha2033f70dbba4b41@mail.gmail.com> Dinesh B Vadhia wrote: > Hi! I want to process text that contains citations, in this case in legal > documents, and pull-out each individual citation. Here is my stab at it, using regular expressions. Any comments welcome. I had to use two regexes, one to find all citations, and the other one to split-up citations into their components. They are basically the same, the former without grouping, and the latter with named groups. *** text = "?some common-law legal comments?" split_up_cit = re.compile('(?P[A-Z]\w+(?:\s[A-Za-z]\w+)*?)' #name +'\sv\.\s' #versus +'(?P[A-Z]\w+(?:\s[A-Za-z]\w+)*?),' #other name +'(?P[^\(]+)' #references +'(?P\(.*?\d\d\d\d\))[,;.]') # years whole_cit = re.compile('[A-Z]\w+(?:\s[A-Za-z]\w+)*?' #name +'\sv\.\s' #versus +'[A-Z]\w+(?:\s[A-Za-z]\w+)*?,' #other name +'[^\(]+' #references +'\(.*?\d\d\d\d\)[,;.]') # years for cit in whole_cit.findall(text): ref_list = split_up_cit.search(cit).group('refs').split(',') for ref in ref_list: print split_up_cit.search(cit).group('name'), print 'v.', print split_up_cit.search(cit).group('other_name'), print ref, print split_up_cit.search(cit).group('year') *** The results looks like what is expected, with the exception of "In John Doggone Williams" rather than just "John Doggone Williams". As Kent remarked it is difficult to left out of names the parts that should be left out. "Page 500" is easier to deal with, however. I make it mandatory that the first word of the name starts with an uppercase letter ([A-Z]), and that all other words of the name start with a letter ([A-Za-z]). Yes, I include lowercase letter so that names like 'Pierre Choderlos de Laclos' or 'Guido van Rossum' are dealt with correctly. Note that with the [A-Za-z] range, accented letters may not be dealt with correctly. Emmanuel -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 9 01:52:40 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Feb 2009 00:52:40 -0000 Subject: [Tutor] calling other process? References: <830940.23977.qm@web112212.mail.gq1.yahoo.com> Message-ID: "Bernard Rankin" wrote > http://docs.python.org/library/subprocess.html > > Is: > > from subprocess import Popen > output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] > > Really the replacement for: > > output = `mycmd myarg` Yes, because it works more consistently and reliably across operating systems for one reason. Its also much more powerful and flexible. > Is there a less verbose, yet still official supported, way to > capture STDOUT from a different program? os.popen and the commands module still work, they are just deprecated. It is better to get used to subprocess although it is more verbose. But at least it can do all the things you need so you don't need to juggle between backticks, popen(all 4 versions of it!), spawn, system,commands, etc... Remember that in the zen of Python : a) There should be one-- and preferably only one --obvious way to do it. b) explicit is better than implicit. http://www.python.org/dev/peps/pep-0020/ HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From berankin99 at yahoo.com Mon Feb 9 02:06:04 2009 From: berankin99 at yahoo.com (Bernard Rankin) Date: Sun, 8 Feb 2009 17:06:04 -0800 (PST) Subject: [Tutor] calling other process? References: <830940.23977.qm@web112212.mail.gq1.yahoo.com> Message-ID: <630799.75057.qm@web112218.mail.gq1.yahoo.com> > > Is: > > > > from subprocess import Popen > > output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] > > > > Really the replacement for: > > > > output = `mycmd myarg` > > Yes, because it works more consistently and reliably across > operating systems for one reason. Its also much more powerful > and flexible. > [SNIP] > Remember that in the zen of Python : > a) There should be one-- and preferably only one --obvious way to do > it. > b) explicit is better than implicit. > > http://www.python.org/dev/peps/pep-0020/ > Thanks for clearing that up. Not to discount the Python Zen, but me thinks there could be a little more "Make easy things easy, and hard things possible"in this aspect of Python . :) From alan.gauld at btinternet.com Mon Feb 9 02:20:17 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 9 Feb 2009 01:20:17 +0000 (GMT) Subject: [Tutor] calling other process? References: <830940.23977.qm@web112212.mail.gq1.yahoo.com> <630799.75057.qm@web112218.mail.gq1.yahoo.com> Message-ID: <443758.66510.qm@web86707.mail.ird.yahoo.com> > > > from subprocess import Popen > > > output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0] > Not to discount the Python Zen, but me thinks there could be a little more "Make > easy things easy, and hard things possible"in this aspect of Python . :) I sympatjise but to be honest I never use the backtick trick except at the >>> prompt as a quick and dirty hack. It ranks alongside the _ variable in my book as an interactive utility but it's too easy to miss or misread to use in real code. But even popen is easier, I agree, and I am still weaning myself away from popen to Popen... But I can see the reasoning behind the move. Of course if you do a lot of that you could always define a function that supplies default values for everything but the command. Alan G. From berankin99 at yahoo.com Mon Feb 9 02:51:10 2009 From: berankin99 at yahoo.com (Bernard Rankin) Date: Sun, 8 Feb 2009 17:51:10 -0800 (PST) Subject: [Tutor] calling other process? References: <830940.23977.qm@web112212.mail.gq1.yahoo.com> <630799.75057.qm@web112218.mail.gq1.yahoo.com> <443758.66510.qm@web86707.mail.ird.yahoo.com> Message-ID: <795000.4972.qm@web112215.mail.gq1.yahoo.com> > > I sympatjise but to be honest I never use the backtick trick except at > the >>> prompt as a quick and dirty hack. It ranks alongside the _ variable > in my book as an interactive utility but it's too easy to miss or misread to use > > in real code. > > But even popen is easier, I agree, and I am still weaning myself away from > popen to Popen... But I can see the reasoning behind the move. > > Of course if you do a lot of that you could always define a function > that supplies default values for everything but the command. > True enough. On a slight different note, what would be the correct subprocess call if I want to pipe an email message to "/usr/sbin/sendmail -t -i"? (SMTP, thus smtplib, is not liked very much by the sysadmin) Thanks again, :) From bgailer at gmail.com Mon Feb 9 03:29:46 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 08 Feb 2009 21:29:46 -0500 Subject: [Tutor] Is this correct? In-Reply-To: <77222007-CA23-4F39-9D26-B594AA8A04BA@comcast.net> References: <498F589C.4020308@gmail.com> <77222007-CA23-4F39-9D26-B594AA8A04BA@comcast.net> Message-ID: <498F951A.2090608@gmail.com> Please always reply-all so a copy goes to the list. We all participate and learn. Would you also respond to my requests for clarified algorithm? cclpianos at comcast.net wrote: > Hi Bob, > > Thanks for your input! I ran the program in IDLE and it worked just > fine. Apparently my calculations were correct, although sloppy. Some > very good points for me to consider; Thanks for the acknowledgment. > > Indentation. I felt for myself it was a bit more readable, but > considering I'm new and the formatting may not survive other OS's, I > plan on making those changes. > The use of the 1.041 for the interest rate. Here, as I'm not > mathematically inclined I don't see the advantages, but I'll compare > the program to yours to see how it works. Your calculation was, in effect, principal = principal + principal * interest. Do you recall factoring in algebra? principal = principal * (1 + interest). For me it is a little easier on the eyes and thinking to see the latter. You could also do: principal += principal * interest > Starting the count at 2 and eliminating the other if statements is a > great simplification. > It all seems a bit clearer in your rendition. > > Thanks again, > Pat > > On Feb 8, 2009, at 3:11 PM, bob gailer wrote: > >> principal = balance = 500000 # Starting fund amount. >> interestRate = .05 # Interest rate added to the principal annually. >> tuition = 34986 # Starting tuition fee >> tuitionInc = 1.041 # The annual increase applied to the tuition. >> print principal, "Is the starting principal" # This is to show the >> starting balance. >> print tuition, "Is the starting tuition." >> balance = principal - tuition >> print balance," the amount remaining after first tuition deduction. " >> interest = balance * interestRate # calculates the amount added to >> the fund >> print interest, " Interest added to fund for one year. " >> newBalance = balance + interest >> print newBalance, "is the new balance." >> count = 2 # keeps me informed on the number of students benefitting >> from this grant. >> while principal > tuition: >> tuition *= tuitionInc # calculates the rising cost of tuition. >> if newBalance < tuition: >> print newBalance + interest >> newBalance = principal >> print principal," is the new balance. " >> interest = principal * interestRate >> print interest," is the new interest on the principal. " >> balance = principal + interest >> print balance,"is the new principal. " >> tuition *= tuitionInc # calculates the rising cost of tuition. >> print tuition," is the new cost of tuition. " >> principal = newBalance - tuition >> print principal," is the new balance. " >> interest = principal * interestRate >> print interest," is the new interest on the principal. " >> balance = principal + interest >> print balance, "is the new principal. " >> count = count + 1 >> if tuition > principal: >> print principal + interest, "was available for the last student." >> if count > 10: >> print count, "Students used this grant." > -- Bob Gailer Chapel Hill NC 919-636-4239 From haztang17 at gmail.com Mon Feb 9 04:05:59 2009 From: haztang17 at gmail.com (Hi) Date: Sun, 8 Feb 2009 19:05:59 -0800 Subject: [Tutor] UPDATED: Question on how to open other programs and files Message-ID: Re: Question on how to open other programs and files (Alan Gauld) Sorry for being confusing on my last e-mail. I will try to clarify my intents a bit further. In short, I want to be able to read the data in the file as well as launch document viewer in Python. For one of the files I want to read the data from a Python script that's in the same folder as the GUI Python script. For the pdf file I simply want to be able to launch document viewer from Python. I know it is probably a lengthy and demanding request, but I just want to be able to do both eventually in my GUI program. I am still very new at Python, and so any help would be very useful for me. I have tried to look up different tutorials online, but I have not found one that addresses my issues. On Sun, Feb 8, 2009 at 1:10 AM, wrote: > Send Tutor mailing list submissions to > tutor at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request at python.org > > You can reach the person managing the list at > tutor-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. Completed project. Is this correct? Can I simplify my > formulas? (cclpianos at comcast.net) > 2. Oops! I just corrected my file:RE Completed project is this > correct? (cclpianos at comcast.net) > 3. Question on how to open other programs and files (Hi) > 4. Re: Exec(uting) Code in a Dictionary? (spir) > 5. Re: Question on how to open other programs and files (Alan Gauld) > 6. Re: WINSOCK stdin question (Alan Gauld) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Sat, 7 Feb 2009 20:45:25 -0700 > From: cclpianos at comcast.net > Subject: [Tutor] Completed project. Is this correct? Can I simplify my > formulas? > To: tutor at python.org > Message-ID: <4070A0F9-63DC-4BBF-80FA-6D369B65672D at comcast.net> > Content-Type: text/plain; charset="us-ascii"; Format="flowed"; > DelSp="yes" > > Hello, I've enclosed a completed project (my first!) and would like > to know of it's accuracy. Also, what I could do to simplify the > language. > > Thanks, > > Pat > > -------------- next part -------------- > A non-text attachment was scrubbed... > Name: Grant.py > Type: text/x-python-script > Size: 2935 bytes > Desc: not available > URL: < > http://mail.python.org/pipermail/tutor/attachments/20090207/940c1e50/attachment-0001.bin > > > > ------------------------------ > > Message: 2 > Date: Sat, 7 Feb 2009 21:02:21 -0700 > From: cclpianos at comcast.net > Subject: [Tutor] Oops! I just corrected my file:RE Completed project > is this correct? > To: tutor at python.org > Message-ID: <47B95607-D82C-4C70-B16B-D4BE610BF633 at comcast.net> > Content-Type: text/plain; charset="us-ascii"; Format="flowed" > > Forget the first, this is the corrected version. > > Thanks, > > Pat > -------------- next part -------------- > A non-text attachment was scrubbed... > Name: Grant.py > Type: text/x-python-script > Size: 2901 bytes > Desc: not available > URL: < > http://mail.python.org/pipermail/tutor/attachments/20090207/afc8b9e6/attachment-0001.bin > > > > ------------------------------ > > Message: 3 > Date: Sat, 7 Feb 2009 22:09:04 -0800 > From: Hi > Subject: [Tutor] Question on how to open other programs and files > To: tutor at python.org > Message-ID: > > Content-Type: text/plain; charset="iso-8859-1" > > I have a question regarding how to open other programs and files in Python > code. I am creating a simple interface and I want it to be able to open > other files, such as a text file or a pdf file. However, those files are > usually associated with other programs - for instance, gedit for text and > document viewer for pdf (I am using Ubuntu 8.10). What syntax or commands > do > I need in order to do so. I've used os.popen in Windows XP and it works > fine, but the same code does not work in Ubuntu. This is the part of my > code > that deals with opening files/programs: > > def openfile(self, event): > result = os.popen("home/user/textfile.txt") > > In the terminal it simply says, sh: home/user/textfile.txt: not found. And > I > have already set permissions via chmod +x on the files of my choosing. Any > help would be greatly appreciated. > -------------- next part -------------- > An HTML attachment was scrubbed... > URL: < > http://mail.python.org/pipermail/tutor/attachments/20090207/83a89869/attachment-0001.htm > > > > ------------------------------ > > Message: 4 > Date: Sun, 8 Feb 2009 09:56:03 +0100 > From: spir > Subject: Re: [Tutor] Exec(uting) Code in a Dictionary? > To: tutor at python.org > Message-ID: <20090208095603.70a1f24e at o> > Content-Type: text/plain; charset=UTF-8 > > Le Sat, 07 Feb 2009 13:50:01 -0800, > Wayne Watson a ?crit : > > > That's something for me to ponder, setattr. I'd rather not go off and > pick up on something like ConfigParser at this stage. I'd like to keep this > code somewhat simple and easy to understand, but yet have some flexibility > for changes. > > Dicts are very handy because they are still starightforwardly usable when a > name/key is unknown at design time, in addition to the value: > > d["foo"] = val > d[name] = val > > A typical use is precisely reading data from a config file where both names > and values are data, meaning defined by the user. So that you cannot > directly store them in a custom config object writing: > > config.name = val > > Setattr addresses this need: > > setattr(config,name,val) > > So that finally using an object or a dict are more or less equivalent, > rather a programmer choice. > * dict is slightly easier > * object allows slightly lighter code (obj.name vs obj["name"]) and a > syntax better consistent with the rest of python > * additionnal data attibutes, custom behaviour > > Denis > > > ------ > la vida e estranya > > > ------------------------------ > > Message: 5 > Date: Sun, 8 Feb 2009 09:03:07 -0000 > From: "Alan Gauld" > Subject: Re: [Tutor] Question on how to open other programs and files > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "Hi" wrote > > >I have a question regarding how to open other programs and files in > >Python > > code. I am creating a simple interface and I want it to be able to > > open > > other files, such as a text file or a pdf file. > > OK, lets clarify something first. > When you say open do you mean you want to open the file in Python > such that you can read the data into your python program? Or do > you mean you want to open the file in the default application on > your computer. In other words for a pdf file do you want to read > the data in the file or do you want to launch Acrobat on the file? > > > usually associated with other programs - for instance, gedit for > > text and > > document viewer for pdf (I am using Ubuntu 8.10). What syntax or > > commands do > > I need in order to do so. > > The "official" approach to laumnching applications is to > use the subprocess module. This replaces several other > mechanisms which are now considred obsolete. > > > I've used os.popen in Windows XP and it works > > fine, but the same code does not work in Ubuntu. > > It should work but subprocess replaces popen. > > > def openfile(self, event): > > result = os.popen("home/user/textfile.txt") > > > > In the terminal it simply says, sh: home/user/textfile.txt: not > > found. > > I suspect your path is wrong. Notice you are not using > an absolute path but a relative path, so unless you have > a directory called home in your current directory it will fail. > > But this is not opening the text file this is trying to execute > the text file and that is unlikely to work on Ubuntu. (In Windows > it will launch the default app - probably Notepad) So back to > the original question: do you want to open the t5extfile in > Python or do you want to launch gedit from Python? > > Untiol you resolve that conundrum we can't really help > much more. > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > > > > ------------------------------ > > Message: 6 > Date: Sun, 8 Feb 2009 09:08:09 -0000 > From: "Alan Gauld" > Subject: Re: [Tutor] WINSOCK stdin question > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed; charset="utf-8"; > reply-type=original > > > Yes, this is exactly what I am looking to accomplish. > > On one host I have an application that is sending > > cmd.exe to a second host. > > OK, how is that application doing that? What port is > it sending the output to on the remote host? You say > CMD.exe but that is the windows shell. There is no > way to direct it to another host directly so how is > this application redirecting cmd.exe? Does it have > a name? > > You might need to write two programs, one on the > host computer to run and redirect cmd.exe to the > remote PC and then relay the returned data as > input to CMD.exe as well as another app on the > remote PC to pick up the incoming data and > relay the user input back down the socket. > > We need to know a lot more about how this thing > is glued together. > > Alan G. > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 60, Issue 36 > ************************************* > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Feb 9 04:07:22 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 8 Feb 2009 22:07:22 -0500 Subject: [Tutor] Picking up citations In-Reply-To: <7296745c0902081453g70a3aeb2ha2033f70dbba4b41@mail.gmail.com> References: <7296745c0902081453g70a3aeb2ha2033f70dbba4b41@mail.gmail.com> Message-ID: <1c2a2c590902081907x5dd36c9yf2c833fa8d9a9036@mail.gmail.com> On Sun, Feb 8, 2009 at 5:53 PM, Emmanuel Ruellan wrote: > Dinesh B Vadhia wrote: >> Hi! I want to process text that contains citations, in this case in legal >> documents, and pull-out each individual citation. > > > Here is my stab at it, using regular expressions. Any comments welcome. It's a lot shorter than my parser versions, but it doesn't handle multiple page numbers correctly (the second Doggone Williams citation). You could probably handle this by processing the list of split references. > I had to use two regexes, one to find all citations, and the other one to > split-up citations into their components. They are basically the same, the > former without grouping, and the latter with named groups. Why not use the grouped regex alone? If you use finditer() instead of findall() you get a sequence of match objects so you can use the named groups. Kent From david at abbottdavid.com Mon Feb 9 04:55:26 2009 From: david at abbottdavid.com (David) Date: Sun, 08 Feb 2009 22:55:26 -0500 Subject: [Tutor] UPDATED: Question on how to open other programs and files In-Reply-To: References: Message-ID: <498FA92E.707@abbottdavid.com> Hi wrote: > Re: Question on how to open other programs and files Here is one way; #!/usr/bin/python import subprocess print "Starting Adobe Reader " def startReader(): myreader = "acroread" fname = "test.pdf" print "Loading ", fname subprocess.call([myreader, fname]) def main(): startReader() if __name__ == "__main__": main() -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From alan.gauld at btinternet.com Mon Feb 9 10:06:44 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Feb 2009 09:06:44 -0000 Subject: [Tutor] UPDATED: Question on how to open other programs andfiles References: Message-ID: "Hi" wrote > In short, I want to be able to read the data in the > file as well as launch document viewer in Python. For one of the > files I > want to read the data from a Python script that's in the same folder > as the > GUI Python script. OK, You need to be really clear about what you mean. Do you want to run the python script and use the resultant output as data in your script or do you want to read the contents of the python script (variables/constants etc)? If its the latter you could import the script. If its the former then its exactly the same as the pdf file. > For the pdf file I simply want to be able to launch > document viewer from Python. The officially approved way of doing that now is using the subprocess module. If you want to read the output back into your program you need to use subprocess.Popen. If you just want to run the viewer use subprocess.call > I know it is probably a lengthy and demanding > request, but I just want to be able to do both No, its quite a common requirement, it just wasn't clear if you wanted to run the applications or to read the internal data directly. > I have tried to look up different tutorials online, but I have not > found one > that addresses my issues. Try the Using the OS topic of my tutorial. It shows several examples including using subprocess.Popen. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From denis.spir at free.fr Mon Feb 9 11:41:02 2009 From: denis.spir at free.fr (spir) Date: Mon, 9 Feb 2009 11:41:02 +0100 Subject: [Tutor] UPDATED: Question on how to open other programs and files In-Reply-To: References: Message-ID: <20090209114102.3e490333@o> Le Sun, 8 Feb 2009 19:05:59 -0800, Hi a ?crit : > Sorry for being confusing on my last e-mail. I will try to clarify my > intents a bit further. In short, I want to be able to read the data in the > file as well as launch document viewer in Python. For one of the files I > want to read the data from a Python script that's in the same folder as the > GUI Python script. For the pdf file I simply want to be able to launch > document viewer from Python. I know it is probably a lengthy and demanding > request, but I just want to be able to do both eventually in my GUI program. You should first concentrate on the logic, then eventually design the GUI. There are several reasons for that: * internal logic and UI are different points of view * both aspects will be clearer; even if they progress in // * if you mix them, then any change in the logic will require UI updates -- you will end up losing your time redesigning the GUI Denis ------ la vida e estranya From kent37 at tds.net Mon Feb 9 12:53:17 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 9 Feb 2009 06:53:17 -0500 Subject: [Tutor] Picking up citations In-Reply-To: References: <1c2a2c590902070621p19162d25jeb5b3676904ef2ad@mail.gmail.com> <1c2a2c590902070943n38e6f538l6007769edc86f8df@mail.gmail.com> <1c2a2c590902071319u5e984d5dpf2a140b654c03e2f@mail.gmail.com> <1c2a2c590902081004l102d0194vf3488214684dc646@mail.gmail.com> Message-ID: <1c2a2c590902090353u7aa42b5dpa630bf2c12dc25ad@mail.gmail.com> On Sun, Feb 8, 2009 at 7:07 PM, Dinesh B Vadhia wrote: > Hi Kent > > From pyparsing to PLY in a few days ... this is too much to handle! I tried > the program and like you said it works except for the inclusion of the full > name. I tested it on different text and it doesn't work as expected (see > attached file). I'm finding the PLY version a little easier to work with. It exposes more of the internals and feels like I have more control. The errors in parsing sierra.txt are mostly because of over-aggressive inclusion of words in the first name. Attached is a better one. It also errors on unexpected punctuation which prevents "MUYSA Sierra Club". Kent -------------- next part -------------- A non-text attachment was scrubbed... Name: ParseCitationPLY.py Type: text/x-python Size: 4039 bytes Desc: not available URL: From etrade.griffiths at dsl.pipex.com Mon Feb 9 14:24:42 2009 From: etrade.griffiths at dsl.pipex.com (etrade.griffiths at dsl.pipex.com) Date: Mon, 09 Feb 2009 13:24:42 +0000 Subject: [Tutor] Reading binary files #2 In-Reply-To: References: Message-ID: <1234185882.49902e9a75da1@netmail.pipex.net> Hi following last week's discussion with Bob Gailer about reading unformatted FORTRAN files, I have attached an example of the file in ASCII format and the equivalent unformatted version. Below is some code that works OK until it gets to a data item that has no additional associated data, then seems to have got 4 bytes ahead of itself. I though I had trapped this but it appears not. I think the issue is asociated with "newline" characters or the unformatted equivalent. Thanks in advance Alun Griffiths ============================== # Test function to write/read from unformatted files import sys import struct # Read file in one go in_file = open("test.bin","rb") data = in_file.read() in_file.close() # Initialise nrec = len(data) stop = 0 items = [] # Read data until EOF encountered while stop < nrec: # extract data structure start, stop = stop, stop + struct.calcsize('4s8si4s8s') vals = struct.unpack('>4s8si4s8s', data[start:stop]) items.extend(vals) print stop, vals # define format of subsequent data nval = int(vals[2]) if vals[3] == 'INTE': fmt_string = '>i' elif vals[3] == 'CHAR': fmt_string = '>8s' elif vals[3] == 'LOGI': fmt_string = '>i' elif vals[3] == 'REAL': fmt_string = '>f' elif vals[3] == 'DOUB': fmt_string = '>d' elif vals[3] == 'MESS': fmt_string = '>%dd' % nval else: print "Unknown data type ... exiting" print items sys.exit(0) # extract data for i in range(0,nval): start, stop = stop, stop + struct.calcsize(fmt_string) vals = struct.unpack(fmt_string, data[start:stop]) items.extend(vals) # trailing spaces if nval > 0: start, stop = stop, stop + struct.calcsize('4s') vals = struct.unpack('4s', data[start:stop]) # All data read so print items print items ------------------------------------------------- Visit Pipex Business: The homepage for UK Small Businesses Go to http://www.pipex.co.uk/business-services -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: test.asc URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: test.bin Type: application/octet-stream Size: 476 bytes Desc: not available URL: From prasadaraon50 at gmail.com Mon Feb 9 16:27:52 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Mon, 9 Feb 2009 20:57:52 +0530 Subject: [Tutor] Binding Events Message-ID: <9e3fac840902090727o348895ffq8bed42c68addc1ba@mail.gmail.com> Hi I am unable to bind an event to a widget despite of my best efforts. Some one please help me. class app: def __init__(self,root): frame=Frame(root) frame.bind('',self.callback) frame.pack() self.event=event self.button=Button(root,text='quit',fg='red',command=frame.quit) self.button.pack(side='left') self.hi=Button(root,text='hi',fg='SystemWindowFrame',command=self.hi) self.hi.pack(side='right') self.callback def hi (self): print 'hello! there' def callback(self,event): print "clicked at", event.x, event.y from Tkinter import * root=Tk() xx=app(root,event) root.mainloop() Thanks in advance Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 9 18:11:55 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Feb 2009 17:11:55 -0000 Subject: [Tutor] Reading binary files #2 References: <1234185882.49902e9a75da1@netmail.pipex.net> Message-ID: wrote > I have attached an example of the file in ASCII format and the > equivalent unformatted version. Comparing them in vim... It doesn't look too bad except for the DATABEGI / DATAEND message format. That could be tricky to unravel but we have no clear format for MESS. But I assume that all the stuff between BEG and END is supposed to be effectively nested?. > it gets to a data item that has no additional associated data, > then seems to have got 4 bytes ahead of itself. You are creating a format string of >0d but I'm not sure how struct behaves with zero lenths... HTH, Alan G. ============================== # Test function to write/read from unformatted files import sys import struct # Read file in one go in_file = open("test.bin","rb") data = in_file.read() in_file.close() # Initialise nrec = len(data) stop = 0 items = [] # Read data until EOF encountered while stop < nrec: # extract data structure start, stop = stop, stop + struct.calcsize('4s8si4s8s') vals = struct.unpack('>4s8si4s8s', data[start:stop]) items.extend(vals) print stop, vals # define format of subsequent data nval = int(vals[2]) if vals[3] == 'INTE': fmt_string = '>i' elif vals[3] == 'CHAR': fmt_string = '>8s' elif vals[3] == 'LOGI': fmt_string = '>i' elif vals[3] == 'REAL': fmt_string = '>f' elif vals[3] == 'DOUB': fmt_string = '>d' elif vals[3] == 'MESS': fmt_string = '>%dd' % nval else: print "Unknown data type ... exiting" print items sys.exit(0) # extract data for i in range(0,nval): start, stop = stop, stop + struct.calcsize(fmt_string) vals = struct.unpack(fmt_string, data[start:stop]) items.extend(vals) # trailing spaces if nval > 0: start, stop = stop, stop + struct.calcsize('4s') vals = struct.unpack('4s', data[start:stop]) # All data read so print items print items ------------------------------------------------- Visit Pipex Business: The homepage for UK Small Businesses Go to http://www.pipex.co.uk/business-services -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Mon Feb 9 18:17:41 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 9 Feb 2009 17:17:41 -0000 Subject: [Tutor] Binding Events References: <9e3fac840902090727o348895ffq8bed42c68addc1ba@mail.gmail.com> Message-ID: "prasad rao" wrote > Hi I am unable to bind an event to a widget despite of my best > efforts. So give us a clue. What happened? Do you get any error messages in the console when you run it? Does the GUI display but just not respond? Please don't make us guess... > class app: > def __init__(self,root): > frame=Frame(root) > frame.bind('',self.callback) > frame.pack() > self.event=event > self.button=Button(root,text='quit',fg='red',command=frame.quit) > self.button.pack(side='left') > self.hi=Button(root,text='hi',fg='SystemWindowFrame',command=self.hi) > self.hi.pack(side='right') > self.callback > def hi (self): print 'hello! there' > def callback(self,event): > print "clicked at", event.x, event.y > from Tkinter import * Its usual to put the import at the top of the file. Not essential but conventional. > root=Tk() > xx=app(root,event) What is event? app only takes one argument not two. > root.mainloop() HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From sierra_mtnview at sbcglobal.net Mon Feb 9 18:25:07 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 09 Feb 2009 09:25:07 -0800 Subject: [Tutor] Exec(uting) Code in a Dictionary? In-Reply-To: <498E0209.7080202@sbcglobal.net> References: <498DED12.3090001@sbcglobal.net> <1c2a2c590902071240y36f3d1c3i942364bfebe0cd1b@mail.gmail.com> <498DFB62.6090606@sbcglobal.net> <1c2a2c590902071342k366a9dcai419f6ffd989a13b1@mail.gmail.com> <498E0209.7080202@sbcglobal.net> Message-ID: <499066F3.5040904@sbcglobal.net> An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Feb 9 18:49:31 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 09 Feb 2009 12:49:31 -0500 Subject: [Tutor] Reading binary files #2 In-Reply-To: <1234185882.49902e9a75da1@netmail.pipex.net> References: <1234185882.49902e9a75da1@netmail.pipex.net> Message-ID: <49906CAB.8000102@gmail.com> etrade.griffiths at dsl.pipex.com wrote: > Hi > > following last week's discussion with Bob Gailer about reading unformatted FORTRAN files, I have attached an example of the file in ASCII format and the equivalent unformatted version. Thank you. It is good to have real data to work with. > Below is some code that works OK until it gets to a data item that has no additional associated data, then seems to have got 4 bytes ahead of itself. Thank you. It is good to have real code to work with. > I though I had trapped this but it appears not. I think the issue is asociated with "newline" characters or the unformatted equivalent. > I think not, But we will see. I fail to see where the problem is. The data printed below seems to agree with the files you sent. What am I missing? FWIW a few observations re coding style and techniques. 1) put the formats in a dictionary before the while loop: formats = {'INTE': '>i', 'CHAR': '>8s', 'LOGI': '>i', 'REAL': '>f', 'DOUB': '>d', 'MESS': ''>d,} 2) retrieve the format in the while loop from the dictionary: format = formats[vals[3]] 3) condense the 3 infile lines: data = open("test.bin","rb").read() 4) nrec is a misleading name (to me it means # of records), nbytes would be better. 5) Be consistent with the format between calcsize and unpack: struct.calcsize('>4s8si4s8s') 6) Use meaningful variable names instead of val for the unpacked data: blank, name, length, typ = struct.unpack ... etc 7) The format for MESS should be '>d' rather than '>%dd' % nval. When nval is 0 the for loop will make 0 cycles. 8) You don't have a format for DATA (BEGI); therefore the prior format (for CHAR) is being applied. The formats are the same so it does not matter but could be confusing later. > # Test function to write/read from unformatted files > > import sys > import struct > > # Read file in one go > > in_file = open("test.bin","rb") > data = in_file.read() > in_file.close() > > # Initialise > > nrec = len(data) > stop = 0 > items = [] > > # Read data until EOF encountered > > while stop < nrec: > > # extract data structure > > start, stop = stop, stop + struct.calcsize('4s8si4s8s') > vals = struct.unpack('>4s8si4s8s', data[start:stop]) > items.extend(vals) > print stop, vals > > # define format of subsequent data > > nval = int(vals[2]) > > if vals[3] == 'INTE': > fmt_string = '>i' > elif vals[3] == 'CHAR': > fmt_string = '>8s' > elif vals[3] == 'LOGI': > fmt_string = '>i' > elif vals[3] == 'REAL': > fmt_string = '>f' > elif vals[3] == 'DOUB': > fmt_string = '>d' > elif vals[3] == 'MESS': > fmt_string = '>%dd' % nval > else: > print "Unknown data type ... exiting" > print items > sys.exit(0) > > # extract data > > for i in range(0,nval): > start, stop = stop, stop + struct.calcsize(fmt_string) > vals = struct.unpack(fmt_string, data[start:stop]) > items.extend(vals) > > # trailing spaces > > if nval > 0: > start, stop = stop, stop + struct.calcsize('4s') > vals = struct.unpack('4s', data[start:stop]) > > # All data read so print items > > print items > > > ------------------------------------------------- > Visit Pipex Business: The homepage for UK Small Businesses > > Go to http://www.pipex.co.uk/business-services > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer Chapel Hill NC 919-636-4239 From dineshbvadhia at hotmail.com Mon Feb 9 18:51:07 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Mon, 9 Feb 2009 09:51:07 -0800 Subject: [Tutor] Picking up citations Message-ID: Kent /Emmanuel Below are the results using the PLY parser and Regex versions on the attached 'sierra' data which I think covers the common formats. Here are some 'fully unparsed" citations that were missed by the programs: Smith v. Wisconsin Dept. of Agriculture, 23 F.3d 1134, 1141 (7th Cir.1994) Indemnified Capital Investments, S.A. v. R.J. O'Brien & Assoc., Inc., 12 F.3d 1406, 1409 (7th Cir.1993). Hunt v. Washington Apple Advertising Commn., 432 U.S. 333, 343, 97 S.Ct. 2434, 2441, 53 L.Ed.2d 383 (1977) Idaho Conservation League v. Mumma, 956 F.2d 1508, 1517-18 (9th Cir.1992) HTH Dinesh -------------------------------------------------------------------------------- PLY PARSER VERSION RESULTS: Warth v. Seldin, 422 U.S. 490 (1975) Warth v. Seldin, 499 n. 10 (1975) Warth v. Seldin, 95 S.Ct. 2197 (1975) Warth v. Seldin, 2205 n. 10 (1975) Warth v. Seldin, 45 L.Ed.2d 343 (1975) Sierra Club v. Morton, 405 U.S. 727, 734 (1972) Sierra Club v. Morton, 734, 1366 (1972) Sierra Club v. Morton, 1366 (1972) Pennsylvania v. West Virginia, 262 U.S. 553, 593 (1923) Pennsylvania v. West Virginia, 593, 663 (1923) Pennsylvania v. West Virginia, 663 (1923) Oregon Natural Resources Council v. Lowe, 836 F.Supp. 727, 732 (D.Or.1993) Morris v. Myers, 845 F.Supp. 750, 754 (D.Or.1993) Women Voters v. United States Nuclear Regulatory Comm, 679 F.2d 1218, 1221 (7th Cir.1982) REGEX VERSION RESULTS: Warth v. Seldin 422 U.S. 490 (1975) ("The standing question thus bears close affinity to questions of ripeness--whether the harm asserted has matured sufficiently to warrant judicial intervention...."); Gene R. Nichol, Jr., Ripeness and the Constitution, 54 U.Chi.L.Rev. 153, 155, 172-73 (1987) (noting that "the ripeness requirement is often indistinguishable from actionability analysis" and that no "line of demarcation" can be drawn between the Supreme Court's analysis in standing cases where "threatened or actual injury" is at issue and ripeness cases where the focus is on "direct and immediate harm"). Nonetheless, we will address standing and ripeness separately, reviewing the district court's decision on both points de novo. See Indemnified Capital Investments, S.A. v. R.J. O'Brien & Assoc., Inc., 12 F.3d 1406, 1409 (7th Cir.1993) Warth v. Seldin 499 n. 10 (1975) ("The standing question thus bears close affinity to questions of ripeness--whether the harm asserted has matured sufficiently to warrant judicial intervention...."); Gene R. Nichol, Jr., Ripeness and the Constitution, 54 U.Chi.L.Rev. 153, 155, 172-73 (1987) (noting that "the ripeness requirement is often indistinguishable from actionability analysis" and that no "line of demarcation" can be drawn between the Supreme Court's analysis in standing cases where "threatened or actual injury" is at issue and ripeness cases where the focus is on "direct and immediate harm"). Nonetheless, we will address standing and ripeness separately, reviewing the district court's decision on both points de novo. See Indemnified Capital Investments, S.A. v. R.J. O'Brien & Assoc., Inc., 12 F.3d 1406, 1409 (7th Cir.1993) Warth v. Seldin 95 S.Ct. 2197 (1975) ("The standing question thus bears close affinity to questions of ripeness--whether the harm asserted has matured sufficiently to warrant judicial intervention...."); Gene R. Nichol, Jr., Ripeness and the Constitution, 54 U.Chi.L.Rev. 153, 155, 172-73 (1987) (noting that "the ripeness requirement is often indistinguishable from actionability analysis" and that no "line of demarcation" can be drawn between the Supreme Court's analysis in standing cases where "threatened or actual injury" is at issue and ripeness cases where the focus is on "direct and immediate harm"). Nonetheless, we will address standing and ripeness separately, reviewing the district court's decision on both points de novo. See Indemnified Capital Investments, S.A. v. R.J. O'Brien & Assoc., Inc., 12 F.3d 1406, 1409 (7th Cir.1993) Warth v. Seldin 2205 n. 10 (1975) ("The standing question thus bears close affinity to questions of ripeness--whether the harm asserted has matured sufficiently to warrant judicial intervention...."); Gene R. Nichol, Jr., Ripeness and the Constitution, 54 U.Chi.L.Rev. 153, 155, 172-73 (1987) (noting that "the ripeness requirement is often indistinguishable from actionability analysis" and that no "line of demarcation" can be drawn between the Supreme Court's analysis in standing cases where "threatened or actual injury" is at issue and ripeness cases where the focus is on "direct and immediate harm"). Nonetheless, we will address standing and ripeness separately, reviewing the district court's decision on both points de novo. See Indemnified Capital Investments, S.A. v. R.J. O'Brien & Assoc., Inc., 12 F.3d 1406, 1409 (7th Cir.1993) Warth v. Seldin 45 L.Ed.2d 343 (1975) ("The standing question thus bears close affinity to questions of ripeness--whether the harm asserted has matured sufficiently to warrant judicial intervention...."); Gene R. Nichol, Jr., Ripeness and the Constitution, 54 U.Chi.L.Rev. 153, 155, 172-73 (1987) (noting that "the ripeness requirement is often indistinguishable from actionability analysis" and that no "line of demarcation" can be drawn between the Supreme Court's analysis in standing cases where "threatened or actual injury" is at issue and ripeness cases where the focus is on "direct and immediate harm"). Nonetheless, we will address standing and ripeness separately, reviewing the district court's decision on both points de novo. See Indemnified Capital Investments, S.A. v. R.J. O'Brien & Assoc., Inc., 12 F.3d 1406, 1409 (7th Cir.1993) Lujan v. Defenders of Wildlife --- U.S. ---- (1992) Lujan v. Defenders of Wildlife ---- (1992) Lujan v. Defenders of Wildlife 112 S.Ct. 2130 (1992) Lujan v. Defenders of Wildlife 2136 (1992) Lujan v. Defenders of Wildlife 119 L.Ed.2d 351 (1992) Sierra Club v. Morton 405 U.S. 727 (1972) Sierra Club v. Morton 734 (1972) Sierra Club v. Morton 92 S.Ct. 1361 (1972) Sierra Club v. Morton 1366 (1972) Sierra Club v. Morton 31 L.Ed.2d 636 (1972) Whitmore v. Arkansas 495 U.S. 149 (1990) Whitmore v. Arkansas 158 (1990) Whitmore v. Arkansas 110 S.Ct. 1717 (1990) Whitmore v. Arkansas 1724-25 (1990) Whitmore v. Arkansas 109 L.Ed.2d 135 (1990) Pennsylvania v. West Virginia 262 U.S. 553 (1923) Pennsylvania v. West Virginia 593 (1923) Pennsylvania v. West Virginia 43 S.Ct. 658 (1923) Pennsylvania v. West Virginia 663 (1923) Pennsylvania v. West Virginia 67 L.Ed. 1117 (1923) Oregon Natural Resources Council v. Lowe 836 F.Supp. 727 (D.Or.1993) Oregon Natural Resources Council v. Lowe 732 (D.Or.1993) Morris v. Myers 845 F.Supp. 750 (D.Or.1993) Morris v. Myers 754 (D.Or.1993) -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: sierra.txt URL: From administrador.de.red at gmail.com Mon Feb 9 19:29:21 2009 From: administrador.de.red at gmail.com (Network Administrator) Date: Mon, 9 Feb 2009 12:29:21 -0600 Subject: [Tutor] Python & MySQL... Define port. Message-ID: Hello everybody! I want to use Python to query a given MySQL database. However, this database is running on port 3308, instead the traditional 3306. I read that (example): MySQLdb.connect(host="dbserv', db='inv', user='smith') can be used to query a given database; however, it didn't work in my particular case. This is my code: connection = MySQLdb.connect (db = "netlogin", user="netadmin", pass = "r4nas", port="3308") I appreciate if you give me assistance in the proper sintax of the last mentioned instruction. Regards, GatoLinux. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Mon Feb 9 20:03:02 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 09 Feb 2009 11:03:02 -0800 Subject: [Tutor] apply() after class? Message-ID: <49907DE6.8060101@sbcglobal.net> An HTML attachment was scrubbed... URL: From etrade.griffiths at dsl.pipex.com Mon Feb 9 20:40:43 2009 From: etrade.griffiths at dsl.pipex.com (eShopping) Date: Mon, 09 Feb 2009 19:40:43 +0000 Subject: [Tutor] Reading binary files #2 In-Reply-To: <49906CAB.8000102@gmail.com> References: <1234185882.49902e9a75da1@netmail.pipex.net> <49906CAB.8000102@gmail.com> Message-ID: <7jhs5f$6gjsgr@smtp.pipex.tiscali.co.uk> Hi Bob some replies below. One thing I noticed with the "full" file was that I ran into problems when the number of records was 10500, and the file read got misaligned. Presumably 10500 is still within the range of int? Best regards Alun At 17:49 09/02/2009, bob gailer wrote: >etrade.griffiths at dsl.pipex.com wrote: >>Hi >> >>following last week's discussion with Bob Gailer about reading >>unformatted FORTRAN files, I have attached an example of the file >>in ASCII format and the equivalent unformatted version. > >Thank you. It is good to have real data to work with. > >>Below is some code that works OK until it gets to a data item that >>has no additional associated data, then seems to have got 4 bytes >>ahead of itself. > >Thank you. It is good to have real code to work with. > >>I though I had trapped this but it appears not. I think the issue >>is asociated with "newline" characters or the unformatted equivalent. >> > >I think not, But we will see. > >I fail to see where the problem is. The data printed below seems to >agree with the files you sent. What am I missing? When I run the program it exits in the middle but should run through to the end. The output to the console was 236 ('\x00\x00\x00\x10', 'DATABEGI', 0, 'MESS', '\x00\x00\x00\x10\x00\x00\x00\x10') 264 ('TIME', ' \x00\x00\x00\x01', 1380270412, '\x00\x00\x00\x10', '\x00\x00\x00\x04\x00\x00\x00\x00') Here "TIME" is in vals[0] when it should be in vals[1] and so on. I found the problem earlier today and I re-wrote the main loop as follows (before I saw your helpful coding style comments): while stop < nrec: # extract data structure start, stop = stop, stop + struct.calcsize('4s8si4s4s') vals = struct.unpack('>4s8si4s4s', data[start:stop]) items.extend(vals[1:4]) print stop, vals # define format of subsequent data nval = int(vals[2]) if vals[3] == 'INTE': fmt_string = '>i' elif vals[3] == 'CHAR': fmt_string = '>8s' elif vals[3] == 'LOGI': fmt_string = '>i' elif vals[3] == 'REAL': fmt_string = '>f' elif vals[3] == 'DOUB': fmt_string = '>d' elif vals[3] == 'MESS': fmt_string = '>%ds' % nval else: print "Unknown data type ... exiting" print items[-40:] sys.exit(0) # leading spaces if nval > 0: start, stop = stop, stop + struct.calcsize('4s') vals = struct.unpack('4s', data[start:stop]) # extract data for i in range(0,nval): start, stop = stop, stop + struct.calcsize(fmt_string) vals = struct.unpack(fmt_string, data[start:stop]) items.extend(vals) # trailing spaces if nval > 0: start, stop = stop, stop + struct.calcsize('4s') vals = struct.unpack('4s', data[start:stop]) Now I get this output 232 ('\x00\x00\x00\x10', 'DATABEGI', 0, 'MESS', '\x00\x00\x00\x10') 256 ('\x00\x00\x00\x10', 'TIME ', 1, 'REAL', '\x00\x00\x00\x10') and the script runs to the end >FWIW a few observations re coding style and techniques. > >1) put the formats in a dictionary before the while loop: >formats = {'INTE': '>i', 'CHAR': '>8s', 'LOGI': '>i', 'REAL': '>f', >'DOUB': '>d', 'MESS': ''>d,} > >2) retrieve the format in the while loop from the dictionary: >format = formats[vals[3]] Neat!! >3) condense the 3 infile lines: >data = open("test.bin","rb").read() I still don't quite trust myself to "chain" functions together, but I guess that's lack of practice >4) nrec is a misleading name (to me it means # of records), nbytes >would be better. Agreed >5) Be consistent with the format between calcsize and unpack: >struct.calcsize('>4s8si4s8s') > >6) Use meaningful variable names instead of val for the unpacked data: >blank, name, length, typ = struct.unpack ... etc Will do >7) The format for MESS should be '>d' rather than '>%dd' % nval. >When nval is 0 the for loop will make 0 cycles. Wasn't sure about that one. "MESS" implies string but I wasn't sure what to do about a zero-length string >8) You don't have a format for DATA (BEGI); therefore the prior >format (for CHAR) is being applied. The formats are the same so it >does not matter but could be confusing later. DATABEGI should be a keyword to indicate the start of the "proper" data which has format MESS (ie string). You did make me look again at the MESS format and it should be '>%ds' % nval and not '>%dd' % nval From iwasroot at gmail.com Mon Feb 9 21:05:33 2009 From: iwasroot at gmail.com (Moos Heintzen) Date: Mon, 9 Feb 2009 12:05:33 -0800 Subject: [Tutor] Splitting strings and undefined variables Message-ID: <7b13ba330902091205k3c9fb875h43f8190b0ce2fa15@mail.gmail.com> Hello all, I was looking at this: http://www.debian.org/doc/manuals/reference/ch-program.en.html#s-python I have a question about the line of code that uses split() With the python version, the line below only works if there are three fields in line. (first, last, passwd) = line.split() Also, since the variables are used like this: lineout = "%s:%s:%d:%d:%s %s,,/home/%s:/bin/bash\n" % \ (user, passwd, uid, gid, first, last, user) I can't use ":".join(line.split()) But maybe a dictionary could be used for string substitution. In the perl version (above the python version in the link), the script works with the input line having one to three fields. Like "fname lname pw" or "fname lname" ($n1, $n2, $n3) = split / /; Is there a better way to extract the fields from line in a more flexible way, so that the number of fields could vary? I guess we could use conditionals to check each field, but is there a more elegant (or pythonic!) way to do it? Moos P.S. I'm not a Perl user, I was just reading the examples. I've been using C and awk for few years, and Python for few months. Also, I know blank passwords aren't very practical, but I'm just asking this to explore possibilities :) From a.n.grant at gmail.com Mon Feb 9 18:29:34 2009 From: a.n.grant at gmail.com (Alexander Grant) Date: Mon, 9 Feb 2009 12:29:34 -0500 Subject: [Tutor] Tkinter Expanding Canvas with AutoScrollBar Message-ID: Hi Tutors, Thanks in advance for all the advice you've already given to others... it has been extremely useful! I'm working on a project, and I wanted to have a header, a footer and an expanding canvas with (possibly) many widgets inside it. I simply modified Fred Lundh's auto-hiding scrollbar code found here - http://effbot.org/zone/tkinter-autoscrollbar.htm It is almost working as hoped - but I have the problem that the canvas only resizes smaller, not larger - even when the canvas is too large to display in the original window! I'll attach my code... I'm just not sure what's going wrong: ################################################# from Tkinter import * class AutoScrollbar(Scrollbar): # a scrollbar that hides itself if it's not needed. only # works if you use the grid geometry manager. def set(self, lo, hi): if float(lo) <= 0.0 and float(hi) >= 1.0: # grid_remove is currently missing from Tkinter! self.tk.call("grid", "remove", self) else: self.grid() Scrollbar.set(self, lo, hi) def pack(self, **kw): raise TclError, "cannot use pack with this widget" def place(self, **kw): raise TclError, "cannot use place with this widget" # # create scrolled canvas al = Tk() al.columnconfigure(0,weight=1) al.rowconfigure(0,weight=1) header = Frame(al) header.pack(side= TOP, expand = YES) htxt = Label(header,text='TOP TOP TOP... this is the TOP') htxt.pack() footer = Frame(al) footer.pack(side = BOTTOM, expand = YES) ftxt = Label(footer,text='BOTTOM BOTTOM BOTTOM... this is the BOTTOM!') ftxt.pack() root = LabelFrame(al, bd=2, text='Data',relief='groove',padx=5, pady=5) root.pack(side = TOP, expand = YES) vscrollbar = AutoScrollbar(root) vscrollbar.grid(row=0, column=1, sticky=N+S) hscrollbar = AutoScrollbar(root, orient=HORIZONTAL) hscrollbar.grid(row=1, column=0, sticky=E+W) canvas = Canvas(root, yscrollcommand=vscrollbar.set, xscrollcommand=hscrollbar.set) canvas.grid(row=0, column=0, sticky=N+S+E+W) vscrollbar.config(command=canvas.yview) hscrollbar.config(command=canvas.xview) # make the canvas expandable root.grid_rowconfigure(0, weight=1) root.grid_columnconfigure(0, weight=1) # create canvas contents frame = Frame(canvas) frame.rowconfigure(1, weight=1) frame.columnconfigure(1, weight=1) rows = 20 for i in range(1,rows): for j in range(1,20): button = Button(frame, padx=7, pady=7, text="[%d,%d]" % (i,j)) button.grid(row=i, column=j, sticky='news') canvas.create_window(0, 0, anchor=NW, window=frame) frame.update_idletasks() canvas.config(scrollregion=canvas.bbox("all")) root.mainloop() ################################################# Thanks, Al -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.n.grant at gmail.com Mon Feb 9 20:34:48 2009 From: a.n.grant at gmail.com (Alexander Grant) Date: Mon, 9 Feb 2009 14:34:48 -0500 Subject: [Tutor] Tkinter Expanding Canvas with AutoScrollBar In-Reply-To: References: Message-ID: Well. I solved my own problem. Mainly I wasn't using the grid manager everywhere, and I think that's what was messing it up! Thanks anyways! Al On Mon, Feb 9, 2009 at 12:29 PM, Alexander Grant wrote: > Hi Tutors, > Thanks in advance for all the advice you've already given to others... it > has been extremely useful! > > I'm working on a project, and I wanted to have a header, a footer and an > expanding canvas with (possibly) many widgets inside it. > > I simply modified Fred Lundh's auto-hiding scrollbar code found here - > http://effbot.org/zone/tkinter-autoscrollbar.htm > It is almost working as hoped - but I have the problem that the canvas only > resizes smaller, not larger - even when the canvas is too large to display > in the original window! > > I'll attach my code... I'm just not sure what's going wrong: > > > ################################################# > from Tkinter import * > > class AutoScrollbar(Scrollbar): > # a scrollbar that hides itself if it's not needed. only > # works if you use the grid geometry manager. > def set(self, lo, hi): > if float(lo) <= 0.0 and float(hi) >= 1.0: > # grid_remove is currently missing from Tkinter! > self.tk.call("grid", "remove", self) > else: > self.grid() > Scrollbar.set(self, lo, hi) > def pack(self, **kw): > raise TclError, "cannot use pack with this widget" > def place(self, **kw): > raise TclError, "cannot use place with this widget" > > # > # create scrolled canvas > > al = Tk() > al.columnconfigure(0,weight=1) > al.rowconfigure(0,weight=1) > > header = Frame(al) > header.pack(side= TOP, expand = YES) > > htxt = Label(header,text='TOP TOP TOP... this is the TOP') > htxt.pack() > > footer = Frame(al) > footer.pack(side = BOTTOM, expand = YES) > > ftxt = Label(footer,text='BOTTOM BOTTOM BOTTOM... this is the BOTTOM!') > ftxt.pack() > > root = LabelFrame(al, bd=2, text='Data',relief='groove',padx=5, pady=5) > root.pack(side = TOP, expand = YES) > > vscrollbar = AutoScrollbar(root) > vscrollbar.grid(row=0, column=1, sticky=N+S) > hscrollbar = AutoScrollbar(root, orient=HORIZONTAL) > hscrollbar.grid(row=1, column=0, sticky=E+W) > > canvas = Canvas(root, > yscrollcommand=vscrollbar.set, > xscrollcommand=hscrollbar.set) > canvas.grid(row=0, column=0, sticky=N+S+E+W) > > vscrollbar.config(command=canvas.yview) > hscrollbar.config(command=canvas.xview) > > # make the canvas expandable > root.grid_rowconfigure(0, weight=1) > root.grid_columnconfigure(0, weight=1) > > # create canvas contents > > frame = Frame(canvas) > frame.rowconfigure(1, weight=1) > frame.columnconfigure(1, weight=1) > > rows = 20 > for i in range(1,rows): > for j in range(1,20): > button = Button(frame, padx=7, pady=7, text="[%d,%d]" % (i,j)) > button.grid(row=i, column=j, sticky='news') > > canvas.create_window(0, 0, anchor=NW, window=frame) > > frame.update_idletasks() > > canvas.config(scrollregion=canvas.bbox("all")) > > root.mainloop() > ################################################# > > > > Thanks, > > Al > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Mon Feb 9 22:17:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 9 Feb 2009 16:17:26 -0500 Subject: [Tutor] apply() after class? In-Reply-To: <49907DE6.8060101@sbcglobal.net> References: <49907DE6.8060101@sbcglobal.net> Message-ID: <1c2a2c590902091317x70ef10a3sd5b2428157cf5978@mail.gmail.com> On Mon, Feb 9, 2009 at 2:03 PM, Wayne Watson wrote: > I see the following code that follows some of the class definitions in some > python code I'm modifying. I don't see the function anywhere in the program. > Possibly it's called from another module, but I doubt it. There's only one > other non-python library module for it. It has to do with Quick Time. > > def apply(self): > self.sdict["ok"] = True OK...was that a question? Kent From sierra_mtnview at sbcglobal.net Mon Feb 9 22:35:25 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 09 Feb 2009 13:35:25 -0800 Subject: [Tutor] apply() after class? In-Reply-To: <1c2a2c590902091317x70ef10a3sd5b2428157cf5978@mail.gmail.com> References: <49907DE6.8060101@sbcglobal.net> <1c2a2c590902091317x70ef10a3sd5b2428157cf5978@mail.gmail.com> Message-ID: <4990A19D.1010701@sbcglobal.net> An HTML attachment was scrubbed... URL: From ksarikhani at gmail.com Mon Feb 9 22:35:12 2009 From: ksarikhani at gmail.com (Kayvan Sarikhani) Date: Mon, 9 Feb 2009 16:35:12 -0500 Subject: [Tutor] Simple PassGen Message-ID: Hello Tutors, I've been messing around with a simple password generation script...no real crypto or anything, but a little stumped on the output. #!/usr/bin/python import random, string pool = string.digits + string.letters + string.punctuation for i in range(8): print random.choice(pool) This seems to do the job, but it lists the output with newlines, perhaps. For example: $ ./passgen.py t C ( 2 w P x 3 I thought that maybe adding "print random.choice(pool).strip()" might work but not having any luck with that. Is the output this way, simply because of the nature of the range, or can anyone point my in the right direction? Thanks in advance! K -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Feb 9 22:45:04 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 9 Feb 2009 13:45:04 -0800 Subject: [Tutor] Simple PassGen In-Reply-To: References: Message-ID: <40af687b0902091345l2998dd81y511715f00e555059@mail.gmail.com> The print() function adds a newline. Try this instead - above your loop, create an empty string; in place of yor print(), append to the string; at the end, print the whole string. I'd demonstrate but I'm typing this from my phone. --- www.fsrtechnologies.com On Feb 9, 2009 1:35 PM, "Kayvan Sarikhani" wrote: Hello Tutors, I've been messing around with a simple password generation script...no real crypto or anything, but a little stumped on the output. #!/usr/bin/python import random, string pool = string.digits + string.letters + string.punctuation for i in range(8): print random.choice(pool) This seems to do the job, but it lists the output with newlines, perhaps. For example: $ ./passgen.py t C ( 2 w P x 3 I thought that maybe adding "print random.choice(pool).strip()" might work but not having any luck with that. Is the output this way, simply because of the nature of the range, or can anyone point my in the right direction? Thanks in advance! K _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Mon Feb 9 22:53:30 2009 From: srilyk at gmail.com (W W) Date: Mon, 9 Feb 2009 15:53:30 -0600 Subject: [Tutor] Simple PassGen In-Reply-To: References: Message-ID: <333efb450902091353k3eb2608aw26f6b45c925a7296@mail.gmail.com> On Mon, Feb 9, 2009 at 3:35 PM, Kayvan Sarikhani wrote: > Hello Tutors, > I thought that maybe adding "print random.choice(pool).strip()" > might work but not having any luck with that. Is the output this way, simply > because of the nature of the range, or can anyone point my in the right > direction? Thanks in advance! > It's actually not the range but the print function. Print automatically prints a newline. If you were to create a string of what print does: print 'foo' 'foo\n' However, adding a trailing comma will eliminate that. It will still add a trailing space however. A better option would be like Marc suggests, although you have to do concatenation: mystr += random.choice(pool) You do have some other options though. Create a list and join it with '': In [148]: x = ['a','b','c'] In [149]: ''.join(x) Out[149]: 'abc' Create a list, convert it to tuple, and use string formatting: In [151]: '%s%s%s' % t Out[151]: 'abc' Use sys.stdout.write instead: In [154]: for y in x: .....: sys.stdout.write(y) .....: .....: abc and a host of other options. The simplest is probably the concatenation though ;) HTH, Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From ksarikhani at gmail.com Mon Feb 9 22:59:28 2009 From: ksarikhani at gmail.com (Kayvan Sarikhani) Date: Mon, 9 Feb 2009 16:59:28 -0500 Subject: [Tutor] Simple PassGen In-Reply-To: <40af687b0902091345l2998dd81y511715f00e555059@mail.gmail.com> References: <40af687b0902091345l2998dd81y511715f00e555059@mail.gmail.com> Message-ID: Ah, I see what you mean...this does seem to work: #!/usr/bin/python import random, string pool = string.digits + string.letters + string.punctuation outstr = '' for i in range(8): outstr += random.choice(pool) print outstr Thanks very much! K On Mon, Feb 9, 2009 at 4:45 PM, Marc Tompkins wrote: > The print() function adds a newline. Try this instead - above your loop, > create an empty string; in place of yor print(), append to the string; at > the end, print the whole string. > > I'd demonstrate but I'm typing this from my phone. > > --- www.fsrtechnologies.com > > On Feb 9, 2009 1:35 PM, "Kayvan Sarikhani" wrote: > > Hello Tutors, > > I've been messing around with a simple password generation script...no > real crypto or anything, but a little stumped on the output. > > #!/usr/bin/python > import random, string > > pool = string.digits + string.letters + string.punctuation > > for i in range(8): > print random.choice(pool) > > This seems to do the job, but it lists the output with newlines, perhaps. > For example: > > $ ./passgen.py > t > C > ( > 2 > w > P > x > 3 > > I thought that maybe adding "print random.choice(pool).strip()" might > work but not having any luck with that. Is the output this way, simply > because of the nature of the range, or can anyone point my in the right > direction? Thanks in advance! > > K > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ksarikhani at gmail.com Mon Feb 9 23:03:02 2009 From: ksarikhani at gmail.com (Kayvan Sarikhani) Date: Mon, 9 Feb 2009 17:03:02 -0500 Subject: [Tutor] Simple PassGen In-Reply-To: <333efb450902091353k3eb2608aw26f6b45c925a7296@mail.gmail.com> References: <333efb450902091353k3eb2608aw26f6b45c925a7296@mail.gmail.com> Message-ID: On Mon, Feb 9, 2009 at 4:53 PM, W W wrote: > It's actually not the range but the print function. Print automatically > prints a newline. If you were to create a string of what print does: > > print 'foo' > > 'foo\n' > > However, adding a trailing comma will eliminate that. It will still add a > trailing space however. A better option would be like Marc suggests, > although you have to do concatenation: > > mystr += random.choice(pool) > > You do have some other options though. Create a list and join it with '': > > In [148]: x = ['a','b','c'] > > In [149]: ''.join(x) > Out[149]: 'abc' > > Create a list, convert it to tuple, and use string formatting: > > In [151]: '%s%s%s' % t > Out[151]: 'abc' > > Use sys.stdout.write instead: > > In [154]: for y in x: > .....: sys.stdout.write(y) > .....: > .....: > abc > > and a host of other options. The simplest is probably the concatenation > though ;) > HTH, > Wayne > Thanks for the explanations, Wayne...the appending seems to do the trick, but I'm also going to keep these in mind for future reference. So many methods still left to learn. :) K -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Mon Feb 9 23:14:17 2009 From: denis.spir at free.fr (spir) Date: Mon, 9 Feb 2009 23:14:17 +0100 Subject: [Tutor] Simple PassGen In-Reply-To: <40af687b0902091345l2998dd81y511715f00e555059@mail.gmail.com> References: <40af687b0902091345l2998dd81y511715f00e555059@mail.gmail.com> Message-ID: <20090209231417.2db55711@o> Le Mon, 9 Feb 2009 13:45:04 -0800, Marc Tompkins a ?crit : > The print() function adds a newline. Try this instead - above your loop, > create an empty string; in place of yor print(), append to the string; at > the end, print the whole string. > > I'd demonstrate but I'm typing this from my phone. import random, string pool = string.digits + string.letters + string.punctuation pw = '' for i in range(8): pw += random.choice(pool) print pw ------ la vida e estranya From dineshbvadhia at hotmail.com Mon Feb 9 23:15:46 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Mon, 9 Feb 2009 14:15:46 -0800 Subject: [Tutor] Picking up citations Message-ID: Kent /Emmanuel I found a list of words before the first word that can be removed which I think is the only way to successfully parse the citations. Here they are: | E.g. | Accord | See |See + Also | Cf. | Compare | Contra | But + See | But + Cf. | See Generally | Citing | In | Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Feb 9 23:32:49 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 9 Feb 2009 14:32:49 -0800 Subject: [Tutor] Simple PassGen In-Reply-To: <333efb450902091353k3eb2608aw26f6b45c925a7296@mail.gmail.com> References: <333efb450902091353k3eb2608aw26f6b45c925a7296@mail.gmail.com> Message-ID: <40af687b0902091432y3887f13ctd1c431c364879a06@mail.gmail.com> Don't forget - the "print" statement is going away in 3.0, and you really should get into the habit of using the print() function instead for new code. IIRC, print() does NOT support suppressing the newline, but IMNRC (I might not remember correctly.) --- www.fsrtechnologies.com On Feb 9, 2009 1:53 PM, "W W" wrote: On Mon, Feb 9, 2009 at 3:35 PM, Kayvan Sarikhani wrote: > Hello Tutors, > I thought that maybe adding "print random.choice(pool).strip()" > might work but not having any luck with that. Is the output this way, simply > because of the nature of the range, or can anyone point my in the right > direction? Thanks in advance! > It's actually not the range but the print function. Print automatically prints a newline. If you were to create a string of what print does: print 'foo' 'foo\n' However, adding a trailing comma will eliminate that. It will still add a trailing space however. A better option would be like Marc suggests, although you have to do concatenation: mystr += random.choice(pool) You do have some other options though. Create a list and join it with '': In [148]: x = ['a','b','c'] In [149]: ''.join(x) Out[149]: 'abc' Create a list, convert it to tuple, and use string formatting: In [151]: '%s%s%s' % t Out[151]: 'abc' Use sys.stdout.write instead: In [154]: for y in x: .....: sys.stdout.write(y) .....: .....: abc and a host of other options. The simplest is probably the concatenation though ;) HTH, Wayne _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Mon Feb 9 23:33:43 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 09 Feb 2009 14:33:43 -0800 Subject: [Tutor] apply() after class? In-Reply-To: <4990A19D.1010701@sbcglobal.net> References: <49907DE6.8060101@sbcglobal.net> <1c2a2c590902091317x70ef10a3sd5b2428157cf5978@mail.gmail.com> <4990A19D.1010701@sbcglobal.net> Message-ID: <4990AF47.8090502@sbcglobal.net> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Feb 9 23:42:47 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 9 Feb 2009 14:42:47 -0800 Subject: [Tutor] Picking up citations In-Reply-To: References: Message-ID: <40af687b0902091442l7235657ew79194db7262e3021@mail.gmail.com> Aha! My list of "magic words"! (Sorry for the top post - anybody know how to change quoting defaults in Android Gmail?) --- www.fsrtechnologies.com On Feb 9, 2009 2:16 PM, "Dinesh B Vadhia" wrote: Kent /Emmanuel I found a list of words before the first word that can be removed which I think is the only way to successfully parse the citations. Here they are: | E.g. | Accord | See |See + Also | Cf. | Compare | Contra | But + See | But + Cf. | See Generally | Citing | In | Dinesh _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Mon Feb 9 23:47:47 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 9 Feb 2009 23:47:47 +0100 Subject: [Tutor] Simple PassGen In-Reply-To: <40af687b0902091432y3887f13ctd1c431c364879a06@mail.gmail.com> References: <333efb450902091353k3eb2608aw26f6b45c925a7296@mail.gmail.com> <40af687b0902091432y3887f13ctd1c431c364879a06@mail.gmail.com> Message-ID: On Mon, Feb 9, 2009 at 23:32, Marc Tompkins wrote: > Don't forget - the "print" statement is going away in 3.0, and you really > should get into the habit of using the print() function instead for new > code. Why? Python's print statement is not going away in the 2.x series which will be supported for years.Many guides and books use it so unless those have been updated use it. > IIRC, print() does NOT support suppressing the newline, but IMNRC (I > might not remember correctly.) It is even better in 3 as you can have any type of line ending. AFAIK it can be a space or any character you can think of. >From [1]. print([object, ...][, sep=' '][, end='\n'][, file=sys.stdout]) Greets Sander [1] http://docs.python.org/3.0/library/functions.html#print From sierra_mtnview at sbcglobal.net Tue Feb 10 01:00:20 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 09 Feb 2009 16:00:20 -0800 Subject: [Tutor] IDLE vs PythonWin In-Reply-To: <413868.49755.qm@web86709.mail.ird.yahoo.com> References: <417247.59687.qm@web82007.mail.mud.yahoo.com> <413868.49755.qm@web86709.mail.ird.yahoo.com> Message-ID: <4990C394.8090702@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Feb 10 01:31:56 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 10 Feb 2009 00:31:56 +0000 (GMT) Subject: [Tutor] IDLE vs PythonWin References: <417247.59687.qm@web82007.mail.mud.yahoo.com> <413868.49755.qm@web86709.mail.ird.yahoo.com> <4990C394.8090702@sbcglobal.net> Message-ID: <960063.93932.qm@web86705.mail.ird.yahoo.com> > Yes, but how do you debug the code interactively when you have > the editor outside pythonwin? Do you copy it into the pythonwin editor? Do you mean using the Python debugger? If I need to do that I will either use the command line debugger (pdb) inside the shell window or close the vim session and start pythonwin (or Eclipse which has a really good debugger!) But in 10 years of using Python I've only resorted to the debugger maybe a dozen times in total. Usually a few print statements and a session with the >>> prompt is adequate to find any bugs. The best debugging tools are your eyes! Remember too that you can always import the module into the shell window if you need to test specific functions in isolation. Alan G. ALAN GAULD wrote: The point wasn't about vim per se - that just happens to be my favourite editor - but really about the way of working with 3 separate windows. Really it was just to show that you don't necessarily need to use an all-in-one IDE like Pythonwin or IDLE, -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Feb 10 01:40:33 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Feb 2009 00:40:33 -0000 Subject: [Tutor] apply() after class? References: <49907DE6.8060101@sbcglobal.net> <1c2a2c590902091317x70ef10a3sd5b2428157cf5978@mail.gmail.com><4990A19D.1010701@sbcglobal.net> <4990AF47.8090502@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Ah, another function without a link to a use. body, as in : > > class SetDecoderDialog(tkSimpleDialog.Dialog): > def body(self,master): > self.title("Set Video Decoder Register") > > Label(master, text='Register:').grid(row=0, sticky=W) > Label(master, text='New Value:').grid(row=1, sticky=W) > > self.reg = Entry(master, width=10) > self.val = Entry(master, width=10) > > self.reg.grid(row=0, column=1, sticky=W) > self.val.grid(row=1, column=1, sticky=W) > > return self.reg > > def apply(self): > reg = eval(self.reg.get()) > val = eval(self.val.get()) > self.gui.SetDecoder( reg, val ) > > That's the end of the class. Is there something going on > here between body-apply and tkSimpleDialog? > Making them available to it? Yes. This is part of the power of OOP. If we create an instance of this class it inherits all of the methods of simpleDialog. But if one of those methods internally calls self.body or self.apply it will for this instance execute SetDecoderDialog.body or SetDecoderDialog.apply This is a form of polymorphism which is commonly used in object frameworks. Now I don't know whether SimpleDialog does do that but it is entirely possible. Thus it would not seem like anything is calling those two functions but in fact they are being called indirectly. (A couple of print statements would show whether they were or not!) HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Tue Feb 10 01:45:01 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Feb 2009 00:45:01 -0000 Subject: [Tutor] Simple PassGen References: <333efb450902091353k3eb2608aw26f6b45c925a7296@mail.gmail.com> <40af687b0902091432y3887f13ctd1c431c364879a06@mail.gmail.com> Message-ID: "Marc Tompkins" wrote > Don't forget - the "print" statement is going away in 3.0, and you > really > should get into the habit of using the print() function instead for > new > code. IIRC, print() does NOT support suppressing the newline, >From the v3 Whats New document: Old: print x, # Trailing comma suppresses newline New: print(x, end=" ") # Appends a space instead of a newline Presumably you could use "" instead of " " to eliminate the space.... >>> for n in range(4): ... print(n, end="") ... 0123>>> Yes, it does... HTH, Alan G. My first answer on a Python v3 issue! :-) From greg at thewhittiers.com Tue Feb 10 01:59:48 2009 From: greg at thewhittiers.com (greg whittier) Date: Mon, 9 Feb 2009 19:59:48 -0500 Subject: [Tutor] __builtins__ Message-ID: I'm trying to use sparkplot from sparkplot.org as a module. It's normally run from the command line and acts on an input file. I'd like to use it as a module though to render png's for a web application. Anyway, if I try "import sparkplot" from the interpreter, I get >>> import sparkplot Traceback (most recent call last): File "", line 1, in File "sparkplot.py", line 14, in min = __builtins__.min AttributeError: 'dict' object has no attribute 'min' The offending portion of sparkplot.py appears to be from pylab import * # Avoid name collisions with min and max functions from numarray module min = __builtins__.min max = __builtins__.max If I run python sparkplot.py (executing from __main__ namespace?) from the command line it works as __builtins__ appears to a name for the __builtin__ module and the __builtins__.min reference works, but when I "import sparkplot," the __builtins__ in the sparksplot module is a dict and __builtins__.min fails. In fact changing the above to min = __buitlins__['min'] eliminates the error on "import sparkplot." I think the practical answer is to clean up the namespace in sparkplot.py (get rid of the from pylab import *) as I was planning to do anyway, but I'm wondering what's behind this __builtins__ behavior. Thanks, Greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Tue Feb 10 02:09:56 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 09 Feb 2009 17:09:56 -0800 Subject: [Tutor] IDLE vs PythonWin In-Reply-To: <960063.93932.qm@web86705.mail.ird.yahoo.com> References: <417247.59687.qm@web82007.mail.mud.yahoo.com> <413868.49755.qm@web86709.mail.ird.yahoo.com> <4990C394.8090702@sbcglobal.net> <960063.93932.qm@web86705.mail.ird.yahoo.com> Message-ID: <4990D3E4.1040901@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Tue Feb 10 02:14:29 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 09 Feb 2009 17:14:29 -0800 Subject: [Tutor] apply() after class? In-Reply-To: References: <49907DE6.8060101@sbcglobal.net> <1c2a2c590902091317x70ef10a3sd5b2428157cf5978@mail.gmail.com><4990A19D.1010701@sbcglobal.net> <4990AF47.8090502@sbcglobal.net> Message-ID: <4990D4F5.4000200@sbcglobal.net> An HTML attachment was scrubbed... URL: From cclpianos at comcast.net Tue Feb 10 03:02:20 2009 From: cclpianos at comcast.net (cclpianos at comcast.net) Date: Mon, 9 Feb 2009 19:02:20 -0700 Subject: [Tutor] Is this correct? In-Reply-To: <498F200B.6070501@gmail.com> References: <498F200B.6070501@gmail.com> Message-ID: <7AFF7E25-64B4-4D16-B5CE-9977E817A41B@comcast.net> Hi Bob, I missed this in my in box. Sorry. See below where I have answered your question with yet another. On Feb 8, 2009, at 11:10 AM, bob gailer wrote: > cclpianos at comcast.net wrote: >> HI, >> >> I just realized that I shouldn't enclose my project in an attachment. >> >> This is my first attempt to string together py-code. Is this >> correct? And how would a pro word this? It seems like an awful >> lot of code for such a small task. > > I think we should start with the fundamental algorithm which I > believe is: > > set the starting principal and tuition > set the interest rates > each year: > increase the principal by its interest > increase the tuition by its interest > if principle > tuition > increment student count > decrement principal > > Is this correct? Yes, but I have one element I need to show. The gift is given on alternate years, not each year. This should make the results a bit more substantial. I can't think of anything but to increase the steps in the loop allowing for an extra "years worth" of interest to be accumulated. Surely, there's another simpler solution. Thanks again, Pat > > > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 From cclpianos at comcast.net Tue Feb 10 03:05:48 2009 From: cclpianos at comcast.net (cclpianos at comcast.net) Date: Mon, 9 Feb 2009 19:05:48 -0700 Subject: [Tutor] Is this correct? In-Reply-To: <498F951A.2090608@gmail.com> References: <498F589C.4020308@gmail.com> <77222007-CA23-4F39-9D26-B594AA8A04BA@comcast.net> <498F951A.2090608@gmail.com> Message-ID: <51C4D809-595C-479D-8C94-68FDDAF849B6@comcast.net> Hello again, just getting back to the computer, real world etc. I hate to say this, but I never did well in algebra. But I am determined to slog through this to understand it well. On Feb 8, 2009, at 7:29 PM, bob gailer wrote: > Please always reply-all so a copy goes to the list. We all > participate and learn. > > Would you also respond to my requests for clarified algorithm? > > cclpianos at comcast.net wrote: >> Hi Bob, >> Thanks for your input! I ran the program in IDLE and it worked >> just fine. Apparently my calculations were correct, although >> sloppy. Some very good points for me to consider; > > Thanks for the acknowledgment. >> >> Indentation. I felt for myself it was a bit more readable, but >> considering I'm new and the formatting may not survive other OS's, >> I plan on making those changes. > >> The use of the 1.041 for the interest rate. Here, as I'm not >> mathematically inclined I don't see the advantages, but I'll >> compare the program to yours to see how it works. > > Your calculation was, in effect, principal = principal + principal > * interest. Do you recall factoring in algebra? > > principal = principal * (1 + interest). For me it is a little > easier on the eyes and thinking to see the latter. Yes, this is way easier on the eyes! > > You could also do: > > principal += principal * interest > Thanks for your explanation. Pat > > >> Starting the count at 2 and eliminating the other if statements is >> a great simplification. >> It all seems a bit clearer in your rendition. >> Thanks again, Pat >> >> On Feb 8, 2009, at 3:11 PM, bob gailer wrote: >> >>> principal = balance = 500000 # Starting fund amount. >>> interestRate = .05 # Interest rate added to the principal annually. >>> tuition = 34986 # Starting tuition fee >>> tuitionInc = 1.041 # The annual increase applied to the tuition. >>> print principal, "Is the starting principal" # This is to show >>> the starting balance. >>> print tuition, "Is the starting tuition." >>> balance = principal - tuition >>> print balance," the amount remaining after first tuition >>> deduction. " >>> interest = balance * interestRate # calculates the amount added >>> to the fund >>> print interest, " Interest added to fund for one year. " >>> newBalance = balance + interest >>> print newBalance, "is the new balance." >>> count = 2 # keeps me informed on the number of students >>> benefitting from this grant. >>> while principal > tuition: >>> tuition *= tuitionInc # calculates the rising cost of tuition. >>> if newBalance < tuition: >>> print newBalance + interest >>> newBalance = principal >>> print principal," is the new balance. " >>> interest = principal * interestRate >>> print interest," is the new interest on the principal. " >>> balance = principal + interest >>> print balance,"is the new principal. " >>> tuition *= tuitionInc # calculates the rising cost of tuition. >>> print tuition," is the new cost of tuition. " >>> principal = newBalance - tuition >>> print principal," is the new balance. " >>> interest = principal * interestRate >>> print interest," is the new interest on the principal. " >>> balance = principal + interest >>> print balance, "is the new principal. " >>> count = count + 1 >>> if tuition > principal: >>> print principal + interest, "was available for the last student." >>> if count > 10: >>> print count, "Students used this grant." >> > > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 From kent37 at tds.net Tue Feb 10 03:46:21 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 9 Feb 2009 21:46:21 -0500 Subject: [Tutor] Simple PassGen In-Reply-To: <40af687b0902091432y3887f13ctd1c431c364879a06@mail.gmail.com> References: <333efb450902091353k3eb2608aw26f6b45c925a7296@mail.gmail.com> <40af687b0902091432y3887f13ctd1c431c364879a06@mail.gmail.com> Message-ID: <1c2a2c590902091846v2d8d2258l461d8a7dc92b0edd@mail.gmail.com> On Mon, Feb 9, 2009 at 5:32 PM, Marc Tompkins wrote: > Don't forget - the "print" statement is going away in 3.0, and you really > should get into the habit of using the print() function instead for new > code. IIRC, print() does NOT support suppressing the newline, but IMNRC (I > might not remember correctly.) Except they are not equivalent when you want to print more than one thing. In Python 3: >>> print(3, 4) 3 4 Python 2.6: In [1]: print(3, 4) (3, 4) Kent From kent37 at tds.net Tue Feb 10 03:54:54 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 9 Feb 2009 21:54:54 -0500 Subject: [Tutor] apply() after class? In-Reply-To: <4990AF47.8090502@sbcglobal.net> References: <49907DE6.8060101@sbcglobal.net> <1c2a2c590902091317x70ef10a3sd5b2428157cf5978@mail.gmail.com> <4990A19D.1010701@sbcglobal.net> <4990AF47.8090502@sbcglobal.net> Message-ID: <1c2a2c590902091854t5088b19dsbd01c762957e6cdc@mail.gmail.com> On Mon, Feb 9, 2009 at 5:33 PM, Wayne Watson wrote: > Ah, another function without a link to a use. body, as in : > (note that apply really is part of the class. It looked outside it earlier.) > > class SetDecoderDialog(tkSimpleDialog.Dialog): > > def __init__(self, parent, gui): > self.gui = gui > tkSimpleDialog.Dialog.__init__(self, parent) > > def body(self,master): > self.title("Set Video Decoder Register") > > Label(master, text='Register:').grid(row=0, sticky=W) > Label(master, text='New Value:').grid(row=1, sticky=W) > > self.reg = Entry(master, width=10) > self.val = Entry(master, width=10) > > self.reg.grid(row=0, column=1, sticky=W) > self.val.grid(row=1, column=1, sticky=W) > > return self.reg > > def apply(self): > reg = eval(self.reg.get()) > val = eval(self.val.get()) > self.gui.SetDecoder( reg, val ) > > That's the end of the class. Is there something going on here between > body-apply and tkSimpleDialog? Making them available to it? Apparently you are required to override body() when subclassing tkSimpleDialog.Dialog, and optionally you can override apply() to handle the results. http://epydoc.sourceforge.net/stdlib/tkSimpleDialog.Dialog-class.html#body Kent From dorseye at gmail.com Tue Feb 10 04:29:58 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Mon, 9 Feb 2009 20:29:58 -0700 Subject: [Tutor] IDLE vs PythonWin In-Reply-To: <4990D3E4.1040901@sbcglobal.net> References: <417247.59687.qm@web82007.mail.mud.yahoo.com> <413868.49755.qm@web86709.mail.ird.yahoo.com> <4990C394.8090702@sbcglobal.net> <960063.93932.qm@web86705.mail.ird.yahoo.com> <4990D3E4.1040901@sbcglobal.net> Message-ID: You can call a .py script from the command line, and it will run there. So, in Windows XP: Start > Run > type "CMD" Vista: Start > type "CMD" into the Start Search field. If you're in Linux, get to a Terminal. In Windows another window will open with something like...C:\FolderWithMyPyFile> Linux something like.... me at ubuntu-desktop:~$ Assuming "uberprogram.py" is in the current folder, you can then just type into the command prompt like C:\FolderWithMyPyFile>uberprogram You can see the results of the program right in the command prompt/terminal window. On Mon, Feb 9, 2009 at 6:09 PM, Wayne Watson wrote: > You must be up 24/7! > When I open a py file with pythonwin, it brings up the dialog and in its > window, there are two windows. One is called interactive window (IW), and > the other (script window--SW) contains the program py code. To execute it, I > press the little running icon or F5 and two printed lines appear, as they > should, in the IW. If I remove the SW, how do I run it in another "editor", > vi, vim, emacs, notebook, ... whatever, and see the output in the IW? > > ALAN GAULD wrote: > > > Yes, but how do you debug the code interactively when you have > > the editor outside pythonwin? Do you copy it into the pythonwin editor? > > Do you mean using the Python debugger? > If I need to do that I will either use the command line debugger (pdb) > inside the shell window or close the vim session and start pythonwin > (or Eclipse which has a really good debugger!) But in 10 years of using > Python I've only resorted to the debugger maybe a dozen times in total. > Usually a few print statements and a session with the >>> prompt is > adequate to find any bugs. The best debugging tools are your eyes! > > Remember too that you can always import the module into the shell > window if you need to test specific functions in isolation. > > Alan G. > > > ALAN GAULD wrote: > > The point wasn't about vim per se - that just > happens to be my favourite editor - but really > about the way of working with 3 separate windows. > > Really it was just to show that you don't necessarily > need to use an all-in-one IDE like Pythonwin or IDLE, > > > > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) > > *The Richard Feynman Problem-Solving Algorithm:* > * (1) write down the problem;* > * (2) think very hard;* > * (3) write down the answer.*** > ** > > ****** Web Page: > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldl08 at gmx.net Tue Feb 10 05:37:55 2009 From: ldl08 at gmx.net (David) Date: Tue, 10 Feb 2009 12:37:55 +0800 Subject: [Tutor] help with loop that is to be fed out of a word list Message-ID: <499104A3.2030802@gmx.net> Dear list, out of "Thinking in Python" I take the following code, which "takes a word and a string of required letters, and that returns True if the word uses all the required letters at least once". def uses_all(word, required): for letter in required: if letter not in word: return False return True Now, I want to feed this code a list of words. This is what I have so far: def uses_all(required): fin = open('words.txt') for line in fin: word = line.strip() for letter in required: if letter not in word: # print "False!" return False print word required = raw_input("what letters have to be used? ") print required uses_all(required) The code runs, but does not print the words. All I get it the output of the 'print required' command: david at ubuntu:~/Documents/Tools/Python/Code$ python downey_9.5.py what letters have to be used? zhg zhg aa z david at ubuntu:~/Documents/Tools/Python/Code$ I realise that my loop fails to execute beyond the first word in the list ("aa"), but why? Thanks in advance for your insights! David From john at fouhy.net Tue Feb 10 05:43:54 2009 From: john at fouhy.net (John Fouhy) Date: Tue, 10 Feb 2009 17:43:54 +1300 Subject: [Tutor] help with loop that is to be fed out of a word list In-Reply-To: <499104A3.2030802@gmx.net> References: <499104A3.2030802@gmx.net> Message-ID: <5e58f2e40902092043m29fb7f4ewff4abc6c381602be@mail.gmail.com> 2009/2/10 David : > Dear list, > > out of "Thinking in Python" I take the following code, which > "takes a word and a string of required letters, and that returns True if > the word uses all the required letters at least once". > > > def uses_all(word, required): > for letter in required: > if letter not in word: > return False > return True > > Now, I want to feed this code a list of words. This is what I have so far: > > > def uses_all(required): > fin = open('words.txt') > for line in fin: > word = line.strip() > for letter in required: > if letter not in word: > # print "False!" > return False > print word Hi David, Your first function, top, is pretty good. Rather than throwing it away, or changing it, you should seek to use it. Programming is all about separating tasks. You've got a function that answers the question: "Does this word use all the required letters?" Your next step should be to write another function, which says: "For each word in the list, Does this word use all the required letters? If so, print it out." You can use your first function to make that loop work. Hope this helps. -- John. From prasadaraon50 at gmail.com Tue Feb 10 06:41:37 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Tue, 10 Feb 2009 11:11:37 +0530 Subject: [Tutor] re.Binding Events Message-ID: <9e3fac840902092141n4bf28c0ek8520db861aa694fc@mail.gmail.com> HelloI tried various permutations of the code.Nothing worked. I am mixing 2 examples given in "an-introduction-to- tkinter " by Fredrik Lundh.(and got this code) Today I got this error message Traceback (most recent call last): File "", line 1, in pp() File "", line 18, in pp xx=app(root,event) NameError: global name 'event' is not defined Example1= # File: hello2.py from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="QUIT", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): print "hi there, everyone!" root = Tk() app = App(root) root.mainloop() Running the Example Example2= # File: bind1.py from Tkinter import * root = Tk() def callback(event): print "clicked at", event.x, event.y frame = Frame(root, width=100, height=100) frame.bind("", callback) frame.pack() root.mainloop() How can I mix the two? Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Feb 10 09:31:44 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Tue, 10 Feb 2009 08:31:44 +0000 (GMT) Subject: [Tutor] re.Binding Events References: <9e3fac840902092141n4bf28c0ek8520db861aa694fc@mail.gmail.com> Message-ID: <832104.92682.qm@web86710.mail.ird.yahoo.com> > I am mixing 2 examples given in "an-introduction-to- tkinter " > by Fredrik Lundh.(and got this code) > Today I got this error message > > Traceback (most recent call last): > File "", line 1, in > xx=app(root,event) > NameError: global name 'event' is not defined Which tells you that event is not recognised. Where do you define event? Also look at your call to app() It is different to both calls in the examples: > Example1= ... > app = App(root) > Example2= > root = Tk() > root.mainloop() Where does your "event" come from? What purpose is it supposed to serve? Alan G -------------- next part -------------- An HTML attachment was scrubbed... URL: From prasadaraon50 at gmail.com Tue Feb 10 11:14:52 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Tue, 10 Feb 2009 15:44:52 +0530 Subject: [Tutor] re Binding Event Message-ID: <9e3fac840902100214v281db45cr77bcb59487b8219e@mail.gmail.com> HelloI changed the code as follows.But still the callback function is not working. The he() is working well but clicking on the frame has no result. class app: def __init__(self,root): frame=Frame(root) frame.bind("", callback) frame.pack() self.button=Button(root,text='quit',fg='red',command=frame.quit) self.button.pack(side='left') self.hi=Button(root,text='hi',fg='SystemWindowFrame',command=self.hi) self.hi.pack(side='right') self.callback def hi (self): print 'hello! there' def callback(self,event): print "clicked at", event.x, event.y >>> root=Tk() >>> xx=app(root) >>> root.mainloop() hello! there hello! there -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Tue Feb 10 11:28:52 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Feb 2009 10:28:52 -0000 Subject: [Tutor] re Binding Event References: <9e3fac840902100214v281db45cr77bcb59487b8219e@mail.gmail.com> Message-ID: "prasad rao" wrote > HelloI changed the code as follows.But still the callback function > is not > working. > The he() is working well but clicking on the frame has no result. > > > class app: > def __init__(self,root): > frame=Frame(root) > frame.bind("", callback) Should this not be self.callback? > def callback(self,event): > print "clicked at", event.x, event.y This looks like a method? Although the indentation is messed up in the mail so I can't be sure. >>>> root=Tk() >>>> xx=app(root) >>>> root.mainloop() > hello! there > hello! there HTH Alan G From alan.gauld at btinternet.com Tue Feb 10 11:39:30 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 10 Feb 2009 10:39:30 -0000 Subject: [Tutor] help with loop that is to be fed out of a word list References: <499104A3.2030802@gmx.net> Message-ID: "David" wrote > def uses_all(word, required): > for letter in required: > if letter not in word: > return False > return True > > Now, I want to feed this code a list of words. This is what I have > so far: > > > def uses_all(required): It is usually better to leave things that work alone. You could have renamed the original finction then used it in your new one. That would make the code much simpler. > fin = open('words.txt') > for line in fin: > word = line.strip() if old_uses_all(word, required) print word But as ever its better to return a value from a function rather than print from inside so i'd make your new function: def uses_all(required, wordfile="wordlist.txt"): words = [] for line in open(wordfile): word = line.strip() if old_uses_all(word, required) words.append(word) return words required = raw_input("what letters have to be used? ") print required for word in uses_all(required) print word > The code runs, but does not print the words. All I get it the output > of > the 'print required' command: > I realise that my loop fails to execute beyond the first word in the > list ("aa"), but why? Look at your code: > def uses_all(required): > fin = open('words.txt') > for line in fin: > word = line.strip() > for letter in required: > if letter not in word: > # print "False!" > return False return exits the function so the first letter you find that is not in a word you will exit. -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From lie.1296 at gmail.com Tue Feb 10 12:22:41 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 10 Feb 2009 11:22:41 +0000 (UTC) Subject: [Tutor] Picking up citations References: <40af687b0902091442l7235657ew79194db7262e3021@mail.gmail.com> Message-ID: On Mon, 09 Feb 2009 14:42:47 -0800, Marc Tompkins wrote: > Aha! My list of "magic words"! > (Sorry for the top post - anybody know how to change quoting defaults in > Android Gmail?) > --- www.fsrtechnologies.com > > On Feb 9, 2009 2:16 PM, "Dinesh B Vadhia" > wrote: > > Kent /Emmanuel > > I found a list of words before the first word that can be removed which > I think is the only way to successfully parse the citations. Here they > are: > > | E.g. | Accord | See |See + Also | Cf. | Compare | Contra | But + See | > But + Cf. | See Generally | Citing | In | > I think the only reliable way to parse all the citations correctly, in the absence of "magic word" is to have a list of names. It involves a bit of manual work, but should be good enough if there are a small number of cases that is cited a lot of times. >>> names = '|'.join(['Carter', 'Jury Commision of Greene County', 'Lathe Turner', 'Fouche']) >>> rep = '|'.join(['.*?']) >>> dd = {'names': names, 'publ': rep} >>> re.search(r'((%(names)s) v. (%(names)s)(, [0-9]+ (%(publ)s) [0-9]+)* \([0-9]+\))' % dd, text).group() From srilyk at gmail.com Tue Feb 10 12:44:32 2009 From: srilyk at gmail.com (W W) Date: Tue, 10 Feb 2009 05:44:32 -0600 Subject: [Tutor] IDLE vs PythonWin In-Reply-To: References: <417247.59687.qm@web82007.mail.mud.yahoo.com> <413868.49755.qm@web86709.mail.ird.yahoo.com> <4990C394.8090702@sbcglobal.net> <960063.93932.qm@web86705.mail.ird.yahoo.com> <4990D3E4.1040901@sbcglobal.net> Message-ID: <333efb450902100344wad22a80vc5f8425d6256b55b@mail.gmail.com> On Mon, Feb 9, 2009 at 9:29 PM, Eric Dorsey wrote: > You can call a .py script from the command line, and it will run there. So, > in Windows XP: Start > Run > type "CMD" > Vista: Start > type "CMD" into the Start Search field. > If you're in Linux, get to a Terminal. > In Windows another window will open with something > like...C:\FolderWithMyPyFile> > Linux something like.... me at ubuntu-desktop:~$ > > Assuming "uberprogram.py" is in the current folder, you can then just type > into the command prompt like C:\FolderWithMyPyFile>uberprogram enter> > > You can see the results of the program right in the command prompt/terminal > window. > Unless your program doesn't wait for any input before quitting.Then you just have to add a line like this: raw_input("Press to quit") and that will block until you hit return. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Feb 10 13:01:57 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 10 Feb 2009 07:01:57 -0500 Subject: [Tutor] Picking up citations In-Reply-To: References: Message-ID: <1c2a2c590902100401w7ac4971bx844b31c3c90d0339@mail.gmail.com> On Mon, Feb 9, 2009 at 12:51 PM, Dinesh B Vadhia wrote: > Kent /Emmanuel > > Below are the results using the PLY parser and Regex versions on the > attached 'sierra' data which I think covers the common formats. Here are > some 'fully unparsed" citations that were missed by the programs: > > Smith v. Wisconsin Dept. of Agriculture, 23 F.3d 1134, 1141 (7th Cir.1994) > > Indemnified Capital Investments, S.A. v. R.J. O'Brien & Assoc., Inc., 12 > F.3d 1406, 1409 (7th Cir.1993). > > Hunt v. Washington Apple Advertising Commn., 432 U.S. 333, 343, 97 S.Ct. > 2434, 2441, 53 L.Ed.2d 383 (1977) > > Idaho Conservation League v. Mumma, 956 F.2d 1508, 1517-18 (9th Cir.1992) A few issues here: S.A. - this is hard, to allow this while filtering out sentences R.J. O'Brien, etc. - Loosening up the rules for the second name can allow these 1517-18 - allow page ranges The name issues are getting to be too much for me. Attached is a PLY version that just pulls out the citation without the name; at one point you indicated that would work for you. Kent -------------- next part -------------- A non-text attachment was scrubbed... Name: ParseCitationNoNamesPLY.py Type: text/x-python Size: 3801 bytes Desc: not available URL: From python at bdurham.com Tue Feb 10 15:43:18 2009 From: python at bdurham.com (python at bdurham.com) Date: Tue, 10 Feb 2009 09:43:18 -0500 Subject: [Tutor] Simple PassGen In-Reply-To: <1c2a2c590902091846v2d8d2258l461d8a7dc92b0edd@mail.gmail.com> References: <333efb450902091353k3eb2608aw26f6b45c925a7296@mail.gmail.com> <40af687b0902091432y3887f13ctd1c431c364879a06@mail.gmail.com> <1c2a2c590902091846v2d8d2258l461d8a7dc92b0edd@mail.gmail.com> Message-ID: <1234276998.12280.1299569363@webmail.messagingengine.com> Kent, > Except they are not equivalent when you want to print more than one thing. > ... > Python 2.6: > In [1]: print(3, 4) > (3, 4) I'm running Python 2.6.1 (32-bit) on Windows XP. I don't get the tuple-like output that you get. Here's what I get: >>> print( 3, 4 ) 3 4 Malcolm From sierra_mtnview at sbcglobal.net Tue Feb 10 15:59:41 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 10 Feb 2009 06:59:41 -0800 Subject: [Tutor] Tkinter program start with focus?` In-Reply-To: <333efb450901311047o34059716o923fe286acfc63bb@mail.gmail.com> References: <333efb450901311047o34059716o923fe286acfc63bb@mail.gmail.com> Message-ID: <4991965D.5040802@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Tue Feb 10 16:02:05 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 10 Feb 2009 07:02:05 -0800 Subject: [Tutor] IDLE vs PythonWin In-Reply-To: <667051.84438.qm@web86710.mail.ird.yahoo.com> References: <417247.59687.qm@web82007.mail.mud.yahoo.com> <413868.49755.qm@web86709.mail.ird.yahoo.com> <4990C394.8090702@sbcglobal.net> <960063.93932.qm@web86705.mail.ird.yahoo.com> <4990D3B9.9020500@sbcglobal.net> <667051.84438.qm@web86710.mail.ird.yahoo.com> Message-ID: <499196ED.1060909@sbcglobal.net> An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Tue Feb 10 16:15:01 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 10 Feb 2009 15:15:01 +0000 (UTC) Subject: [Tutor] Simple PassGen References: <333efb450902091353k3eb2608aw26f6b45c925a7296@mail.gmail.com> <40af687b0902091432y3887f13ctd1c431c364879a06@mail.gmail.com> <1c2a2c590902091846v2d8d2258l461d8a7dc92b0edd@mail.gmail.com> <1234276998.12280.1299569363@webmail.messagingengine.com> Message-ID: On Tue, 10 Feb 2009 09:43:18 -0500, python wrote: > Kent, > >> Except they are not equivalent when you want to print more than one >> thing. ... >> Python 2.6: >> In [1]: print(3, 4) >> (3, 4) > > I'm running Python 2.6.1 (32-bit) on Windows XP. > > I don't get the tuple-like output that you get. > > Here's what I get: > >>>> print( 3, 4 ) > 3 4 Are you sure it isn't python 3.x you're playing with? The reason why simple print function "works" in python 2.x is because of a syntactical coincidence, it is still a 100% statement. From python at bdurham.com Tue Feb 10 16:26:54 2009 From: python at bdurham.com (python at bdurham.com) Date: Tue, 10 Feb 2009 10:26:54 -0500 Subject: [Tutor] Simple PassGen In-Reply-To: References: <333efb450902091353k3eb2608aw26f6b45c925a7296@mail.gmail.com> <40af687b0902091432y3887f13ctd1c431c364879a06@mail.gmail.com> <1c2a2c590902091846v2d8d2258l461d8a7dc92b0edd@mail.gmail.com> <1234276998.12280.1299569363@webmail.messagingengine.com> Message-ID: <1234279614.22140.1299578469@webmail.messagingengine.com> Lie, >> Here's what I get: >> >> >>> print( 3, 4 ) >> 3 4 > Are you sure it isn't python 3.x you're playing with? The reason why simple print function "works" in python 2.x is because of a syntactical coincidence, it is still a 100% statement. Yes, I'm sure :) I restarted IDLE and pasted my session output below: Python 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 2.6.1 >>> from __future__ import print_function >>> print( 3, 4 ) 3 4 >>> Malcolm ----- Original message ----- From: "Lie Ryan" To: tutor at python.org Date: Tue, 10 Feb 2009 15:15:01 +0000 (UTC) Subject: Re: [Tutor] Simple PassGen On Tue, 10 Feb 2009 09:43:18 -0500, python wrote: > Kent, > >> Except they are not equivalent when you want to print more than one >> thing. ... >> Python 2.6: >> In [1]: print(3, 4) >> (3, 4) > > I'm running Python 2.6.1 (32-bit) on Windows XP. > > I don't get the tuple-like output that you get. > > Here's what I get: > >>>> print( 3, 4 ) > 3 4 Are you sure it isn't python 3.x you're playing with? The reason why simple print function "works" in python 2.x is because of a syntactical coincidence, it is still a 100% statement. _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From denis.spir at free.fr Tue Feb 10 16:35:26 2009 From: denis.spir at free.fr (spir) Date: Tue, 10 Feb 2009 16:35:26 +0100 Subject: [Tutor] Simple PassGen In-Reply-To: <1234279614.22140.1299578469@webmail.messagingengine.com> References: <333efb450902091353k3eb2608aw26f6b45c925a7296@mail.gmail.com> <40af687b0902091432y3887f13ctd1c431c364879a06@mail.gmail.com> <1c2a2c590902091846v2d8d2258l461d8a7dc92b0edd@mail.gmail.com> <1234276998.12280.1299569363@webmail.messagingengine.com> <1234279614.22140.1299578469@webmail.messagingengine.com> Message-ID: <20090210163526.2390ff26@o> Le Tue, 10 Feb 2009 10:26:54 -0500, python at bdurham.com a ?crit : > IDLE 2.6.1 > >>> from __future__ import print_function > >>> print( 3, 4 ) > 3 4 lol! ------ la vida e estranya From sierra_mtnview at sbcglobal.net Tue Feb 10 16:59:50 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 10 Feb 2009 07:59:50 -0800 Subject: [Tutor] Reply All Dilemma of This List Message-ID: <4991A476.2070609@sbcglobal.net> An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: moz-screenshot-171.jpg Type: image/jpeg Size: 13068 bytes Desc: not available URL: From payo2000 at gmail.com Tue Feb 10 18:08:26 2009 From: payo2000 at gmail.com (pa yo) Date: Tue, 10 Feb 2009 18:08:26 +0100 Subject: [Tutor] Inserting special characters into urlencoded string Message-ID: Novice programmer here. I am using urllib.urlencode to post content to a web page: ... >>Title = "First Steps" >>Text = "Hello World." >>Username = "Payo2000" >>Content = Text + "From: " + Username >>SubmitText = urllib.urlencode(dict(Action = 'submit', Headline = Title, Textbox = Content)) >>Submit = opener.open('http://www.website.com/index.php?', SubmitText) This works fine to produce in this: "Hello World From Payo2000" ...on the page. However I can't work out how to add a linefeed (urlencode: %0A) in front of Username so that I get: "Hello World. From: Payo2000" Any hints, tips or suggestions welcome! Payo From brian.mathis at gmail.com Tue Feb 10 18:20:51 2009 From: brian.mathis at gmail.com (Brian Mathis) Date: Tue, 10 Feb 2009 12:20:51 -0500 Subject: [Tutor] Reply All Dilemma of This List In-Reply-To: <4991A476.2070609@sbcglobal.net> References: <4991A476.2070609@sbcglobal.net> Message-ID: <183c528b0902100920y18e2217ld7e1524eb06ebaca@mail.gmail.com> You've stepped on a religious-war landmine. You can read all about why this is bad here: http://www.unicom.com/pw/reply-to-harmful.html ("Reply-To" Munging Considered Harmful) and why it's good here: http://www.metasystema.net/essays/reply-to.mhtml (Reply-To Munging Considered Useful) This war has been raging since the dawn of mailing lists, and you're not likely to get a resolution now either. To me, the context of a mailing list warrants the use of Reply-All to the list, since a mailing list is typically meant to be a group discussion. In this configuration, it takes extra effort to reply privately, which is exactly the sort of thing you'd want to promote in a group discussion. On Tue, Feb 10, 2009 at 10:59 AM, Wayne Watson wrote: > I belong to many, many forums, Yahoo Groups, (Usenet) newsgroups, and mail > lists. Probably 100 or more. I think it's fair to say that none of them but > this one has an implicit "Reply All". For newsgroups and mail lists, I just > press my Mozilla Seamonkey mailer Reply button and the resulting message is > ready to be seen by everyone, a single address. Here a Reply goes only to > the poster, none to Tutor. Elsewhere, for e-mail-like posts, if I really > want to make a special effort to single out the poster too, "Reply All" > works to additionally get it directly to them (actually they'd get two > messages directly) and the entire list. For YGs and forums, the "Reply > All" is implicit in a response. > > Since this group, in my world, is unique in these matters, I'll just offer > the following header for a mail list I belong to, the ASTC, for someone's > consideration. I suppose that someone might be whoever created this mail > list. It' definitely different than used here, and no one uses "Reply All" > to my knowledge. > > Maybe they can figure out if it has applicability here. > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) > > > The Richard Feynman Problem-Solving Algorithm: > (1) write down the problem; > (2) think very hard; > (3) write down the answer. > > Web Page: > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From mwalsh at mwalsh.org Tue Feb 10 18:26:33 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Tue, 10 Feb 2009 11:26:33 -0600 Subject: [Tutor] Reply All Dilemma of This List In-Reply-To: <4991A476.2070609@sbcglobal.net> References: <4991A476.2070609@sbcglobal.net> Message-ID: <4991B8C9.7030505@mwalsh.org> Wayne Watson wrote: > I belong to many, many forums, Yahoo Groups, (Usenet) newsgroups, and > mail lists. Probably 100 or more. I think it's fair to say that none of > them but this one has an implicit "Reply All". For newsgroups and mail > lists, I just press my Mozilla Seamonkey mailer Reply button and the > resulting message is ready to be seen by everyone, a single address. > Here a Reply goes only to the poster, none to Tutor. Elsewhere, for > e-mail-like posts, if I really want to make a special effort to single > out the poster too, "Reply All" works to additionally get it directly to > them (actually they'd get two messages directly) and the entire list. > For YGs and forums, the "Reply All" is implicit in a response. > > Since this group, in my world, is unique in these matters, I'll just > offer the following header for a mail list I belong to, the ASTC, for > someone's consideration. I suppose that someone might be whoever created > this mail list. It' definitely different than used here, and no one uses > "Reply All" to my knowledge. > > Maybe they can figure out if it has applicability here. This is a contentious topic which comes up at least once a year on this list. A search of the archives will turn up some interesting debate, most likely. FWIW, I like the behavior of this list as opposed to others. You may find these additional references illuminating ... you may not. http://effbot.org/pyfaq/tutor-why-do-my-replies-go-to-the-person-who-sent-the-message-and-not-to-the-list.htm http://woozle.org/~neale/papers/reply-to-still-harmful.html HTH, Marty From dineshbvadhia at hotmail.com Tue Feb 10 18:42:16 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Tue, 10 Feb 2009 09:42:16 -0800 Subject: [Tutor] Picking up citations In-Reply-To: <1c2a2c590902100401w7ac4971bx844b31c3c90d0339@mail.gmail.com> References: <1c2a2c590902100401w7ac4971bx844b31c3c90d0339@mail.gmail.com> Message-ID: Kent The citation without the name is perfect (and this appears to be how most citation parsers work). There are two issues in the test run: 1. The parallel citation 422 U.S. 490, 499 n. 10, 95 S.Ct. 2197, 2205 n. 10, 45 L.Ed.2d 343 (1975) is resolved as: 422 U.S. 490 (1975) 499 n. 10 (1975) 95 S.Ct. 2197 (1975) 2205 n. 10 (1975) 45 L.Ed.2d 343 (1975) instead of as: 422 U.S. 490, 499 n. 10 (1975) 95 S.Ct. 2197, 2205 n. 10 (1975) 45 L.Ed.2d 343 (1975) ie. parsing the second page references should pick up all alphanumeric chars between the commas. 2. It doesn't parse the last citation ie. 463 U.S. 29, 43, 103 S.Ct. 2856, 2867, 77 L.Ed.2d 443 (1983). I tested it on another sample text and it missed the last citation too. Thanks! Dinesh From: Kent Johnson Sent: Tuesday, February 10, 2009 4:01 AM To: Dinesh B Vadhia Cc: tutor at python.org Subject: Re: [Tutor] Picking up citations On Mon, Feb 9, 2009 at 12:51 PM, Dinesh B Vadhia wrote: > Kent /Emmanuel > > Below are the results using the PLY parser and Regex versions on the > attached 'sierra' data which I think covers the common formats. Here are > some 'fully unparsed" citations that were missed by the programs: > > Smith v. Wisconsin Dept. of Agriculture, 23 F.3d 1134, 1141 (7th Cir.1994) > > Indemnified Capital Investments, S.A. v. R.J. O'Brien & Assoc., Inc., 12 > F.3d 1406, 1409 (7th Cir.1993). > > Hunt v. Washington Apple Advertising Commn., 432 U.S. 333, 343, 97 S.Ct. > 2434, 2441, 53 L.Ed.2d 383 (1977) > > Idaho Conservation League v. Mumma, 956 F.2d 1508, 1517-18 (9th Cir.1992) A few issues here: S.A. - this is hard, to allow this while filtering out sentences R.J. O'Brien, etc. - Loosening up the rules for the second name can allow these 1517-18 - allow page ranges The name issues are getting to be too much for me. Attached is a PLY version that just pulls out the citation without the name; at one point you indicated that would work for you. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Tue Feb 10 18:43:00 2009 From: python at bdurham.com (python at bdurham.com) Date: Tue, 10 Feb 2009 12:43:00 -0500 Subject: [Tutor] Simple PassGen In-Reply-To: <20090210163526.2390ff26@o> References: <333efb450902091353k3eb2608aw26f6b45c925a7296@mail.gmail.com> <40af687b0902091432y3887f13ctd1c431c364879a06@mail.gmail.com> <1c2a2c590902091846v2d8d2258l461d8a7dc92b0edd@mail.gmail.com> <1234276998.12280.1299569363@webmail.messagingengine.com> <1234279614.22140.1299578469@webmail.messagingengine.com> <20090210163526.2390ff26@o> Message-ID: <1234287780.20235.1299606633@webmail.messagingengine.com> DOH! I just realized why we're getting different results. Sorry for the confusion - I wasn't trying to be a smart-ass! We've been trying to future proof our new code for Python 3.x so we automatically have 3.0 print() functionality enabled in our Python 2.6 dev environments. Malcolm ----- Original message ----- From: "spir" To: tutor at python.org Date: Tue, 10 Feb 2009 16:35:26 +0100 Subject: Re: [Tutor] Simple PassGen Le Tue, 10 Feb 2009 10:26:54 -0500, python at bdurham.com a ?crit : > IDLE 2.6.1 > >>> from __future__ import print_function > >>> print( 3, 4 ) > 3 4 lol! ------ la vida e estranya _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor From denis.spir at free.fr Tue Feb 10 18:48:29 2009 From: denis.spir at free.fr (spir) Date: Tue, 10 Feb 2009 18:48:29 +0100 Subject: [Tutor] Inserting special characters into urlencoded string In-Reply-To: References: Message-ID: <20090210184829.7decfcf1@o> Le Tue, 10 Feb 2009 18:08:26 +0100, pa yo a ?crit : > Novice programmer here. > > I am using urllib.urlencode to post content to a web page: > > ... > >>Title = "First Steps" > >>Text = "Hello World." > >>Username = "Payo2000" > >>Content = Text + "From: " + Username > >>SubmitText = urllib.urlencode(dict(Action = 'submit', Headline = Title, Textbox = Content)) > >>Submit = opener.open('http://www.website.com/index.php?', SubmitText) > > This works fine to produce in this: > > "Hello World From Payo2000" > > ...on the page. > > However I can't work out how to add a linefeed (urlencode: %0A) in > front of Username so that I get: > > "Hello World. > From: Payo2000" > > Any hints, tips or suggestions welcome! In python (and many other languages) some special characters that are not easy to represent have a code: LF : \n CR : \r TAB : \t So just add \n to to first line to add an eol: Text = "Hello World.\n" [Beware that inside python \n actually both means char #10 and 'newline', transparently, whatever the os uses as 'newline' code for text files. Very handy.] Alternatively, as you seem to be used to web codes, you can have hexa representation \x0a or even octal \012 Denis ----- la vida e estranya From denis.spir at free.fr Tue Feb 10 18:51:42 2009 From: denis.spir at free.fr (spir) Date: Tue, 10 Feb 2009 18:51:42 +0100 Subject: [Tutor] Reply All Dilemma of This List In-Reply-To: <183c528b0902100920y18e2217ld7e1524eb06ebaca@mail.gmail.com> References: <4991A476.2070609@sbcglobal.net> <183c528b0902100920y18e2217ld7e1524eb06ebaca@mail.gmail.com> Message-ID: <20090210185142.3a1af0d6@o> Le Tue, 10 Feb 2009 12:20:51 -0500, Brian Mathis a ?crit : > This war has been raging since the dawn of mailing lists, and you're > not likely to get a resolution now either. Newer mail user agents have a "to list" reply button. End of war? ------ la vida e estranya From payo2000 at gmail.com Tue Feb 10 18:54:28 2009 From: payo2000 at gmail.com (pa yo) Date: Tue, 10 Feb 2009 18:54:28 +0100 Subject: [Tutor] Inserting special characters into urlencoded string In-Reply-To: <20090210184829.7decfcf1@o> References: <20090210184829.7decfcf1@o> Message-ID: "Denis,\n\nThat works perfectly!\n\nMerci Beaucoup!\n\nPayo" :-) On Tue, Feb 10, 2009 at 6:48 PM, spir wrote: > Le Tue, 10 Feb 2009 18:08:26 +0100, > pa yo a ?crit : > >> Novice programmer here. >> >> I am using urllib.urlencode to post content to a web page: >> >> ... >> >>Title = "First Steps" >> >>Text = "Hello World." >> >>Username = "Payo2000" >> >>Content = Text + "From: " + Username >> >>SubmitText = urllib.urlencode(dict(Action = 'submit', Headline = Title, Textbox = Content)) >> >>Submit = opener.open('http://www.website.com/index.php?', SubmitText) >> >> This works fine to produce in this: >> >> "Hello World From Payo2000" >> >> ...on the page. >> >> However I can't work out how to add a linefeed (urlencode: %0A) in >> front of Username so that I get: >> >> "Hello World. >> From: Payo2000" >> >> Any hints, tips or suggestions welcome! > > In python (and many other languages) some special characters that are not easy to represent have a code: > LF : \n > CR : \r > TAB : \t > So just add \n to to first line to add an eol: Text = "Hello World.\n" [Beware that inside python \n actually both means char #10 and 'newline', transparently, whatever the os uses as 'newline' code for text files. Very handy.] > Alternatively, as you seem to be used to web codes, you can have hexa representation \x0a or even octal \012 > > Denis > ----- > la vida e estranya > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bermanrl at cfl.rr.com Tue Feb 10 18:56:08 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Tue, 10 Feb 2009 12:56:08 -0500 Subject: [Tutor] Reply All Dilemma of This List In-Reply-To: <20090210185142.3a1af0d6@o> References: <4991A476.2070609@sbcglobal.net> <183c528b0902100920y18e2217ld7e1524eb06ebaca@mail.gmail.com> <20090210185142.3a1af0d6@o> Message-ID: <4991BFB8.2070303@cfl.rr.com> An HTML attachment was scrubbed... URL: From andreas at kostyrka.org Tue Feb 10 19:45:47 2009 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Tue, 10 Feb 2009 19:45:47 +0100 Subject: [Tutor] Splitting strings and undefined variables In-Reply-To: <7b13ba330902091205k3c9fb875h43f8190b0ce2fa15@mail.gmail.com> References: <7b13ba330902091205k3c9fb875h43f8190b0ce2fa15@mail.gmail.com> Message-ID: <20090210194547.3056bde7@andi-lap> Am Mon, 9 Feb 2009 12:05:33 -0800 schrieb Moos Heintzen : > Hello all, > > I was looking at this: > http://www.debian.org/doc/manuals/reference/ch-program.en.html#s-python > > I have a question about the line of code that uses split() > > With the python version, the line below only works if there are three > fields in line. > > (first, last, passwd) = line.split() > > Also, since the variables are used like this: > > lineout = "%s:%s:%d:%d:%s %s,,/home/%s:/bin/bash\n" % \ > (user, passwd, uid, gid, first, last, user) > > I can't use ":".join(line.split()) > But maybe a dictionary could be used for string substitution. > > In the perl version (above the python version in the link), the script > works with the input line having one to three fields. Like "fname > lname pw" or "fname lname" > > ($n1, $n2, $n3) = split / /; > > Is there a better way to extract the fields from line in a more > flexible way, so that the number of fields could vary? > I guess we could use conditionals to check each field, but is there a > more elegant (or pythonic!) way to do it? Well, the problem you are getting is probably a ValueError, meaning that the number of items does not match the expected number: >>> a, b = 1, 2, 3 Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack >>> a, b, c, d = 1, 2, 3 Traceback (most recent call last): File "", line 1, in ValueError: need more than 3 values to unpack Assuming that you want to have empty strings as the default you can use: a, b, c = (line.split() + ["", ""])[:3] Ok, step by step: line.split() produces a list with at least one string, assuming that line is a string. line.split() + ["", ""] creates a new list with two empty strings added to the end. [:3] gives you the first three strings of that list. Generally speaking, the above should be only used when you really really know that you want to threat your data such a way (ignore all later fields, add empty strings), it has a real potential for later debugging pains, when the data turns out to be different than what you expected. Another way would be: a, b, c = "defaultA", "defaultB", "defaultC" try: flds = line.split() a = flds[0] b = flds[1] c = flds[2] except IndexError: pass That still ignores any errors coming your way, usually it's better to check on len(flds). Generally, defensive programming (as in processing ANY data given, e.g. HTML parsing in browsers) is sometimes necessary, but often not such a good idea (one usually prefers an error message than faulty output data. Nothing more embarrasing then contacting your customers to tell them that the billing program was faulty and you billed them to much the last two years *g*). Andreas > > Moos > > P.S. I'm not a Perl user, I was just reading the examples. I've been > using C and awk for few years, and Python for few months. Also, I know > blank passwords aren't very practical, but I'm just asking this to > explore possibilities :) > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Tue Feb 10 19:57:46 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 10 Feb 2009 13:57:46 -0500 Subject: [Tutor] Picking up citations In-Reply-To: References: <1c2a2c590902100401w7ac4971bx844b31c3c90d0339@mail.gmail.com> Message-ID: <1c2a2c590902101057k15441bd4kc9e852a7905c70f4@mail.gmail.com> On Tue, Feb 10, 2009 at 12:42 PM, Dinesh B Vadhia wrote: > Kent > > The citation without the name is perfect (and this appears to be how most > citation parsers work). There are two issues in the test run: > > 1. The parallel citation 422 U.S. 490, 499 n. 10, 95 S.Ct. 2197, 2205 n. > 10, 45 L.Ed.2d 343 (1975) is resolved as: > > 422 U.S. 490 (1975) > 499 n. 10 (1975) > 95 S.Ct. 2197 (1975) > 2205 n. 10 (1975) > 45 L.Ed.2d 343 (1975) > > instead of as: > > 422 U.S. 490, 499 n. 10 (1975) > 95 S.Ct. 2197, 2205 n. 10 (1975) > 45 L.Ed.2d 343 (1975) > > ie. parsing the second page references should pick up all alphanumeric chars > between the commas. So 499 n. 10 is a page reference? I can't pick up all alphanumeric chars between commas, that would include a second reference. Kent From jfabiani at yolo.com Tue Feb 10 19:42:58 2009 From: jfabiani at yolo.com (johnf) Date: Tue, 10 Feb 2009 10:42:58 -0800 Subject: [Tutor] can't import Danny.OOo.OOoLib.py Message-ID: <200902101042.58369.jfabiani@yolo.com> Hi, How silly of me to think I understood the import command. I'm trying to learn how to automate printing documents from OpenOffice using python. I found several ways and I was able to get some of them to work. But I found the Danny.OOo.OOoLib.py tools (kind of old 2005 but still on the wiki) and was hoping I could try them. I placed the Danny.OOo.OOoLib.py file into my local folder and attempted to import. It immediately fails with the following message: ImportError: No module named Danny.OOo.OOoLib So could someone enlighten me as to why it reports this error? The file is in the local directory/folder. I cd to the directory. What else is required? -- John Fabiani From kent37 at tds.net Tue Feb 10 21:13:44 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 10 Feb 2009 15:13:44 -0500 Subject: [Tutor] can't import Danny.OOo.OOoLib.py In-Reply-To: <200902101042.58369.jfabiani@yolo.com> References: <200902101042.58369.jfabiani@yolo.com> Message-ID: <1c2a2c590902101213x37f282bcj6095c0f249425fcf@mail.gmail.com> On Tue, Feb 10, 2009 at 1:42 PM, johnf wrote: > Hi, > How silly of me to think I understood the import command. I'm trying to learn > how to automate printing documents from OpenOffice using python. I found > several ways and I was able to get some of them to work. But I found the > Danny.OOo.OOoLib.py tools (kind of old 2005 but still on the wiki) and was > hoping I could try them. I placed the Danny.OOo.OOoLib.py file into my local > folder and attempted to import. It immediately fails with the following > message: > ImportError: No module named Danny.OOo.OOoLib It's looking for Danny/OOo/OOoLib.py. Try renaming the file to have no . in the file name. Kent From ptmcg at austin.rr.com Tue Feb 10 21:29:20 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 10 Feb 2009 14:29:20 -0600 Subject: [Tutor] Picking up citations In-Reply-To: References: Message-ID: <0A8F5CCA89BF4B08BECD3C4B86F18D86@AWA2> Dinesh and Kent - I've been lurking along as you run this problem to ground. The syntax you are working on looks very slippery, and reminds me of some of the issues I had writing a generic street address parser with pyparsing (http://pyparsing.wikispaces.com/file/view/streetAddressParser.py). Mailing list companies spend beaucoup $$$ trying to parse addresses in order to filter duplicates, to group by zip code, street, neighborhood, etc., and this citation format looks similarly scary. Congratulations on getting to a 95% solution using PLY. -- Paul From dineshbvadhia at hotmail.com Tue Feb 10 22:09:24 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Tue, 10 Feb 2009 13:09:24 -0800 Subject: [Tutor] Picking up citations In-Reply-To: <1c2a2c590902100401w7ac4971bx844b31c3c90d0339@mail.gmail.com> <1c2a2c590902101057k15441bd4kc9e852a7905c70f4@mail.gmail.com> References: <1c2a2c590902100401w7ac4971bx844b31c3c90d0339@mail.gmail.com> <1c2a2c590902101057k15441bd4kc9e852a7905c70f4@mail.gmail.com> Message-ID: I'm guessing that '499 n. 10' is a page reference ie. page 499, point number 10. Legal citations are all a mystery - they even have their own citation bluebook (http://www.legalbluebook.com/) ! Dinesh From: Kent Johnson Sent: Tuesday, February 10, 2009 10:57 AM To: Dinesh B Vadhia Cc: tutor at python.org Subject: Re: [Tutor] Picking up citations On Tue, Feb 10, 2009 at 12:42 PM, Dinesh B Vadhia wrote: > Kent > > The citation without the name is perfect (and this appears to be how most > citation parsers work). There are two issues in the test run: > > 1. The parallel citation 422 U.S. 490, 499 n. 10, 95 S.Ct. 2197, 2205 n. > 10, 45 L.Ed.2d 343 (1975) is resolved as: > > 422 U.S. 490 (1975) > 499 n. 10 (1975) > 95 S.Ct. 2197 (1975) > 2205 n. 10 (1975) > 45 L.Ed.2d 343 (1975) > > instead of as: > > 422 U.S. 490, 499 n. 10 (1975) > 95 S.Ct. 2197, 2205 n. 10 (1975) > 45 L.Ed.2d 343 (1975) > > ie. parsing the second page references should pick up all alphanumeric chars > between the commas. So 499 n. 10 is a page reference? I can't pick up all alphanumeric chars between commas, that would include a second reference. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Feb 10 23:54:10 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 10 Feb 2009 17:54:10 -0500 Subject: [Tutor] Picking up citations In-Reply-To: References: <1c2a2c590902100401w7ac4971bx844b31c3c90d0339@mail.gmail.com> Message-ID: <1c2a2c590902101454l6679ffd7ve8a960327b89d612@mail.gmail.com> On Tue, Feb 10, 2009 at 12:42 PM, Dinesh B Vadhia wrote: > Kent > > The citation without the name is perfect (and this appears to be how most > citation parsers work). There are two issues in the test run: > > 1. The parallel citation 422 U.S. 490, 499 n. 10, 95 S.Ct. 2197, 2205 n. > 10, 45 L.Ed.2d 343 (1975) is resolved as: > > 422 U.S. 490 (1975) > 499 n. 10 (1975) > 95 S.Ct. 2197 (1975) > 2205 n. 10 (1975) > 45 L.Ed.2d 343 (1975) > 2. It doesn't parse the last citation ie. 463 U.S. 29, 43, 103 S.Ct. 2856, > 2867, 77 L.Ed.2d 443 (1983). I tested it on another sample text and it > missed the last citation too. Another attempt attached, it recognizes the n. separator and gets the last item. Kent From wferguson1 at socal.rr.com Wed Feb 11 00:25:03 2009 From: wferguson1 at socal.rr.com (WM.) Date: Tue, 10 Feb 2009 15:25:03 -0800 Subject: [Tutor] IDLE Message-ID: <49920CCF.20001@socal.rr.com> A while back I made a big fuss about how IDLE indenting works. Kent was finally able to use language simple enough for me to understand. So I kept working IDLE. Today I got an error message. Somebody fixed it! It now indents just like all the other Python windows. Great going, Snake. And thank you guys. From alan.gauld at btinternet.com Wed Feb 11 01:15:33 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Feb 2009 00:15:33 -0000 Subject: [Tutor] IDLE References: <49920CCF.20001@socal.rr.com> Message-ID: "WM." wrote >A while back I made a big fuss about how IDLE indenting works. Kent >was finally able to use language simple enough for me to understand. >So I kept working IDLE. Today I got an error message. Somebody fixed >it! It now indents just like all the other Python windows. Great >going, Snake. Can you share how you got it fixed? I'd love to see an IDLE that indented sensibly! Alan G From sierra_mtnview at sbcglobal.net Wed Feb 11 03:02:32 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 10 Feb 2009 18:02:32 -0800 Subject: [Tutor] Reply All Dilemma of This List In-Reply-To: <4991B8C9.7030505@mwalsh.org> References: <4991A476.2070609@sbcglobal.net> <4991B8C9.7030505@mwalsh.org> Message-ID: <499231B8.3010108@sbcglobal.net> An HTML attachment was scrubbed... URL: From wferguson1 at socal.rr.com Wed Feb 11 03:37:23 2009 From: wferguson1 at socal.rr.com (WM.) Date: Tue, 10 Feb 2009 18:37:23 -0800 Subject: [Tutor] IDLE Message-ID: <499239E3.40102@socal.rr.com> Allen G.asked me how I made IDLE work. I did nothing on purpose. One can open Python into the IDLE window or into the program window. I recently changed from the program window to the IDLE window. IDLE now works exactly right. As a bonus my DOS-oidle window which used to produce error messages now works like a Trojan, also. From sierra_mtnview at sbcglobal.net Wed Feb 11 04:33:50 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 10 Feb 2009 19:33:50 -0800 Subject: [Tutor] IDLE/phythonWin -- Who's On First? (Abbott and Costello) Message-ID: <4992471E.40300@sbcglobal.net> An HTML attachment was scrubbed... URL: From dineshbvadhia at hotmail.com Wed Feb 11 07:35:15 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Tue, 10 Feb 2009 22:35:15 -0800 Subject: [Tutor] Picking up citations Message-ID: You're probably right Paul. But, my assumption is that the originators of legal documents pay a little more attention to getting the citation correct and in the right format then say Joe Bloggs does when completing an address block. I think that Kent has reached the end of his commendable effort. I'll test out the latest version in anger over the coming weeks on large numbers of legal documents. Dinesh -------------------------------------------------------------------------------- Message: 2 Date: Tue, 10 Feb 2009 14:29:20 -0600 From: "Paul McGuire" Subject: Re: [Tutor] Picking up citations To: Message-ID: <0A8F5CCA89BF4B08BECD3C4B86F18D86 at AWA2> Content-Type: text/plain; charset="us-ascii" Dinesh and Kent - I've been lurking along as you run this problem to ground. The syntax you are working on looks very slippery, and reminds me of some of the issues I had writing a generic street address parser with pyparsing (http://pyparsing.wikispaces.com/file/view/streetAddressParser.py). Mailing list companies spend beaucoup $$$ trying to parse addresses in order to filter duplicates, to group by zip code, street, neighborhood, etc., and this citation format looks similarly scary. Congratulations on getting to a 95% solution using PLY. -- Paul -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Wed Feb 11 10:28:51 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Feb 2009 09:28:51 -0000 Subject: [Tutor] IDLE/phythonWin -- Who's On First? (Abbott and Costello) References: <4992471E.40300@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Signature.htmlMy program in IDLE bombed with: > ============== > Exception in Tkinter callback > Traceback (most recent call last): > dialog = OperationalSettingsDialog( self.master, set_loc_dict ) > tkSimpleDialog.Dialog.__init__(self, parent) > self.wait_visibility() # window needs to be visible for the grab > But runs fine in pythonWin performing the same entry operation. Lets eliminate some variables by avoiding any IDEs. Does it work OK when run from a DOS console? Or if you just double click the file in Windows explorer? If it does that means its some kind of interaction between the program and IDLE. This is not unusual since IDLE is itself a Tkinter program and although recent versions are much better behaved with Tkinter it can still cause some strangeness. If you still get an error running outside the IDE then we can analyze it more closely. For that we will need the code, at least the function that calls the dialog. And if its a subclass the dialog class too. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From alan.gauld at btinternet.com Wed Feb 11 10:33:42 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 11 Feb 2009 09:33:42 -0000 Subject: [Tutor] IDLE References: <499239E3.40102@socal.rr.com> Message-ID: "WM." wrote > Allen G.asked me how I made IDLE work. I did nothing on purpose. One > can open Python into the IDLE window or into the program window. I assume you mean the editor window? Yes that will produce proper indentation, it is only the shell window that is broken because the >>> prompt produces an offset in the first line. > changed from the program window to the IDLE window. IDLE now works > exactly right. Except you don't evaluate the expressions as you type them which is what tbe shell window does... You need to run the program. > As a bonus my DOS-idle window which used to produce error messages > now works like a Trojan, also. I don't know what you mean by the dos-idle window? Alan G. From sierra_mtnview at sbcglobal.net Wed Feb 11 11:03:06 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 11 Feb 2009 02:03:06 -0800 Subject: [Tutor] IDLE/phythonWin -- Who's On First? (Abbott and Costello) In-Reply-To: References: <4992471E.40300@sbcglobal.net> Message-ID: <4992A25A.8010401@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Feb 11 11:36:06 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 11 Feb 2009 02:36:06 -0800 Subject: [Tutor] IDLE/phythonWin -- Who's On First? (Abbott and Costello) In-Reply-To: <4992A25A.8010401@sbcglobal.net> References: <4992471E.40300@sbcglobal.net> <4992A25A.8010401@sbcglobal.net> Message-ID: <4992AA16.4080400@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Feb 11 12:31:08 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Feb 2009 06:31:08 -0500 Subject: [Tutor] Picking up citations In-Reply-To: <1c2a2c590902101454l6679ffd7ve8a960327b89d612@mail.gmail.com> References: <1c2a2c590902100401w7ac4971bx844b31c3c90d0339@mail.gmail.com> <1c2a2c590902101454l6679ffd7ve8a960327b89d612@mail.gmail.com> Message-ID: <1c2a2c590902110331o1f196bccy38aae28d0502e66d@mail.gmail.com> On Tue, Feb 10, 2009 at 5:54 PM, Kent Johnson wrote: > Another attempt attached, it recognizes the n. separator and gets the last item. And here is the actual attachment. Kent -------------- next part -------------- A non-text attachment was scrubbed... Name: ParseCitationNoNamesPLY.py Type: text/x-python Size: 3544 bytes Desc: not available URL: From lie.1296 at gmail.com Wed Feb 11 13:16:11 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 11 Feb 2009 23:16:11 +1100 Subject: [Tutor] Simple PassGen In-Reply-To: <1234279614.22140.1299578469@webmail.messagingengine.com> References: <333efb450902091353k3eb2608aw26f6b45c925a7296@mail.gmail.com> <40af687b0902091432y3887f13ctd1c431c364879a06@mail.gmail.com> <1c2a2c590902091846v2d8d2258l461d8a7dc92b0edd@mail.gmail.com> <1234276998.12280.1299569363@webmail.messagingengine.com> <1234279614.22140.1299578469@webmail.messagingengine.com> Message-ID: On Wed, Feb 11, 2009 at 2:26 AM, wrote: > > > Are you sure it isn't python 3.x you're playing with? The reason why > simple print function "works" in python 2.x is because of a syntactical > coincidence, it is still a 100% statement. > > Yes, I'm sure :) I restarted IDLE and pasted my session output below: You didn't tell that you imported __future__'s print_function! I thought I was having a hallucination or something... seeing that behavior in python2.6 -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Wed Feb 11 16:19:20 2009 From: python at bdurham.com (python at bdurham.com) Date: Wed, 11 Feb 2009 10:19:20 -0500 Subject: [Tutor] Simple PassGen In-Reply-To: References: <333efb450902091353k3eb2608aw26f6b45c925a7296@mail.gmail.com> <40af687b0902091432y3887f13ctd1c431c364879a06@mail.gmail.com> <1c2a2c590902091846v2d8d2258l461d8a7dc92b0edd@mail.gmail.com> <1234276998.12280.1299569363@webmail.messagingengine.com> <1234279614.22140.1299578469@webmail.messagingengine.com> Message-ID: <1234365560.11468.1299793971@webmail.messagingengine.com> Lie, The import from __future__ print_function happens automatically in our environment and I took this for granted. Sorry about the confusion :) Regards, Malcolm ----- Original message ----- From: "Lie Ryan" To: python at bdurham.com Cc: tutor at python.org Date: Wed, 11 Feb 2009 23:16:11 +1100 Subject: Re: [Tutor] Simple PassGen On Wed, Feb 11, 2009 at 2:26 AM, <[1]python at bdurham.com> wrote: > Are you sure it isn't python 3.x you're playing with? The reason why simple print function "works" in python 2.x is because of a syntactical coincidence, it is still a 100% statement. Yes, I'm sure :) I restarted IDLE and pasted my session output below: You didn't tell that you imported __future__'s print_function! I thought I was having a hallucination or something... seeing that behavior in python2.6 References 1. mailto:python at bdurham.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From telmo_andres at yahoo.com Wed Feb 11 21:01:36 2009 From: telmo_andres at yahoo.com (Andres Sanchez) Date: Wed, 11 Feb 2009 12:01:36 -0800 (PST) Subject: [Tutor] Extracting information from an EXCEL/Matlab file to use in Python Message-ID: <985447.46864.qm@web59910.mail.ac4.yahoo.com> Fellows, I am trying to extract information from a spreadsheet to use it in Python. For instance, say I have?the number 5.6 in cell A1 of?Sheet1 in the file example.xls?. Could anyone of you ladies and gentleman let me know what commands I need to type in Pyhton to open the file?that contains?the spreadsheet, localize cell A1, and finally save the value in that cell, e.g. 5.6,?as a variable in Python? Thank you for your help!! Andres -------------- next part -------------- An HTML attachment was scrubbed... URL: From =?UTF-8?Q?=22Shantanoo_Mahajan_=28=E0=A4=B6=E0=A4=82=E0=A4=A4?= Wed Feb 11 21:16:56 2009 From: =?UTF-8?Q?=22Shantanoo_Mahajan_=28=E0=A4=B6=E0=A4=82=E0=A4=A4?= (=?UTF-8?Q?=22Shantanoo_Mahajan_=28=E0=A4=B6=E0=A4=82=E0=A4=A4?=) Date: Thu, 12 Feb 2009 01:46:56 +0530 Subject: [Tutor] Extracting information from an EXCEL/Matlab file to use in Python In-Reply-To: <985447.46864.qm@web59910.mail.ac4.yahoo.com> References: <985447.46864.qm@web59910.mail.ac4.yahoo.com> Message-ID: <927628F7-9EBA-4FD3-A8A3-F7A5EAB4707E@gmail.com> On 12-Feb-09, at 1:31 AM, Andres Sanchez wrote: > Fellows, > > I am trying to extract information from a spreadsheet to use it in > Python. For instance, say I have the number 5.6 in cell A1 of Sheet1 > in the file example.xls . Could anyone of you ladies and gentleman > let me know what commands I need to type in Pyhton to open the file > that contains the spreadsheet, localize cell A1, and finally save > the value in that cell, e.g. 5.6, as a variable in Python? > > Thank you for your help!! > > Andres For reading .xls: http://pypi.python.org/pypi/xlrd/0.5.2 For writing .xls: http://sourceforge.net/projects/pyxlwriter/ regards, shantanoo From wescpy at gmail.com Wed Feb 11 23:44:42 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 11 Feb 2009 14:44:42 -0800 Subject: [Tutor] Extracting information from an EXCEL/Matlab file to use in Python In-Reply-To: <927628F7-9EBA-4FD3-A8A3-F7A5EAB4707E@gmail.com> References: <985447.46864.qm@web59910.mail.ac4.yahoo.com> <927628F7-9EBA-4FD3-A8A3-F7A5EAB4707E@gmail.com> Message-ID: <78b3a9580902111444h1f6893du7c80107ef85b5f4b@mail.gmail.com> On Wed, Feb 11, 2009 at 12:16 PM, "Shantanoo Mahajan (????? ?????)" wrote: > On 12-Feb-09, at 1:31 AM, Andres Sanchez wrote: > >> I am trying to extract information from a spreadsheet to use it in Python. > > For reading .xls: http://pypi.python.org/pypi/xlrd/0.5.2 > For writing .xls: http://sourceforge.net/projects/pyxlwriter/ pyXLWriter -- http://pypi.python.org/pypi/pyXLWriter ...stopped active development back in Aug 2004. it was "replaced" by... pyExcelerator -- http://pypi.python.org/pypi/pyExcelerator ...which has also stopped development (last release was Aug 2005). now ppl use... xlwt -- http://pypi.python.org/pypi/xlwt ... which appears to be actively maintained and developed. xlrd and xlrt do not require a win32 box, i.e., you can use *ix/MacOS to read/write .xls files. if you are an active win32 developer, you may wish to consider Python's Extensions for Windows to control/manipulate Excel directly -- http://pywin32.sf.net -- FWIW, there is some info on how to do this in Chapter 23 of "Core Python Programming". hope this helps! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From wescpy at gmail.com Wed Feb 11 23:47:15 2009 From: wescpy at gmail.com (wesley chun) Date: Wed, 11 Feb 2009 14:47:15 -0800 Subject: [Tutor] Extracting information from an EXCEL/Matlab file to use in Python In-Reply-To: <78b3a9580902111444h1f6893du7c80107ef85b5f4b@mail.gmail.com> References: <985447.46864.qm@web59910.mail.ac4.yahoo.com> <927628F7-9EBA-4FD3-A8A3-F7A5EAB4707E@gmail.com> <78b3a9580902111444h1f6893du7c80107ef85b5f4b@mail.gmail.com> Message-ID: <78b3a9580902111447j775e131fg31fb1d83f1a51f69@mail.gmail.com> >>> I am trying to extract information from a spreadsheet to use it in Python. >> For reading .xls: http://pypi.python.org/pypi/xlrd/0.5.2 i forgot to mention that xlrd is on version 0.6.1 now: http://pypi.python.org/pypi/xlrd -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From daychilde at gmail.com Thu Feb 12 00:20:58 2009 From: daychilde at gmail.com (Isaac Eiland-Hall) Date: Wed, 11 Feb 2009 15:20:58 -0800 Subject: [Tutor] How to foreach over a dynamic number of levels Message-ID: <00d701c98c9f$6a9506d0$3fbf1470$@com> I'm probably trying to go about this the wrong way - so I'm asking more for what direction to head in, at least. The group I'm working with has a python program (the Model Framework) that runs data through a number of models. For each possible step, there are multiple possible models. Each run also is for a single date. So the ini for Model Framework might be something like this: step1 = step1model-a step2 = step2model-a step3 = step3model-b step4 = step4model-a (so for any given step, one or more models exist. For a Model Framework run, you choose one model for any given step you choose to run) The program I'm working on will drive the framework and run it multiple times. For example, to run a range of dates; but also, to run a range of models - so you might want to run models a-h on days Jan1-Jan30 - that would be 8 times 30 = 240 runs. The program I'm working on needs to be Framework-agnostic. That is, I know that the framework's ini file consists of a number of key and value pairs, but my program has no concept of what these values *do*, or which ones *exist*. The end-user will basically take a Framework ini file, and change some values from strings to lists, for example: step1=["step1model-a","step1model-b","step1model-c"] My program will parse that, and know that it must iterate three times because of that line alone. So I do not know in advance how many keys I will have, nor how many of them will be arrays vs. strings, although my initial thought is that I can treat strings like single-member arrays - I don't care if I foreach a single time - execution time on that order of magnitude is irrelevant. I'm really not sure how in the world to accomplish this. The best method I can think of would involve somehow iterating through and generating code to exec, but frankly I don't even have that as a complete working solution. The other thought would be a function that called itself, but that is also very very ugly. I come from PHP, where you have variable variables. I think that would help me a lot here - I could at least dynamically nest my arrays, and call my arrays using variable vars. I'm definitely a pretty new programmer. I don't mind reading - but I've spent about 6 hours today googling for terms like "dynamic nesting" and found a lot of interesting stuff - but no clear direction to head in. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Isaac at Eiland-Hall.com Thu Feb 12 00:11:44 2009 From: Isaac at Eiland-Hall.com (Isaac Eiland-Hall) Date: Wed, 11 Feb 2009 15:11:44 -0800 Subject: [Tutor] How to foreach over a dynamic number of levels Message-ID: <00c701c98c9e$1c40cce0$54c266a0$@com> I'm probably trying to go about this the wrong way - so I'm asking more for what direction to head in, at least. The group I'm working with has a python program (the Model Framework) that runs data through a number of models. For each possible step, there are multiple possible models. Each run also is for a single date. So the ini for Model Framework might be something like this: step1 = step1model-a step2 = step2model-a step3 = step3model-b step4 = step4model-a (so for any given step, one or more models exist. For a Model Framework run, you choose one model for any given step you choose to run) The program I'm working on will drive the framework and run it multiple times. For example, to run a range of dates; but also, to run a range of models - so you might want to run models a-h on days Jan1-Jan30 - that would be 8 times 30 = 240 runs. The program I'm working on needs to be Framework-agnostic. That is, I know that the framework's ini file consists of a number of key and value pairs, but my program has no concept of what these values *do*, or which ones *exist*. The end-user will basically take a Framework ini file, and change some values from strings to lists, for example: step1=["step1model-a","step1model-b","step1model-c"] My program will parse that, and know that it must iterate three times because of that line alone. So I do not know in advance how many keys I will have, nor how many of them will be arrays vs. strings, although my initial thought is that I can treat strings like single-member arrays - I don't care if I foreach a single time - execution time on that order of magnitude is irrelevant. I'm really not sure how in the world to accomplish this. The best method I can think of would involve somehow iterating through and generating code to exec, but frankly I don't even have that as a complete working solution. The other thought would be a function that called itself, but that is also very very ugly. I come from PHP, where you have variable variables. I think that would help me a lot here - I could at least dynamically nest my arrays, and call my arrays using variable vars. I'm definitely a pretty new programmer. I don't mind reading - but I've spent about 6 hours today googling for terms like "dynamic nesting" and found a lot of interesting stuff - but no clear direction to head in. -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at abbottdavid.com Thu Feb 12 01:42:05 2009 From: david at abbottdavid.com (David) Date: Wed, 11 Feb 2009 19:42:05 -0500 Subject: [Tutor] Program to report if file was modified today Message-ID: <4993705D.3040202@abbottdavid.com> Hi Everyone and thanks for the list and your help. In my adventure in learning Python (never programed before) I am attempting to findout if a file has been modified today given a search path. It is working somewhat. Here it is; #!/usr/bin/python import sys import os import time def Mod(): """Find files modified today, given a file path.""" latest = 0 dir = os.path.dirname(sys.argv[1]) for fname in os.listdir(dir): if fname.endswith('.py'): modtime = os.stat(os.path.join(dir, fname)).st_mtime if modtime > latest: latest = modtime out = time.strftime('%Y-%m-%d', time.localtime(latest)) my_list = [fname, out] print fname now = time.strftime('%Y-%m-%d', time.localtime()) if my_list[-1] == now: print "This file has changed today." print "*"*30 else: print "This file did not change" results; ./py_lastmod_date.py /home/david/ py_pyparse_end.py This file did not change ****************************** cologne_time.py This file did not change ****************************** py_find_word_prefix.py This file did not change ****************************** py_round_by_five.py This file did not change ****************************** graphics.py This file did not change ****************************** py_countdown_generator.py This file did not change ****************************** py_compare_time.py This file has changed today. ****************************** py_lastmod_date.py This file has changed today. ****************************** OK here are my questions. Is there an easier way of doing this? Why does it only return 8 results, I have a ton of .py files in /home/david Why do both the if and else get printed? How do I do this without all the if statments? I don't understand the if modtime > latest part, is this to loop over the files and put the oldest last? I found that part in another program and my program does not work without it. Thank you, -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From kent37 at tds.net Thu Feb 12 01:44:00 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Feb 2009 19:44:00 -0500 Subject: [Tutor] How to foreach over a dynamic number of levels In-Reply-To: <00d701c98c9f$6a9506d0$3fbf1470$@com> References: <00d701c98c9f$6a9506d0$3fbf1470$@com> Message-ID: <1c2a2c590902111644x880b01dlfa07e94432120389@mail.gmail.com> On Wed, Feb 11, 2009 at 6:20 PM, Isaac Eiland-Hall wrote: > The group I'm working with has a python program (the Model Framework) that > runs data through a number of models. For each possible step, there are > multiple possible models. Each run also is for a single date. > > So the ini for Model Framework might be something like this: > > step1 = step1model-a > > step2 = step2model-a > > step3 = step3model-b > > step4 = step4model-a > The program I'm working on will drive the framework and run it multiple > times. For example, to run a range of dates; but also, to run a range of > models ? so you might want to run models a-h on days Jan1-Jan30 ? that would > be 8 times 30 = 240 runs. > > The end-user will basically take a Framework ini file, and change > some values from strings to lists, for example: > > step1=["step1model-a","step1model-b","step1model-c"] > > > > My program will parse that, and know that it must iterate three times > because of that line alone? > > > > So I do not know in advance how many keys I will have, nor how many of them > will be arrays vs. strings, although my initial thought is that I can treat > strings like single-member arrays ? I don't care if I foreach a single time > ? execution time on that order of magnitude is irrelevant? > > > > I'm really not sure how in the world to accomplish this? > > > > The best method I can think of would involve somehow iterating through and > generating code to exec, but frankly I don't even have that as a complete > working solution? The other thought would be a function that called itself, > but that is also very very ugly? It's much easier than that. You haven't asked about reading the ini file or running the model, so I'll leave that for another time. Let's assume you have the steps read in to variables like this: step1=["step1model-a","step1model-b","step1model-c"] step2 = "step2model-a" step3 = ["step3model-a", "step3model-b"] Make a list containing all the steps: steps = [step1, step2, step3] Now you need to convert all steps to lists. This loop builds a new list from the original step list, wrapping any bare strings in lists: step_lists = [] for step in steps: if isinstance(step, basestring): step = [step] step_lists.append(step) Now what you want is the Cartesian product of all the lists. Python has a function (new in Python 2.6) in the itertools library module that will do this: from itertools import product for model_set in product(*step_lists): print model_set (The * in the argument list means, take the elements of step_list and use them as the arguments to product()) The output is ('step1model-a', 'step2model-a', 'step3model-a') ('step1model-a', 'step2model-a', 'step3model-b') ('step1model-b', 'step2model-a', 'step3model-a') ('step1model-b', 'step2model-a', 'step3model-b') ('step1model-c', 'step2model-a', 'step3model-a') ('step1model-c', 'step2model-a', 'step3model-b') HTH Kent From bgailer at gmail.com Thu Feb 12 02:46:11 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 11 Feb 2009 20:46:11 -0500 Subject: [Tutor] Program to report if file was modified today In-Reply-To: <4993705D.3040202@abbottdavid.com> References: <4993705D.3040202@abbottdavid.com> Message-ID: <49937F63.6090908@gmail.com> David wrote: > Hi Everyone and thanks for the list and your help. > In my adventure in learning Python (never programed before) I am > attempting to findout if a file has been modified today given a search > path. It is working somewhat. Here it is; > > #!/usr/bin/python > import sys > import os > import time > > def Mod(): > """Find files modified today, given a file path.""" > latest = 0 > dir = os.path.dirname(sys.argv[1]) > for fname in os.listdir(dir): > if fname.endswith('.py'): > modtime = os.stat(os.path.join(dir, fname)).st_mtime > if modtime > latest: > latest = modtime > out = time.strftime('%Y-%m-%d', time.localtime(latest)) > my_list = [fname, out] > print fname > now = time.strftime('%Y-%m-%d', time.localtime()) > if my_list[-1] == now: > print "This file has changed today." > print "*"*30 > else: > print "This file did not change" > 1) That can't be the entire program, as there is no call to Mod()! 2) Convention says function names start with lower case. Save initial caps for class names. 3) Get rid of latest - that is why you are not getting all the files. 4) Use glob.glob() so you can specify *.py 5) It is not necessary to convert times to strings. You can get midnight today from int(time.localtime()) 6) Move calculation of now outside the loop, as it does not change. 7) my_list is not necessary. 8) revised (untested) code: #!/usr/bin/python import sys import os import time import glob def mod(): """Find files modified today, given a file path.""" dir = os.path.dirname(sys.argv[1]) start_of_today = int(time.localtime()) for fname in glob.glob(dir + '/*.py'): modtime = os.stat(os.path.join(dir, fname)).st_mtime print fname if modtime >= start_of_today: print "This file has changed today." print "*"*30 else: print "This file did not change" mod() > results; > ./py_lastmod_date.py /home/david/ > > py_pyparse_end.py > This file did not change > ****************************** > cologne_time.py > This file did not change > ****************************** > py_find_word_prefix.py > This file did not change > ****************************** > py_round_by_five.py > This file did not change > ****************************** > graphics.py > This file did not change > ****************************** > py_countdown_generator.py > This file did not change > ****************************** > py_compare_time.py > This file has changed today. > ****************************** > py_lastmod_date.py > This file has changed today. > ****************************** > > OK here are my questions. > Is there an easier way of doing this? > Why does it only return 8 results, I have a ton of .py files in > /home/david > Why do both the if and else get printed? > How do I do this without all the if statments? > I don't understand the if modtime > latest part, is this to loop over > the files and put the oldest last? I found that part in another > program and my program does not work without it. > Thank you, > -david > > -- Bob Gailer Chapel Hill NC 919-636-4239 From kent37 at tds.net Thu Feb 12 03:23:53 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 11 Feb 2009 21:23:53 -0500 Subject: [Tutor] Program to report if file was modified today In-Reply-To: <49937F63.6090908@gmail.com> References: <4993705D.3040202@abbottdavid.com> <49937F63.6090908@gmail.com> Message-ID: <1c2a2c590902111823u4e7d6183u6e3ad6f2b1b1b5c7@mail.gmail.com> On Wed, Feb 11, 2009 at 8:46 PM, bob gailer wrote: > 5) It is not necessary to convert times to strings. You can get midnight > today from int(time.localtime()) ?? In [1]: import time In [2]: time.localtime() Out[2]: time.struct_time(tm_year=2009, tm_mon=2, tm_mday=11, tm_hour=21, tm_min=20, tm_sec=11, tm_wday=2, tm_yday=42, tm_isdst=0) In [4]: int(time.localtime()) TypeError: int() argument must be a string or a number, not 'time.struct_time' Kent From david at abbottdavid.com Thu Feb 12 03:26:40 2009 From: david at abbottdavid.com (David) Date: Wed, 11 Feb 2009 21:26:40 -0500 Subject: [Tutor] Program to report if file was modified today In-Reply-To: <49937F63.6090908@gmail.com> References: <4993705D.3040202@abbottdavid.com> <49937F63.6090908@gmail.com> Message-ID: <499388E0.4010700@abbottdavid.com> bob gailer wrote: > 1) That can't be the entire program, as there is no call to Mod()! Yep, it was lost in my copy paste > 2) Convention says function names start with lower case. Save initial > caps for class names. Thanks for the reminder, I had forgotten :) > 3) Get rid of latest - that is why you are not getting all the files. For some reason when I take that out it reports all file have been modified. > 4) Use glob.glob() so you can specify *.py > 5) It is not necessary to convert times to strings. You can get midnight > today from int(time.localtime()) OK > 6) Move calculation of now outside the loop, as it does not change. Good Point, makes since now. > 7) my_list is not necessary. Ok, my reason was to make sure the file and date remained together but It works fine without it. > 8) revised (untested) code: I get this error with the int(time.localtime()) start_of_today = int(time.localtime()) TypeError: int() argument must be a string or a number, not 'time.struct_time' Thanks Bob, I really only want it to report when a file has been modified so this seems to work, next I will work on putting glob.glob working plus any other suggestions. #!/usr/bin/python import sys import os import time def mod(): """Find files modified today, given a file path.""" latest = 0 now = time.strftime('%Y-%m-%d', time.localtime()) dir = os.path.dirname(sys.argv[1]) for fname in os.listdir(dir): if fname.endswith('.py'): modtime = os.stat(os.path.join(dir, fname)).st_mtime if modtime > latest: latest = modtime out = time.strftime('%Y-%m-%d', time.localtime(latest)) if out == now: print fname, "has changed today. " else: pass mod() results; david [09:25 PM] opteron ~ $ ./py_lastmod_date.py /home/david/ py_compare_time.py has changed today. py_lastmod_date.py has changed today. -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From sierra_mtnview at sbcglobal.net Thu Feb 12 03:48:05 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 11 Feb 2009 18:48:05 -0800 Subject: [Tutor] Keeping Dictonary Entries Ordered Message-ID: <49938DE5.6070609@sbcglobal.net> An HTML attachment was scrubbed... URL: From wferguson1 at socal.rr.com Thu Feb 12 03:50:17 2009 From: wferguson1 at socal.rr.com (WM.) Date: Wed, 11 Feb 2009 18:50:17 -0800 Subject: [Tutor] [tutor] IDLE Message-ID: <49938E69.1020205@socal.rr.com> At one time I could not run a skit in IDLE nor with the command line. IDLE gave error messages because (Alan G. says) of the 3 chevrons. The command opened into a wee square & issued only error messages. Then the command line opened into a 4x7 box and worked perfectly. IDLE also now works perfectly, whether I open into IDLE or edit window. Below is a copy/paste: IDLE 2.6 >>> i = 9 >>> while i > 2: print i i -= 1 9 8 7 6 5 4 3 >>> just so, with no adjustments From dorseye at gmail.com Thu Feb 12 04:26:47 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Wed, 11 Feb 2009 20:26:47 -0700 Subject: [Tutor] Keeping Dictonary Entries Ordered In-Reply-To: <49938DE5.6070609@sbcglobal.net> References: <49938DE5.6070609@sbcglobal.net> Message-ID: >>> config_names = {'start_time': '18:00:00', 'gray_scale': True, 'long': 120.0} >>> config_names {'start_time': '18:00:00', 'gray_scale': True, 'long': 120.0} >>> for i, x in config_names.items(): ... print i, x ... start_time 18:00:00 gray_scale True long 120.0 >>> On Wed, Feb 11, 2009 at 7:48 PM, Wayne Watson wrote: > I have a dictionary that looks like: > > config_names = {"start_time : '18:00:00', 'gray_scale' : True, "long": > 120.00} > > If I iterate over it, the entries will appear in any order, as opposed to > what I see above. However, in the config file, I'd like to keep them in the > order above. That I want to write the config file in order. Perhaps, I need > a list like c_names = ["start_time", "gray_scale", "long"] to get the keys > out in the order I need? Maybe there's another way? > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) > > *The Richard Feynman Problem-Solving Algorithm:* > * (1) write down the problem;* > * (2) think very hard;* > * (3) write down the answer.*** > ** > > ****** Web Page: > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Thu Feb 12 05:21:35 2009 From: bgailer at gmail.com (bob gailer) Date: Wed, 11 Feb 2009 23:21:35 -0500 Subject: [Tutor] Program to report if file was modified today In-Reply-To: <499388E0.4010700@abbottdavid.com> References: <4993705D.3040202@abbottdavid.com> <49937F63.6090908@gmail.com> <499388E0.4010700@abbottdavid.com> Message-ID: <4993A3CF.7010405@gmail.com> David wrote: > I get this error with the int(time.localtime()) > start_of_today = int(time.localtime()) > TypeError: int() argument must be a string or a number, not > 'time.struct_time' Should have been start_of_today = int(time.time()) -- Bob Gailer Chapel Hill NC 919-636-4239 From sierra_mtnview at sbcglobal.net Thu Feb 12 05:35:31 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 11 Feb 2009 20:35:31 -0800 Subject: [Tutor] Keeping Dictonary Entries Ordered In-Reply-To: References: <49938DE5.6070609@sbcglobal.net> Message-ID: <4993A713.7010207@sbcglobal.net> An HTML attachment was scrubbed... URL: From wormwood_3 at yahoo.com Thu Feb 12 05:57:52 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Wed, 11 Feb 2009 20:57:52 -0800 (PST) Subject: [Tutor] Python & MySQL... Define port. References: Message-ID: <423557.47245.qm@web110814.mail.gq1.yahoo.com> Hello, You can specify the port of the instance you want to connect to simply by passing "port=NUM" in MySQLdb.connect(). Here is a formulation I have found generally useful: import MySQLdb def run_mysql(query, db, user, passwd, port=3306, socket="/var/run/mysqld/mysqld.sock", host="localhost"): """Runs query passed with connection info passed, returns results.""" try: db = MySQLdb.connect(user=user, passwd=passwd, db=db, port=port, unix_socket=socket, host=host) except MySQLdb.Error, e: raise e cursor = db.cursor() cursor.execute(query) data = cursor.fetchall() db.close() return data This sets common defaults, but you can of course pass in whatever you want when you call it. You might also want to check out the MySQLdb docs: http://mysql-python.sourceforge.net/MySQLdb.html. It contains a number of examples. _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins ________________________________ From: Network Administrator To: tutor at python.org Sent: Monday, February 9, 2009 1:29:21 PM Subject: [Tutor] Python & MySQL... Define port. Hello everybody! I want to use Python to query a given MySQL database. However, this database is running on port 3308, instead the traditional 3306. I read that (example): MySQLdb.connect(host="dbserv', db='inv', user='smith') can be used to query a given database; however, it didn't work in my particular case. This is my code: connection = MySQLdb.connect (db = "netlogin", user="netadmin", pass = "r4nas", port="3308") I appreciate if you give me assistance in the proper sintax of the last mentioned instruction. Regards, GatoLinux. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Feb 12 06:09:01 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 11 Feb 2009 21:09:01 -0800 Subject: [Tutor] IDLE/phythonWin -- Who's On First? (Abbott and Costello) In-Reply-To: <4992AA16.4080400@sbcglobal.net> References: <4992471E.40300@sbcglobal.net> <4992A25A.8010401@sbcglobal.net> <4992AA16.4080400@sbcglobal.net> Message-ID: <4993AEED.2060602@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Feb 12 09:32:14 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 12 Feb 2009 08:32:14 +0000 (GMT) Subject: [Tutor] IDLE/phythonWin -- Who's On First? (Abbott and Costello) References: <4992471E.40300@sbcglobal.net> <4992A25A.8010401@sbcglobal.net> <4992AA16.4080400@sbcglobal.net> <4993AEED.2060602@sbcglobal.net> Message-ID: <766503.43245.qm@web86705.mail.ird.yahoo.com> There used to be a lot of problems running Tkinter programs inside IDLE but most of these have been solved since about v2.3. However it does still through up issues, so the simple solution it to always test GUI programs outside of the IDE. Another reason why for serious programming I tend to favour the 3 window setup... Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ ________________________________ From: Wayne Watson To: Alan Gauld ; "tutor at python.org" Sent: Thursday, 12 February, 2009 5:09:01 AM Subject: Re: [Tutor] IDLE/phythonWin -- Who's On First? (Abbott and Costello) This appears to be an old problem. . However, the question remains. What to do about it? reboot? I killed about a dozen pythonwin.exe task, but to no avail. Wayne Watson wrote: Using WinMerge, I found a difference between the two that shouldn't have been, but it didn't solve the problem. dialog.rateVar.get() versus dialog.rateVar.get There was another like it with get(), but it wouldn't have been executed in my test run. I suspect something else like that lurks in the code. Wayne Watson wrote: I ran it w/o using either IDLE/pyWin, and it worked without any messages, as shown by the console window. Isn't this the same as using the console? Outside of the two, my guess is that some subtle was made to the code, accidentally, and one tolerates it and the other doesn't. I'm going to do a WinMerge compare between the current py and a slightly older one. Alan Gauld wrote: "Wayne Watson" wrote Signature.htmlMy program in IDLE bombed with: ============== Exception in Tkinter callback Traceback (most recent call last): dialog = OperationalSettingsDialog( self.master, set_loc_dict ) tkSimpleDialog.Dialog.__init__(self, parent) self.wait_visibility() # window needs to be visible for the grab But runs fine in pythonWin performing the same entry operation. Lets eliminate some variables by avoiding any IDEs. Does it work OK when run from a DOS console? Or if you just double click the file in Windows explorer? If it does that means its some kind of interaction between the program and IDLE. This is not unusual since IDLE is itself a Tkinter program and although recent versions are much better behaved with Tkinter it can still cause some strangeness. If you still get an error running outside the IDE then we can analyze it more closely. For that we will need the code, at least the function that calls the dialog. And if its a subclass the dialog class too. -- Signature.html Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) The Richard Feynman Problem-Solving Algorithm: (1) write down the problem; (2) think very hard; (3) write down the answer. Web Page: ________________________________ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- Signature.html Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) The Richard Feynman Problem-Solving Algorithm: (1) write down the problem; (2) think very hard; (3) write down the answer. Web Page: ________________________________ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -- Signature.html Wayne Watson (Watson Adventures, Prop., Nevada City, CA) (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) The Richard Feynman Problem-Solving Algorithm: (1) write down the problem; (2) think very hard; (3) write down the answer. Web Page: -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Feb 12 09:59:17 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Feb 2009 08:59:17 -0000 Subject: [Tutor] Program to report if file was modified today References: <4993705D.3040202@abbottdavid.com> <49937F63.6090908@gmail.com> <499388E0.4010700@abbottdavid.com> Message-ID: "David" wrote > I really only want it to report when a file has been modified so > this seems to work, > #!/usr/bin/python > import sys > import os > import time > > def mod(): > """Find files modified today, given a file path.""" > latest = 0 > now = time.strftime('%Y-%m-%d', time.localtime()) > dir = os.path.dirname(sys.argv[1]) > for fname in os.listdir(dir): > if fname.endswith('.py'): > modtime = os.stat(os.path.join(dir, fname)).st_mtime > if modtime > latest: > latest = modtime Why do you modify latest to whatever the mod time of the file is? Surely you want to always compare mod time with now? > out = time.strftime('%Y-%m-%d', > time.localtime(latest)) > if out == now: > print fname, "has changed today. " > else: > pass You don't need the else:pass bit. It does nothing. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at btinternet.com Thu Feb 12 10:10:01 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Feb 2009 09:10:01 -0000 Subject: [Tutor] [tutor] IDLE References: <49938E69.1020205@socal.rr.com> Message-ID: "WM." wrote > IDLE also now works perfectly, whether I open into IDLE or edit > window. > Below is a copy/paste: > > IDLE 2.6 > >>> i = 9 > >>> while i > 2: > print i > i -= 1 The problem occurs when you go to a second level block: >>> if 42 > 66: print 'false' else: print 'true' Whjat happens is a beginner will try to align the else with the if as shown in the text books etc anmd get an error from IDLE. Whereas if IDLE provided the ... secondary prompt it would look like: >>> if 42 > 66: ... print 'false' ... else: ... print 'true' Which matches the text books. Alan G From alan.gauld at btinternet.com Thu Feb 12 10:25:22 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Feb 2009 09:25:22 -0000 Subject: [Tutor] Keeping Dictonary Entries Ordered References: <49938DE5.6070609@sbcglobal.net> Message-ID: "Wayne Watson" wrote > config_names = {"start_time : '18:00:00', 'gray_scale' : True, > "long": 120.00} > > If I iterate over it, the entries will appear in any order, as > opposed to > what I see above. However, in the config file, I'd like to keep them > in the order above. Thats tricky! Dictionaries are not sorted and do not retain insertion order. If you can define a sort order you can use sorted: >>> d = {1:2, 3:4, 8:9, 5:7} >>> for n in d: print n ... 8 1 3 5 >>> for n in sorted(d): print n ... 1 3 5 8 >>> But you need to have an order that will work with sorted(). Its not just the order you add items to the dict. To store an arbitrary order I suspect you would need to maintain a secondary list with the keys in the order of insertion. The most reliable way to dop that would be to subclass dict. Somebody may already have done that so its worth a google... HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Thu Feb 12 10:28:23 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Feb 2009 09:28:23 -0000 Subject: [Tutor] Keeping Dictonary Entries Ordered References: <49938DE5.6070609@sbcglobal.net> Message-ID: "Eric Dorsey" wrote >>>> config_names > {'start_time': '18:00:00', 'gray_scale': True, 'long': 120.0} >>>> for i, x in config_names.items(): > ... print i, x > ... > start_time 18:00:00 > gray_scale True > long 120.0 Thats pretty much a happy coincidence, there is no guarantee that it will work like that for all dictionaries: >>> d = {1:2,3:4,8:9,5:7} >>> for i,x in d.items(): print i,x ... 8 9 1 2 3 4 5 7 Alan G. From orsenthil at gmail.com Thu Feb 12 10:54:00 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Thu, 12 Feb 2009 15:24:00 +0530 Subject: [Tutor] Keeping Dictonary Entries Ordered In-Reply-To: <7c42eba10902120153u406882fbq278081f7ec223c13@mail.gmail.com> References: <49938DE5.6070609@sbcglobal.net> <7c42eba10902120153u406882fbq278081f7ec223c13@mail.gmail.com> Message-ID: <7c42eba10902120154k7c1799d6pd1436f9116338473@mail.gmail.com> On Thu, Feb 12, 2009 at 2:55 PM, Alan Gauld wrote: > But you need to have an order that will work with sorted(). > Its not just the order you add items to the dict. And yes algorithmically, there is No Requirement or I should say a good Use Case for a Dict to have sorted keys. More we work with dictionaries. we will understand this rationale better. -- Senthil From kent37 at tds.net Thu Feb 12 13:04:12 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 Feb 2009 07:04:12 -0500 Subject: [Tutor] Keeping Dictonary Entries Ordered In-Reply-To: References: <49938DE5.6070609@sbcglobal.net> Message-ID: <1c2a2c590902120404s47468f32o7e2936fdf83adbf2@mail.gmail.com> On Thu, Feb 12, 2009 at 4:25 AM, Alan Gauld wrote: > Thats tricky! Dictionaries are not sorted and do not retain insertion order. > But you need to have an order that will work with sorted(). > Its not just the order you add items to the dict. To store an > arbitrary order I suspect you would need to maintain a > secondary list with the keys in the order of insertion. > The most reliable way to dop that would be to subclass > dict. Somebody may already have done that so its worth > a google... In fact this is planned for inclusion in Python 2.7: http://www.python.org/dev/peps/pep-0372/ The PEP lists several implementations including one with the specified API: http://dev.pocoo.org/hg/sandbox/raw-file/tip/odict.py Kent From sierra_mtnview at sbcglobal.net Thu Feb 12 13:44:51 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 12 Feb 2009 04:44:51 -0800 Subject: [Tutor] IDLE/phythonWin -- Who's On First? (Abbott and Costello) In-Reply-To: <766503.43245.qm@web86705.mail.ird.yahoo.com> References: <4992471E.40300@sbcglobal.net> <4992A25A.8010401@sbcglobal.net> <4992AA16.4080400@sbcglobal.net> <4993AEED.2060602@sbcglobal.net> <766503.43245.qm@web86705.mail.ird.yahoo.com> Message-ID: <499419C3.7040708@sbcglobal.net> An HTML attachment was scrubbed... URL: From denis.spir at free.fr Thu Feb 12 14:38:54 2009 From: denis.spir at free.fr (spir) Date: Thu, 12 Feb 2009 14:38:54 +0100 Subject: [Tutor] Keeping Dictonary Entries Ordered In-Reply-To: References: <49938DE5.6070609@sbcglobal.net> Message-ID: <20090212143854.3ef8bec4@o> Le Thu, 12 Feb 2009 09:25:22 -0000, "Alan Gauld" a ?crit : > > config_names = {"start_time : '18:00:00', 'gray_scale' : True, > > "long": 120.00} > > > > If I iterate over it, the entries will appear in any order, as > > opposed to > > what I see above. However, in the config file, I'd like to keep them > > in the order above. > > Thats tricky! Dictionaries are not sorted and do not retain insertion > order. Had to do something similar. I just subtyped dict to add a separate list a keys. Initiated with the possible initial arguments, then updated by setattr. Very few code lines. Then Ordict had a simplissim method to return values (and pairs) the keylist's order. The only issue was rather a semantic one: should a value change keep the keylist unchanged or move the key to the last position? Denis ------ la vida e estranya From kent37 at tds.net Thu Feb 12 15:19:06 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 Feb 2009 09:19:06 -0500 Subject: [Tutor] Program to report if file was modified today In-Reply-To: <4993A3CF.7010405@gmail.com> References: <4993705D.3040202@abbottdavid.com> <49937F63.6090908@gmail.com> <499388E0.4010700@abbottdavid.com> <4993A3CF.7010405@gmail.com> Message-ID: <1c2a2c590902120619p4ac39953k3ca2952cc4d60aa5@mail.gmail.com> On Wed, Feb 11, 2009 at 11:21 PM, bob gailer wrote: > David wrote: >> >> I get this error with the int(time.localtime()) >> start_of_today = int(time.localtime()) >> TypeError: int() argument must be a string or a number, not >> 'time.struct_time' > > Should have been start_of_today = int(time.time()) No, that rounds to the current second, not the current day: In [5]: int(time.time()) Out[5]: 1234438429 In [6]: int(time.time()) Out[6]: 1234438432 In [7]: int(time.time()) Out[7]: 1234438433 Here are two ways to get the time at midnight in seconds since the epoch. The first one gives local midnight, the second one is UTC: import time from datetime import date Convert datetime.date.today() to seconds: In [21]: time.mktime(date.today().timetuple()) Out[21]: 1234414800.0 Round down to the nearest whole day: In [24]: now = int(time.time()) In [27]: now - (now % (60*60*24)) Out[27]: 1234396800 Kent From david at abbottdavid.com Thu Feb 12 16:48:05 2009 From: david at abbottdavid.com (David) Date: Thu, 12 Feb 2009 10:48:05 -0500 Subject: [Tutor] Program to report if file was modified today In-Reply-To: <1c2a2c590902120619p4ac39953k3ca2952cc4d60aa5@mail.gmail.com> References: <4993705D.3040202@abbottdavid.com> <49937F63.6090908@gmail.com> <499388E0.4010700@abbottdavid.com> <4993A3CF.7010405@gmail.com> <1c2a2c590902120619p4ac39953k3ca2952cc4d60aa5@mail.gmail.com> Message-ID: <499444B5.3010505@abbottdavid.com> Kent Johnson wrote: > On Wed, Feb 11, 2009 at 11:21 PM, bob gailer wrote: > > Thanks Alan and Kent, This works as expected; #!/usr/bin/python import sys import os import time def mod(): """Find files modified today, given a file path.""" now = time.strftime('%Y-%m-%d', time.localtime()) dir = os.path.dirname(sys.argv[1]) for fname in os.listdir(dir): if fname.endswith('.py'): modtime = os.stat(os.path.join(dir, fname)).st_mtime out = time.strftime('%Y-%m-%d', time.localtime(modtime)) if out == now: print fname, "has changed today. " mod() -david -- powered by Gentoo/GNU Linux http://linuxcrazy.com From david at abbottdavid.com Thu Feb 12 16:49:23 2009 From: david at abbottdavid.com (David) Date: Thu, 12 Feb 2009 10:49:23 -0500 Subject: [Tutor] Program to report if file was modified today In-Reply-To: <499444B5.3010505@abbottdavid.com> References: <4993705D.3040202@abbottdavid.com> <49937F63.6090908@gmail.com> <499388E0.4010700@abbottdavid.com> <4993A3CF.7010405@gmail.com> <1c2a2c590902120619p4ac39953k3ca2952cc4d60aa5@mail.gmail.com> <499444B5.3010505@abbottdavid.com> Message-ID: <49944503.6010102@abbottdavid.com> David wrote: > Kent Johnson wrote: > >> On Wed, Feb 11, 2009 at 11:21 PM, bob gailer wrote: >> >> >> > Thanks Alan and Kent, > This works as expected; > > #!/usr/bin/python > import sys > import os > import time > > def mod(): > """Find files modified today, given a file path.""" > now = time.strftime('%Y-%m-%d', time.localtime()) > dir = os.path.dirname(sys.argv[1]) > for fname in os.listdir(dir): > if fname.endswith('.py'): > modtime = os.stat(os.path.join(dir, fname)).st_mtime > out = time.strftime('%Y-%m-%d', time.localtime(modtime)) > if out == now: > print fname, "has changed today. " > mod() > > -david > > Sorry and Bob :) -- powered by Gentoo/GNU Linux http://linuxcrazy.com From daychilde at gmail.com Thu Feb 12 19:04:05 2009 From: daychilde at gmail.com (Alexander Daychilde (Gmail)) Date: Thu, 12 Feb 2009 10:04:05 -0800 Subject: [Tutor] How to foreach over a dynamic number of levels In-Reply-To: <1c2a2c590902111644x880b01dlfa07e94432120389@mail.gmail.com> References: <00d701c98c9f$6a9506d0$3fbf1470$@com> <1c2a2c590902111644x880b01dlfa07e94432120389@mail.gmail.com> Message-ID: <004c01c98d3c$4baf8cc0$e30ea640$@com> First, thank you VERY much for your help! That's amazingly much easier than I thought it would be... I was considering looping through and generating nested for loops, then exec'ing the whole mess.. UGH, and security risk, to boot... Couple of questions: > Make a list containing all the steps: > steps = [step1, step2, step3] > > Now you need to convert all steps to lists. This loop builds a new > list from the original step list, wrapping any bare strings in lists: > > step_lists = [] > for step in steps: > if isinstance(step, basestring): > step = [step] > step_lists.append(step) > > Now what you want is the Cartesian product of all the lists. Python > has a function (new in Python 2.6) in the itertools library module > that will do this: I'm stuck on 2.5.2 because of the framework I'm driving... Does that preclude this solution? > from itertools import product > for model_set in product(*step_lists): > print model_set > > (The * in the argument list means, take the elements of step_list and > use them as the arguments to product()) > > The output is > ('step1model-a', 'step2model-a', 'step3model-a') > ('step1model-a', 'step2model-a', 'step3model-b') > ('step1model-b', 'step2model-a', 'step3model-a') > ('step1model-b', 'step2model-a', 'step3model-b') > ('step1model-c', 'step2model-a', 'step3model-a') > ('step1model-c', 'step2model-a', 'step3model-b') I hate to ask such a n00b question, but I am still learning python, and I must just be missing how to do this: How can I reference the key name as well? Basically, what I'm imputing is more like this: date = {2008-01-01:2008-01-30} # I'll parse that into 30 days model1 = some_model1 model2 = {some_model2;othermodel2} # I'll parse into a real list [...] somekey = somevalue What I'm outputting is a series of INI files, one for each run. In this case, that's 30 days times the two models, but since any key/value pair can be an array, it may end up being hundreds or thousands (or millions) of runs... For each run, I output something like this: date = 2008-01-01 model1 = some_model1 model2 = some_model2 [...] somekey = somevalue So I have to be able to regurgitate the key name -- and I'm not sure how to address that... Like in PHP, I'd use a variable variable. (I feel like this is a st00pid n00b question, and if so, I do apologize, but I'm just... missing it somewhere... I'm honestly trying to improve my coding skills, but you know how it is - you don't know something until you learn it... and python is in some ways refreshing and awesome, and in some ways just blowing my mind...) > HTH > Kent Very much, indeed! :) From timomlists at gmail.com Thu Feb 12 19:25:59 2009 From: timomlists at gmail.com (Timo) Date: Thu, 12 Feb 2009 19:25:59 +0100 Subject: [Tutor] ConfigParser re-read fails Message-ID: <499469B7.4070604@gmail.com> Hello all, I use a file for my program that I read with ConfigParser. I append all sections of this file into a treeview (using pyGTK). The user can add, edit or remove sections, options and values. These I write back to the file and then update the treeview. The problem is that it doesn't update, the values are still the same. How can I re-read the configuration file? This is (very simple) what I do: conf = ConfigParser.RawConfigParser() configFile = 'config.cfg' conf.read(configFile) fill_treeview() def fill_treeview() # Do the treeview stuff here def button_clicked() write_config(section, option, value) conf.read(configFile) # It needs to be re-read here fill_treeview() def write_config(section, option, value) if not conf.has_section(section): conf.add_section(section) conf.set(section, key, value) conf.write(open(configFile, 'w')) From kent37 at tds.net Thu Feb 12 19:35:42 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 12 Feb 2009 13:35:42 -0500 Subject: [Tutor] How to foreach over a dynamic number of levels In-Reply-To: <004c01c98d3c$4baf8cc0$e30ea640$@com> References: <00d701c98c9f$6a9506d0$3fbf1470$@com> <1c2a2c590902111644x880b01dlfa07e94432120389@mail.gmail.com> <004c01c98d3c$4baf8cc0$e30ea640$@com> Message-ID: <1c2a2c590902121035i5355b1f4h8870b2dc246400dd@mail.gmail.com> On Thu, Feb 12, 2009 at 1:04 PM, Alexander Daychilde (Gmail) wrote: >> Now what you want is the Cartesian product of all the lists. Python >> has a function (new in Python 2.6) in the itertools library module >> that will do this: > > I'm stuck on 2.5.2 because of the framework I'm driving... Does that > preclude this solution? The docs for itertools.product() give a pure-Python equivalent, just paste that into your code: http://docs.python.org/library/itertools.html#itertools.product > Basically, what I'm imputing is more like this: > > date = {2008-01-01:2008-01-30} # I'll parse that into 30 days > model1 = some_model1 > model2 = {some_model2;othermodel2} # I'll parse into a real list > [...] > somekey = somevalue > > What I'm outputting is a series of INI files, one for each run. In this > case, that's 30 days times the two models, but since any key/value pair can > be an array, it may end up being hundreds or thousands (or millions) of > runs... > > For each run, I output something like this: > > date = 2008-01-01 > model1 = some_model1 > model2 = some_model2 > [...] > somekey = somevalue > > > So I have to be able to regurgitate the key name -- and I'm not sure how to > address that... Like in PHP, I'd use a variable variable. Maybe you should use a list of pairs (tuples) where the first element is the name and the second is the list of models: steps = [ ('model1', ['some_model1']), ('model2', ['some_model2', 'othermodel2']) # etc ] You could perhaps modify the product() function to create the strings you need. You might want to get a little practice working with lists first... Kent From telmo_andres at yahoo.com Thu Feb 12 21:06:26 2009 From: telmo_andres at yahoo.com (Andres Sanchez) Date: Thu, 12 Feb 2009 12:06:26 -0800 (PST) Subject: [Tutor] Converting a numerical variable into a string variable Message-ID: <407320.65672.qm@web59912.mail.ac4.yahoo.com> Folks, Please, give me a hand with this. Say I have a vector defined as x=[1,2,3,4,...,9]. I need to write string variables with the names G1BF....G9BF. Thus, the first string variable would be 'G'+'1'+'BF', being the number 1 equal to x[0]. Now, using a for loop, I want to do something like: y[i]='G'+x[i-1]+'BF' , to create my string variables. Yes, the problem is that I am mixing numerical and string variables and Python reports an error when I try to do this. So, the question is: how do I do to convert the numerical variable x[0]=1 into a string variable '1', so I can do my 'G'+'1'+BF' thing? Your thoughts are appreciated. By the way, 'G'+'x[0]'+'BF' reports 'Gx[0]BF'? :) Regards, Andres -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Thu Feb 12 21:31:01 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 12 Feb 2009 21:31:01 +0100 Subject: [Tutor] Converting a numerical variable into a string variable In-Reply-To: <407320.65672.qm@web59912.mail.ac4.yahoo.com> References: <407320.65672.qm@web59912.mail.ac4.yahoo.com> Message-ID: On Thu, Feb 12, 2009 at 21:06, Andres Sanchez wrote: > Please, give me a hand with this. Say I have a vector defined as > x=[1,2,3,4,...,9]. I need to write string variables with the names > G1BF...G9BF. Thus, the first string variable would be 'G'+'1'+'BF', being > the number 1 equal to x[0]. Now, using a for loop, I want to do something > like: y[i]='G'+x[i-1]+'BF' , to create my string variables. Yes, the problem > is that I am mixing numerical and string variables and Python reports an > error when I try to do this. So, the question is: how do I do to convert the > numerical variable x[0]=1 into a string variable '1', so I can do my > 'G'+'1'+BF' thing? >>> x = 100 >>> x 100 >>> str(x) '100' You can use str() to convert the numbers to strings. To print what you are looking for do something like this. >>> x = [x for x in range(1,10)] >>> x [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> for var in x: print 'G' + str(var) + 'BF' G1BF G2BF G3BF G4BF G5BF G6BF G7BF G8BF G9BF Or: >>> for var in x: print 'G%sBF' % var G1BF G2BF G3BF G4BF G5BF G6BF G7BF G8BF G9BF > By the way, 'G'+'x[0]'+'BF' reports 'Gx[0]BF' :) Correct, 'x[0]' is a string not the number you are looking for. See above on how you can do this. Greets Sander PS: personally I like the second one better :-) From Shawn at Milochik.com Thu Feb 12 22:05:44 2009 From: Shawn at Milochik.com (Shawn Milochik) Date: Thu, 12 Feb 2009 16:05:44 -0500 Subject: [Tutor] Converting a numerical variable into a string variable In-Reply-To: References: <407320.65672.qm@web59912.mail.ac4.yahoo.com> Message-ID: <2dc0c81b0902121305u2cb902c6y19222222a8123909@mail.gmail.com> >>> for x in range(1,9): print("G%dBF" % (x,)) G1BF G2BF G3BF G4BF G5BF G6BF G7BF G8BF >>> From sander.sweers at gmail.com Thu Feb 12 22:33:56 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 12 Feb 2009 22:33:56 +0100 Subject: [Tutor] print function in python 2.6 and 3 Message-ID: Hello, I see more people posting answers with the new print() function only available in python 3 and in python 2.6 via an import from __future__. Now I am not confused by this but I can understand that people very new to python can get confused byt this. Especially people following a guide online or a book which almost all use the old print statement. Now what should be used and promoted on the list? Greets Sander From alan.gauld at btinternet.com Thu Feb 12 22:50:44 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 12 Feb 2009 21:50:44 -0000 Subject: [Tutor] print function in python 2.6 and 3 References: Message-ID: "Sander Sweers" wrote > I see more people posting answers with the new print() function only > available in python 3 and in python 2.6 via an import from > __future__. > Now I am not confused by this but I can understand that people very > new to python can get confused byt this. Especially people following > a > guide online or a book which almost all use the old print statement. Yes, it is unfiortunate but will settle down over the next year or so I guess. > Now what should be used and promoted on the list? We can't shouldn't promote one over the other since the remit of this list is to help newbies, regardless of the Python version. We had similar issues when Python 2 introduced strings as objects and string methods replaced the functions in the string module - indeed we still get posts using string.foo... The only thing I would strongly request is that posters specify the Python version (both in questions and replies) . That's always a good idea but especially during a time of change. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From ricaraoz at gmail.com Thu Feb 12 13:36:29 2009 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 12 Feb 2009 10:36:29 -0200 Subject: [Tutor] Detecting wx Message-ID: <499417CD.5010502@gmail.com> There are a couple of utilities I want to be able to run from the command window. Now, if I'm at the command window, or Idle, or other non wx shell I want to establish a wx app. But if I'm in pythonWin, PyCrust, or any other wx based shell then there is a wx event loop already running and if I create other I'll be in trouble. My question is if there is a way in which I can detect if there is a wx event loop running in my environment? TIA From sander.sweers at gmail.com Thu Feb 12 23:15:28 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Thu, 12 Feb 2009 23:15:28 +0100 Subject: [Tutor] print function in python 2.6 and 3 In-Reply-To: References: Message-ID: On Thu, Feb 12, 2009 at 22:50, Alan Gauld wrote: >> Now what should be used and promoted on the list? > > We can't shouldn't promote one over the other since the remit > of this list is to help newbies, regardless of the Python version. OK, understood. > The only thing I would strongly request is that posters specify > the Python version (both in questions and replies) . That's always > a good idea but especially during a time of change. Maybe it is an idea to actively request the versoin if not immediatly obvious? Greets Sander From john at fouhy.net Thu Feb 12 23:39:59 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 13 Feb 2009 11:39:59 +1300 Subject: [Tutor] Detecting wx In-Reply-To: <499417CD.5010502@gmail.com> References: <499417CD.5010502@gmail.com> Message-ID: <5e58f2e40902121439v7d4c9fdcvdb4b8571cb0be834@mail.gmail.com> 2009/2/13 Ricardo Ar?oz : > There are a couple of utilities I want to be able to run from the > command window. Now, if I'm at the command window, or Idle, or other non > wx shell I want to establish a wx app. But if I'm in pythonWin, PyCrust, > or any other wx based shell then there is a wx event loop already > running and if I create other I'll be in trouble. My question is if > there is a way in which I can detect if there is a wx event loop running > in my environment? You could try something like: wx.CallAfter(lambda: None) Here's what I get in a quick test with no app running: >>> import wx >>> wx.CallAfter(lambda: None) Traceback (most recent call last): File "", line 1, in File "//Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/wx-2.8-mac-unicode/wx/_core.py", line 14359, in CallAfter assert app is not None, 'No wx.App created yet' AssertionError: No wx.App created yet Whereas if I do the same thing from pycrust, nothing happens (that is, presumably my lambda executes). -- John. From emadnawfal at gmail.com Fri Feb 13 00:20:53 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Thu, 12 Feb 2009 18:20:53 -0500 Subject: [Tutor] extracting phrases and their memberships from syntax trees Message-ID: <652641e90902121520v59262d23vb7a2f0e96b202e7f@mail.gmail.com> Dear Tutors, I have syntax trees like the one below. I need to extract the membership information like which adjective belongs to which noun phrase, and so on. In short, I want to do something like this: http://ilk.uvt.nl/team/sabine/chunklink/README.html I already have the Perl script that does that, so I do not need a script. I just want to be able to do this myself. My question is: what tools do I need for this? Could you please give me pointers to where to start? I'll then try to do it myself, and ask questions when I get stuck. Thank you in anticipation with a syntax tree like this: ( (S (NP-SBJ-1 (NP (NNP Rudolph) (NNP Agnew) ) (, ,) (UCP (ADJP (NP (CD 55) (NNS years) ) (JJ old) ) (CC and) (NP (NP (JJ former) (NN chairman) ) (PP (IN of) (NP (NNP Consolidated) (NNP Gold) (NNP Fields) (NNP PLC) )))) (, ,) ) (VP (VBD was) (VP (VBN named) (S (NP-SBJ (-NONE- *-1) ) (NP-PRD (NP (DT a) (JJ nonexecutive) (NN director) ) (PP (IN of) (NP (DT this) (JJ British) (JJ industrial) (NN conglomerate) )))))) (. .) )) -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Feb 13 01:18:50 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Feb 2009 00:18:50 -0000 Subject: [Tutor] Detecting wx References: <499417CD.5010502@gmail.com> Message-ID: "Ricardo Ar?oz" wrote > wx shell I want to establish a wx app. But if I'm in pythonWin I didn't think pythonwin was a wx application. I believe it's written in pure Windows, using the pywin extensions on top of Scintilla. But that aside I'd be interested in the answer to this one. > there is a way in which I can detect if there is a wx event loop > running > in my environment? I've never actually had any problems with wxPython from inside any of the IDEs but I'm not sure I've actually tried because I just habitually test all GUIs outside the IDE. Alan G From alan.gauld at btinternet.com Fri Feb 13 01:23:19 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Feb 2009 00:23:19 -0000 Subject: [Tutor] IDLE/phythonWin -- Who's On First? (Abbott and Costello) References: <4992471E.40300@sbcglobal.net> <4992A25A.8010401@sbcglobal.net> <4992AA16.4080400@sbcglobal.net><4993AEED.2060602@sbcglobal.net> <766503.43245.qm@web86705.mail.ird.yahoo.com> Message-ID: "ALAN GAULD" wrote > solved since about v2.3. However it does still > through up issues, Ahem! That should of course be "throw up issues"! Sorry, Alan Gauld Author of the Learn To Program website http://www.alan-g.me.uk/ From dorseye at gmail.com Fri Feb 13 03:13:36 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Thu, 12 Feb 2009 19:13:36 -0700 Subject: [Tutor] Keeping Dictonary Entries Ordered In-Reply-To: References: <49938DE5.6070609@sbcglobal.net> Message-ID: >>>> But you need to have an order that will work with sorted(). > Its not just the order you add items to the dict. To store an > arbitrary order I suspect you would need to maintain a > secondary list with the keys in the order of insertion. > The most reliable way to dop that would be to subclass > dict. Somebody may already have done that so its worth > a google... > > HTH, > Alan, can you give a short snippet of what that would look like? I was trying to code out some idea of how you'd retain insertion order using another dict or a list and didn't get anywhere. -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Fri Feb 13 03:41:01 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 13 Feb 2009 15:41:01 +1300 Subject: [Tutor] Keeping Dictonary Entries Ordered In-Reply-To: References: <49938DE5.6070609@sbcglobal.net> Message-ID: <5e58f2e40902121841r46b27678i2b32db68de95be1d@mail.gmail.com> 2009/2/13 Eric Dorsey : > Alan, can you give a short snippet of what that would look like? I was > trying to code out some idea of how you'd retain insertion order using > another dict or a list and didn't get anywhere. Here's something basic: class o_dict(dict): def __init__(self, *args, **kw): dict.__init__(self, *args, **kw) self.__keylist = [] def __setitem__(self, key, val): dict.__setitem__(self, key, val) if key not in self.__keylist: self.__keylist.append(key) def __iter__(self): return iter(self.__keylist) It will do the right thing if you do 'for key in odict:', but not for things like iteritems(). It will break if you delete keys from the dictionary, and the 'key not in self.__keylist' test will get slow if you have lots and lots of keys. It will also not do what you want if you initialise it as something like: o_dict(foo=1, bar=2) All of which goes to show that you're probably better off looking for an implementation online, since someone else is bound to have tied off all the issues :-) -- John. From a.t.hofkamp at tue.nl Fri Feb 13 08:43:31 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Fri, 13 Feb 2009 08:43:31 +0100 Subject: [Tutor] extracting phrases and their memberships from syntax trees In-Reply-To: <652641e90902121520v59262d23vb7a2f0e96b202e7f@mail.gmail.com> References: <652641e90902121520v59262d23vb7a2f0e96b202e7f@mail.gmail.com> Message-ID: <499524A3.1080401@tue.nl> Emad Nawfal (???? ????) wrote: > just want to be able to do this myself. My question is: what tools do I need > for this? Could you please give me pointers to where to start? I'll then try > to do it myself, and ask questions when I get stuck. I'd start with parsing (reading) the tree to a generic abstract tree, and do the processing on the tree as a separate second step. For your tree, it seems feasible to write a parser by hand (you'd need to read about recursive descendant parsers then). Another approach is to use a parser generator tool. There are many: http://wiki.python.org/moin/LanguageParsing To give you a rough classification, LL(1) is the weakest parsing algorithm (but also the simplest to understand, comparable to recursive descendant), LALR(1) is 'normal', you can parse source code of many real programming languages with it (eg C and Python). GLR is the heavy-duty equipment but is also much slower and more memory-greedy. Many people are fond of PyParsing. My personal favorite is PLY. Enjoy your yourney! Sincerely, Albert From iwasroot at gmail.com Fri Feb 13 09:38:20 2009 From: iwasroot at gmail.com (Moos Heintzen) Date: Fri, 13 Feb 2009 00:38:20 -0800 Subject: [Tutor] List weirdness Message-ID: <4995317C.8040906@gmail.com> Hi, I was wondering why this happens. I was trying to create a list of lists. >>> d = [[]] >>> d[0][0]=1 Traceback (most recent call last): File "", line 1, in ? IndexError: list assignment index out of range >>> d [[]] What's wrong with that? However: >>> d[0].append(1) >>> d [[1]] I guess I can't reference [0] on an empty list. (I come from a C background.) From alan.gauld at btinternet.com Fri Feb 13 09:47:06 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Feb 2009 08:47:06 -0000 Subject: [Tutor] List weirdness References: <4995317C.8040906@gmail.com> Message-ID: "Moos Heintzen" wrote > >>> d = [[]] > >>> d[0][0]=1 > IndexError: list assignment index out of range > >>> d[0].append(1) > >>> d > [[1]] > > I guess I can't reference [0] on an empty list. Thats right. You can't assign a value to a position in a list that hasn't been created yet. It has nothing to do with nesting, its the same for a simople lust: >>> lst = [] >>> lst[0] = 66 Traceback (most recent call last): File "", line 1, in IndexError: list assignment index out of range >>> lst.append(66) >>> lst [66] You can also use insert, which takes an index. But if the index is non existent it appends... >>> lst2 = [] >>> lst2.insert(3,66) >>> lst2 [66] >>> lst.insert(3,66) >>> lst [66, 66] >>> HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From denis.spir at free.fr Fri Feb 13 11:16:34 2009 From: denis.spir at free.fr (spir) Date: Fri, 13 Feb 2009 11:16:34 +0100 Subject: [Tutor] Keeping Dictonary Entries Ordered In-Reply-To: <5e58f2e40902121841r46b27678i2b32db68de95be1d@mail.gmail.com> References: <49938DE5.6070609@sbcglobal.net> <5e58f2e40902121841r46b27678i2b32db68de95be1d@mail.gmail.com> Message-ID: <20090213111634.75bd677a@o> Le Fri, 13 Feb 2009 15:41:01 +1300, John Fouhy a ?crit : > 2009/2/13 Eric Dorsey : > > Alan, can you give a short snippet of what that would look like? I was > > trying to code out some idea of how you'd retain insertion order using > > another dict or a list and didn't get anywhere. > > Here's something basic: > > class o_dict(dict): > def __init__(self, *args, **kw): > dict.__init__(self, *args, **kw) > self.__keylist = [] > > def __setitem__(self, key, val): > dict.__setitem__(self, key, val) > if key not in self.__keylist: > self.__keylist.append(key) > > def __iter__(self): > return iter(self.__keylist) > > It will do the right thing if you do 'for key in odict:', but not for > things like iteritems(). It will break if you delete keys from the > dictionary, and the 'key not in self.__keylist' test will get slow if > you have lots and lots of keys. It will also not do what you want if > you initialise it as something like: o_dict(foo=1, bar=2) An issue is that obviously you can't initialize an ordered dict from another dict or a set of keyword arguments, for those are unordered. So I simply took **kwargs off the __init__ method. And let as single possible init stuff a list of (key,value) pairs. Also, as a built_in dict accepts only a single arg, there is no need for *arg: the seq of pairs must be contained in a list or tuple. From the pairs can then the keylist be properly initialised. This led me to something similar to the following: class Ordict(dict): def __init__(self, pairs): dict.__init__(self, pairs) self._keylist = [k for (k,v) in pairs] def __setitem__(self, key, val): dict.__setitem__(self, key, val) if key not in self._keylist: self._keylist.append(key) def __iter__(self): return iter(self._keylist) def __str__(self): pair_texts = ["%s:%s" % (k,self[k]) for k in self._keylist] return "[%s]" % ", ".join(pair_texts) od = Ordict([('a',1), ('d',4), ('b',2)]) od[' '] = 0 ; od['c'] = 3 print od._keylist for k in od: print "%s: %s " % (k,od[k]), print; print od ==> ['a', 'd', 'b', ' ', 'c'] a: 1 d: 4 b: 2 : 0 c: 3 [a:1, d:4, b:2, :0, c:3] I remember there were some more minor issues. Denis ------ la vida e estranya From philip.enid at tesco.net Fri Feb 13 11:37:36 2009 From: philip.enid at tesco.net (Philip Cooper) Date: Fri, 13 Feb 2009 10:37:36 -0000 Subject: [Tutor] Python Message-ID: Dear Tutor, I am preparing a data base saving it with pickle. I want to add additional information to the data base but seem to to have to recover the whole file from disc then add to it and save it again. Is there and append function within Pickle that will add information to the end of an existing file, similar to the append fuction used with text files, without recovering the file from the disc. The data file will eventually be quite large and I can see a time coming when there will be a time delay problem. Look forward to your help, Regards Philip cooper -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Feb 13 12:50:21 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 13 Feb 2009 06:50:21 -0500 Subject: [Tutor] Python In-Reply-To: References: Message-ID: <1c2a2c590902130350r127574acya465568749cb0078@mail.gmail.com> On Fri, Feb 13, 2009 at 5:37 AM, Philip Cooper wrote: > Dear Tutor, > > I am preparing a data base saving it with pickle. I want to add additional > information to the data base but seem to to have to recover the whole file > from disc then add to it and save it again. Is there and append function > within Pickle that will add information to the end of an existing file, > similar to the append fuction used with text files, without recovering the > file from the disc. The data file will eventually be quite large and I can > see a time coming when there will be a time delay problem. Pickle loads and saves whole objects. You can have multiple objects in one file but if one object changes you have to re-write the file. So if your database object is for example a big dict in which you are changing or adding elements, you will have to rewrite the whole dict. The shelve module provides a persistent dict that might be better suited to what you are doing. But it sounds like you might be well served by using a real database such as SQLite, which comes with recent versions of Python. Kent From kent37 at tds.net Fri Feb 13 14:18:31 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 13 Feb 2009 08:18:31 -0500 Subject: [Tutor] extracting phrases and their memberships from syntax trees In-Reply-To: <652641e90902121520v59262d23vb7a2f0e96b202e7f@mail.gmail.com> References: <652641e90902121520v59262d23vb7a2f0e96b202e7f@mail.gmail.com> Message-ID: <1c2a2c590902130518w26d64eb8g4c599e534f48ee59@mail.gmail.com> On Thu, Feb 12, 2009 at 6:20 PM, Emad Nawfal (???? ????) wrote: > Dear Tutors, > I have syntax trees like the one below. I need to extract the membership > information like which adjective belongs to which noun phrase, and so on. In > short, I want to do something like this: > http://ilk.uvt.nl/team/sabine/chunklink/README.html > I already have the Perl script that does that, so I do not need a script. I > just want to be able to do this myself. My question is: what tools do I need > for this? Could you please give me pointers to where to start? I'll then try > to do it myself, and ask questions when I get stuck. I guess I'm in the mood for writing parsers this week :-) Attached is a parser that uses PLY to parse the structure you provided. The result is a nested list structure with exactly the same structure as the original; it builds the list you would get by replacing all the () with [] and quoting the strings. Also in the attachment is a function that walks the resulting tree to print a table similar to the one in the chunklink reference. This is a pretty simple example of both PLY usage and recursive walking of a tree, if anyone wants to learn about either one. I hope I haven't taken all your fun :-) Kent PS to the list: I know, I'm setting a bad example. Usually we like to teach people to write Python, not write their programs for them. -------------- next part -------------- A non-text attachment was scrubbed... Name: ParsePennTree.py Type: text/x-python Size: 2489 bytes Desc: not available URL: From david at abbottdavid.com Fri Feb 13 15:38:19 2009 From: david at abbottdavid.com (David) Date: Fri, 13 Feb 2009 09:38:19 -0500 Subject: [Tutor] *nix tail -f multiple log files with Thread Message-ID: <499585DB.1090409@abbottdavid.com> Hi everyone, I copied a program from C to track multiple log files. I would like to be able to print a label when a log file is updated. Here is the program; #!/usr/bin/python from threading import Thread import subprocess from Queue import Queue num_threads = 3 queue = Queue() logfiles = ["/var/log/messages", "/var/log/apache2/access_log", "/var/log/apache2/error_log"] def logtailer(i, q,): while True: lfile = q.get() sudo = "sudo" tail = "tail" arg = "-f" ret = subprocess.call([sudo, tail, arg, lfile]) q.task_done() for i in range(num_threads): worker = Thread(target=logtailer, args=(i, queue)) worker.setDaemon(True) worker.start() for lfile in logfiles: queue.put(lfile) queue.join() And here is a sample of the output; [Fri Feb 13 08:58:48 2009] [error] [client 127.0.0.1] File does not exist: /var/www/localhost/htdocs/moodle/favicon.ico [Fri Feb 13 08:58:51 2009] [error] [client 127.0.0.1] File does not exist: /var/www/localhost/htdocs/moodle/favicon.ico Feb 13 09:02:26 opteron sudo: david : TTY=pts/4 ; PWD=/home/david ; USER=root ; COMMAND=/bin/tail -f /var/log/apache2/error_log Feb 13 09:02:26 opteron sudo: pam_unix(sudo:session): session opened for user root by david(uid=0) Feb 13 09:02:26 opteron sudo: pam_unix(sudo:session): session closed for user root Feb 13 09:10:01 opteron cron[10633]: (root) CMD (test -x /usr/sbin/run-crons && /usr/sbin/run-crons ) Feb 13 09:18:33 opteron su[10678]: Successful su for root by david Feb 13 09:18:33 opteron su[10678]: + pts/6 david:root Feb 13 09:18:33 opteron su[10678]: pam_unix(su:session): session opened for user root by david(uid=1000) 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET /theme/custom_corners/favicon.ico HTTP/1.1" 200 894 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET /lib/speller/spellChecker.js HTTP/1.1" 200 15980 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET / HTTP/1.1" 200 13718 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET /theme/custom_corners/styles.php HTTP/1.1" 200 30709 I would like to be able to add a label like; [Fri Feb 13 08:58:48 2009] [error] [client 127.0.0.1] File does not exist: /var/www/localhost/htdocs/moodle/favicon.ico [Fri Feb 13 08:58:51 2009] [error] [client 127.0.0.1] File does not exist: /var/www/localhost/htdocs/moodle/favicon.ico Feb 13 09:02:26 opteron sudo: david : TTY=pts/4 ; PWD=/home/david ; USER=root ; COMMAND=/bin/tail -f /var/log/apache2/error_log Feb 13 09:02:26 opteron sudo: pam_unix(sudo:session): session opened for user root by david(uid=0) Feb 13 09:02:26 opteron sudo: pam_unix(sudo:session): session closed for user root Feb 13 09:10:01 opteron cron[10633]: (root) CMD (test -x /usr/sbin/run-crons && /usr/sbin/run-crons ) Feb 13 09:18:33 opteron su[10678]: Successful su for root by david Feb 13 09:18:33 opteron su[10678]: + pts/6 david:root Feb 13 09:18:33 opteron su[10678]: pam_unix(su:session): session opened for user root by david(uid=1000) 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET /theme/custom_corners/favicon.ico HTTP/1.1" 200 894 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET /lib/speller/spellChecker.js HTTP/1.1" 200 15980 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET / HTTP/1.1" 200 13718 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET /theme/custom_corners/styles.php HTTP/1.1" 200 30709 I can create the label like this; def label() print "<%s\n>" % lfile But I have no idea how to get it to work when a thread is updated. thanks -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From ptmcg at austin.rr.com Fri Feb 13 16:20:28 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 13 Feb 2009 09:20:28 -0600 Subject: [Tutor] extracting phrases and their memberships from syntax In-Reply-To: References: Message-ID: <415B718CF29245A29E0BC07D58D1F099@AWA2> Pyparsing has a built-in helper called nestedExpr that fits neatly in with this data. Here is the whole script: from pyparsing import nestedExpr syntax_tree = nestedExpr() results = syntax_tree.parseString(st_data) from pprint import pprint pprint(results.asList()) Prints: [[['S', ['NP-SBJ-1', ['NP', ['NNP', 'Rudolph'], ['NNP', 'Agnew']], [',', ','], ['UCP', ['ADJP', ['NP', ['CD', '55'], ['NNS', 'years']], ['JJ', 'old']], ['CC', 'and'], ['NP', ['NP', ['JJ', 'former'], ['NN', 'chairman']], ['PP', ['IN', 'of'], ['NP', ['NNP', 'Consolidated'], ['NNP', 'Gold'], ['NNP', 'Fields'], ['NNP', 'PLC']]]]], [',', ',']], ['VP', ['VBD', 'was'], ['VP', ['VBN', 'named'], ['S', ['NP-SBJ', ['-NONE-', '*-1']], ['NP-PRD', ['NP', ['DT', 'a'], ['JJ', 'nonexecutive'], ['NN', 'director']], ['PP', ['IN', 'of'], ['NP', ['DT', 'this'], ['JJ', 'British'], ['JJ', 'industrial'], ['NN', 'conglomerate']]]]]]], ['.', '.']]]] If you want to delve deeper into this, you could, since the content of the () groups is so regular. You in essence reconstruct nestedExpr in your own code, but you do get some increased control and visibility to the parsed content. Since this is a recursive syntax, you will need to use pyparsing's mechanism for recursion, which is the Forward class. Forward is sort of a "I can't define the whole thing yet, just create a placeholder" placeholder. syntax_element = Forward() LPAR,RPAR = map(Suppress,"()") syntax_tree = LPAR + syntax_element + RPAR Now in your example, a syntax_element can be one of 4 things: - a punctuation mark, twice - a syntax marker followed by one or more syntax_trees - a syntax marker followed by a word - a syntax tree Here is how I define those: marker = oneOf("VBD ADJP VBN JJ DT PP NN UCP NP-PRD " "NP NNS NNP CC NP-SBJ-1 CD VP -NONE- " "IN NP-SBJ S") punc = oneOf(", . ! ?") wordchars = printables.replace("(","").replace(")","") syntax_element << ( punc + punc | marker + OneOrMore(Group(syntax_tree)) | marker + Word(wordchars) | syntax_tree ) Note that we use '<<' operator to "inject" the definition of a syntax_element - we can't use '=' or we would get a different expression than the one we used to define syntax_tree. Now parse the string, and voila! Same as before. Here is the entire script: from pyparsing import nestedExpr, Suppress, oneOf, Forward, OneOrMore, Word, printables, Group syntax_element = Forward() LPAR,RPAR = map(Suppress,"()") syntax_tree = LPAR + syntax_element + RPAR marker = oneOf("VBD ADJP VBN JJ DT PP NN UCP NP-PRD " "NP NNS NNP CC NP-SBJ-1 CD VP -NONE- " "IN NP-SBJ S") punc = oneOf(", . ! ?") wordchars = printables.replace("(","").replace(")","") syntax_element << ( punc + punc | marker + OneOrMore(Group(syntax_tree)) | marker + Word(wordchars) | syntax_tree ) results = syntax_tree.parseString(st_data) from pprint import pprint pprint(results.asList()) -- Paul From cclpianos at comcast.net Fri Feb 13 17:47:58 2009 From: cclpianos at comcast.net (cclpianos at comcast.net) Date: Fri, 13 Feb 2009 09:47:58 -0700 Subject: [Tutor] Copy file function works, but not with adding the date copied Message-ID: <7755CC1D-9D90-44BC-B392-F51F41EFB292@comcast.net> Hello, I am modifying a simple program "copy file" from the tutorials Alan Gauld wrote. In it's first simpler instance (W/O date) it works beautifully. But I wanted to add the date the file was copied. I've kept it simple by pointing to a single file. The problem lies somewhere in how the program modifies the information. It creates the new copied file, but can't open with the application TextEdit. However, I can read the file from the shell interpreter and do see the date the file was copied: The date this file was copied Friday February 13 {\rtf1\mac\ansicpg10000\cocoartf824\cocoasubrtf440 {\fonttbl\f0\fnil\fcharset77 LucidaGrande;\f1\fnil\fcharset77 Verdana; \f2\fmodern\fcharset77 Courier; \f3\fswiss\fcharset77 Helvetica;\f4\fnil\fcharset77 LucidaGrande-Bold; \f5\fswiss\fcharset77 ArialMT; } {\colortbl;\red255\green255\blue255;\red249\green249\blue249;\red51 \green51\blue51;} \margl1440\margr1440\vieww14060\viewh10300\viewkind0 \deftab720 \pard\pardeftab720\sl320\ql\qnatural \f0\fs24 \cf0 \ tcpdump -q -ien1 lists tcp activity reatime\ \ ps axc -U root Lists processes by "root" users\ \ \ I'm using 2.61 on OS X 10.4.11. My apologies in advance for the indention format. TIA, Pat below is the file: # this is a simple tool to copy a file from the console (modified to show the date it was copied). import time inp = open( "/Users/pw/Desktop/Terminal_commands.rtf","r") # file to be opened using the path outp = open( "/Users/pw/Desktop/Terminalback_commands.rtf","w") # Copied file modified name today = time.localtime(time.time()) #Using the time function to output the date file was copied theDate = time.strftime("%A %B %d", today) outp.write( "The date this file was copied %s\n\n" % theDate) for line in inp: outp.write(line) print "This copied file has now been modified only by the date copied." inp.close() outp.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From bgailer at gmail.com Fri Feb 13 18:01:39 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 13 Feb 2009 12:01:39 -0500 Subject: [Tutor] List weirdness In-Reply-To: <4995317C.8040906@gmail.com> References: <4995317C.8040906@gmail.com> Message-ID: <4995A773.6070106@gmail.com> Moos Heintzen wrote: > Hi, > I was wondering why this happens. I was trying to create a list of lists. > > >>> d = [[]] > >>> d[0][0]=1 > Traceback (most recent call last): > File "", line 1, in ? > IndexError: list assignment index out of range > >>> d > [[]] > > What's wrong with that? > > However: > >>> d[0].append(1) > >>> d > [[1]] > > I guess I can't reference [0] on an empty list. (I come from a C > background.) Can you have an empty array in C? If so, it does not have any elements, so you can't refer to element 0. -- Bob Gailer Chapel Hill NC 919-636-4239 From haztang17 at gmail.com Fri Feb 13 19:05:44 2009 From: haztang17 at gmail.com (Hi) Date: Fri, 13 Feb 2009 10:05:44 -0800 Subject: [Tutor] Calling variable from two different classes Message-ID: I want to be able to call a variable from one of my classes to my main class (interface layout) and have it update every minute. I am using Python and wxPython. Is it better to be in the main class and read the variable or should I have the class the variable resides in to send the variable along to the main class? In my interface class I have it as: display = wx.StaticText(self, -1, '', (50, 50)) while the class where the variable is in: data_rate = 5000 and I want to be able to put the value stored in data_rate into display so that I can show it on my interface. And regarding the update per some time, I am looking into the poll command. Is that the direction where I should be heading? (I know updating data_rate won't do anything right now since it's a constant, but it will vary later on... just one step at a time here). -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Feb 13 20:11:37 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Feb 2009 19:11:37 -0000 Subject: [Tutor] Copy file function works, but not with adding the date copied References: <7755CC1D-9D90-44BC-B392-F51F41EFB292@comcast.net> Message-ID: wrote > > I am modifying a simple program "copy file" from the tutorials Alan > Gauld wrote. In it's first simpler instance (W/O date) it works > beautifully. But I wanted to > add the date the file was copied. I've kept it simple by pointing to > a single file. > > The problem lies somewhere in how the program modifies the > information. It creates the new copied file, but can't open with the > application TextEdit. > The date this file was copied Friday February 13 > > {\rtf1\mac\ansicpg10000\cocoartf824\cocoasubrtf440 The problem is that this is an RTF format which is a binary format. You can process binary data ion Python (see the box on the files topic page) but it is much more difficult that normal plain text files. So you have written a line of plain text at the front of the RTF file and the word processor doesn't know how to interpret that their. So it ignores it! > import time > inp = open( "/Users/pw/Desktop/Terminal_commands.rtf","r") # file to Open a plain text file (eg foo.txt) instead of an RTF file. That should work. Unfortunatey reading and writing RTF files is a much more advanced topic than you might expect, too much for your level of skill just now. By the time you've completed the tutorial you might be ready to try :-) Also I think there is a Python module somewhere for reading/writing RTF files if that is a real need that you have. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From srilyk at gmail.com Fri Feb 13 20:12:59 2009 From: srilyk at gmail.com (W W) Date: Fri, 13 Feb 2009 13:12:59 -0600 Subject: [Tutor] List weirdness In-Reply-To: <4995A773.6070106@gmail.com> References: <4995317C.8040906@gmail.com> <4995A773.6070106@gmail.com> Message-ID: <333efb450902131112g531bf59au9550745f7f9ddcf9@mail.gmail.com> On Fri, Feb 13, 2009 at 11:01 AM, bob gailer wrote: > Moos Heintzen wrote: > >> I guess I can't reference [0] on an empty list. (I come from a C >> background.) >> > Can you have an empty array in C? If so, it does not have any elements, so > you can't refer to element 0. I think the OP was confusing an empty array in C (something like int foo[10] = {}; ) where memory is allocated, just not "used", to an empty list in Python. AFAIK, creating an empty list in python is a lot more similar to creating an empty vector in C++. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Feb 13 20:18:50 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 13 Feb 2009 19:18:50 -0000 Subject: [Tutor] Calling variable from two different classes References: Message-ID: "Hi" wrote >I want to be able to call a variable from one of my classes to my >main class > (interface layout) and have it update every minute. Sp provuide an update method in the class that has the variable. Do not pass the variable to another class to update it, Objects should always do it to themselves. > wxPython. Is it better to be in the main class and read the variable > or > should I have the class the variable resides in to send the variable > along > to the main class? Neither its better for the mainclass to update the variable by sending a message to the class with the variable. Now the next question is what determines when it needs to be updated? In Python reading the data from a class is considered OK - in most OOP languages its considered better to write a "getter" method. But if you need to display and set it in your main class are you sure the variable shouldn't be stored in the main class? Is it part of the display or part of the underlying logic that the GUI is controlling? If the latter I'd go for using a getter and an update method but if its just a display feature move it to the main class. What you really want to eliminate is any knowledge of the GUI in the application classes. A little bit of knowledge of the app classes by the GUI is not so bad. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From marc.tompkins at gmail.com Fri Feb 13 20:35:41 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 13 Feb 2009 11:35:41 -0800 Subject: [Tutor] Copy file function works, but not with adding the date copied In-Reply-To: References: <7755CC1D-9D90-44BC-B392-F51F41EFB292@comcast.net> Message-ID: <40af687b0902131135k5e091a9fm784a025423e67920@mail.gmail.com> On Fri, Feb 13, 2009 at 11:11 AM, Alan Gauld wrote: > >> {\rtf1\mac\ansicpg10000\cocoartf824\cocoasubrtf440 >> > > The problem is that this is an RTF format which is a binary format. > You can process binary data ion Python (see the box on the files > topic page) but it is much more difficult that normal plain text files. > I'd like to correct a misapprehension here: RTF files are not a "binary format" in the usual sense of that phrase - there are no non-ASCII characters, newlines are handled normally, etc. They're text files, but with lots of funky formatting codes included - which are themselves all text. They're a lot like badly-formatted, insanely complicated XML, actually. They're full of gibberish-looking strings like the above, and the nesting of curly braces can run to dozens of layers deep - however, if you want to get a quick idea of what's going on in an RTF, the fastest way is to unfold it (search-and-replace each "{" and "}" with "{\n" and "}\n" respectively) and indent each opened curly brace. Then if you want to give yourself a headache, you can sit down with Microsoft's RTF specification and figure out what all those codes do. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Fri Feb 13 21:10:05 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 13 Feb 2009 12:10:05 -0800 Subject: [Tutor] Copy file function works, but not with adding the date copied In-Reply-To: <40af687b0902131135k5e091a9fm784a025423e67920@mail.gmail.com> References: <7755CC1D-9D90-44BC-B392-F51F41EFB292@comcast.net> <40af687b0902131135k5e091a9fm784a025423e67920@mail.gmail.com> Message-ID: <40af687b0902131210s55c654faq2ebe9bdb7b6dbe38@mail.gmail.com> On Fri, Feb 13, 2009 at 11:35 AM, Marc Tompkins wrote: > On Fri, Feb 13, 2009 at 11:11 AM, Alan Gauld wrote: > >> >>> {\rtf1\mac\ansicpg10000\cocoartf824\cocoasubrtf440 >>> >> Here's a quick-and-dirty way to do what (I think) you want to do: Skip the first curly brace ("{") - find the next one. Just before it, insert a space + the datestamp text. That's it. Now if you open the RTF file in Word, or WordPad, or whatever RTF reader you have on your system, your text will appear (in the system-default font and style, 'cause you inserted it before any document styles) at the top of the document. Note: this is absolutely NOT valid RTF; it only works because Microsoft specifically requires that RTF readers obey Posten's Law. If you later edit the modified file in Word, WordPad, etc. your datestamp text will be moved to a more appropriate area of the file and you might have a hard time finding it again. -------------- next part -------------- An HTML attachment was scrubbed... URL: From payo2000 at gmail.com Fri Feb 13 23:31:35 2009 From: payo2000 at gmail.com (pa yo) Date: Fri, 13 Feb 2009 23:31:35 +0100 Subject: [Tutor] Loops Message-ID: I need some help. I have written a filter called Peqibot that takes posts from Twitter and makes them into wikipages on peqipedia.com So if you post the following message on Twitter: >@peqi Tallinn=The capital city of [[Estonia]]. It makes a page on peqipedia.com with "Tallinn" as the headline and with the article text being "The captial city of [[Estonia]]." ... it seems to be working ok - but I discovered that if someone posts a message starting with "@peqi" but without an "=" sign the program crashes. The way I have come up with to solve this problem is to put the following loop in: >> rawfeed = feedparser(http//twitter.com/foobar....) >> feedstring = rawfeed.split('=',1) #this splits the feed at the first "=" >> headline = feedstring[0] #this is the text infront of the "=" sign. >> if len(headlinestring) == len(rawfeed) #ie. if the split hasn't worked they will be exactly the same length >> body = "\x7b\x7bEmpty\x7d\x7d" #this adds an "{{Empty}}" template to the wiki >> else: >> body = feedstring[1] >> #....here I use urllib to encode a post from headline and body that can be posted to the wiki. But I can't get it to work - I have tried various indents and break and continues - but I don't know enough about loops to identify what I have done wrong. Any advice or suggestions would be great. (it's my first program so there might well be a better way to avoid this problem in the first place). Best wishes Payo From sierra_mtnview at sbcglobal.net Sat Feb 14 00:50:51 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 13 Feb 2009 15:50:51 -0800 Subject: [Tutor] Variable to String? Message-ID: <4996075B.9080601@sbcglobal.net> An HTML attachment was scrubbed... URL: From bill at celestial.net Sat Feb 14 00:57:32 2009 From: bill at celestial.net (Bill Campbell) Date: Fri, 13 Feb 2009 15:57:32 -0800 Subject: [Tutor] Variable to String? In-Reply-To: <4996075B.9080601@sbcglobal.net> References: <4996075B.9080601@sbcglobal.net> Message-ID: <20090213235732.GA30141@ayn.mi.celestial.com> On Fri, Feb 13, 2009, Wayne Watson wrote: > > That's pretty much the question in Subject. I've got a date time > variable with, for example, 15:00:00 in hh:mm:ss format, and I'd like > to make it a string. The easiest way is probably to use the strftime method available on any datetime object. It uses the standard strftime expansion, which on any Linux/Unix box will be found with ``man strftime''. Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 Scientists are explorers. Philosophers are tourists. -- Richard Feynman From kent37 at tds.net Sat Feb 14 01:06:06 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 13 Feb 2009 19:06:06 -0500 Subject: [Tutor] Variable to String? In-Reply-To: <4996075B.9080601@sbcglobal.net> References: <4996075B.9080601@sbcglobal.net> Message-ID: <1c2a2c590902131606ke1088c1g4c279f37b1a6f41a@mail.gmail.com> On Fri, Feb 13, 2009 at 6:50 PM, Wayne Watson wrote: > That's pretty much the question in Subject. I've got a date time variable > with, for example, 15:00:00 in hh:mm:ss format, and I'd like to make it a > string. Lots of choices: In [1]: from datetime import datetime In [2]: d=datetime.now() In [4]: str(d) Out[4]: '2009-02-13 19:03:43.517789' In [6]: d.isoformat() Out[6]: '2009-02-13T19:03:43.517789' strftime() takes a format string so you can get pretty much whatever format you want: In [7]: d.strftime("%a, %d %b %Y %H:%M:%S +0000") Out[7]: 'Fri, 13 Feb 2009 19:03:43 +0000' Kent From wescpy at gmail.com Sat Feb 14 01:43:51 2009 From: wescpy at gmail.com (wesley chun) Date: Fri, 13 Feb 2009 16:43:51 -0800 Subject: [Tutor] Variable to String? In-Reply-To: <4996075B.9080601@sbcglobal.net> References: <4996075B.9080601@sbcglobal.net> Message-ID: <78b3a9580902131643t738a5ecag84756f0dea1cd5b5@mail.gmail.com> On Fri, Feb 13, 2009 at 3:50 PM, Wayne Watson wrote: > That's pretty much the question in Subject. I've got a date time variable > with, for example, 15:00:00 in hh:mm:ss format, and I'd like to make it a string. >>> import datetime >>> d = datetime.time(15,0) datetime.time(15, 0) >>> d datetime.time(15, 0) >>> str(d) '15:00:00' is this what you're looking for, or was there something else? -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Sat Feb 14 01:46:57 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 Feb 2009 00:46:57 -0000 Subject: [Tutor] Copy file function works, but not with adding the date copied References: <7755CC1D-9D90-44BC-B392-F51F41EFB292@comcast.net><40af687b0902131135k5e091a9fm784a025423e67920@mail.gmail.com> <40af687b0902131210s55c654faq2ebe9bdb7b6dbe38@mail.gmail.com> Message-ID: "Marc Tompkins" wrote > Here's a quick-and-dirty way to do what (I think) you want to do: > > Skip the first curly brace ("{") - find the next one. Just before > it, > insert a space + the datestamp text. That's it. If the OP is just working through my tutor I doubt if he will be able to do much of that yet. Especially since the "handling text" topic is the one *after* handling files! :-) BTW Thanks for the reminder about RTF format, you are right it is not strictly a binary file it is formatted text. The end result is the same in that the OP needs to use a plain unformatted text file rather than trying to write to RTF. Also The RTF module I mentioned is here: http://www.nava.de/2005/04/06/pyrtf/ HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Feb 14 01:52:11 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 Feb 2009 00:52:11 -0000 Subject: [Tutor] Loops References: Message-ID: "pa yo" wrote > The way I have come up with to solve this problem is to put the > following loop in: > >>> rawfeed = feedparser(http//twitter.com/foobar....) >>> feedstring = rawfeed.split('=',1) #this splits the feed at >>> the first "=" >>> headline = feedstring[0] #this is the text >>> infront of the "=" sign. >>> if len(headlinestring) == len(rawfeed) #ie. if the split hasn't >>> worked they will be exactly the same >>> body = >>> "\x7b\x7bEmpty\x7d\x7d" #this adds an "{{Empty}}" template >>> to the wiki >>> else: >>> body = feedstring[1] Sorry, where is the loop? > But I can't get it to work - I have tried various indents and break > and continues - but I don't know enough about loops to identify what > I > have done wrong. I'm confused, there is no loop only a conditional statement (if/else) The only loops supported in Python are for and while (OK you could count list comprehensions/generator expressions too) and neither of them are in your code. However you don't tell us what is happening that you don;t expect. Are you getting an error message? If so what (all of it please)? Or is it just the output that is different to what you expect? if so what did you expect and what did you get? And finally which version of Python and which OS please? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bgailer at gmail.com Sat Feb 14 02:17:21 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 13 Feb 2009 20:17:21 -0500 Subject: [Tutor] Copy file function works, but not with adding the date copied In-Reply-To: <7755CC1D-9D90-44BC-B392-F51F41EFB292@comcast.net> References: <7755CC1D-9D90-44BC-B392-F51F41EFB292@comcast.net> Message-ID: <49961BA1.3050400@gmail.com> cclpianos at comcast.net wrote: > Hello, > > "but can't open with the application TextEdit" What are you doing to open it? What does "can't open" mean"? Error messages or what? Could this be a resource fork issue? AFAIK Python does not reproduce the resource fork. -- Bob Gailer
Chapel Hill NC
919-636-4239 From sierra_mtnview at sbcglobal.net Sat Feb 14 03:29:12 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 13 Feb 2009 18:29:12 -0800 Subject: [Tutor] Variable to String? In-Reply-To: <78b3a9580902131643t738a5ecag84756f0dea1cd5b5@mail.gmail.com> References: <4996075B.9080601@sbcglobal.net> <78b3a9580902131643t738a5ecag84756f0dea1cd5b5@mail.gmail.com> Message-ID: <49962C78.5050009@sbcglobal.net> An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Sat Feb 14 15:59:08 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Sat, 14 Feb 2009 09:59:08 -0500 Subject: [Tutor] extracting phrases and their memberships from syntax In-Reply-To: <415B718CF29245A29E0BC07D58D1F099@AWA2> References: <415B718CF29245A29E0BC07D58D1F099@AWA2> Message-ID: <652641e90902140659v2dd82f09u58ea791c0e9d72af@mail.gmail.com> On Fri, Feb 13, 2009 at 10:20 AM, Paul McGuire wrote: > Pyparsing has a built-in helper called nestedExpr that fits neatly in with > this data. Here is the whole script: > > from pyparsing import nestedExpr > > syntax_tree = nestedExpr() > results = syntax_tree.parseString(st_data) > > from pprint import pprint > pprint(results.asList()) > > > Prints: > > [[['S', > ['NP-SBJ-1', > ['NP', ['NNP', 'Rudolph'], ['NNP', 'Agnew']], > [',', ','], > ['UCP', > ['ADJP', ['NP', ['CD', '55'], ['NNS', 'years']], ['JJ', 'old']], > ['CC', 'and'], > ['NP', > ['NP', ['JJ', 'former'], ['NN', 'chairman']], > ['PP', > ['IN', 'of'], > ['NP', > ['NNP', 'Consolidated'], > ['NNP', 'Gold'], > ['NNP', 'Fields'], > ['NNP', 'PLC']]]]], > [',', ',']], > ['VP', > ['VBD', 'was'], > ['VP', > ['VBN', 'named'], > ['S', > ['NP-SBJ', ['-NONE-', '*-1']], > ['NP-PRD', > ['NP', ['DT', 'a'], ['JJ', 'nonexecutive'], ['NN', 'director']], > ['PP', > ['IN', 'of'], > ['NP', > ['DT', 'this'], > ['JJ', 'British'], > ['JJ', 'industrial'], > ['NN', 'conglomerate']]]]]]], > ['.', '.']]]] > > If you want to delve deeper into this, you could, since the content of the > () groups is so regular. You in essence reconstruct nestedExpr in your own > code, but you do get some increased control and visibility to the parsed > content. > > Since this is a recursive syntax, you will need to use pyparsing's > mechanism > for recursion, which is the Forward class. Forward is sort of a "I can't > define the whole thing yet, just create a placeholder" placeholder. > > syntax_element = Forward() > LPAR,RPAR = map(Suppress,"()") > syntax_tree = LPAR + syntax_element + RPAR > > Now in your example, a syntax_element can be one of 4 things: > - a punctuation mark, twice > - a syntax marker followed by one or more syntax_trees > - a syntax marker followed by a word > - a syntax tree > > Here is how I define those: > > marker = oneOf("VBD ADJP VBN JJ DT PP NN UCP NP-PRD " > "NP NNS NNP CC NP-SBJ-1 CD VP -NONE- " > "IN NP-SBJ S") > punc = oneOf(", . ! ?") > > wordchars = printables.replace("(","").replace(")","") > > syntax_element << ( > punc + punc | > marker + OneOrMore(Group(syntax_tree)) | > marker + Word(wordchars) | > syntax_tree ) > > Note that we use '<<' operator to "inject" the definition of a > syntax_element - we can't use '=' or we would get a different expression > than the one we used to define syntax_tree. > > Now parse the string, and voila! Same as before. > > Here is the entire script: > > from pyparsing import nestedExpr, Suppress, oneOf, Forward, OneOrMore, > Word, > printables, Group > > syntax_element = Forward() > LPAR,RPAR = map(Suppress,"()") > syntax_tree = LPAR + syntax_element + RPAR > > marker = oneOf("VBD ADJP VBN JJ DT PP NN UCP NP-PRD " > "NP NNS NNP CC NP-SBJ-1 CD VP -NONE- " > "IN NP-SBJ S") > punc = oneOf(", . ! ?") > > wordchars = printables.replace("(","").replace(")","") > > syntax_element << ( > punc + punc | > marker + OneOrMore(Group(syntax_tree)) | > marker + Word(wordchars) | > syntax_tree ) > > results = syntax_tree.parseString(st_data) > from pprint import pprint > pprint(results.asList()) > > -- Paul > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Thank you so much Paul, Kent, and Hoftkamp. I was asking what the right tools were, and I got two fully-functional scripts back. Much more than I had expected. I'm planning to use these scripts instead of the Perl one. I've also started with PyParsing as it seems to be a little easier to understand than PLY. Thank you again, -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Sat Feb 14 16:10:41 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 14 Feb 2009 09:10:41 -0600 Subject: [Tutor] extracting phrases and their memberships from syntax In-Reply-To: <652641e90902140659v2dd82f09u58ea791c0e9d72af@mail.gmail.com> References: <415B718CF29245A29E0BC07D58D1F099@AWA2> <652641e90902140659v2dd82f09u58ea791c0e9d72af@mail.gmail.com> Message-ID: <4999ADEDFA0043E28AC4D3B10C37D1EA@AWA2> -----Original Message----- From: Emad Nawfal (???? ????) [mailto:emadnawfal at gmail.com] Sent: Saturday, February 14, 2009 8:59 AM To: Paul McGuire Cc: tutor at python.org Subject: Re: [Tutor] extracting phrases and their memberships from syntax Thank you so much Paul, Kent, and Hoftkamp. I was asking what the right tools were, and I got two fully-functional scripts back. Much more than I had expected. I'm planning to use these scripts instead of the Perl one. I've also started with PyParsing as it seems to be a little easier to understand than PLY. --------------------------- Glad to help - actually, I sent 2 working scripts, and Kent sent 1, so I count THREE fully-functional scripts! ;) Also, Kent's recursive example code for traversing the returned parse tree should also work with the data structure that the pyparsing example returns. Please make use of the pyparsing samples and documentation available at the pyparsing wiki - pyparsing.wikispaces.com. Also, if you use the Windows binary or easy_install installations, you don't get the help and example directories - download the source ZIP distribution, and you get a lot more helpful information. -- Paul From sierra_mtnview at sbcglobal.net Sat Feb 14 16:21:55 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 14 Feb 2009 07:21:55 -0800 Subject: [Tutor] Keeping Dictonary Entries Ordered In-Reply-To: References: <49938DE5.6070609@sbcglobal.net> Message-ID: <4996E193.3080607@sbcglobal.net> An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Sat Feb 14 16:28:12 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Sat, 14 Feb 2009 10:28:12 -0500 Subject: [Tutor] extracting phrases and their memberships from syntax In-Reply-To: <4999ADEDFA0043E28AC4D3B10C37D1EA@AWA2> References: <415B718CF29245A29E0BC07D58D1F099@AWA2> <652641e90902140659v2dd82f09u58ea791c0e9d72af@mail.gmail.com> <4999ADEDFA0043E28AC4D3B10C37D1EA@AWA2> Message-ID: <652641e90902140728s1013fb0blb6735fe321c804f7@mail.gmail.com> 2009/2/14 Paul McGuire > -----Original Message----- > From: Emad Nawfal (???? ????) [mailto:emadnawfal at gmail.com] > Sent: Saturday, February 14, 2009 8:59 AM > To: Paul McGuire > Cc: tutor at python.org > Subject: Re: [Tutor] extracting phrases and their memberships from syntax > > > Thank you so much Paul, Kent, and Hoftkamp. > I was asking what the right tools were, and I got two fully-functional > scripts back. Much more than I had expected. > > I'm planning to use these scripts instead of the Perl one. I've also > started > with PyParsing as it seems to be a little easier to understand than PLY. > > > --------------------------- > Glad to help - actually, I sent 2 working scripts, and Kent sent 1, so I > count THREE fully-functional scripts! ;) Also, Kent's recursive example > code for traversing the returned parse tree should also work with the data > structure that the pyparsing example returns. > > Please make use of the pyparsing samples and documentation available at the > pyparsing wiki - pyparsing.wikispaces.com. Also, if you use the Windows > binary or easy_install installations, you don't get the help and example > directories - download the source ZIP distribution, and you get a lot more > helpful information. > > -- Paul > > Thanks Paul. Yesterday I downloaded PyParsing and downloaded "Getting Started with Pyparsing" from O'Reilly. It is really good. What I like most about Pyparsing is that it is very easy to understand. Suitable for an ever-amateur like me. This is all I can say. I have no means of telling what the difference between it and PLY is. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From bryan.fodness at gmail.com Sat Feb 14 17:40:59 2009 From: bryan.fodness at gmail.com (Bryan Fodness) Date: Sat, 14 Feb 2009 11:40:59 -0500 Subject: [Tutor] Extract image from RTF file Message-ID: I have a large amount of RTF files where the only thing in them is an image. I would like to extract them an save them as a png. Eventually, I would like to also grab some text that is on the image. I think PIL has something for this. Does anyone have any suggestion on how to start this? From alan.gauld at btinternet.com Sat Feb 14 20:34:18 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 14 Feb 2009 19:34:18 -0000 Subject: [Tutor] Extract image from RTF file References: Message-ID: "Bryan Fodness" wrote >I have a large amount of RTF files where the only thing in them is an > image. I would like to extract them an save them as a png. The link I posted on another thread claims to handle images in RTF files http://www.nava.de/2005/04/06/pyrtf/ HTH. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ From marc.tompkins at gmail.com Sat Feb 14 20:36:40 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sat, 14 Feb 2009 11:36:40 -0800 Subject: [Tutor] Fwd: Extract image from RTF file In-Reply-To: <40af687b0902141135l2a98f701h6e91f9076c2218@mail.gmail.com> References: <40af687b0902141135l2a98f701h6e91f9076c2218@mail.gmail.com> Message-ID: <40af687b0902141136g5d92a4b8n4d4ac5e0996f46a9@mail.gmail.com> Forgot to Reply All. ---------- Forwarded message ---------- From: Marc Tompkins Date: Sat, Feb 14, 2009 at 11:35 AM Subject: Re: [Tutor] Extract image from RTF file To: Bryan Fodness On Sat, Feb 14, 2009 at 8:40 AM, Bryan Fodness wrote: > I have a large amount of RTF files where the only thing in them is an > image. I would like to extract them an save them as a png. > Eventually, I would like to also grab some text that is on the image. > I think PIL has something for this. > > Does anyone have any suggestion on how to start this? > I'm no kind of expert, but I do have a pointer or two... RTF files are text with lots and lots of funky-looking formatting, but generally not "binary" in the sense of requiring special handling (although, now that I just read about how pictures are stored in them, it seems there might be some exceptions...) There's a Python library for dealing with RTF files ( http://www.nava.de/2005/04/06/pyrtf/) but I haven't tried it; if you're comfortable opening text files and handling their contents, it might be simpler to roll your own for this task. You'll want to look at the Microsoft RTF specification, the latest version of which (1.6) is available here: http://msdn.microsoft.com/en-us/library/aa140277(office.10).aspx In particular, you'll be interested in the section on Pictures, which I'll excerpt here: Pictures An RTF file can include pictures created with other applications. These pictures can be in hexadecimal (the default) or binary format. Pictures are destinations, and begin with the \*pict* control word. The *\pict* keyword is preceded by* \*\shppict* destination control keyword as described in the following example. A picture destination has the following syntax: '{' *\pict* (? & ? & & & ?) '}' |* \emfblip* |* \pngblip* |*\jpegblip | \macpict * | *\pmmetafile* | *\wmetafile* | *\dibitmap* | *\wbitmap * *\wbmbitspixel *& *\wbmplanes* & *\wbmwidthbytes* (\*picw* & *\pich*) \*picwgoal*? & \*pichgoal*? *\picscalex*? & * \picscaley*? & *\picscaled*? & *\piccropt*? & *\piccropb*? & *\piccropr*? & *\piccropl*? *\picbmp *& *\picbpp* (\*bin* #BDATA) | #SDATA Basically, it looks like you can search for "{\pict", then search for the closing "}". Everything in between will be your picture, plus metadata that tells you how to decode it. Now that you've caught your rabbit... I'm out of advice; I've never used PIL (though I used to listen to them all the time.) -- www.fsrtechnologies.com -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From cclpianos at comcast.net Sat Feb 14 23:13:05 2009 From: cclpianos at comcast.net (cclpianos at comcast.net) Date: Sat, 14 Feb 2009 15:13:05 -0700 Subject: [Tutor] Copy file function works, but not with adding the date copied In-Reply-To: <49961B5F.1020700@gmail.com> References: <7755CC1D-9D90-44BC-B392-F51F41EFB292@comcast.net> <49961B5F.1020700@gmail.com> Message-ID: Hi Bob, I found out from Alan Gauld that the file i was attempting to open was a binary file. And because of that the strangeness occurred. I haven't yet learned to work with the binaries as of yet. Thanks! Pat 4. Re: Copy file function works, but not with adding the date copied (Alan Gauld) Tutor Digest Vol 60, Issue 69 On Feb 13, 2009, at 6:16 PM, bob gailer wrote: > cclpianos at comcast.net wrote: >> Hello, >> >> "but can't open with the application TextEdit" > What are you doing to open it? What does "can't open" mean"? Error > messages or what? > > Could this be a resource fork issue? AFAIK Python does not > reproduce the resource fork. > > -- > Bob Gailer > Chapel Hill NC > 919-636-4239 From bgailer at gmail.com Sat Feb 14 23:55:15 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 14 Feb 2009 17:55:15 -0500 Subject: [Tutor] Copy file function works, but not with adding the date copied In-Reply-To: References: <7755CC1D-9D90-44BC-B392-F51F41EFB292@comcast.net> <49961B5F.1020700@gmail.com> Message-ID: <49974BD3.2050802@gmail.com> Please don't attach a reply of this nature to comments I made that you have not responded to. If you want our help, please respond to our comments and questions. cclpianos at comcast.net wrote: > Hi Bob, > > I found out from Alan Gauld that the file i was attempting to open was > a binary file. And because of that the strangeness occurred. I haven't > yet learned to work with the binaries as of yet. > > Thanks! > Pat > > 4. Re: Copy file function works, but not with adding the date > copied (Alan Gauld) Tutor Digest Vol 60, Issue 69 > On Feb 13, 2009, at 6:16 PM, bob gailer wrote: > > > > >> cclpianos at comcast.net wrote: >>> Hello, >>> >>> "but can't open with the application TextEdit" >> What are you doing to open it? What does "can't open" mean"? Error >> messages or what? >> >> Could this be a resource fork issue? AFAIK Python does not reproduce >> the resource fork. >> >> -- >> Bob Gailer >> Chapel Hill NC >> 919-636-4239 > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Bob Gailer Chapel Hill NC 919-636-4239 From payo2000 at gmail.com Sat Feb 14 23:57:42 2009 From: payo2000 at gmail.com (pa yo) Date: Sat, 14 Feb 2009 23:57:42 +0100 Subject: [Tutor] Loops In-Reply-To: References: Message-ID: Thanks Alan. after a few hours scratching my head I finally fixed it by removing all the indents and remaking them in the correct position. Payo On Sat, Feb 14, 2009 at 1:52 AM, Alan Gauld wrote: > "pa yo" wrote > >> The way I have come up with to solve this problem is to put the >> following loop in: >> >>>> rawfeed = feedparser(http//twitter.com/foobar....) >>>> feedstring = rawfeed.split('=',1) #this splits the feed at the >>>> first "=" >>>> headline = feedstring[0] #this is the text infront of >>>> the "=" sign. >>>> if len(headlinestring) == len(rawfeed) #ie. if the split hasn't >>>> worked they will be exactly the same >>> body = "\x7b\x7bEmpty\x7d\x7d" >>>> #this adds an "{{Empty}}" template to the wiki >>>> else: >>>> body = feedstring[1] > > Sorry, where is the loop? > >> But I can't get it to work - I have tried various indents and break >> and continues - but I don't know enough about loops to identify what I >> have done wrong. > > I'm confused, there is no loop only a conditional statement (if/else) > The only loops supported in Python are for and while (OK you > could count list comprehensions/generator expressions too) and > neither of them are in your code. > > However you don't tell us what is happening that you don;t expect. > Are you getting an error message? If so what (all of it please)? > Or is it just the output that is different to what you expect? > if so what did you expect and what did you get? > > And finally which version of Python and which OS please? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From jay.amorin at gmail.com Sun Feb 15 11:09:09 2009 From: jay.amorin at gmail.com (Jay Jesus Amorin) Date: Sun, 15 Feb 2009 18:09:09 +0800 Subject: [Tutor] url parsing Message-ID: Hi, Can you please help my how to parse. url = http://this/is/my/url/to/parse how do i parse url to print "http://this/is/my/url/to" i want to remove the last part of my url with is "parse". I would like to remove the last string of my url. i have try split, but i think it wont work as i dont know how long my url would be in my real application. Thanks, Newbie, Jay -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Sun Feb 15 11:53:42 2009 From: norman at khine.net (Norman Khine) Date: Sun, 15 Feb 2009 11:53:42 +0100 Subject: [Tutor] advise on using re Message-ID: <4997F436.7050307@khine.net> Hello, What am I doing wrong here. >>> import smtplib, socket, re, os, operator, sys >>> domain = 'abakuc.com' >>> validMXservers = [] >>> MXlocate = re.compile('^.*preference = (\d*).*exchanger = (.*)$', re.IGNORECASE) >>> MXservers = os.popen('nslookup -querytype=MX %s' %domain, 'r') >>> for line in MXservers: ... if 'mail exchanger' in line: ... MXcheck = MXlocate.match(line) ... if MXcheck: ... MXserver = MXcheck.group(1), MXcheck.group(2) ... validMXservers.append(MXserver) ... >>> validMXservers [] >>> print MXservers >>> print line >>> print MXcheck None >>> On the shell, the command $ nslookup -querytype=MX abakuc.com Server: 193.252.19.3 Address: 193.252.19.3#53 Non-authoritative answer: abakuc.com mail exchanger = 30 ASPMX3.GOOGLEMAIL.com. abakuc.com mail exchanger = 30 ASPMX4.GOOGLEMAIL.com. abakuc.com mail exchanger = 30 ASPMX5.GOOGLEMAIL.com. abakuc.com mail exchanger = 60 mail.abakuc.com. abakuc.com mail exchanger = 10 ASPMX.L.GOOGLE.com. abakuc.com mail exchanger = 20 ALT1.ASPMX.L.GOOGLE.com. abakuc.com mail exchanger = 20 ALT2.ASPMX.L.GOOGLE.com. abakuc.com mail exchanger = 30 ASPMX2.GOOGLEMAIL.com. I would like to extract the MX servers in to a list. Cheers Norman From emadnawfal at gmail.com Sun Feb 15 13:37:50 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Sun, 15 Feb 2009 07:37:50 -0500 Subject: [Tutor] url parsing In-Reply-To: References: Message-ID: <652641e90902150437r49006dc7x759e66f387a76ec9@mail.gmail.com> On Sun, Feb 15, 2009 at 5:09 AM, Jay Jesus Amorin wrote: > Hi, > > Can you please help my how to parse. > > url = http://this/is/my/url/to/parse > > how do i parse url to print "http://this/is/my/url/to" > > i want to remove the last part of my url with is "parse". I would like to > remove the last string of my url. > > i have try split, but i think it wont work as i dont know how long my url > would be in my real application. > > Thanks, > > > Newbie, > > Jay > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > I'm not sure this is the best strategy, but it seems to work: >>> url ="http://this/is/my/url/to/parse" >>> m = url.replace("//", '/').split("/") >>> n = m[0]+"//"+"/".join(new[1:]) >>> n 'http://this/is/my/url/to' >>> -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Sun Feb 15 13:39:57 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Sun, 15 Feb 2009 07:39:57 -0500 Subject: [Tutor] url parsing In-Reply-To: <652641e90902150437r49006dc7x759e66f387a76ec9@mail.gmail.com> References: <652641e90902150437r49006dc7x759e66f387a76ec9@mail.gmail.com> Message-ID: <652641e90902150439l4d913ad9s26bb8f5959d3e3d4@mail.gmail.com> On Sun, Feb 15, 2009 at 7:37 AM, Emad Nawfal (???? ????) < emadnawfal at gmail.com> wrote: > > > On Sun, Feb 15, 2009 at 5:09 AM, Jay Jesus Amorin wrote: > >> Hi, >> >> Can you please help my how to parse. >> >> url = http://this/is/my/url/to/parse >> >> how do i parse url to print "http://this/is/my/url/to" >> >> i want to remove the last part of my url with is "parse". I would like to >> remove the last string of my url. >> >> i have try split, but i think it wont work as i dont know how long my url >> would be in my real application. >> >> Thanks, >> >> >> Newbie, >> >> Jay >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> I'm not sure this is the best strategy, but it seems to work: > > >>> url ="http://this/is/my/url/to/parse" > >>> m = url.replace("//", '/').split("/") > >>> n = m[0]+"//"+"/".join(m[1:]) > >>> n > 'http://this/is/my/url/to' > >>> Sorry there was something wrong in the first reply > > > > > > -- > ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? > ??????? > "No victim has ever been more repressed and alienated than the truth" > > Emad Soliman Nawfal > Indiana University, Bloomington > http://emnawfal.googlepages.com > -------------------------------------------------------- > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Sun Feb 15 14:22:09 2009 From: andreengels at gmail.com (Andre Engels) Date: Sun, 15 Feb 2009 14:22:09 +0100 Subject: [Tutor] url parsing In-Reply-To: <652641e90902150437r49006dc7x759e66f387a76ec9@mail.gmail.com> References: <652641e90902150437r49006dc7x759e66f387a76ec9@mail.gmail.com> Message-ID: <6faf39c90902150522x7fa1eeerb59043200faf751c@mail.gmail.com> On Sun, Feb 15, 2009 at 1:37 PM, Emad Nawfal (???? ????) wrote: > I'm not sure this is the best strategy, but it seems to work: > >>>> url ="http://this/is/my/url/to/parse" >>>> m = url.replace("//", '/').split("/") >>>> n = m[0]+"//"+"/".join(new[1:]) >>>> n > 'http://this/is/my/url/to' What is 'new' in your solution? Apart from that, the following looks simpler: >>> url = "http://this/is/my/url/to/parse" >>> parts = url.split('/') >>> sol = '/'.join(parts[:-1]) >>> sol 'http://this/is/my/url/to' -- Andr? Engels, andreengels at gmail.com From lie.1296 at gmail.com Sun Feb 15 14:29:37 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 15 Feb 2009 13:29:37 +0000 (UTC) Subject: [Tutor] url parsing References: <652641e90902150437r49006dc7x759e66f387a76ec9@mail.gmail.com> <6faf39c90902150522x7fa1eeerb59043200faf751c@mail.gmail.com> Message-ID: On Sun, 15 Feb 2009 14:22:09 +0100, Andre Engels wrote: > What is 'new' in your solution? Apart from that, the following looks > simpler: > >>>> url = "http://this/is/my/url/to/parse" parts = url.split('/') >>>> sol = '/'.join(parts[:-1]) >>>> sol > 'http://this/is/my/url/to' do you want something even more simpler? >>> url ="http://this/is/my/url/to/parse" >>> url.rsplit('/', 1)[0] 'http://this/is/my/url/to' From jay.amorin at gmail.com Sun Feb 15 14:33:26 2009 From: jay.amorin at gmail.com (Jay Jesus Amorin) Date: Sun, 15 Feb 2009 21:33:26 +0800 Subject: [Tutor] url parsing In-Reply-To: References: <652641e90902150437r49006dc7x759e66f387a76ec9@mail.gmail.com> <6faf39c90902150522x7fa1eeerb59043200faf751c@mail.gmail.com> Message-ID: Thanks this is much more simple and is what i need. On Sun, Feb 15, 2009 at 9:29 PM, Lie Ryan wrote: > On Sun, 15 Feb 2009 14:22:09 +0100, Andre Engels wrote: > > What is 'new' in your solution? Apart from that, the following looks > > simpler: > > > >>>> url = "http://this/is/my/url/to/parse" parts = url.split('/') > >>>> sol = '/'.join(parts[:-1]) > >>>> sol > > 'http://this/is/my/url/to' > > do you want something even more simpler? > > >>> url ="http://this/is/my/url/to/parse" > >>> url.rsplit('/', 1)[0] > 'http://this/is/my/url/to' > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sun Feb 15 15:16:57 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 15 Feb 2009 06:16:57 -0800 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate Message-ID: <499823D9.7070006@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Feb 15 15:27:31 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Feb 2009 09:27:31 -0500 Subject: [Tutor] advise on using re In-Reply-To: <4997F436.7050307@khine.net> References: <4997F436.7050307@khine.net> Message-ID: <1c2a2c590902150627v1bf3a7c7sfd88769aa9bd1817@mail.gmail.com> On Sun, Feb 15, 2009 at 5:53 AM, Norman Khine wrote: >>>> MXlocate = re.compile('^.*preference = (\d*).*exchanger = (.*)$', > On the shell, the command > > $ nslookup -querytype=MX abakuc.com > Server: 193.252.19.3 > Address: 193.252.19.3#53 > > Non-authoritative answer: > abakuc.com mail exchanger = 30 ASPMX3.GOOGLEMAIL.com. > abakuc.com mail exchanger = 30 ASPMX4.GOOGLEMAIL.com. > abakuc.com mail exchanger = 30 ASPMX5.GOOGLEMAIL.com. > abakuc.com mail exchanger = 60 mail.abakuc.com. > abakuc.com mail exchanger = 10 ASPMX.L.GOOGLE.com. > abakuc.com mail exchanger = 20 ALT1.ASPMX.L.GOOGLE.com. > abakuc.com mail exchanger = 20 ALT2.ASPMX.L.GOOGLE.com. > abakuc.com mail exchanger = 30 ASPMX2.GOOGLEMAIL.com. > > > I would like to extract the MX servers in to a list. None of your output lines contain the text 'preference = ' so your re does not match any of them. A standalone re tester can help with figuring out re's, for example Tools/scripts/redemo.py which comes with Python. Kent From kent37 at tds.net Sun Feb 15 15:30:59 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Feb 2009 09:30:59 -0500 Subject: [Tutor] url parsing In-Reply-To: References: Message-ID: <1c2a2c590902150630j20198896gdbbf99d63b221ce5@mail.gmail.com> On Sun, Feb 15, 2009 at 5:09 AM, Jay Jesus Amorin wrote: > Hi, > > Can you please help my how to parse. > > url = http://this/is/my/url/to/parse > > how do i parse url to print "http://this/is/my/url/to" > > i want to remove the last part of my url with is "parse". I would like to > remove the last string of my url. > > i have try split, but i think it wont work as i dont know how long my url > would be in my real application. If you just want to remove everything after the last / then rsplit() with an argument telling it how many times to split will do it: In [13]: url = 'http://this/is/my/url/to/parse' In [14]: url.rsplit('/', 1) Out[14]: ['http://this/is/my/url/to', 'parse'] In [15]: url.rsplit('/', 1)[0] Out[15]: 'http://this/is/my/url/to' Kent From alan.gauld at btinternet.com Sun Feb 15 15:48:02 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 15 Feb 2009 14:48:02 -0000 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate References: <499823D9.7070006@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Three questions about askopenfilename and enumerate. > > For askopenfilename: > 1. Do I have to close the file before exiting from it? > 2. How do I read each line of text in the file and quit when an eof > is reached? This has nothing to do with askopenfilename! Askopenfilename is the GUI equivalent of doing fname = raw_input("What f8ile d9o you want to open?") It simply returns a string which is a file name. It does NOT open the file, process the file or do anything else. It just returns the name as a string. So for your questions: > 1. Do I have to close the file before exiting from it? Yes, it is good practice, but you need to open it first. > 2. How do I read each line of text in the file and quit when an eof > is reached? for line in open(fname): # process line > This certainly doesn't do it. > > def OpenConfigFile(self): > > config_file = askopenfilename( title="Open Configuration > File", > filetypes=CEN_FILE_TYPES ) > print "cfile-------: ",config_file, type(config_file) > for it in config_file: No, this will asign each letter in the filename to 'it' You need to open(config-file) Just as you would in any other non GUI program. If you had used askopenfile then it would be different because it does return an open file object, then your code would do what you expect. But personally I prefer to open the file myself since that keeps my code more independant of the GUI. > I get a "'str' object has no attribute 'readline'" msg Because you are processing the file name not the file. > 3. Where can I find out more about enumerate, as used here: > > input_file=open('Initial.sen','r') > for (line_cnt, each_line) in enumerate(input_file): In the python documentation - try the search box on the python site or just google for python enumerate. The latter took me on the third link to: http://python.active-venture.com/whatsnew/section-enumerate.html Which is probably the simplest and shortest explanayin you will get! > Documentation for enumerate seems scarce. > BTW, is there a thorough document on the use of files in Python out there somewhere? There is a ton of it and every tutorial (including mine) will have a section on handling files. The official tutorial has a fair bit on it and the reference manual has a whole section. A good place to start might be the Library Reference (the one they suggest keeping under your pillow!) http://docs.python.org/library/stdtypes.html#file-objects HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From damontimm at gmail.com Sun Feb 15 17:00:54 2009 From: damontimm at gmail.com (Damon Timm) Date: Sun, 15 Feb 2009 11:00:54 -0500 Subject: [Tutor] General Feedback, Script Structure Message-ID: <262679b50902150800w47775935tde5d0737a72cb1ef@mail.gmail.com> Hi - Am still new to python -- was writing a script that is used by mdadm (linux software raid utility) when there was a raid "event" ... the script then sends an email (using another python script caled "gmailme") to me with the information from the event and attaches the details of the raid device that triggered the problem. It works fine -- seems to do what I need -- but, to be very frank, I don't think it is very *pretty* ! But, I am not sure what the "python-way" would be to re-structure this so it continues to do what it needs to do but is more readable and future-friendly. Could you take a look ? http://python.pastebin.com/m4e1694d5 Would be interested in any feedback (obviously, I should add some doc strings!). Thanks, Damon From sierra_mtnview at sbcglobal.net Sun Feb 15 17:36:35 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 15 Feb 2009 08:36:35 -0800 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate In-Reply-To: References: <499823D9.7070006@sbcglobal.net> Message-ID: <49984493.6020603@sbcglobal.net> An HTML attachment was scrubbed... URL: From d.conca at gmail.com Sun Feb 15 15:04:17 2009 From: d.conca at gmail.com (Daniele) Date: Sun, 15 Feb 2009 15:04:17 +0100 Subject: [Tutor] url parsing Message-ID: <537341c70902150604x511b6aferbd526bcbef40304b@mail.gmail.com> use this if you want to take a hammer to crack a nut :D import os url = 'http://this/is/my/url/to/parse' os.path.basename(url) #gives "parse" os.path.dirname(url) #gives 'http://this/is/my/url/to' -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Feb 15 18:09:52 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Feb 2009 12:09:52 -0500 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate In-Reply-To: <499823D9.7070006@sbcglobal.net> References: <499823D9.7070006@sbcglobal.net> Message-ID: <1c2a2c590902150909q424362f0q1dec19d6e090e785@mail.gmail.com> On Sun, Feb 15, 2009 at 9:16 AM, Wayne Watson wrote: > 3. Where can I find out more about enumerate, as used here: > > input_file=open('Initial.sen','r') > for (line_cnt, each_line) in enumerate(input_file): > print each_line > input_file.close() > > I used this small program for other purposes in the distant past, but what's > going here with enumerate? Documentation for enumerate seems scarce. The official docs are here: http://docs.python.org/library/functions.html#enumerate It's pretty simple, perhaps that is why not a lot is written about it. When you iterate a sequence with a for loop, you get just the elements in the sequence: In [18]: seasons = ['Spring', 'Summer', 'Fall', 'Winter'] In [19]: for season in seasons: ....: print season Spring Summer Fall Winter Sometimes it is useful to also get the index of the element, not just the element. That is when you use enumerate: In [20]: for i, season in enumerate(seasons): ....: print i, season 0 Spring 1 Summer 2 Fall 3 Winter Technically, the result of calling enumerate() is a sequence whose elements are pairs (tuples) of (index, item). Using tuple assignment you can easily assign these to two variables, as above. This is the most common use. You can also use enumerate() without unpacking the tuples, maybe this makes it a little clearer what is happening: In [22]: for item in enumerate(seasons): print item (0, 'Spring') (1, 'Summer') (2, 'Fall') (3, 'Winter') Kent From kent37 at tds.net Sun Feb 15 18:20:45 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Feb 2009 12:20:45 -0500 Subject: [Tutor] General Feedback, Script Structure In-Reply-To: <262679b50902150800w47775935tde5d0737a72cb1ef@mail.gmail.com> References: <262679b50902150800w47775935tde5d0737a72cb1ef@mail.gmail.com> Message-ID: <1c2a2c590902150920l28e2b4fbi5776c4c5f9a6bfe0@mail.gmail.com> On Sun, Feb 15, 2009 at 11:00 AM, Damon Timm wrote: > Hi - > > Am still new to python -- was writing a script that is used by mdadm > (linux software raid utility) when there was a raid "event" ... the > script then sends an email (using another python script caled > "gmailme") to me with the information from the event and attaches the > details of the raid device that triggered the problem. > > It works fine -- seems to do what I need -- but, to be very frank, I > don't think it is very *pretty* ! But, I am not sure what the > "python-way" would be to re-structure this so it continues to do what > it needs to do but is more readable and future-friendly. > > Could you take a look ? > > http://python.pastebin.com/m4e1694d5 > > Would be interested in any feedback (obviously, I should add some doc strings!). Some ideas: - put the main code in a main() function rather than splitting it across the file. - the use of tmpfile is awkward, can you make the gmailme script take its input in strings? - I would use plain positional parameters to getMessage(), rather than supplying defaults. - the status dict could be built once, containing just the format strings, e.g. status = dict( TestMessage = "This was a crazy test message! Woo hoo!", RebuildStarted = "The rebuilding of %(mddevice)s has begun!", # etc } then you can build the message as body = status.get(event, nomatch) % vars() message = header + body + footer Kent From damontimm at gmail.com Sun Feb 15 19:01:06 2009 From: damontimm at gmail.com (Damon Timm) Date: Sun, 15 Feb 2009 13:01:06 -0500 Subject: [Tutor] General Feedback, Script Structure In-Reply-To: <1c2a2c590902150920l28e2b4fbi5776c4c5f9a6bfe0@mail.gmail.com> References: <262679b50902150800w47775935tde5d0737a72cb1ef@mail.gmail.com> <1c2a2c590902150920l28e2b4fbi5776c4c5f9a6bfe0@mail.gmail.com> Message-ID: <262679b50902151001x53b4fdddta935d37c07b586ff@mail.gmail.com> Hi Kent - thanks for taking a look! Follow-up below: On Sun, Feb 15, 2009 at 12:20 PM, Kent Johnson wrote: > - put the main code in a main() function rather than splitting it > across the file. That's a good idea - I will do that. Is it proper to create a def main() or just under: if __name__ == "__main__" > - the use of tmpfile is awkward, can you make the gmailme script take > its input in strings? that gmail script needs an actual file to attach ... or rather, the location of a file to attach ... would have to change something so it could take text that it could save as a file. but that would probably be better. > - I would use plain positional parameters to getMessage(), rather than > supplying defaults. > - the status dict could be built once, containing just the format strings, e.g. > status = dict( > TestMessage = "This was a crazy test message! Woo hoo!", > RebuildStarted = "The rebuilding of %(mddevice)s has begun!", > # etc > } > > then you can build the message as > body = status.get(event, nomatch) % vars() > message = header + body + footer That last part I am not so clear on ... how does: body = status.get(event, nomatch) % vars() work ? Does it say, first look for "event" as a key and then, if it doesn't find a match with event,, use the "nomatch" key ? I was trying to do something like that but couldn't figure out how to make it work ... Thanks! > > Kent > From sierra_mtnview at sbcglobal.net Sun Feb 15 19:40:34 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 15 Feb 2009 10:40:34 -0800 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate In-Reply-To: <1c2a2c590902150909q424362f0q1dec19d6e090e785@mail.gmail.com> References: <499823D9.7070006@sbcglobal.net> <1c2a2c590902150909q424362f0q1dec19d6e090e785@mail.gmail.com> Message-ID: <499861A2.2020304@sbcglobal.net> An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Feb 15 19:54:49 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 15 Feb 2009 18:54:49 -0000 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate References: <499823D9.7070006@sbcglobal.net> <49984493.6020603@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Thanks to your use of the word pillow it's not likely I will be > able to find the link to the Library Reference more easily, > strange as that may seem. You are right it seems very strange!? > My browser's bookmark capabilities have put me in the > corner of disorganization, Mozilla Seamonkey. I used Mozilla briefly before moving to Firefox, but I don't recall it having anything odd about its bookmarking capabilities! In fact I still use the directory structure I created for my bookmarks on Mozilla in Firefox to this day. (And on IE via importing), > I easily have 1000 bookmarks and probably 40 or more > on python. Me too, but I just have a programming folder with a Python one inside that. I then name the bookmark clearly - like Library Reference say... and it's been no problem. > chance at finding my python bkmrks, I've put python in the > title to make sure I have a fighting chance with their search to > find them I just file them in the python folder when I bookmark them! > This may change. I'm about to install Firefox. It might help because the new version of Firefox has tagged bookmarks, but personally I find my folder structure faster and more useful and saves me adding tags. Have you tried GoogleChrome yet? It might suit your style better. It looks at addresses you type and searches both your history and bookmarks for previous sites visited that might match. It sweems to work pretty well. I tend to primarily use Firefox and Chrome for all my browsing now except for a couple of sites that I know are IE only (including my bank sadly!) Alan G. From alan.gauld at btinternet.com Sun Feb 15 20:00:39 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 15 Feb 2009 19:00:39 -0000 Subject: [Tutor] General Feedback, Script Structure References: <262679b50902150800w47775935tde5d0737a72cb1ef@mail.gmail.com> Message-ID: "Damon Timm" wrote > It works fine -- seems to do what I need -- but, to be very frank, I > don't think it is very *pretty* ! But, I am not sure what the > http://python.pastebin.com/m4e1694d5 > > Would be interested in any feedback (obviously, I should add some > doc strings!). It doesn't look too bad to me, I'd probably do the dictionary assignments as a single statement rather than all the separate assignment lines and I'd also move it out of the function as a module level variable. Other than that it's not too bad IMHO Alan G From kent37 at tds.net Sun Feb 15 20:25:59 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Feb 2009 14:25:59 -0500 Subject: [Tutor] General Feedback, Script Structure In-Reply-To: <262679b50902151001x53b4fdddta935d37c07b586ff@mail.gmail.com> References: <262679b50902150800w47775935tde5d0737a72cb1ef@mail.gmail.com> <1c2a2c590902150920l28e2b4fbi5776c4c5f9a6bfe0@mail.gmail.com> <262679b50902151001x53b4fdddta935d37c07b586ff@mail.gmail.com> Message-ID: <1c2a2c590902151125k44daf60bqcb00f3c32481fb7d@mail.gmail.com> On Sun, Feb 15, 2009 at 1:01 PM, Damon Timm wrote: > On Sun, Feb 15, 2009 at 12:20 PM, Kent Johnson wrote: >> - put the main code in a main() function rather than splitting it >> across the file. > > That's a good idea - I will do that. Is it proper to create a def > main() or just under: if __name__ == "__main__" Either one works; I usually don't put more than a few lines of code in the if block so I would make a main() function. >> then you can build the message as >> body = status.get(event, nomatch) % vars() >> message = header + body + footer > > > That last part I am not so clear on ... how does: body = > status.get(event, nomatch) % vars() work ? Does it say, first look > for "event" as a key and then, if it doesn't find a match with event,, > use the "nomatch" key ? Exactly. dict.get() does a key lookup with a default for missing keys, then the result is used as a string format. See http://docs.python.org/library/stdtypes.html#dict.get BTW I strongly recommend becoming familiar with the Built-in Functions and Built-in Types sections of the standard library docs: http://docs.python.org/library/ Kent From sierra_mtnview at sbcglobal.net Sun Feb 15 20:47:30 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 15 Feb 2009 11:47:30 -0800 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate In-Reply-To: References: <499823D9.7070006@sbcglobal.net> <49984493.6020603@sbcglobal.net> Message-ID: <49987152.7000508@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Feb 15 20:56:16 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Feb 2009 14:56:16 -0500 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate In-Reply-To: References: <499823D9.7070006@sbcglobal.net> <49984493.6020603@sbcglobal.net> Message-ID: <1c2a2c590902151156g6242ce43xe9237b356438a1a4@mail.gmail.com> On Sun, Feb 15, 2009 at 1:54 PM, Alan Gauld wrote: > Have you tried GoogleChrome yet? It might suit your style better. > It looks at addresses you type and searches both your history and > bookmarks for previous sites visited that might match. Firefox 3 also does that. Very handy! Kent From kent37 at tds.net Sun Feb 15 21:06:24 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 15 Feb 2009 15:06:24 -0500 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate In-Reply-To: <49987152.7000508@sbcglobal.net> References: <499823D9.7070006@sbcglobal.net> <49984493.6020603@sbcglobal.net> <49987152.7000508@sbcglobal.net> Message-ID: <1c2a2c590902151206q3e4ef144l303c827bdfe15ead@mail.gmail.com> On Sun, Feb 15, 2009 at 2:47 PM, Wayne Watson wrote: > I'm still looking for an explanation of "for (line_cnt, each_line) in > enumerate(input_file)". Why the tuple? Apparently, line_count gets a line > number, and each_line gets the string of text. Do you know about sequence unpacking? In an assignment statement, when the right side is a sequence, the left side can be a list of variables of the same length as the sequence. Then each sequence element is assigned to one variable. For example, In [24]: item = (0, 'Spring') In [25]: i, season = item In [26]: i Out[26]: 0 In [28]: season Out[28]: 'Spring' This can be used in a for loop, too, if the items are sequences. That is what is commonly done with enumerate(). Kent From sierra_mtnview at sbcglobal.net Sun Feb 15 21:30:10 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 15 Feb 2009 12:30:10 -0800 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate In-Reply-To: <1c2a2c590902151206q3e4ef144l303c827bdfe15ead@mail.gmail.com> References: <499823D9.7070006@sbcglobal.net> <49984493.6020603@sbcglobal.net> <49987152.7000508@sbcglobal.net> <1c2a2c590902151206q3e4ef144l303c827bdfe15ead@mail.gmail.com> Message-ID: <49987B52.6070707@sbcglobal.net> An HTML attachment was scrubbed... URL: From damontimm at gmail.com Sun Feb 15 22:03:11 2009 From: damontimm at gmail.com (Damon Timm) Date: Sun, 15 Feb 2009 16:03:11 -0500 Subject: [Tutor] General Feedback, Script Structure In-Reply-To: <1c2a2c590902151125k44daf60bqcb00f3c32481fb7d@mail.gmail.com> References: <262679b50902150800w47775935tde5d0737a72cb1ef@mail.gmail.com> <1c2a2c590902150920l28e2b4fbi5776c4c5f9a6bfe0@mail.gmail.com> <262679b50902151001x53b4fdddta935d37c07b586ff@mail.gmail.com> <1c2a2c590902151125k44daf60bqcb00f3c32481fb7d@mail.gmail.com> Message-ID: <262679b50902151303x354bebeel9b9beedf3b5fd8b8@mail.gmail.com> Kent and Alan - thanks! I moved things around a bit and I think it "looks" better: http://python.pastebin.com/m64e4565d On Sun, Feb 15, 2009 at 2:25 PM, Kent Johnson wrote: > Exactly. dict.get() does a key lookup with a default for missing keys, > then the result is used as a string format. See > http://docs.python.org/library/stdtypes.html#dict.get > > BTW I strongly recommend becoming familiar with the Built-in Functions > and Built-in Types sections of the standard library docs: > http://docs.python.org/library/ Great - thanks. That's exactly what I needed! My issue is that I don't use Python enough (or computers, for that matter) to remember everything I've learned previously ... after I saw that, I remember I had read it before ... I just do it for fun, so one of the challenges is finding the right word/answer to what I need to do ... hopefully, if I stick with Python long enough it will become more second nature ... This list is a great resource because I learn a lot from other people's issues ... and is easy to search, too, for my own! Thanks again, everyone. > > Kent > From alan.gauld at btinternet.com Sun Feb 15 23:41:31 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 15 Feb 2009 22:41:31 -0000 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate References: <499823D9.7070006@sbcglobal.net> <49984493.6020603@sbcglobal.net> <49987152.7000508@sbcglobal.net> Message-ID: "Wayne Watson" wrote > I'm still looking for an explanation of " > for (line_cnt, each_line) in enumerate(input_file)". > Why the tuple? > Apparently, line_count gets a line number, and each_line gets the > string OK, Back up from the specific problem to the more general case. enumerate does not return the line number it returns the current index of the collection: for index, item in [9,8,7,6]: print index, item 0 9 1 8 2 7 3 6 If you are familiar with list comprehensions (or generator expressions) you could do the same yourself with: >>> lst = [9,8,7,6] >>> for i,n in ((i,lst[i]) for i in range(len(lst))): ... print i, n ... 0 9 1 8 2 7 3 6 >>> But enumerate is easier on the eye. And if its the i,n bit that confuses that is just tuple unpacking. We can do this: >>> a,b = (1,2) >>> print a, b 1 2 Now, coming back to your specific case. The index of a file "collection" is the line number (starting at zero of course) and the item is the line of text. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From john at fouhy.net Sun Feb 15 23:57:27 2009 From: john at fouhy.net (John Fouhy) Date: Mon, 16 Feb 2009 11:57:27 +1300 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate In-Reply-To: References: <499823D9.7070006@sbcglobal.net> <49984493.6020603@sbcglobal.net> <49987152.7000508@sbcglobal.net> Message-ID: <5e58f2e40902151457p1309fb1ya72bd73f7d30ccb@mail.gmail.com> 2009/2/16 Alan Gauld : > for index, item in [9,8,7,6]: > print index, item > > > 0 9 > 1 8 > 2 7 > 3 6 You mean: for index, item in enumerate([9,8,7,6]): print index, item :-) -- John. From alan.gauld at btinternet.com Mon Feb 16 01:19:24 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Feb 2009 00:19:24 -0000 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate References: <499823D9.7070006@sbcglobal.net> <49984493.6020603@sbcglobal.net> <49987152.7000508@sbcglobal.net> <5e58f2e40902151457p1309fb1ya72bd73f7d30ccb@mail.gmail.com> Message-ID: "John Fouhy" wrote >> for index, item in [9,8,7,6]: >> print index, item >> >> 0 9 >> 1 8 >> 2 7 >> 3 6 > > You mean: > > for index, item in enumerate([9,8,7,6]): > print index, item Oops, yes, thanks for catching that. It was fairly fundamental to the discussion! Alan G From iwasroot at gmail.com Mon Feb 16 01:40:22 2009 From: iwasroot at gmail.com (Moos Heintzen) Date: Sun, 15 Feb 2009 16:40:22 -0800 Subject: [Tutor] ConfigParser re-read fails In-Reply-To: <499469B7.4070604@gmail.com> References: <499469B7.4070604@gmail.com> Message-ID: <7b13ba330902151640u17750d19ye97949a4bf725d4b@mail.gmail.com> It looks way too simplified. I have no idea where the problem is. Would you mind showing the script? gist.github.com is good for posting code. From sierra_mtnview at sbcglobal.net Mon Feb 16 01:52:19 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 15 Feb 2009 16:52:19 -0800 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate In-Reply-To: References: <499823D9.7070006@sbcglobal.net> <49984493.6020603@sbcglobal.net> <49987152.7000508@sbcglobal.net> <5e58f2e40902151457p1309fb1ya72bd73f7d30ccb@mail.gmail.com> Message-ID: <4998B8C3.7050005@sbcglobal.net> An HTML attachment was scrubbed... URL: From bgailer at gmail.com Mon Feb 16 02:33:13 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 15 Feb 2009 20:33:13 -0500 Subject: [Tutor] *nix tail -f multiple log files with Thread In-Reply-To: <499585DB.1090409@abbottdavid.com> References: <499585DB.1090409@abbottdavid.com> Message-ID: <4998C259.8010604@gmail.com> David wrote: > Hi everyone, > > I copied a program from C to track multiple log files. I would like to > be able to print a label when a log file is updated. Did the C program accomplish that? If so, it might help to see that code. If not why mention it? Your example output falls short of your stated goal as I understand it! My guess is that you want what you showed: [snip] 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET /theme/custom_corners/favicon.ico HTTP/1.1" 200 894 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET /lib/speller/spellChecker.js HTTP/1.1" 200 15980 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET / HTTP/1.1" 200 13718 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET /theme/custom_corners/styles.php HTTP/1.1" 200 30709 followed by, for example: [Fri Feb 13 10:08:01 2009] [error] [client 127.0.0.1] File does not exist: /var/www/localhost/htdocs/moodle/favicon.ico When tail discovers more records in the error log. Is this accurate? If so I think solutions might lie in either redirecting tail output to files that would be post-processed later or monitoring the logs using python rather than the tail command. How shall we proceed? > Here is the program; > > #!/usr/bin/python > from threading import Thread > import subprocess > from Queue import Queue > > num_threads = 3 > queue = Queue() > logfiles = ["/var/log/messages", > "/var/log/apache2/access_log", > "/var/log/apache2/error_log"] > > def logtailer(i, q,): > while True: > lfile = q.get() > sudo = "sudo" > tail = "tail" > arg = "-f" > ret = subprocess.call([sudo, tail, arg, lfile]) > q.task_done() > > for i in range(num_threads): > worker = Thread(target=logtailer, args=(i, queue)) > worker.setDaemon(True) > worker.start() > > for lfile in logfiles: > queue.put(lfile) > > queue.join() > > And here is a sample of the output; > > [Fri Feb 13 08:58:48 2009] [error] [client 127.0.0.1] File does not > exist: /var/www/localhost/htdocs/moodle/favicon.ico > [Fri Feb 13 08:58:51 2009] [error] [client 127.0.0.1] File does not > exist: /var/www/localhost/htdocs/moodle/favicon.ico > Feb 13 09:02:26 opteron sudo: david : TTY=pts/4 ; PWD=/home/david ; > USER=root ; COMMAND=/bin/tail -f /var/log/apache2/error_log > Feb 13 09:02:26 opteron sudo: pam_unix(sudo:session): session opened > for user root by david(uid=0) > Feb 13 09:02:26 opteron sudo: pam_unix(sudo:session): session closed > for user root > Feb 13 09:10:01 opteron cron[10633]: (root) CMD (test -x > /usr/sbin/run-crons && /usr/sbin/run-crons ) > Feb 13 09:18:33 opteron su[10678]: Successful su for root by david > Feb 13 09:18:33 opteron su[10678]: + pts/6 david:root > Feb 13 09:18:33 opteron su[10678]: pam_unix(su:session): session > opened for user root by david(uid=1000) > 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET > /theme/custom_corners/favicon.ico HTTP/1.1" 200 894 > 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET > /lib/speller/spellChecker.js HTTP/1.1" 200 15980 > 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET / HTTP/1.1" 200 13718 > 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET > /theme/custom_corners/styles.php HTTP/1.1" 200 30709 > > I would like to be able to add a label like; > > > [Fri Feb 13 08:58:48 2009] [error] [client 127.0.0.1] File does not > exist: /var/www/localhost/htdocs/moodle/favicon.ico > [Fri Feb 13 08:58:51 2009] [error] [client 127.0.0.1] File does not > exist: /var/www/localhost/htdocs/moodle/favicon.ico > > Feb 13 09:02:26 opteron sudo: david : TTY=pts/4 ; PWD=/home/david ; > USER=root ; COMMAND=/bin/tail -f /var/log/apache2/error_log > Feb 13 09:02:26 opteron sudo: pam_unix(sudo:session): session opened > for user root by david(uid=0) > Feb 13 09:02:26 opteron sudo: pam_unix(sudo:session): session closed > for user root > Feb 13 09:10:01 opteron cron[10633]: (root) CMD (test -x > /usr/sbin/run-crons && /usr/sbin/run-crons ) > Feb 13 09:18:33 opteron su[10678]: Successful su for root by david > Feb 13 09:18:33 opteron su[10678]: + pts/6 david:root > Feb 13 09:18:33 opteron su[10678]: pam_unix(su:session): session > opened for user root by david(uid=1000) > > 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET > /theme/custom_corners/favicon.ico HTTP/1.1" 200 894 > 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET > /lib/speller/spellChecker.js HTTP/1.1" 200 15980 > 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET / HTTP/1.1" 200 13718 > 127.0.0.1 - - [13/Feb/2009:09:18:47 -0500] "GET > /theme/custom_corners/styles.php HTTP/1.1" 200 30709 > > I can create the label like this; > def label() > print "<%s\n>" % lfile > > But I have no idea how to get it to work when a thread is updated. > thanks > -david > > > -- Bob Gailer Chapel Hill NC 919-636-4239 From david at abbottdavid.com Mon Feb 16 03:36:40 2009 From: david at abbottdavid.com (David) Date: Sun, 15 Feb 2009 21:36:40 -0500 Subject: [Tutor] *nix tail -f multiple log files with Thread In-Reply-To: <4998CDCE.9000607@abbottdavid.com> References: <499585DB.1090409@abbottdavid.com> <4998C259.8010604@gmail.com> <4998CDCE.9000607@abbottdavid.com> Message-ID: <4998D138.6030901@abbottdavid.com> David wrote: > bob gailer wrote: > >> Did the C program accomplish that? If so, it might help to see that >> code. If not why mention it? It is here if you want to check it out; http://dwabbott.com/downloads/logtailer.c.txt >> Your example output falls short of your stated goal as I understand >> it! My guess is that you want what you showed: >> Is this accurate? Yes, thanks for the reply, It was good practice but come to find out that tail will do what I want on its own. The only thing I would like to do is add color to the labels but that is for another list :) I am new to python and never programed before and would like to thank everyone on the list. It has made learning python fun. -david Resent because I forgot to reply all :( -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From bill at celestial.net Mon Feb 16 04:09:53 2009 From: bill at celestial.net (Bill Campbell) Date: Sun, 15 Feb 2009 19:09:53 -0800 Subject: [Tutor] *nix tail -f multiple log files with Thread In-Reply-To: <4998C259.8010604@gmail.com> References: <499585DB.1090409@abbottdavid.com> <4998C259.8010604@gmail.com> Message-ID: <20090216030953.GA8613@ayn.mi.celestial.com> On Sun, Feb 15, 2009, bob gailer wrote: > David wrote: >> Hi everyone, >> >> I copied a program from C to track multiple log files. I would like to >> be able to print a label when a log file is updated. > > Did the C program accomplish that? If so, it might help to see that > code. If not why mention it? > The ``swatch'' program, written in perl, does this by using the gnu-tail program via a pipe using. gtail --follow=name --lines=1 file1 file2 ... Use the source Luke. Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 The day-to-day travails of the IBM programmer are so amusing to most of us who are fortunate enough never to have been one -- like watching Charlie Chaplin trying to cook a shoe. From alan.gauld at btinternet.com Mon Feb 16 09:44:35 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Feb 2009 08:44:35 -0000 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate References: <499823D9.7070006@sbcglobal.net> <49984493.6020603@sbcglobal.net> <49987152.7000508@sbcglobal.net> <5e58f2e40902151457p1309fb1ya72bd73f7d30ccb@mail.gmail.com> <4998B8C3.7050005@sbcglobal.net> Message-ID: "Wayne Watson" wrote > If you ever get a chance to try the Moz experiment above, > I'd be interested in your reaction. I no longer have Mozilla loaded - far too resource hungry. I use IE, Firefox and Chrome plus occasionally Safari on my Mac. All of them move bookmarks using simple drag n drop. Alan G From norman at khine.net Mon Feb 16 14:12:55 2009 From: norman at khine.net (Norman Khine) Date: Mon, 16 Feb 2009 14:12:55 +0100 Subject: [Tutor] urllib unquote Message-ID: <49996657.9050203@khine.net> Hello, Can someone point me in the right direction. I would like to return the string for the following: Type "help", "copyright", "credits" or "license" for more information. >>> import base64, urllib >>> data = 'hL/FGNS40fjoTnp2zIqq73reK60%3D%0A' >>> data = urllib.unquote(data) >>> print base64.decodestring(data) ???????Nzv???z?+? >>> What am I missing? Cheers Norman From lie.1296 at gmail.com Mon Feb 16 12:35:55 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Mon, 16 Feb 2009 22:35:55 +1100 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate In-Reply-To: References: Message-ID: <1234784155.32310.12.camel@lieryan-laptop> On Sun, 2009-02-15 at 21:29 +0100, tutor-request at python.org wrote: > Do you know about sequence unpacking? In an assignment statement, when > the right side is a sequence, the left side can be a list of variables > of the same length as the sequence. Then each sequence element is > assigned to one variable. For example The left side can only be a tuple of "names". The tuple unpacking is a little bit of violation of python's object model, since while python's tuple usually contain objects, in tuple unpacking the tuple contains a list of names to be assigned. From sander.sweers at gmail.com Mon Feb 16 14:48:11 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Mon, 16 Feb 2009 14:48:11 +0100 Subject: [Tutor] urllib unquote In-Reply-To: <49996657.9050203@khine.net> References: <49996657.9050203@khine.net> Message-ID: On Mon, Feb 16, 2009 at 14:12, Norman Khine wrote: > Type "help", "copyright", "credits" or "license" for more information. >>>> import base64, urllib >>>> data = 'hL/FGNS40fjoTnp2zIqq73reK60%3D%0A' >>>> data = urllib.unquote(data) >>>> print base64.decodestring(data) > ???????Nzv???z?+? >>>> > > What am I missing? Not an expert here but I think you can skip the last step... >>> urllib.unquote('hL/FGNS40fjoTnp2zIqq73reK60%3D%0A') 'hL/FGNS40fjoTnp2zIqq73reK60=\n' Greets Sander From bgailer at gmail.com Mon Feb 16 15:38:40 2009 From: bgailer at gmail.com (bob gailer) Date: Mon, 16 Feb 2009 09:38:40 -0500 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate In-Reply-To: <1234784155.32310.12.camel@lieryan-laptop> References: <1234784155.32310.12.camel@lieryan-laptop> Message-ID: <49997A70.1010306@gmail.com> Lie Ryan wrote: > On Sun, 2009-02-15 at 21:29 +0100, tutor-request at python.org wrote: > > >> Do you know about sequence unpacking? In an assignment statement, when >> the right side is a sequence, the left side can be a list of variables >> of the same length as the sequence. Then each sequence element is >> assigned to one variable. For example >> > > > The left side can only be a tuple of "names". The tuple unpacking is a > little bit of violation of python's object model, since while python's > tuple usually contain objects, in tuple unpacking the tuple contains a > list of names to be assigned. > > It's time to take a look at the Language Reference. 6.3 Assignment statements. assignment_stmt ::= (target_list "=")+ expression_list a target list is not a tuple, even though it can look like one. So I don't see it as any violation. -- Bob Gailer Chapel Hill NC 919-636-4239 From lie.1296 at gmail.com Mon Feb 16 16:02:16 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 17 Feb 2009 02:02:16 +1100 Subject: [Tutor] Reading a Text File with tkFileDialog, askopenfilename+enumerate In-Reply-To: <49997A70.1010306@gmail.com> References: <1234784155.32310.12.camel@lieryan-laptop> <49997A70.1010306@gmail.com> Message-ID: <1234796536.32310.37.camel@lieryan-laptop> On Mon, 2009-02-16 at 09:38 -0500, bob gailer wrote: > Lie Ryan wrote: > > On Sun, 2009-02-15 at 21:29 +0100, tutor-request at python.org wrote: > > > > > >> Do you know about sequence unpacking? In an assignment statement, when > >> the right side is a sequence, the left side can be a list of variables > >> of the same length as the sequence. Then each sequence element is > >> assigned to one variable. For example > >> > > > > > > The left side can only be a tuple of "names". The tuple unpacking is a > > little bit of violation of python's object model, since while python's > > tuple usually contain objects, in tuple unpacking the tuple contains a > > list of names to be assigned. > > > > > It's time to take a look at the Language Reference. > 6.3 Assignment statements. > assignment_stmt ::= (target_list "=")+ expression_list > a target list is not a tuple, even though it can look like one. > So I don't see it as any violation. Every time I heard about tuple unpacking, everyone always describes the target_list as tuple. I've never looked at the Language Reference on this particular case before, so I admit I didn't know that the Language Reference does make a distinction between the two. So, I'll retract calling it as violation, tuple and target_list is a completely different beast. From david at abbottdavid.com Mon Feb 16 17:13:38 2009 From: david at abbottdavid.com (David) Date: Mon, 16 Feb 2009 11:13:38 -0500 Subject: [Tutor] *nix tail -f multiple log files with Thread In-Reply-To: <20090216030953.GA8613@ayn.mi.celestial.com> References: <499585DB.1090409@abbottdavid.com> <4998C259.8010604@gmail.com> <20090216030953.GA8613@ayn.mi.celestial.com> Message-ID: <499990B2.8010805@abbottdavid.com> Bill Campbell wrote: > > The ``swatch'' program, written in perl, does this by using the > gnu-tail program via a pipe using. > > gtail --follow=name --lines=1 file1 file2 ... > > Use the source Luke. > > Bill > Thanks Bill, That looks like the right tool for the job at hand. Looking at setting up the configuration file, a stumbling block in my learning to program is my lack of a good understanding of regular expressions. I have started studying grep, sed and awk. It is a lot more fun to just write little python programs and watch in amazement when they work as expected. I have been avoiding this phase of learning. -david -- powered by Gentoo/GNU Linux http://linuxcrazy.com From sierra_mtnview at sbcglobal.net Mon Feb 16 17:19:13 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 16 Feb 2009 08:19:13 -0800 Subject: [Tutor] Control Variables and a Dictionary with a GUI Interface Message-ID: <49999201.8050600@sbcglobal.net> An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: moz-screenshot-180.jpg Type: image/jpeg Size: 18008 bytes Desc: not available URL: From bill at celestial.net Mon Feb 16 18:13:25 2009 From: bill at celestial.net (Bill Campbell) Date: Mon, 16 Feb 2009 09:13:25 -0800 Subject: [Tutor] *nix tail -f multiple log files with Thread In-Reply-To: <499990B2.8010805@abbottdavid.com> References: <499585DB.1090409@abbottdavid.com> <4998C259.8010604@gmail.com> <20090216030953.GA8613@ayn.mi.celestial.com> <499990B2.8010805@abbottdavid.com> Message-ID: <20090216171325.GA13670@ayn.mi.celestial.com> On Mon, Feb 16, 2009, David wrote: >Bill Campbell wrote: >> >> The ``swatch'' program, written in perl, does this by using the >> gnu-tail program via a pipe using. >> >> gtail --follow=name --lines=1 file1 file2 ... >> >> Use the source Luke. >> ... >That looks like the right tool for the job at hand. Looking at setting >up the configuration file, a stumbling block in my learning to program >is my lack of a good understanding of regular expressions. I have >started studying grep, sed and awk. It is a lot more fun to just write >little python programs and watch in amazement when they work as >expected. I have been avoiding this phase of learning. Looking at other people's scripts can be very enlightening. When I started learning Xenix in 1982, there were about 2 books on the subjects, Jean Thompson's blue one, and I forget the other. I learned a lot by reading system administration scripts, once I figured out that these were working programs. One of the best books I've ever seen for general *nix text processing and use of tools is ``Unix Text Processing'' by Dougherty and O'Reilly. It has been out of print for years, but can probably be found through bookfinder.com It has lots on regular expressions, using ``vi'', etc. There is information on regular expressions in any book on python, perl, and other scripting languages. O'Reilly has a book ``Mastering Regular Expressions'' which is probably pretty good, but I have never read it. Bill -- INTERNET: bill at celestial.com Bill Campbell; Celestial Software LLC URL: http://www.celestial.com/ PO Box 820; 6641 E. Mercer Way Voice: (206) 236-1676 Mercer Island, WA 98040-0820 Fax: (206) 232-9186 About all I can say for the United States Senate is that it opens with prayer and closes with an investigation. -- Will Rogers From alan.gauld at btinternet.com Mon Feb 16 19:14:41 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Feb 2009 18:14:41 -0000 Subject: [Tutor] *nix tail -f multiple log files with Thread References: <499585DB.1090409@abbottdavid.com> <4998C259.8010604@gmail.com><20090216030953.GA8613@ayn.mi.celestial.com><499990B2.8010805@abbottdavid.com> <20090216171325.GA13670@ayn.mi.celestial.com> Message-ID: "Bill Campbell" wrote > There is information on regular expressions in any book on python, > perl, > and other scripting languages. O'Reilly has a book ``Mastering > Regular > Expressions'' which is probably pretty good, but I have never read > it. It is pretty much the definitive reference on regex. However I read somewhere recently that O'Reilly are bringing out a new tutorial style book on regex specifically for Python. No more info but it might be worth visiting the ora.com website to see whats on offer. OTOH I don't find I use regex all that often. Usually I can find another (better?() way. regex are powerful tools and invaluable when you need them but if you don't *need* them then they can be deceptively difficult to get right! Its always worth trying to live without in the first instance. If that doesn't work out then at least you know why you need the regex! Alan G. From alan.gauld at btinternet.com Mon Feb 16 19:24:44 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Feb 2009 18:24:44 -0000 Subject: [Tutor] Control Variables and a Dictionary with a GUI Interface References: <49999201.8050600@sbcglobal.net> Message-ID: "Wayne Watson" wrote > The question here is how is sdict being used here in terms > of its need within the GUI? Probably if I had written the > program from scratch, I would have made all these > variables global to Sentinel_GUI. Most programmers try to avoid global variables as a general principle. In this case the programmer has opted for a dict and is then able to pass the values around with a single variable, as in: > def DisplaySettings(self): > print "OSett self = ", self, "type =", type(self) <<---debug > code > sdict = {} <<-------- local sdict > sdict[ "ok" ] = False <<---- ok > ... more sdict ... > dialog = DisplaySettingsDialog( self.master, sdict ) > class DisplaySettingsDialog(tkSimpleDialog.Dialog): > > def __init__(self, parent, sdict): > self.sdict = sdict <<------- > tkSimpleDialog.Dialog.__init__(self, parent) You could use globals if both classes were in the samemodule, or import the module wherever they values were needed. But by keeping the values in a dict and keeping the dict as a class variable the programmer potentially has more control over access. Thats the only reason I can see for it - after all of 2 minutes reading the code :-)... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From jojo.mwebaze at gmail.com Mon Feb 16 19:33:59 2009 From: jojo.mwebaze at gmail.com (Jojo Mwebaze) Date: Mon, 16 Feb 2009 21:33:59 +0300 Subject: [Tutor] =?windows-1252?q?Newton=96Raphson=27s_method?= Message-ID: <3124be320902161033t34c57192t58839feb40ff47f8@mail.gmail.com> Hello There Any body who has implemented Newton?Raphson's method for nonlinear systems of equations in python. Consider the case where we want to solve simultaneously f(x,y) = 0 g(x,y) = 0 Please assist with the code. Regards Jojo. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Mon Feb 16 18:47:45 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Mon, 16 Feb 2009 11:47:45 -0600 Subject: [Tutor] =?utf-8?q?Newton=E2=80=93Raphson=27s_method?= In-Reply-To: <3124be320902161033t34c57192t58839feb40ff47f8@mail.gmail.com> References: <3124be320902161033t34c57192t58839feb40ff47f8@mail.gmail.com> Message-ID: <200902161147.46071.cfuller084@thinkingplanet.net> You should look into Numpy or ScientificPython. http://numpy.scipy.org http://dirac.cnrs-orleans.fr/plone/software/scientificpython Also, the main Python Wiki has a page devoted to numeric/scientific topics: http://wiki.python.org/moin/NumericAndScientific Cheers On Monday 16 February 2009 12:33, Jojo Mwebaze wrote: > Hello There > > Any body who has implemented Newton?Raphson's method for nonlinear systems > of equations in python. Consider the case where we want to solve > simultaneously > > f(x,y) = 0 > > g(x,y) = 0 > > Please assist with the code. > > Regards > > Jojo. From david at abbottdavid.com Mon Feb 16 20:04:14 2009 From: david at abbottdavid.com (David) Date: Mon, 16 Feb 2009 14:04:14 -0500 Subject: [Tutor] *nix tail -f multiple log files with Thread In-Reply-To: <20090216171325.GA13670@ayn.mi.celestial.com> References: <499585DB.1090409@abbottdavid.com> <4998C259.8010604@gmail.com> <20090216030953.GA8613@ayn.mi.celestial.com> <499990B2.8010805@abbottdavid.com> <20090216171325.GA13670@ayn.mi.celestial.com> Message-ID: <4999B8AE.3030608@abbottdavid.com> Bill Campbell wrote: > On Mon, Feb 16, 2009, David wrote: > >> Bill Campbell wrote: >> >>> The ``swatch'' program, written in perl, does this by using the >>> gnu-tail program via a pipe using. >>> >>> gtail --follow=name --lines=1 file1 file2 ... >>> >>> Use the source Luke. >>> >>> > ... > >> That looks like the right tool for the job at hand. Looking at setting >> up the configuration file, a stumbling block in my learning to program >> is my lack of a good understanding of regular expressions. I have >> started studying grep, sed and awk. It is a lot more fun to just write >> little python programs and watch in amazement when they work as >> expected. I have been avoiding this phase of learning. >> > > Looking at other people's scripts can be very enlightening. When I started > learning Xenix in 1982, there were about 2 books on the subjects, Jean > Thompson's blue one, and I forget the other. I learned a lot by reading > system administration scripts, once I figured out that these were working > programs. > > One of the best books I've ever seen for general *nix text processing and > use of tools is ``Unix Text Processing'' by Dougherty and O'Reilly. It has > been out of print for years, but can probably be found through > bookfinder.com It has lots on regular expressions, using ``vi'', etc. > > There is information on regular expressions in any book on python, perl, > and other scripting languages. O'Reilly has a book ``Mastering Regular > Expressions'' which is probably pretty good, but I have never read it. > > Bill > OK, I found ``Unix Text Processing`` for $5 and I did start ``Mastering Regular Expressions so I have the material, now I just need a photographic memory to speed the process up :) -david -- powered by Gentoo/GNU Linux http://linuxcrazy.com From sierra_mtnview at sbcglobal.net Mon Feb 16 20:58:52 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 16 Feb 2009 11:58:52 -0800 Subject: [Tutor] exec "self.abc=22" ? Message-ID: <4999C57C.3090804@sbcglobal.net> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Mon Feb 16 21:01:24 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 16 Feb 2009 12:01:24 -0800 Subject: [Tutor] exec "self.abc=22" ? In-Reply-To: <4999C57C.3090804@sbcglobal.net> References: <4999C57C.3090804@sbcglobal.net> Message-ID: <40af687b0902161201u65f16f35v2e33828e6521265@mail.gmail.com> On Mon, Feb 16, 2009 at 11:58 AM, Wayne Watson wrote: > Python doesn't like the code in the Subject (unqualified exec not allowed > in function). but easily likes self.abc="22". However, I'd like to assemble > the assignment as a string, as shown in Subject, and execute it. Is there a > way to do this? > -- > > varName = "abc" varValue = 22 setattr(self, varName, varValue) -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 16 21:11:28 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 16 Feb 2009 20:11:28 -0000 Subject: [Tutor] exec "self.abc=22" ? References: <4999C57C.3090804@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Python doesn't like the code in the Subject (unqualified exec > not allowed in function). but easily likes self.abc="22". We'd need to see the code and traceback to guess why... > However, I'd like to assemble the assignment as a string, > as shown in Subject, and execute it. Is there a way to do this? exec is the usual way but it's also usually a bad idea. Any reason why you want to do that rather than any of the safer alternatives? (dict, setattr etc) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From denis.spir at free.fr Mon Feb 16 21:20:11 2009 From: denis.spir at free.fr (spir) Date: Mon, 16 Feb 2009 21:20:11 +0100 Subject: [Tutor] exec "self.abc=22" ? In-Reply-To: <40af687b0902161201u65f16f35v2e33828e6521265@mail.gmail.com> References: <4999C57C.3090804@sbcglobal.net> <40af687b0902161201u65f16f35v2e33828e6521265@mail.gmail.com> Message-ID: <20090216212011.4d6a80b8@o> Le Mon, 16 Feb 2009 12:01:24 -0800, Marc Tompkins a ?crit : > On Mon, Feb 16, 2009 at 11:58 AM, Wayne Watson > wrote: > > > Python doesn't like the code in the Subject (unqualified exec not allowed > > in function). but easily likes self.abc="22". However, I'd like to assemble > > the assignment as a string, as shown in Subject, and execute it. Is there a > > way to do this? > > -- > > > > varName = "abc" > varValue = 22 > setattr(self, varName, varValue) >>> exec("name='22'") >>> name '22' >>> exec("name=\"22\"") >>> name '22' ------ la vida e estranya From sierra_mtnview at sbcglobal.net Mon Feb 16 22:01:33 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 16 Feb 2009 13:01:33 -0800 Subject: [Tutor] exec "self.abc=22" ? In-Reply-To: References: <4999C57C.3090804@sbcglobal.net> Message-ID: <4999D42D.5040107@sbcglobal.net> An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: moz-screenshot-181.jpg Type: image/jpeg Size: 11758 bytes Desc: not available URL: From sierra_mtnview at sbcglobal.net Mon Feb 16 22:04:40 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 16 Feb 2009 13:04:40 -0800 Subject: [Tutor] Control Variables and a Dictionary with a GUI Interface In-Reply-To: References: <49999201.8050600@sbcglobal.net> Message-ID: <4999D4E8.80501@sbcglobal.net> An HTML attachment was scrubbed... URL: From inthefridge at gmail.com Mon Feb 16 23:05:26 2009 From: inthefridge at gmail.com (Spencer Parker) Date: Mon, 16 Feb 2009 15:05:26 -0700 Subject: [Tutor] passig parameter with CGI... Message-ID: I am looking for a little instruction on how one would process a set of parameters being sent to it through CGI. I have a script that sends info to another script that lives on another server. The second script would then process the information that is passed to it through a parameters list in a URL. It would then trigger the script to do some things via XMLRPC. I have the portion that connects to the XMLRPC server, but not the 1st part. I can send it a list of command line parameters, but the spec has changed. We want to do it with just curl and send it parameters with a URL string. Not really looking for direct code...just some ideas on how this is done for the most part. I looked around, but nothing really fit what I wanted...mostly form processing...thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Tue Feb 17 05:24:03 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 16 Feb 2009 20:24:03 -0800 Subject: [Tutor] Changing the Attribute of a Variable Message-ID: <499A3BE3.4080209@sbcglobal.net> An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: moz-screenshot-182.jpg Type: image/jpeg Size: 22234 bytes Desc: not available URL: From wescpy at gmail.com Tue Feb 17 06:26:47 2009 From: wescpy at gmail.com (wesley chun) Date: Mon, 16 Feb 2009 21:26:47 -0800 Subject: [Tutor] Changing the Attribute of a Variable In-Reply-To: <499A3BE3.4080209@sbcglobal.net> References: <499A3BE3.4080209@sbcglobal.net> Message-ID: <78b3a9580902162126x2488e80fw30771e52b346a0ae@mail.gmail.com> On Mon, Feb 16, 2009 at 8:24 PM, Wayne Watson wrote: > I suspect I'm in need of setattr for this in a GUI program I'm modifying. > > Initally, a variable. self.stop_time is created as type datetime.time, with > the default value 06:00:00, a time stamp, during entry into the mainloop. > self.stop_time = datetime.time(10,10,10). The user reads his configuration > file with the time stamp value of 08:00:00. self.time_stop becomes type > string. He then goes to a dialog to change time stop, and it tries to access > self.time_stop, and find is needs to have the attribute strftime, as in: > set_loc_dict[ "stop_time" ] = self.stop_time.strftime("%H:%M:%S") > > When reading the configuration file, how do I make sure that self.time_stop > is really has the strftime attribute? close. what you need is hasattr(), which returns True/False. you can also use getattr() with a default value as well. the problem you're facing is that the object is now a str and not a datetime.time as you mentioned. you have 2 options: a. keep everything as a string and manipulate the value that way, or b. convert the string to a datetime.time object and keep it like that good luck! -wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From dorseye at gmail.com Tue Feb 17 06:34:23 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Mon, 16 Feb 2009 22:34:23 -0700 Subject: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu Message-ID: Greetings Tutor: I've managed to install Python 2.6 on my Ubuntu VM from source, however, it looks as though I missed something important along the way. My 2.6 interpreter does not have readline support (example: I cant hit up arrow to repeat the last command) Is there a way to add this functionality now? Or alternative, if I just rebuild it, does anyone know the flag or verbage to get readline support in? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Tue Feb 17 06:53:26 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Mon, 16 Feb 2009 21:53:26 -0800 Subject: [Tutor] Changing the Attribute of a Variable In-Reply-To: <78b3a9580902162126x2488e80fw30771e52b346a0ae@mail.gmail.com> References: <499A3BE3.4080209@sbcglobal.net> <78b3a9580902162126x2488e80fw30771e52b346a0ae@mail.gmail.com> Message-ID: <499A50D6.605@sbcglobal.net> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Tue Feb 17 08:44:18 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Mon, 16 Feb 2009 23:44:18 -0800 Subject: [Tutor] Changing the Attribute of a Variable In-Reply-To: <499A3BE3.4080209@sbcglobal.net> References: <499A3BE3.4080209@sbcglobal.net> Message-ID: <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> On Mon, Feb 16, 2009 at 8:24 PM, Wayne Watson wrote: > I suspect I'm in need of setattr for this in a GUI program I'm modifying. > > Initally, a variable. self.stop_time is created as type datetime.time, with > the default value 06:00:00, a time stamp, during entry into the mainloop. > self.stop_time = datetime.time(10,10,10). The user reads his configuration > file with the time stamp value of 08:00:00. self.time_stop becomes type > string. He then goes to a dialog to change time stop, and it tries to access > self.time_stop, and find is needs to have the attribute strftime, as in: > set_loc_dict[ "stop_time" ] = self.stop_time.strftime("%H:%M:%S") > When reading the configuration file, how do I make sure that self.time_stop > is really has the strftime attribute? > You already received an answer to your immediate question, but I wanted to clarify: "strftime" is NOT an attribute, it's a method. Calling the strftime method of a time object returns a string, formatted according to the pattern you specify - so what you're storing as "stop_time" is not a time, but a string. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From norman at khine.net Tue Feb 17 08:54:53 2009 From: norman at khine.net (Norman Khine) Date: Tue, 17 Feb 2009 08:54:53 +0100 Subject: [Tutor] urllib unquote In-Reply-To: References: <49996657.9050203@khine.net> Message-ID: <499A6D4D.6050809@khine.net> Thank you, but is it possible to get the original string from this? Sander Sweers wrote: > On Mon, Feb 16, 2009 at 14:12, Norman Khine wrote: >> Type "help", "copyright", "credits" or "license" for more information. >>>>> import base64, urllib >>>>> data = 'hL/FGNS40fjoTnp2zIqq73reK60%3D%0A' >>>>> data = urllib.unquote(data) >>>>> print base64.decodestring(data) >> ???????Nzv???z?+? >> What am I missing? > > Not an expert here but I think you can skip the last step... > >>>> urllib.unquote('hL/FGNS40fjoTnp2zIqq73reK60%3D%0A') > 'hL/FGNS40fjoTnp2zIqq73reK60=\n' > > > Greets > Sander > From wescpy at gmail.com Tue Feb 17 09:16:10 2009 From: wescpy at gmail.com (wesley chun) Date: Tue, 17 Feb 2009 00:16:10 -0800 Subject: [Tutor] Changing the Attribute of a Variable In-Reply-To: <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> References: <499A3BE3.4080209@sbcglobal.net> <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> Message-ID: <78b3a9580902170016i462f462ek38f99e41216aa27@mail.gmail.com> >> Initally, a variable. self.stop_time is created as type datetime.time, >> with the default value 06:00:00, a time stamp, during entry into the >> mainloop. self.stop_time = datetime.time(10,10,10). The user reads his >> configuration file with the time stamp value of 08:00:00. self.time_stop >> becomes type string. He then goes to a dialog to change time stop, and it >> tries to access self.time_stop, and find is needs to have the attribute >> strftime, as in: >> set_loc_dict[ "stop_time" ] = self.stop_time.strftime("%H:%M:%S") >> When reading the configuration file, how do I make sure that >> self.time_stop is really has the strftime attribute? > > You already received an answer to your immediate question, but I wanted to > clarify: "strftime" is NOT an attribute, it's a method. Calling the > strftime method of a time object returns a string, formatted according to > the pattern you specify - so what you're storing as "stop_time" is not a > time, but a string. this is a reply to both: wayne: the initial setting of self.stop_time as a datetime.time object seems to be ok, but i'm uncomfortable with the fact that after "[the] user reads his [config] file," it becomes a str. i think that the code that processes the config file should be setting self.stop_time as another datetime.time object, so that way, when you want to set the value for set_loc_dict, it would not have any problems calling its strftime() method. marc: i will slightly disagree with you with regards to strftime *not* being an attribute. it *is* an attribute, just not a *data attribute*... i call it a "function attribute," but that's just terminology. any time you have an object x with an attribute y, the fact that you can issue x.y means that y is indeed an attribute of x. if it's a data attribute, you access it with x.y. if it's a function attribute, i.e., a method, you also access it with x.y, esp. if you want to pass the function object around, and finally, if you actually want to *execute* it *and* it's a method, then you add the parens, x.y(). hope this helps, -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Python Web Development with Django", Addison Wesley, (c) 2009 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From denis.spir at free.fr Tue Feb 17 09:22:18 2009 From: denis.spir at free.fr (spir) Date: Tue, 17 Feb 2009 09:22:18 +0100 Subject: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu In-Reply-To: References: Message-ID: <20090217092218.6688d6b2@o> Le Mon, 16 Feb 2009 22:34:23 -0700, Eric Dorsey a ?crit : > Greetings Tutor: > I've managed to install Python 2.6 on my Ubuntu VM from source, however, it > looks as though I missed something important along the way. My 2.6 > interpreter does not have readline support (example: I cant hit up arrow to > repeat the last command) Is there a way to add this functionality now? > > Or alternative, if I just rebuild it, does anyone know the flag or verbage > to get readline support in? As far as I know, it's built-in by default. But I have 2.5.2, not 2.6. Have you tried to import it, just to check? spir at o:~/prog/io$ python Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import readline >>> readline denis ------ la vida e estranya From andreengels at gmail.com Tue Feb 17 09:48:00 2009 From: andreengels at gmail.com (Andre Engels) Date: Tue, 17 Feb 2009 09:48:00 +0100 Subject: [Tutor] exec "self.abc=22" ? In-Reply-To: <6faf39c90902170047g2a0d56dbh547d12719e7c72ea@mail.gmail.com> References: <4999C57C.3090804@sbcglobal.net> <4999D42D.5040107@sbcglobal.net> <6faf39c90902170047g2a0d56dbh547d12719e7c72ea@mail.gmail.com> Message-ID: <6faf39c90902170048v4ee1fa3fx9ce1ae5f32200446@mail.gmail.com> On Mon, Feb 16, 2009 at 10:01 PM, Wayne Watson wrote: > My limited repertoire. Actually, there wasn't much of a traceback. It came > up in a small OK dialog. I copied what I could. I see my image I used above > did make it to the list, so here's the skinny. > > > I see Marc covered it with setattr. How does one do it with a dictionary? > What else lurks out there that might be useful along these lines? It all depends on what you will use it for. As said, exec should work, but it usually is not the way to go - if there's outside input involved, it's _extremely_ unsafe, if everything comes from inside your program it's an ugly sledgehammer to crack a nut. So please take one step back - WHY do you want to do this? Where does this string "self.abc = 22" come from? What are the values it can have? Can you create a toy example that shows the problem you want to solve? -- Andr? Engels, andreengels at gmail.com From marc.tompkins at gmail.com Tue Feb 17 10:00:39 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 17 Feb 2009 01:00:39 -0800 Subject: [Tutor] Changing the Attribute of a Variable In-Reply-To: <78b3a9580902170016i462f462ek38f99e41216aa27@mail.gmail.com> References: <499A3BE3.4080209@sbcglobal.net> <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> <78b3a9580902170016i462f462ek38f99e41216aa27@mail.gmail.com> Message-ID: <40af687b0902170100o1ef7266x242e1121ab4c91f9@mail.gmail.com> On Tue, Feb 17, 2009 at 12:16 AM, wesley chun wrote: > marc: i will slightly disagree with you with regards to strftime *not* > being an attribute. it *is* an attribute, just not a *data > attribute*... i call it a "function attribute," but that's just > terminology. any time you have an object x with an attribute y, the > fact that you can issue x.y means that y is indeed an attribute of x. > if it's a data attribute, you access it with x.y. if it's a function > attribute, i.e., a method, you also access it with x.y, esp. if you > want to pass the function object around, and finally, if you actually > want to *execute* it *and* it's a method, then you add the parens, > x.y(). > Which follows from the fact that in Python, functions are objects too. However, in the context of the OP's question, I think that if he referenced strftime with no parentheses the result would NOT be what he expected or intended; the distinction between methods and what you call "data attributes" can be an important one. Point taken, though. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander.sweers at gmail.com Tue Feb 17 10:15:16 2009 From: sander.sweers at gmail.com (Sander Sweers) Date: Tue, 17 Feb 2009 10:15:16 +0100 Subject: [Tutor] urllib unquote In-Reply-To: <499A6D4D.6050809@khine.net> References: <49996657.9050203@khine.net> <499A6D4D.6050809@khine.net> Message-ID: On Tue, Feb 17, 2009 at 08:54, Norman Khine wrote: > Thank you, but is it possible to get the original string from this? You mean something like this? >>> urllib.quote('hL/FGNS40fjoTnp2zIqq73reK60=\n') 'hL/FGNS40fjoTnp2zIqq73reK60%3D%0A' Greets Sander From orsenthil at gmail.com Tue Feb 17 10:22:52 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Tue, 17 Feb 2009 14:52:52 +0530 Subject: [Tutor] urllib unquote In-Reply-To: <499A6D4D.6050809@khine.net> References: <49996657.9050203@khine.net> <499A6D4D.6050809@khine.net> Message-ID: <7c42eba10902170122n3c8697bcxd621dd2bf80c64b4@mail.gmail.com> On Tue, Feb 17, 2009 at 1:24 PM, Norman Khine wrote: > Thank you, but is it possible to get the original string from this? What do you mean by the original string Norman? Look at these definitions: Quoted String: In the different parts of the URL, there are set of characters, for e.g. space character in path, that must be quoted, which means converted to a different form so that url is understood by the program. So ' ' is quoted to %20. Unquoted String: When %20 comes in the URL, humans need it unquoted so that we can understand it. What do you mean by original string? Why are you doing base64 encoding? And what are you trying to achieve? Perhaps these can help us to help you better? -- -- Senthil From =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2Kc=?= Tue Feb 17 10:38:19 2009 From: =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2Kc=?= (=?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2Kc=?=) Date: Tue, 17 Feb 2009 12:38:19 +0300 Subject: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu In-Reply-To: References: Message-ID: <20090217123819.59574372@ubuntu> On Mon, 16 Feb 2009 22:34:23 -0700 Eric Dorsey wrote: > Greetings Tutor: > I've managed to install Python 2.6 on my Ubuntu VM from source, > however, it looks as though I missed something important along the > way. My 2.6 interpreter does not have readline support (example: I > cant hit up arrow to repeat the last command) Is there a way to add > this functionality now? > > Or alternative, if I just rebuild it, does anyone know the flag or > verbage to get readline support in? I think you need to recompile it again, this time make sure that "libreadline5-dev" package is installed. Hope that help. Ziyad. From gdi at teamlog.com Tue Feb 17 10:38:35 2009 From: gdi at teamlog.com (Geneviève DIAGORN) Date: Tue, 17 Feb 2009 10:38:35 +0100 Subject: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu In-Reply-To: <20090217123819.59574372@ubuntu> from Ziyad Albatly on Tue, 17 Feb 2009 12:38:19 +0300 References: <20090217123819.59574372@ubuntu> Message-ID: <200902170938.n1H9cZSH003227@tlgmlp01.teamlog.com> Bonjour, Je suis absente jusqu'au 22/02/09 inclus. Cordialement. Genevi?ve From kent37 at tds.net Tue Feb 17 12:35:35 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Feb 2009 06:35:35 -0500 Subject: [Tutor] exec "self.abc=22" ? In-Reply-To: <4999D42D.5040107@sbcglobal.net> References: <4999C57C.3090804@sbcglobal.net> <4999D42D.5040107@sbcglobal.net> Message-ID: <1c2a2c590902170335p5d5d62ffk37789fa81b4f851c@mail.gmail.com> On Mon, Feb 16, 2009 at 4:01 PM, Wayne Watson wrote: > I see Marc covered it with setattr. How does one do it with a dictionary? Instead of trying to create variables with variable names, use the names as keys in a dict. So instead of exec "self.abc=22" you might use self.values = {} self.values['abc'] = 22 Kent From kent37 at tds.net Tue Feb 17 12:40:01 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Feb 2009 06:40:01 -0500 Subject: [Tutor] urllib unquote In-Reply-To: <49996657.9050203@khine.net> References: <49996657.9050203@khine.net> Message-ID: <1c2a2c590902170340y2f649ab9t9b7b138582cf347e@mail.gmail.com> On Mon, Feb 16, 2009 at 8:12 AM, Norman Khine wrote: > Hello, > Can someone point me in the right direction. I would like to return the > string for the following: > > Type "help", "copyright", "credits" or "license" for more information. >>>> import base64, urllib >>>> data = 'hL/FGNS40fjoTnp2zIqq73reK60%3D%0A' >>>> data = urllib.unquote(data) >>>> print base64.decodestring(data) > ???????Nzv???z?+? >>>> > > What am I missing? How is data created? Since it doesn't decode as you expect, either it isn't base64 or there is some other processing needed. Do you have an example of a data string where you know the desired decoded value? Kent From sierra_mtnview at sbcglobal.net Tue Feb 17 13:44:18 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 17 Feb 2009 04:44:18 -0800 Subject: [Tutor] Changing the Attribute of a Variable In-Reply-To: <40af687b0902170100o1ef7266x242e1121ab4c91f9@mail.gmail.com> References: <499A3BE3.4080209@sbcglobal.net> <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> <78b3a9580902170016i462f462ek38f99e41216aa27@mail.gmail.com> <40af687b0902170100o1ef7266x242e1121ab4c91f9@mail.gmail.com> Message-ID: <499AB122.40607@sbcglobal.net> Note that the diagnostic output in the image shows attributeError: 'str' object has no attribute 'strftime'. Let me see if I clarify what's really going on by including some of the code. In Sentinel_GUI, the mainloop, the code shows (hard coded default values): ... self.slowdown = 1 self.stop_time = datetime.time(6,0,0) <<--- self.start_time = datetime.time(18,0,0) The code for OpenConfigFile is below, which reads the text file containing the configuration variables and values. ===========Sample of config file========== Sentinel NC Configuration File Sentinel User 3 - 1/3/2009 (Meteor Software) config_file_name=Initial.sen mask_file_name=*none* gray_scale=True post_event_stack=False post_event_format=Tiff 2 show_real_time=False hourly_rate=12 slowdown=1 start_time=22:00:00 stop_time=06:00:00 lat=40.0 ... ===========end of sample============== Note below that I'm trying to pick off "user" variables in the file that are dates. self.config_var_list contains DAT (user) type for stop_time. Note the use of setattr at the bottom. I may have gone wrong here, when the code handles the DAT differently than the other user variables. See the code after this, where the error is raised when the dialog begins to be activated. There are a few more comments below this. ==============OpenConfigFile========== def OpenConfigFile(self): def time_tuple(tstring): t = tstring.split(':') print 'here is t', t tnum = () for j in range(0,len(t)): tnum = tnum+(string.atoi(t[j]),) return tnum print "OCFile entered" print config_file_name = askopenfilename( title="Open Configuration File", filetypes=CEN_FILE_TYPES ) config_file=open(config_file_name,'r') first_line = config_file.readline() # skip first line for (j,newline) in enumerate(config_file): aline = newline[:-1] aline.rstrip() (config_var, config_value) = aline.split('=') config_type = self.config_var_list[j][1][1] self_var = "self." + config_var print "ocf: ",config_var,config_value,"self_var=",self_var if config_var == DAT: # Date type, expecting hh:mm:ss t_ntup = time_tuple(config_value) stime = datetime.time(t_ntup[0],t_ntup[1],t_ntup[2]) print "type stime: ",type(stime) # Date vars should be type datetime.time config_value = str(stime) else: self_var_assignment = self_var +'='+ config_value print "self_var_assignment", self_var_assignment abc = self # self_var_assignment setattr(self, config_var, config_value) config_file.close() =============End of OpenConfigFile=========== When the program brings up the dialog, this piece of code gets me into trouble, as marked. ===========OperationalSettings=============== def OperationalSettings(self): print "OSett self = ", self, "type =", type(self) print set_loc_dict = {} set_loc_dict[ "ok" ] = False set_loc_dict[ "color" ] = 2 if self.gray_scale: set_loc_dict[ "color"] = 1 print "gray scale now--wtw: ", self.gray_scale set_loc_dict[ "hourly_rate" ] = self.hourly_rate print "wtw self.stop_time", self.stop_time, type(self.stop_time) # set in GUI as datetime.time(6,0,0) # HEY wtw self.stop_time.strftime("%H:%M:%S") set_loc_dict[ "stop_time" ] = self.stop_time.strftime("%H:%M:%S") <<----problem, see image in first post set_loc_dict[ "start_time" ] = self.start_time.strftime("%H:%M:%S") set_loc_dict[ "slowdown" ] = self.slowdown ... ===============End of OperationalSettings====== I've defined several user types, DAT (date-time format, time really--hh:mm:ss), BOO (boolean), STR (string), FLT (float), ... In the OpenConfigFile, I've deliberately singled out DAT, and just relegated all others to STR. I figured I'd have trouble here, so put DAT on stage first. Note though that gray_scale is boolean, and "seems" to have been set without a fuss. From norman at khine.net Tue Feb 17 14:00:15 2009 From: norman at khine.net (Norman Khine) Date: Tue, 17 Feb 2009 14:00:15 +0100 Subject: [Tutor] urllib unquote In-Reply-To: <1c2a2c590902170340y2f649ab9t9b7b138582cf347e@mail.gmail.com> References: <49996657.9050203@khine.net> <1c2a2c590902170340y2f649ab9t9b7b138582cf347e@mail.gmail.com> Message-ID: <499AB4DF.7050507@khine.net> it is my error, the data is a sha string and it is not possible to get the string back, unless you use rainbowtables or something of the sort. Kent Johnson wrote: > On Mon, Feb 16, 2009 at 8:12 AM, Norman Khine wrote: >> Hello, >> Can someone point me in the right direction. I would like to return the >> string for the following: >> >> Type "help", "copyright", "credits" or "license" for more information. >>>>> import base64, urllib >>>>> data = 'hL/FGNS40fjoTnp2zIqq73reK60%3D%0A' >>>>> data = urllib.unquote(data) >>>>> print base64.decodestring(data) >> ???????Nzv???z?+? >> What am I missing? > > How is data created? Since it doesn't decode as you expect, either it > isn't base64 or there is some other processing needed. Do you have an > example of a data string where you know the desired decoded value? > > Kent > From python at bdurham.com Tue Feb 17 17:57:25 2009 From: python at bdurham.com (python at bdurham.com) Date: Tue, 17 Feb 2009 11:57:25 -0500 Subject: [Tutor] Possible to change values of scalar function parameters? Message-ID: <1234889845.20133.1300885369@webmail.messagingengine.com> Is there a way to change values of scalar function parameters? I know you can change the values of parameters if the parameter is a mutable type like a list, but is there a way to update the value of scalar parameters of type integer or string? Simple example: Is there a way to have the following function update its changeme parameter in a 'call by reference' manner? >>> def test1( changeme ): changeme = 'Changed!' >>> ref_value = 'blah' >>> test1( ref_value ) >>> ref_value 'blah' Thanks! Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Feb 17 18:34:50 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Feb 2009 12:34:50 -0500 Subject: [Tutor] Possible to change values of scalar function parameters? In-Reply-To: <1234889845.20133.1300885369@webmail.messagingengine.com> References: <1234889845.20133.1300885369@webmail.messagingengine.com> Message-ID: <1c2a2c590902170934w284c41a5jb217d392b425c95f@mail.gmail.com> On Tue, Feb 17, 2009 at 11:57 AM, wrote: > Is there a way to change values of scalar function parameters? I know you > can change the values of parameters if the parameter is a mutable type like > a list, but is there a way to update the value of scalar parameters of type > integer or string? > > Simple example: Is there a way to have the following function update its > changeme parameter in a 'call by reference' manner? > >>>> def test1( changeme ): > changeme = 'Changed!' No, not a simple way at least. Possibly you can do it with hackery involving stack frames but I wouldn't recommend that. Either pass the values in some kind of container (list, dict, class instance) or return the new value and assign it in the caller. Kent From python at bdurham.com Tue Feb 17 18:41:29 2009 From: python at bdurham.com (python at bdurham.com) Date: Tue, 17 Feb 2009 12:41:29 -0500 Subject: [Tutor] Possible to change values of scalar function parameters? In-Reply-To: <1c2a2c590902170934w284c41a5jb217d392b425c95f@mail.gmail.com> References: <1234889845.20133.1300885369@webmail.messagingengine.com> <1c2a2c590902170934w284c41a5jb217d392b425c95f@mail.gmail.com> Message-ID: <1234892489.30283.1300895511@webmail.messagingengine.com> Kent, > No, not a simple way at least. Possibly you can do it with hackery involving stack frames but I wouldn't recommend that. Either pass the values in some kind of container (list, dict, class instance) or return the new value and assign it in the caller. That's what I thought. Thank you! Malcolm From marc.tompkins at gmail.com Tue Feb 17 19:11:00 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 17 Feb 2009 10:11:00 -0800 Subject: [Tutor] Changing the Attribute of a Variable In-Reply-To: <499AB122.40607@sbcglobal.net> References: <499A3BE3.4080209@sbcglobal.net> <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> <78b3a9580902170016i462f462ek38f99e41216aa27@mail.gmail.com> <40af687b0902170100o1ef7266x242e1121ab4c91f9@mail.gmail.com> <499AB122.40607@sbcglobal.net> Message-ID: <40af687b0902171011k42a779eayc51ebf0f0396eab1@mail.gmail.com> On Tue, Feb 17, 2009 at 4:44 AM, Wayne Watson wrote: > Note that the diagnostic output in the image shows attributeError: 'str' > object has no attribute 'strftime'. > > Let me see if I clarify what's really going on by including some of the > code. > Everything in Python - both variables and code - is an object. Objects have attributes - data, basically - and methods - functions - associated with them. (As Wesley pointed out, since pieces of code are also objects, methods are attributes too.) However, not all objects have the same attributes or methods associated with them! datetime.time objects have a "strftime" method, which, when called, returns a string representation of the time. String objects do not have any such method or data attribute, hence the error. You're showing us both too much code and too little - print "wtw self.stop_time", self.stop_time, type(self.stop_time) # set in GUI as datetime.time(6,0,0) # HEY wtw self.stop_time.strftime("%H:%M:%S") set_loc_dict[ "stop_time" ] = self.stop_time.strftime("%H:%M:%S") <<----problem, see image in first post I'd like to see the output of that "print" - I'm pretty sure that "type" will return "str", not "time". On another front, have you considered ConfigObj ( http://www.voidspace.org.uk/python/modules.shtml#configobj)? When I first came to Python, I wrote myself a config-file handler (serializing to XML, actually) and it worked OK - but everything was so much work! I discovered ConfigObj and life is good. Here's a quick example from one of my early programs I refactored to use ConfigObj (NOT as a shining example of code, but just to show the power): from configobj import ConfigObj > from validate import Validator ... > cfgFileName = os.getcwd() + os.sep + 'fsr_1500.ini' > tmpStr = """ > npiXMLFile = string(default="npiMap.XML") > UCFformLength = integer(min=50, max=80, default=66) > FIformLength = integer(min=50, max=80, default=64) > OutformLength = integer(min=50, max=80, default=64) > IncludeLegacy = boolean(default=False) > TopLeft = int_list(min=2, max=2) > BottomRight = int_list(min=2, max=2) > FIHist = string_list(default=None) > UCFHist = string_list(default=None) > OutHist = string_list(default=None) > LastRunUCF = boolean(default=True) > LastRunPrinter = boolean(default=False) > detailLeft = integer(min=0, max=80, default=0) > detailTo = integer(min=0, max=80, default=9) > detailPOS = integer(min=0, max=80, default=19) > detailCode = integer(min=0, max=80, default=25) > detailMods = integer(min=0, max=80, default=32) > detailDiags = integer(min=0, max=80, default=44) > detailCharge = integer(min=0, max=80, default=49) > detailUnits = integer(min=0, max=80, default=58) > detailEPSDT = integer(min=0, max=80, default=62) > detailEMG = integer(min=0, max=80, default=22) > detailID = integer(min=0, max=80, default=67) > bodyLeftBlock = integer(min=0, max=80, default=0) > bodyMidBlock = integer(min=0, max=80, default=24) > bodyRightBlock = integer(min=0, max=80, default=49) > bodyLabelEdge = integer(min=0, max=80, default=40) > ConfirmSuccess = boolean(default=True) > """ > cfgSpec = StringIO.StringIO(tmpStr) > cfgFile = ConfigObj(cfgFileName, > configspec=cfgSpec, raise_errors=True, > write_empty_values=True, > create_empty=True, indent_type=' ', list_values=True) > vtor = Validator() ... > cfgFile['TopLeft'] = data.GetMarginTopLeft() # writing a couple of > values > cfgFile['BottomRight'] = data.GetMarginBottomRight() > ... > test = cfgFile.validate(Global.vtor, copy=True) > cfgFile.write() > Looking at that, I see a few things I want to clean up. That's the danger (and advantage) of exposing your own code to public scrutiny... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Tue Feb 17 19:16:35 2009 From: wescpy at gmail.com (wesley chun) Date: Tue, 17 Feb 2009 10:16:35 -0800 Subject: [Tutor] Changing the Attribute of a Variable In-Reply-To: <499AB122.40607@sbcglobal.net> References: <499A3BE3.4080209@sbcglobal.net> <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> <78b3a9580902170016i462f462ek38f99e41216aa27@mail.gmail.com> <40af687b0902170100o1ef7266x242e1121ab4c91f9@mail.gmail.com> <499AB122.40607@sbcglobal.net> Message-ID: <78b3a9580902171016u48633bd2jd4df7a0e9eb4c5d2@mail.gmail.com> > # Date vars should be type datetime.time > config_value = str(stime) this is pretty much the offending code right here... in fact, the comment contradicts the assignment. it says that date vars should be of type datetime.time, yet it assigns a *string* to config_value, which then gets set later using setattr(). if you just remove that assignment, things should work better..., at least from what i can see. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From alan.gauld at btinternet.com Tue Feb 17 19:46:36 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 17 Feb 2009 18:46:36 -0000 Subject: [Tutor] Possible to change values of scalar function parameters? References: <1234889845.20133.1300885369@webmail.messagingengine.com><1c2a2c590902170934w284c41a5jb217d392b425c95f@mail.gmail.com> <1234892489.30283.1300895511@webmail.messagingengine.com> Message-ID: wrote >> No, not a simple way at least. Possibly you can do it with hackery > involving stack frames but I wouldn't recommend that. Either pass > the > values in some kind of container (list, dict, class instance) or > return the new value and assign it in the caller. > > That's what I thought. Thank you! But don't forget that in python you can return multiple values from a function... def f(): return 42, 66, 101 a,b,c = f() HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From python at bdurham.com Tue Feb 17 19:51:42 2009 From: python at bdurham.com (python at bdurham.com) Date: Tue, 17 Feb 2009 13:51:42 -0500 Subject: [Tutor] Possible to change values of scalar function parameters? In-Reply-To: References: <1234889845.20133.1300885369@webmail.messagingengine.com><1c2a2c590902170934w284c41a5jb217d392b425c95f@mail.gmail.com> <1234892489.30283.1300895511@webmail.messagingengine.com> Message-ID: <1234896702.14530.1300908937@webmail.messagingengine.com> Alan, > But don't forget that in python you can return multiple values from a function. Yes. Thank you! Malcolm From sierra_mtnview at sbcglobal.net Tue Feb 17 20:01:58 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 17 Feb 2009 11:01:58 -0800 Subject: [Tutor] Changing the Attribute of a Variable In-Reply-To: <40af687b0902171011k42a779eayc51ebf0f0396eab1@mail.gmail.com> References: <499A3BE3.4080209@sbcglobal.net> <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> <78b3a9580902170016i462f462ek38f99e41216aa27@mail.gmail.com> <40af687b0902170100o1ef7266x242e1121ab4c91f9@mail.gmail.com> <499AB122.40607@sbcglobal.net> <40af687b0902171011k42a779eayc51ebf0f0396eab1@mail.gmail.com> Message-ID: <499B09A6.7000605@sbcglobal.net> An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 20177 bytes Desc: not available URL: From kent37 at tds.net Tue Feb 17 20:11:19 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 17 Feb 2009 14:11:19 -0500 Subject: [Tutor] Changing the Attribute of a Variable In-Reply-To: <499AB122.40607@sbcglobal.net> References: <499A3BE3.4080209@sbcglobal.net> <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> <78b3a9580902170016i462f462ek38f99e41216aa27@mail.gmail.com> <40af687b0902170100o1ef7266x242e1121ab4c91f9@mail.gmail.com> <499AB122.40607@sbcglobal.net> Message-ID: <1c2a2c590902171111m66425f05peca4cb2a8cba5a6c@mail.gmail.com> On Tue, Feb 17, 2009 at 7:44 AM, Wayne Watson wrote: > ==============OpenConfigFile========== > def OpenConfigFile(self): > def time_tuple(tstring): > t = tstring.split(':') > print 'here is t', t > tnum = () > for j in range(0,len(t)): > tnum = tnum+(string.atoi(t[j]),) return tnum > > print "OCFile entered" > print > config_file_name = askopenfilename( title="Open Configuration File", > filetypes=CEN_FILE_TYPES ) > config_file=open(config_file_name,'r') > first_line = config_file.readline() # skip first line > for (j,newline) in enumerate(config_file): > aline = newline[:-1] > aline.rstrip() > (config_var, config_value) = aline.split('=') > config_type = self.config_var_list[j][1][1] > self_var = "self." + config_var > print "ocf: ",config_var,config_value,"self_var=",self_var > if config_var == DAT: # Date type, expecting hh:mm:ss What is DAT? Where is it defined? Why should the config variable name (config_var) be equal to DAT? Is this code block being executed at all? Kent > t_ntup = time_tuple(config_value) > stime = datetime.time(t_ntup[0],t_ntup[1],t_ntup[2]) > print "type stime: ",type(stime) > # Date vars should be type datetime.time > config_value = str(stime) > else: > self_var_assignment = self_var +'='+ config_value > print "self_var_assignment", self_var_assignment > abc = self > # self_var_assignment > setattr(self, config_var, config_value) > config_file.close() From marc.tompkins at gmail.com Tue Feb 17 20:17:31 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Tue, 17 Feb 2009 11:17:31 -0800 Subject: [Tutor] Changing the Attribute of a Variable In-Reply-To: <499B09A6.7000605@sbcglobal.net> References: <499A3BE3.4080209@sbcglobal.net> <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> <78b3a9580902170016i462f462ek38f99e41216aa27@mail.gmail.com> <40af687b0902170100o1ef7266x242e1121ab4c91f9@mail.gmail.com> <499AB122.40607@sbcglobal.net> <40af687b0902171011k42a779eayc51ebf0f0396eab1@mail.gmail.com> <499B09A6.7000605@sbcglobal.net> Message-ID: <40af687b0902171117h1dab8247mdbedcdfd2a56bfa0@mail.gmail.com> On Tue, Feb 17, 2009 at 11:01 AM, Wayne Watson wrote: > Here's the print from the code line below. > > Second line from the top. > There it is - stop_time is a str at this point in the program, so has no strftime attribute or method. Step back through your code and see why... I find Control-F very helpful in situations like this! > > Regarding, ConfigObj, I was aware of it when I decided to go this route. > That's the one that uses has an init file like Windows? Rather than have to > go through a learning process on it (the Win init module/object), and some > uncertainty about it's acceptability in my situation, I thought I'd be more > exploratory and proceed as I have. So far it has paid off in many learning > dividends. ConfigObj, if not the Win stuff, may be attractive. Anyway, I'd > like to proceed for the moment with this effort. > There's nothing sacred about the ".ini" extension - any text file that contains "variable = value" pairs is game. ConfigObj is not Windows-centric. The advantage - which is what I was trying to show when I posted that gosh-awful hunk of code - is that you can define the format of the file in one central section of your program - it could even be a separate module if you wanted - and in one swell foop you tell ConfigObj the name of the variable, its type, acceptable values or range, and a default value in case it's missing. Opening, reading, closing, writing, validating - all handled. I certainly wouldn't want to dissuade you from writing your own as a learning exercise - I'm glad I did - but each time I need to update one of my old programs that still uses my homegrown ConfigFile, that's the first thing I re-factor. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 20177 bytes Desc: not available URL: From lie.1296 at gmail.com Wed Feb 18 03:24:59 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 18 Feb 2009 02:24:59 +0000 (UTC) Subject: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu References: Message-ID: On Mon, 16 Feb 2009 22:34:23 -0700, Eric Dorsey wrote: > Greetings Tutor: > I've managed to install Python 2.6 on my Ubuntu VM from source, however, > it looks as though I missed something important along the way. My 2.6 > interpreter does not have readline support (example: I cant hit up arrow > to repeat the last command) Is there a way to add this functionality > now? WORKSFORME I have Ubuntu and python2.6 and the up arrow history works fine. From sierra_mtnview at sbcglobal.net Wed Feb 18 04:09:32 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Tue, 17 Feb 2009 19:09:32 -0800 Subject: [Tutor] Changing the Attribute of a Variable In-Reply-To: <40af687b0902171117h1dab8247mdbedcdfd2a56bfa0@mail.gmail.com> References: <499A3BE3.4080209@sbcglobal.net> <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> <78b3a9580902170016i462f462ek38f99e41216aa27@mail.gmail.com> <40af687b0902170100o1ef7266x242e1121ab4c91f9@mail.gmail.com> <499AB122.40607@sbcglobal.net> <40af687b0902171011k42a779eayc51ebf0f0396eab1@mail.gmail.com> <499B09A6.7000605@sbcglobal.net> <40af687b0902171117h1dab8247mdbedcdfd2a56bfa0@mail.gmail.com> Message-ID: <499B7BEC.9000802@sbcglobal.net> An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: image/jpeg Size: 20177 bytes Desc: not available URL: From marc.tompkins at gmail.com Wed Feb 18 10:00:26 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 18 Feb 2009 01:00:26 -0800 Subject: [Tutor] Changing the Attribute of a Variable In-Reply-To: <499B7BEC.9000802@sbcglobal.net> References: <499A3BE3.4080209@sbcglobal.net> <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> <78b3a9580902170016i462f462ek38f99e41216aa27@mail.gmail.com> <40af687b0902170100o1ef7266x242e1121ab4c91f9@mail.gmail.com> <499AB122.40607@sbcglobal.net> <40af687b0902171011k42a779eayc51ebf0f0396eab1@mail.gmail.com> <499B09A6.7000605@sbcglobal.net> <40af687b0902171117h1dab8247mdbedcdfd2a56bfa0@mail.gmail.com> <499B7BEC.9000802@sbcglobal.net> Message-ID: <40af687b0902180100k705f7836o2e109585137f73c3@mail.gmail.com> On Tue, Feb 17, 2009 at 7:09 PM, Wayne Watson wrote: I have a few notes, but first I just have to say: you're working very hard to implement an ordered dictionary, and you really, really don't need to. Python's (unordered) dictionaries work just fine for reading and writing configurations; you just need to rethink a little. Or, try ConfigObj, which reads and writes your config files exactly according to your specification with very little fuss and minimal wheel-reinvention. 'Nuff said. Ok, let's see how this works. I've defined this function and the > config_var_list. stop time is the last entry shown. It is part of the > constructor for mainloop, Sentinel_GUI. and loads sdict as shown. > def Set_ConfigDictionary(): > > *config_var_list* = (['config_file_name', ['Initial.sen', > STR]], > ['mask_file_name', ['xyz', STR]], > ... > ['stop_time', ['datetime.time(6, 0, 0)', DAT]], > ... > ) > # load sdict > *sdict* = {} > for j in range(0, len(config_var_list)): > # print "j: ", j, "str part: ", str(config_var_list[j][0]), > config_var_list[j][1] > sdict[str(config_var_list[j][0])] = > config_var_list[j][1][0] > ... > These two lines are unnecessary: *self.sdict = sdict* *self.config_var_list* = config_var_list You don't need to create and load "sdict" and "config_var_list" before assigning them to self - you could start out with *self.sdict* = {} and *self.config_var_list* = etc. and work from there. ... > sdict and config_var_list become global to Sentinel_GUI. The first index of > conf_var_list maintains order for sdict. That is, when I want to output the > config file, I use to to fetch from sdict what I need, which is a value and > the "user" type, i.e., STR, DAT, BOO, etc. > I don't understand the need for STR, DAT, BOO - if you're type-checking, you don't need to create your own types to do it, and if they're informational only, you could just give your variables descriptive names. Relax and learn to love Python's iterators. You don't need an index to step through the members of a list or tuple - Python is happy to give them to you one at a time and in order! Instead of: for j in range(0, len(config_var_list)): sdict[str(config_var_list[j][0])] = config_var_list[j][1][0] try this: for var in config_var_list: sdict[var[0]] = var[1][0] Also - config_var_list is a tuple of lists. (I'm guessing you intended to make it a list of lists - that's what the name indicates, after all - but putting it between "( )" makes it a tuple.) Myself, I'd make it either a list of dictionaries (preserves ordering), or a dictionary of dictionaries. Here's what I'm talking about - *config_var_list* = [{"name":"config_file_name", "value":"Initial.sen", "type": "STR"}, {"name":"mask_file_name", "value":"xyz", "type":"STR"}, ... {"name":"stop_time", "value":"datetime.time(6, 0, 0)", "type":"DAT"}, ... ] # load sdict *sdict* = {} for var in config_var_list: sdict[var["name"]] = var["value"] I just find it much, much easier to understand what's going on - with [0] and [1][0] I had to read the code four or five times to grok it. I haven't benchmarked the two approaches - it's possible that access by list indices is faster - but it's hard to overestimate the importance of clarity. Now in SaveConfigFile, I go merrily along thusly: > > ... > # SAVE CONFIG FILE > items = self.sdict.keys() > items.sort() > for (j, conf_entry) in enumerate(self.config_var_list): > varName = conf_entry[0] > varType = self.config_var_list[j][1][1] > # Note, date-time vars are in hh:mm:ss > varValue = eval('self.' + varName) > var_assignment = varName + "=" + str(varValue) <<--- Beep, > beep > config_file.write(var_assignment + "\n") > ... > Don't work so hard! You're using enumerate() to get both the index and the item - but you don't need to, and it's easier to use and to read if you don't. In other words, varType = self.config_var_list[j][1][1] could be shortened to varType = conf_entry[1][1] You already did that for varName - just take it the rest of the way. Next, that eval() - better this way: varValue = getattr(self, varName) There _are_ some valid use cases for eval() - but getting and setting attributes ain't it. So, taking just this section in isolation (assuming you don't implement any of my other suggestions) - for conf_entry in enumerate(self.config_var_list): varName = conf_entry[0] varType = conf_entry[1][1] varValue = getattr(self, varName) var_assignment = varName + "=" + str(varValue) + "\n" config_file.write(var_assignment) > "Beep, beep" shows the likely problem. > You haven't actually explained what the "problem" is, but I'm going to take a stab at it... datetime objects are not strings. They are - how shall I put this - datetime objects. You can't actually write them to a configuration file (you could pickle/shelve them, but that's a topic for another time) - you can only write a string representation to the file. When you want to read them back, you need to convert them back from a string into a datetime.time; this is called "round-tripping". The complementary function to strftime() is called strptime(): >>>tstTime = datetime.time(9,10,11) >>>outStr = tstTime.strftime("%H:%M:%S") # produces a string >>>print outStr '09:10:11' >>>inTime = datetime.datetime.strptime(outStr, "%H:%M:%S") # creates a datetime object from our string >>>print inTime 1900-01-01 09:10:11 # if no date is specified, datetime objects default to 1 Jan 1900 (on Windows XP, anyway) >>>print inTime.time() # just the time portion 09:10:11 > Here, I suspect that I should put out something like datetime.time(11, 20, > 10). The time being 11:00:10. Instead I chose, to put 11:00:10 in the file. > Please, please, please don't put "datetime.time(11, 20, 10)" in your config file. Apart from being hard on the eyes, it pretty much requires that you use eval() - a terrible, terrible idea. If somebody edits your config file by hand, and either intentionally or accidentally puts something funky in there, you want the worst possible consequence to be an error message, not disaster. You could store "(11,20,10)", but it's probably clearer to store the time in a human-readable format and convert it back with strptime() as above. Hope that helps... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwalsh at mwalsh.org Wed Feb 18 12:19:13 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Wed, 18 Feb 2009 05:19:13 -0600 Subject: [Tutor] Changing the Attribute of a Variable In-Reply-To: <40af687b0902180100k705f7836o2e109585137f73c3@mail.gmail.com> References: <499A3BE3.4080209@sbcglobal.net> <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> <78b3a9580902170016i462f462ek38f99e41216aa27@mail.gmail.com> <40af687b0902170100o1ef7266x242e1121ab4c91f9@mail.gmail.com> <499AB122.40607@sbcglobal.net> <40af687b0902171011k42a779eayc51ebf0f0396eab1@mail.gmail.com> <499B09A6.7000605@sbcglobal.net> <40af687b0902171117h1dab8247mdbedcdfd2a56bfa0@mail.gmail.com> <499B7BEC.9000802@sbcglobal.net> <40af687b0902180100k705f7836o2e109585137f73c3@mail.gmail.com> Message-ID: <499BEEB1.5060702@mwalsh.org> Marc Tompkins wrote: > Also - config_var_list is a tuple of lists. (I'm guessing you intended > to make it a list of lists - that's what the name indicates, after all - > but putting it between "( )" makes it a tuple.) Sound advice, but a subtle clarification is warranted I think. It's the comma(s) that make a tuple not the parens (and an absence of square brackets, I suppose). Consider the following: In [1]: a = (1) In [2]: a Out[2]: 1 In [3]: type(a) Out[3]: In [4]: b = (1,) In [5]: b Out[5]: (1,) In [6]: type(b) Out[6]: In [7]: c = 1, 2, 3 In [8]: c Out[8]: (1, 2, 3) In [9]: type(c) Out[9]: ... Wayne, I second Marc's advice that you're making it hard on yourself. Understandable to a degree, if you are trying to avoid major modification to inherited code. But, loading and saving configuration data is a 'solved' problem in that there are many choices of ready-made tools to help you accomplish the task. And, I don't see anything in your description that would indicate a custom solution is necessary -- except perhaps for the learning experience, almost never a bad idea, IMHO. Marc has already pointed out ConfigObj, which is excellent, but I thought I would also suggest ConfigParser -- part of the standard lib, if a bit less feature-full. Back to your original question, and I'm probably overstating the obvious at this point, but the underlying problem is that the operation causing the exception is expecting a datetime.time object and getting a str. So, it's less about adding a strftime attribute to the str object, and more about 'converting' the str into a datetime.time object. Short of re-writing for ConfigObj (which provides a type conversion and validation mechanism), or pickle, or similar -- you'll need to work out how to convert between str and datetime.time. Here are some (untested) examples: def time_to_str(t): return t.strftime('%H:%M:%S') def str_to_time(s): h, m, s = [int(u) for u in s.split(':')] return datetime.time(h, m, s) HTH, Marty PS. You can avoid posting images of tracebacks by enabling 'Quick Edit' mode in your windows command prompt. More info here: http://support.microsoft.com/kb/282301 From sierra_mtnview at sbcglobal.net Wed Feb 18 14:53:55 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Feb 2009 05:53:55 -0800 Subject: [Tutor] Changing the Attribute of a Variable In-Reply-To: <40af687b0902180100k705f7836o2e109585137f73c3@mail.gmail.com> References: <499A3BE3.4080209@sbcglobal.net> <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> <78b3a9580902170016i462f462ek38f99e41216aa27@mail.gmail.com> <40af687b0902170100o1ef7266x242e1121ab4c91f9@mail.gmail.com> <499AB122.40607@sbcglobal.net> <40af687b0902171011k42a779eayc51ebf0f0396eab1@mail.gmail.com> <499B09A6.7000605@sbcglobal.net> <40af687b0902171117h1dab8247mdbedcdfd2a56bfa0@mail.gmail.com> <499B7BEC.9000802@sbcglobal.net> <40af687b0902180100k705f7836o2e109585137f73c3@mail.gmail.com> Message-ID: <499C12F3.2050401@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Feb 18 15:18:31 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Feb 2009 06:18:31 -0800 Subject: [Tutor] Changing the Attribute of a Variable In-Reply-To: <499BEEB1.5060702@mwalsh.org> References: <499A3BE3.4080209@sbcglobal.net> <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> <78b3a9580902170016i462f462ek38f99e41216aa27@mail.gmail.com> <40af687b0902170100o1ef7266x242e1121ab4c91f9@mail.gmail.com> <499AB122.40607@sbcglobal.net> <40af687b0902171011k42a779eayc51ebf0f0396eab1@mail.gmail.com> <499B09A6.7000605@sbcglobal.net> <40af687b0902171117h1dab8247mdbedcdfd2a56bfa0@mail.gmail.com> <499B7BEC.9000802@sbcglobal.net> <40af687b0902180100k705f7836o2e109585137f73c3@mail.gmail.com> <499BEEB1.5060702@mwalsh.org> Message-ID: <499C18B7.1060200@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Wed Feb 18 16:30:06 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Feb 2009 07:30:06 -0800 Subject: [Tutor] Looking for ConfigObj Documentation Message-ID: <499C297E.4070300@sbcglobal.net> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Wed Feb 18 19:22:18 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 18 Feb 2009 10:22:18 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <499C297E.4070300@sbcglobal.net> References: <499C297E.4070300@sbcglobal.net> Message-ID: <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> On Wed, Feb 18, 2009 at 7:30 AM, Wayne Watson wrote: > See Subject. I've run across a 58 page document > , > but am uncertain of its applicability to my present needs (see my thread on > "Changing the Attribute"). Usually, I end up with some 3-4 page document, so > this raises an eyebrow. Am I on the right trail? In the meantime, I think > I'll turn it into a more manageable pdf file before putting it to paper. > It's a very powerful module - does lots of things you don't need yet, and maybe never will - and I agree that it could benefit from a hit-the-ground-running guide... Here's a quick-and-dirty; you can flesh out the details from the documentation you downloaded. (By the way, you'll also want to use the validate module - another 14 pages or so...) ====================================================== * Download configobj.py and validate.py; put them somewhere in your Python path (or in the same folder as your project, if you want) * Add two lines to the top of your program: from configobj import ConfigObj from validate import Validator * To make working with your spec easier, import StringIO # allows you to work with strings as if they were files # You could just create a spec file, and open it normally, but this keeps everything in one place. * Somewhere in your program, create your spec and load it. There are a lot of ways you can do this - for me, the simple thing is to put it in a class. I create a class called Global - it's a crutch, I know... class Global(object): cfgFileName = os.getcwd() + os.sep + 'Initial.sen' # current directory + "\" + filename - but you could put it anywhere and call it anything # create your spec as a multi-line string between triple quotes tmpStr = """ mask_file_name = string(default=None) gray_scale = boolean(default=True) post_event_stack = boolean(default=False) post_event_format = string(default="Tiff 2") show_real_time = boolean(default=False) hourly_rate = integer(min=0, default=0) slowdown= integer(min=0, max=10, default=1) # I don't know what this value is/does, so this is probably wrong start_time = string(default="00:00:00") # or you could make the default None? stop_time = string(default="00:00:00") lat = float(min=0.0, max=90.0) # I have no idea what you'd want as a default latitude, if any... """ cfgSpec = StringIO.StringIO(tmpStr) # turns the above string into a file-like object, which ConfigObj is expecting cfgFile = ConfigObj(cfgFileName, configspec=cfgSpec, raise_errors=True, write_empty_values=True, create_empty=True, indent_type=' ', list_values=True) # creates the actual ConfigObj object vtor = Validator() # creates a validator to match your config data against your spec * Invoke the above code when your program starts - I do it just before my mainloop, like so: def main(argv=None): if argv is None: argv = sys.argv test = Global.cfgFile.validate(Global.vtor, copy=True) # tries to load cfgFile; if it doesn't exist, creates it; fills in defaults for any missing values Global.cfgFile.write() # saves the validated file (you don't need to do this here at the start, but I usually do) app = MyApp(0) app.MainLoop() if __name__ == '__main__': main() * Your ConfigObj is ready to use! Simply access the contents like a regular dictionary. To save back to the file, call the write() method. Global.cfgFile['mask_file_name'] = 'bogus.txt' Global.cfgFile.write() maskFile = Global.cfgFile['mask_file_name'] * Or use the values directly without copying to intermediate variables: with open(Global.cfgFile['mask_file_name'], 'w+b') as maskFile: maskFile.write('some bogus text') ====================================================== I'm attaching that as a text file too - I suspect that my indentation won't survive the trip... My Global class is an ugly hack. I'm sure you'll come up with something more aesthetically pleasing... ConfigObj has lots of very cool features - sections, repeated sections, custom input validators - that's what the 50+ pages of documentation are about. When you need that stuff, it's available. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- * Download configobj.py and validate.py; put them somewhere in your Python path (or in the same folder as your project, if you want) * Add two lines to the top of your program: from configobj import ConfigObj from validate import Validator * To make working with your spec easier, import StringIO # allows you to work with strings as if they were files # You could just create a spec file, and open it normally, but this keeps everything in one place. * Somewhere in your program, create your spec and load it. There are a lot of ways you can do this - for me, the simple thing is to put it in a class. I create a class called Global - it's a crutch, I know... class Global(object): cfgFileName = os.getcwd() + os.sep + 'Initial.sen' # current directory + "\" + filename - but you could put it anywhere and call it anything # create your spec as a multi-line string between triple quotes tmpStr = """ mask_file_name = string(default=None) gray_scale = boolean(default=True) post_event_stack = boolean(default=False) post_event_format = string(default="Tiff 2") show_real_time = boolean(default=False) hourly_rate = integer(min=0, default=0) slowdown= integer(min=0, max=10, default=1) # I don't know what this value is/does, so this is probably wrong start_time = string(default="00:00:00") # or you could make the default None? stop_time = string(default="00:00:00") lat = float(min=0.0, max=90.0) # I have no idea what you'd want as a default latitude, if any... """ cfgSpec = StringIO.StringIO(tmpStr) # turns the above string into a file-like object, which ConfigObj is expecting cfgFile = ConfigObj(cfgFileName, configspec=cfgSpec, raise_errors=True, write_empty_values=True, create_empty=True, indent_type=' ', list_values=True) # creates the actual ConfigObj object vtor = Validator() # creates a validator to match your config data against your spec * Invoke the above code when your program starts - I do it just before my mainloop, like so: def main(argv=None): if argv is None: argv = sys.argv test = Global.cfgFile.validate(Global.vtor, copy=True) # tries to load cfgFile; if it doesn't exist, creates it; fills in defaults for any missing values Global.cfgFile.write() # saves the validated file (you don't need to do this here at the start, but I usually do) app = MyApp(0) app.MainLoop() if __name__ == '__main__': main() * Your ConfigObj is ready to use! Simply access the contents like a regular dictionary. To save back to the file, call the write() method. Global.cfgFile['mask_file_name'] = 'bogus.txt' Global.cfgFile.write() maskFile = Global.cfgFile['mask_file_name'] * Or use the values directly without copying to intermediate variables: with open(Global.cfgFile['mask_file_name'], 'w+b') as maskFile: maskFile.write('some bogus text') From sierra_mtnview at sbcglobal.net Wed Feb 18 22:01:44 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Feb 2009 13:01:44 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> Message-ID: <499C7738.5020103@sbcglobal.net> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Wed Feb 18 22:14:36 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 18 Feb 2009 13:14:36 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <499C7738.5020103@sbcglobal.net> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> Message-ID: <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> On Wed, Feb 18, 2009 at 1:01 PM, Wayne Watson wrote: > OK, I got the ObjectConfig and Validate downloads, and copied your Global > class successfully. Don't I need to get the two files into Python as a > module? How does that work? > Simplest: put them in the same folder as your own program. More standard: put them in one of the folders in your Python path - same general idea as the DOS search path, it's a list of directories where Python will look for modules you ask it to import. >From the docs: (http://docs.python.org/tutorial/modules.html) The Module Search Path? When a module named spam is imported, the interpreter searches for a file named spam.py in the current directory, and then in the list of directories specified by the environment variable *PYTHONPATH*. This has the same syntax as the shell variable *PATH*, that is, a list of directory names. When *PYTHONPATH*is not set, or when the file is not found there, the search continues in an installation-dependent default path; on Unix, this is usually .:/usr/local/lib/python. Actually, modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script (or the current directory), *PYTHONPATH*and the installation- dependent default. This allows Python programs that know what they're doing to modify or replace the module search path. Note that because the directory containing the script being run is on the search path, it is important that the script not have the same name as a standard module, or Python will attempt to load the script as a module when that module is imported. This will generally be an error. See section *Standard Modules* for more information. > > Marc Tompkins wrote: > > On Wed, Feb 18, 2009 at 7:30 AM, Wayne Watson < > sierra_mtnview at sbcglobal.net> wrote: > >> See Subject. I've run across a 58 page document >> , >> but am uncertain of its applicability to my present needs (see my thread on >> "Changing the Attribute"). Usually, I end up with some 3-4 page document, so >> this raises an eyebrow. Am I on the right trail? In the meantime, I think >> I'll turn it into a more manageable pdf file before putting it to paper. >> > > It's a very powerful module - does lots of things you don't need yet, and > maybe never will - and I agree that it could benefit from a > hit-the-ground-running guide... > > Here's a quick-and-dirty; you can flesh out the details from the > documentation you downloaded. (By the way, you'll also want to use the > validate module - another 14 pages or so...) > ====================================================== > * Download configobj.py and validate.py; put them somewhere in your > Python path (or in the same folder as your project, if you want) > * Add two lines to the top of your program: > from configobj import ConfigObj > from validate import Validator > * To make working with your spec easier, > import StringIO # allows you to work with strings as if they were > files > # You could just create a spec file, and open it normally, but this > keeps everything in one place. > * Somewhere in your program, create your spec and load it. There are a > lot of ways you can do this - for me, the simple thing is to put it in a > class. I create a class called Global - it's a crutch, I know... > class Global(object): > cfgFileName = os.getcwd() + os.sep + 'Initial.sen' # current > directory + "\" + filename - but you could put it anywhere and call it > anything > # create your spec as a multi-line string between triple quotes > tmpStr = """ > mask_file_name = string(default=None) > gray_scale = boolean(default=True) > post_event_stack = boolean(default=False) > post_event_format = string(default="Tiff 2") > show_real_time = boolean(default=False) > hourly_rate = integer(min=0, default=0) > slowdown= integer(min=0, max=10, default=1) # I don't know what > this value is/does, so this is probably wrong > start_time = string(default="00:00:00") # or you could make the > default None? > stop_time = string(default="00:00:00") > lat = float(min=0.0, max=90.0) # I have no idea what you'd want > as a default latitude, if any... > > """ > cfgSpec = StringIO.StringIO(tmpStr) # turns the above string > into a file-like object, which ConfigObj is expecting > cfgFile = ConfigObj(cfgFileName, > configspec=cfgSpec, raise_errors=True, > write_empty_values=True, > create_empty=True, indent_type=' ', > list_values=True) # creates the actual ConfigObj object > vtor = Validator() # creates a validator to match your config > data against your spec > * Invoke the above code when your program starts - I do it just before > my mainloop, like so: > def main(argv=None): > if argv is None: > argv = sys.argv > test = Global.cfgFile.validate(Global.vtor, copy=True) # tries > to load cfgFile; if it doesn't exist, creates it; fills in defaults for any > missing values > Global.cfgFile.write() # saves the validated file (you don't > need to do this here at the start, but I usually do) > app = MyApp(0) > app.MainLoop() > if __name__ == '__main__': > main() > * Your ConfigObj is ready to use! Simply access the contents like a > regular dictionary. To save back to the file, call the write() method. > Global.cfgFile['mask_file_name'] = 'bogus.txt' > Global.cfgFile.write() > > maskFile = Global.cfgFile['mask_file_name'] > * Or use the values directly without copying to intermediate variables: > with open(Global.cfgFile['mask_file_name'], 'w+b') as maskFile: > maskFile.write('some bogus text') > ====================================================== > I'm attaching that as a text file too - I suspect that my indentation won't > survive the trip... > > My Global class is an ugly hack. I'm sure you'll come up with something > more aesthetically pleasing... > ConfigObj has lots of very cool features - sections, repeated sections, > custom input validators - that's what the 50+ pages of documentation are > about. When you need that stuff, it's available. > -- > www.fsrtechnologies.com > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor at python.orghttp://mail.python.org/mailman/listinfo/tutor > > > -- > > Wayne Watson (Watson Adventures, Prop., Nevada City, CA) > > (121.01 Deg. W, 39.26 Deg. N) GMT-8 hr std. time) ** > "Nature, to be commanded, must be obeyed." > -- Sir Francis Bacon > > ** > > ****** Web Page: > > -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From payo2000 at gmail.com Wed Feb 18 23:44:57 2009 From: payo2000 at gmail.com (pa yo) Date: Wed, 18 Feb 2009 23:44:57 +0100 Subject: [Tutor] "Ctrl-C (unix)" in python Message-ID: I am running my Twitter>>Wiki bots in infinite loops but can't find an easy way to turn them off gracefully once I have started them. At the moment I have to go into the terminal window where they are running and type "Ctrl-C". (I am running Ubuntu 8.10 and python 2.5.2) I was thinking that I could get the bot script to read a text file at the start of the main loop and have a separate script writing the "exit" order to the same text file.... but before I get too involved with this I wanted to know if there was an built-in function to switch scripts on and off. Any help or assistance much appreciated. Payo From sierra_mtnview at sbcglobal.net Wed Feb 18 23:57:24 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Feb 2009 14:57:24 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> Message-ID: <499C9254.3020701@sbcglobal.net> An HTML attachment was scrubbed... URL: From jfabiani at yolo.com Thu Feb 19 00:10:41 2009 From: jfabiani at yolo.com (johnf) Date: Wed, 18 Feb 2009 15:10:41 -0800 Subject: [Tutor] confused with dates and which way to start Message-ID: <200902181510.41553.jfabiani@yolo.com> Hi, I need to develope a routine that will provide the some dates between a starting date and an ending date. The dates will be used to schedule instructors for specific class dates from the list of available dates. Class is normally on Monday, Wedesday, and Friday (or any days of the week including Sat and Sun). If the length of the class is 6 months (01/01/09 - 06/30/09). I need to generate all the dates that would match the Monday, Wedesday, and Friday (or whatever days are used for the class) for the entire period. I have done this is FoxPro in the past. Now I'm in python 2.5. Now the problem is there appears many ways to deal with dates in python. time(), calendar(), datetime(), dateutil(). Which is the easy way guys??? And is there something already written I should be using???? Also there is something called 'mx'. Thanks in advance. -- John Fabiani From marc.tompkins at gmail.com Thu Feb 19 00:18:03 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 18 Feb 2009 15:18:03 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <499C9254.3020701@sbcglobal.net> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499C9254.3020701@sbcglobal.net> Message-ID: <40af687b0902181518y1e8ed822lb8a3bcbf2de1867c@mail.gmail.com> On Wed, Feb 18, 2009 at 2:57 PM, Wayne Watson wrote: > Thanks. I recall installing several libraries though, where somehow they > were packaged to automatically install when opened. > > In the description, I do not see much of an explanations of examples of items like, > integer(min=0, default=0). It looks like they may be called configspecs. I > see this in section 5.3.2.2. > > key1 = integer(0, 30, default=15) > key2 = integer(default=15) > key3 = boolean(default=True) > key4 = option('Hello', 'Goodbye', 'Not Today', default='Not Today') > > but not much else. Validators? Are there others like integer, booleand and > option? Items like start_time would then be called keywords? > The configspec (configuration specification) is that thing I put inside of triple quotes. It's basically a template of what your config file will look like once it has actual data in it. In 5.3.2, the sentence "The validate method uses the validatemodule to do the validation" links to the validate.py documentation - but you won't see that if you're reading it on paper... Remember I said there's a bunch of stuff there you might not need just now? A good deal of it has to do with extending ConfigObj for your own twisted, nefarious purposes (bwahahahahaha!) - you can write your own validators for just about any kind of values you can imagine. However, just to get started, the built-ins are probably good (from the validate.py doc, http://www.voidspace.org.uk/python/validate.html#the-standard-functions): ======================================================== The standard functions come built-in to every Validator instance. They work with the following basic data types : - integer - float - boolean - string - ip_addr plus lists of these datatypes. Adding additional checks is done through coding simple functions. The full set of standard checks are : 'integer': matches integer values (including negative). Takes optional 'min' and 'max' arguments : integer() integer(3, 9) # any value from 3 to 9 integer(min=0) # any positive value integer(max=9) 'float': matches float values Has the same parameters as the integer check. 'boolean':matches boolean values: True or False. Acceptable string values for True are : true, on, yes, 1 Acceptable string values for False are : false, off, no, 0 Any other value raises an error. 'string': matches any string. Takes optional keyword args 'min' and 'max' to specify min and max length of string. 'ip_addr': matches an Internet Protocol address, v.4, represented by a dotted-quad string, i.e. '1.2.3.4'. 'list': matches any list. Takes optional keyword args 'min', and 'max' to specify min and max sizes of the list. The list checks always return a list. 'tuple': matches any list. This check returns a tuple rather than a list. 'int_list': Matches a list of integers. Takes the same arguments as list. 'float_list': Matches a list of floats. Takes the same arguments as list. 'bool_list': Matches a list of boolean values. Takes the same arguments as list. 'string_list': Matches a list of strings. Takes the same arguments as list. 'ip_addr_list': Matches a list of IP addresses. Takes the same arguments as list. 'mixed_list': Matches a list with different types in specific positions. List size must match the number of arguments. Each position can be one of : int, str, boolean, float, ip_addr So to specify a list with two strings followed by two integers, you write the check as : mixed_list(str, str, int, int) 'pass': matches everything: it never fails and the value is unchanged. It is also the default if no check is specified. 'option': matches any from a list of options. You specify this test with : option('option 1', 'option 2', 'option 3') =============================================================== -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Feb 19 00:35:19 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Feb 2009 18:35:19 -0500 Subject: [Tutor] confused with dates and which way to start In-Reply-To: <200902181510.41553.jfabiani@yolo.com> References: <200902181510.41553.jfabiani@yolo.com> Message-ID: <1c2a2c590902181535t1987b06ds23d934f96872e4ad@mail.gmail.com> On Wed, Feb 18, 2009 at 6:10 PM, johnf wrote: > Hi, > > I need to develope a routine that will provide the some dates between a > starting date and an ending date. The dates will be used to schedule > instructors for specific class dates from the list of available dates. > Class is normally on Monday, Wedesday, and Friday (or any days of the week > including Sat and Sun). If the length of the class is 6 months (01/01/09 - > 06/30/09). I need to generate all the dates that would match the Monday, > Wedesday, and Friday (or whatever days are used for the class) for the entire > period. > > I have done this is FoxPro in the past. Now I'm in python 2.5. > > Now the problem is there appears many ways to deal with dates in python. > time(), calendar(), datetime(), dateutil(). Which is the easy way guys??? This is pretty easy using datetime.date and timedelta. For example, this shows all the M, W, F between (more or less) your given dates: In [1]: from datetime import date, timedelta In [3]: end = date(2009, 6, 30) In [4]: start = date(2009, 1, 4) # a Sunday In [7]: offsets = [timedelta(days=offset) for offset in (1, 3, 5) ] # Mon, Wed, Fri In [8]: current = start In [9]: while current < end: ...: for offset in offsets: ...: print current + offset ...: current += timedelta(days=7) 2009-01-05 2009-01-07 2009-01-09 2009-01-12 2009-01-14 2009-01-16 ...etc Kent From srilyk at gmail.com Thu Feb 19 00:38:39 2009 From: srilyk at gmail.com (W W) Date: Wed, 18 Feb 2009 17:38:39 -0600 Subject: [Tutor] "Ctrl-C (unix)" in python In-Reply-To: References: Message-ID: <333efb450902181538t41b439d8oc3b42bfe81543ae2@mail.gmail.com> On Wed, Feb 18, 2009 at 4:44 PM, pa yo wrote: > I am running my Twitter>>Wiki bots in infinite loops but can't find > an easy way to turn them off gracefully once I have started them. At > the moment I have to go into the terminal window where they are > running and type "Ctrl-C". (I am running Ubuntu 8.10 and python 2.5.2) > > I was thinking that I could get the bot script to read a text file at > the start of the main loop and have a separate script writing the > "exit" order to the same text file.... but before I get too involved > with this I wanted to know if there was an built-in function to > switch scripts on and off. > Unless you want to play with sockets, that's probably the easiest way to do it that I know of. -Wayne -------------- next part -------------- An HTML attachment was scrubbed... URL: From moron.oxy at gmail.com Thu Feb 19 00:43:35 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Thu, 19 Feb 2009 10:43:35 +1100 Subject: [Tutor] Proxies/Interceptors for file-like objects Message-ID: <2096a7260902181543o7b6847ffj9c830407d0bfb94d@mail.gmail.com> Hello, I'm trying to intercept one or more methods in file-like objects (in this particular case just sys.stdin really), essentially I need a decorator/proxy implemented. What's the idiomatic way to do this? Since file objects do not have a base class(?), would I need to implement all methods to delegate down to my wrapped object, or can I use a special method to define default behaviour? I came across http://pypi.python.org/pypi/filelike/0.3.2 on googling. It seems a little overkill for what I want to do however, but it does define a base class. Thanks. -- Kamal From john at fouhy.net Thu Feb 19 00:44:39 2009 From: john at fouhy.net (John Fouhy) Date: Thu, 19 Feb 2009 12:44:39 +1300 Subject: [Tutor] "Ctrl-C (unix)" in python In-Reply-To: References: Message-ID: <5e58f2e40902181544x7bce48d3qa4a25bf4f6389976@mail.gmail.com> 2009/2/19 pa yo : > I am running my Twitter>>Wiki bots in infinite loops but can't find > an easy way to turn them off gracefully once I have started them. At > the moment I have to go into the terminal window where they are > running and type "Ctrl-C". (I am running Ubuntu 8.10 and python 2.5.2) > > I was thinking that I could get the bot script to read a text file at > the start of the main loop and have a separate script writing the > "exit" order to the same text file.... but before I get too involved > with this I wanted to know if there was an built-in function to > switch scripts on and off. You could go multithreaded. Something like this: In your main thread, replace while True: with while not self.done: and then have another thread that does something like: while True: response = raw_input('Type "quit" to quit:') if response.lower() == 'quit': self.done = True break Or even more simply: raw_input("Hit return to quit.") self.done = True It would also be easy to replace this with, say, Tkinter code to put a "Quit" button in a window on your desktop. -- John. From jfabiani at yolo.com Thu Feb 19 00:55:05 2009 From: jfabiani at yolo.com (johnf) Date: Wed, 18 Feb 2009 15:55:05 -0800 Subject: [Tutor] confused with dates and which way to start In-Reply-To: <200902181510.41553.jfabiani@yolo.com> References: <200902181510.41553.jfabiani@yolo.com> Message-ID: <200902181555.05503.jfabiani@yolo.com> On Wednesday 18 February 2009 03:10:41 pm johnf wrote: > Hi, > > I need to develope a routine that will provide the some dates between a > starting date and an ending date. The dates will be used to schedule > instructors for specific class dates from the list of available dates. > Class is normally on Monday, Wedesday, and Friday (or any days of the week > including Sat and Sun). If the length of the class is 6 months (01/01/09 - > 06/30/09). I need to generate all the dates that would match the Monday, > Wedesday, and Friday (or whatever days are used for the class) for the > entire period. > > I have done this is FoxPro in the past. Now I'm in python 2.5. > > Now the problem is there appears many ways to deal with dates in python. > time(), calendar(), datetime(), dateutil(). Which is the easy way guys??? > And is there something already written I should be using???? Also there is > something called 'mx'. > > Thanks in advance. Kent Johnson provided the following: This is pretty easy using datetime.date and timedelta. For example, this shows all the M, W, F between (more or less) your given dates: In [1]: from datetime import date, timedelta In [3]: end = date(2009, 6, 30) In [4]: start = date(2009, 1, 4) # a Sunday In [7]: offsets = [timedelta(days=offset) for offset in (1, 3, 5) ] # Mon, Wed, Fri In [8]: current = start In [9]: while current < end: ? ?...: ? ? for offset in offsets: ? ?...: ? ? ? ? print current + offset ? ?...: ? ? current += timedelta(days=7) 2009-01-05 2009-01-07 2009-01-09 2009-01-12 2009-01-14 2009-01-16 ...etc Kent thanks Kent. This appears to work. I was not aware of datetime.timedelta(). I really think there should be a place to find this type of information. I'll study the module. Again, thanks. -- John Fabiani From alan.gauld at btinternet.com Thu Feb 19 01:27:56 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Feb 2009 00:27:56 -0000 Subject: [Tutor] Changing the Attribute of a Variable References: <499A3BE3.4080209@sbcglobal.net> <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> <78b3a9580902170016i462f462ek38f99e41216aa27@mail.gmail.com> <40af687b0902170100o1ef7266x242e1121ab4c91f9@mail.gmail.com> <499AB122.40607@sbcglobal.net> <40af687b0902171011k42a779eayc51ebf0f0396eab1@mail.gmail.com> <499B09A6.7000605@sbcglobal.net> <40af687b0902171117h1dab8247mdbedcdfd2a56bfa0@mail.gmail.com> <499B7BEC.9000802@sbcglobal.net> <40af687b0902180100k705f7836o2e109585137f73c3@mail.gmail.com><499BEEB1.5060702@mwalsh.org> <499C18B7.1060200@sbcglobal.net> Message-ID: "Wayne Watson" wrote > I'll look into Quick Edit. I use Snagit to screen capture. Quick edit allows you to use the mouse to select text on the console screen then use the Enter key to copy it to the clipboard. So to paste an error message into an email simple select it with the mouse, hit enter then go to your mail message and paste it in as normal text. Avoids any screen captures or attachments etc. You can do the same thing more slowly without QuickEdit using the menu accessed via the icon on the left of the window title bar. Navigate to the edit submenu... Alan G. From alan.gauld at btinternet.com Thu Feb 19 01:34:55 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 19 Feb 2009 00:34:55 -0000 Subject: [Tutor] Changing the Attribute of a Variable References: <499A3BE3.4080209@sbcglobal.net> <40af687b0902162344p3940a238scb9abecad369a03b@mail.gmail.com> <78b3a9580902170016i462f462ek38f99e41216aa27@mail.gmail.com> <40af687b0902170100o1ef7266x242e1121ab4c91f9@mail.gmail.com> <499AB122.40607@sbcglobal.net> <40af687b0902171011k42a779eayc51ebf0f0396eab1@mail.gmail.com> <499B09A6.7000605@sbcglobal.net> <40af687b0902171117h1dab8247mdbedcdfd2a56bfa0@mail.gmail.com> <499B7BEC.9000802@sbcglobal.net><40af687b0902180100k705f7836o2e109585137f73c3@mail.gmail.com> <499C12F3.2050401@sbcglobal.net> Message-ID: "Wayne Watson" wrote > Maybe the web documents should warn about the horrors of eval. > VBG. Possibly the same is true of exec? Yes the same is true of exec and also potentially execfile. All need to be used with extreme care where there is any risk of the executed code being tampered with outside the program. Thats why we have been saying that setattr/getattr etc are better ways of doing things. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l From jervisau at gmail.com Thu Feb 19 01:41:58 2009 From: jervisau at gmail.com (Jervis Whitley) Date: Thu, 19 Feb 2009 11:41:58 +1100 Subject: [Tutor] "Ctrl-C (unix)" in python In-Reply-To: References: Message-ID: <8e63a5ce0902181641v4c806ddbief4ea40580c114d9@mail.gmail.com> On Thu, Feb 19, 2009 at 9:44 AM, pa yo wrote: > I am running my Twitter>>Wiki bots in infinite loops but can't find > an easy way to turn them off gracefully once I have started them. At > the moment I have to go into the terminal window where they are > running and type "Ctrl-C". (I am running Ubuntu 8.10 and python 2.5.2) > > I was thinking that I could get the bot script to read a text file at > the start of the main loop and have a separate script writing the > "exit" order to the same text file.... but before I get too involved > with this I wanted to know if there was an built-in function to > switch scripts on and off. > > Any help or assistance much appreciated. > > Payo > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > how about kill -9 :) From emile at fenx.com Thu Feb 19 01:51:08 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 18 Feb 2009 16:51:08 -0800 Subject: [Tutor] Proxies/Interceptors for file-like objects In-Reply-To: <2096a7260902181543o7b6847ffj9c830407d0bfb94d@mail.gmail.com> References: <2096a7260902181543o7b6847ffj9c830407d0bfb94d@mail.gmail.com> Message-ID: Oxymoron wrote: > I'm trying to intercept one or more methods in file-like objects Shadowing perhaps? >>> class open(open): ... def mything(self): ... print "it's my thing" ... >>> a = open(r'c:\testfile','wb') >>> a.mything() it's my thing >>> a.write("this is a test") >>> a.flush() >>> a.close() >>> open(r'c:\testfile','r').read() 'this is a test' >>> Emile From moron.oxy at gmail.com Thu Feb 19 01:59:31 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Thu, 19 Feb 2009 11:59:31 +1100 Subject: [Tutor] Proxies/Interceptors for file-like objects In-Reply-To: References: <2096a7260902181543o7b6847ffj9c830407d0bfb94d@mail.gmail.com> Message-ID: <2096a7260902181659w102e3746ia6b4dfd9105ee5db@mail.gmail.com> On Thu, Feb 19, 2009 at 11:51 AM, Emile van Sebille wrote: > Oxymoron wrote: >> >> I'm trying to intercept one or more methods in file-like objects > > Shadowing perhaps? Neat stuff - but not applicable for me I think: 1. I receive the handle. I need this function in a CGI script for example, so sys.stdin is already open. 2. I actually need to forward requests to the underlying handle before/after intercepting, does shadowing in your example allow me to do that? -- Kamal From kent37 at tds.net Thu Feb 19 03:30:06 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Feb 2009 21:30:06 -0500 Subject: [Tutor] confused with dates and which way to start In-Reply-To: <200902181555.05503.jfabiani@yolo.com> References: <200902181510.41553.jfabiani@yolo.com> <200902181555.05503.jfabiani@yolo.com> Message-ID: <1c2a2c590902181830w47296331nb6244a5deaffc0c1@mail.gmail.com> On Wed, Feb 18, 2009 at 6:55 PM, johnf wrote: > thanks Kent. This appears to work. I was not aware of datetime.timedelta(). > I really think there should be a place to find this type of information. That's what the library reference is for: http://docs.python.org/library/datetime.html http://docs.python.org/library/index.html and comp.lang.python and the tutor list :-) It's really worth your time to at least browse the library reference. Kent From kent37 at tds.net Thu Feb 19 04:01:34 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 18 Feb 2009 22:01:34 -0500 Subject: [Tutor] Proxies/Interceptors for file-like objects In-Reply-To: References: <2096a7260902181543o7b6847ffj9c830407d0bfb94d@mail.gmail.com> Message-ID: <1c2a2c590902181901x6d1e5f93r38494ebc0ba10402@mail.gmail.com> On Wed, Feb 18, 2009 at 7:51 PM, Emile van Sebille wrote: >>>> class open(open): > ... def mything(self): > ... print "it's my thing" Hmm. I guess this is Python 3? In 2.6, open is a function and trying to subclass it gives an error: In [10]: open Out[10]: In [11]: class myopen(open): pass ....: TypeError: Error when calling the metaclass bases cannot create 'builtin_function_or_method' instances In any event, it's pretty easy to define a generic delegate in Python using the __getattr__() hook to delegate attribute access. Here is an example (that assumes all attributes are methods and doesn't actually do anything other than delegate): http://code.activestate.com/recipes/252151/ Here is an example using old-style classes that logs attribute access, both fields and methods: class LoggingWrapper: def __init__(self, instance): self.__dict__['_instance'] = instance # Actual instance def __getattr__(self, attrName): ''' Log member access ''' # Get the attribute from the delegate attrValue = getattr(self._instance, attrName) # Don't log access to private attributes if attrName.startswith('_'): return attrValue if callable(attrValue): # Create a delegate function that will log the actual parameters def delegate(*args, **kwds): params = [] if args: params.extend(map(repr, args)) if kwds: params.extend( ['%s=%s' % (key, repr(value)) for key, value in kwds.items()] ) paramStr = ', '.join(params) __log.debug('%s(%s)' % (attrName, paramStr)) return attrValue(*args, **kwds) return delegate else: __log.debug(attrName) return attrValue def __setattr__(self, attr, value): __log.debug('%s = %s' % (attr, repr(value))) return setattr(self._instance, attr, value) Kent From dorseye at gmail.com Thu Feb 19 04:19:56 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Wed, 18 Feb 2009 20:19:56 -0700 Subject: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu In-Reply-To: References: Message-ID: I did an aptitute install of ibreadline5-dev and then did ./configure and make again, and still don't have any functionality to be able to hit up-arrow and get a command repeated while inside the interpreter. Any ideas? On Tue, Feb 17, 2009 at 7:24 PM, Lie Ryan wrote: > On Mon, 16 Feb 2009 22:34:23 -0700, Eric Dorsey wrote: > > > Greetings Tutor: > > I've managed to install Python 2.6 on my Ubuntu VM from source, however, > > it looks as though I missed something important along the way. My 2.6 > > interpreter does not have readline support (example: I cant hit up arrow > > to repeat the last command) Is there a way to add this functionality > > now? > > WORKSFORME > I have Ubuntu and python2.6 and the up arrow history works fine. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Feb 19 04:42:05 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Wed, 18 Feb 2009 19:42:05 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> Message-ID: <499CD50D.4020305@sbcglobal.net> An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Global_Config.py URL: From =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2Kc=?= Thu Feb 19 07:27:34 2009 From: =?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2Kc=?= (=?UTF-8?B?2LLZitin2K8g2KjZhiDYudio2K/Yp9mE2LnYstmK2LIg2KfZhNio2Kc=?=) Date: Thu, 19 Feb 2009 09:27:34 +0300 Subject: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu In-Reply-To: References: Message-ID: <20090219092734.049b3744@ubuntu> On Wed, 18 Feb 2009 20:19:56 -0700 Eric Dorsey wrote: > I did an aptitute install of ibreadline5-dev and then > did ./configure and make again, and still don't have any > functionality to be able to hit up-arrow and get a command repeated > while inside the interpreter. Any ideas? > > I don't know what's wrong, Python should pickup "libreadline" and use it automatically if it was installed. Try passing "--with-readline" to the "configure" script. If that doesn't help, then I'm sorry, I'm out of ideas. Hope that help. Ziyad. From gdi at teamlog.com Thu Feb 19 07:27:56 2009 From: gdi at teamlog.com (Geneviève DIAGORN) Date: Thu, 19 Feb 2009 07:27:56 +0100 Subject: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu In-Reply-To: <20090219092734.049b3744@ubuntu> from PyTutor on Thu, 19 Feb 2009 09:27:34 +0300 References: <20090219092734.049b3744@ubuntu> Message-ID: <200902190627.n1J6RuU7025182@tlgmlp01.teamlog.com> Bonjour, Je suis absente jusqu'au 22/02/09 inclus. Cordialement. Genevi?ve From pine508 at hotmail.com Thu Feb 19 08:24:36 2009 From: pine508 at hotmail.com (Che M) Date: Thu, 19 Feb 2009 02:24:36 -0500 Subject: [Tutor] confused with dates and which way to start In-Reply-To: <200902181555.05503.jfabiani@yolo.com> References: <200902181510.41553.jfabiani@yolo.com> <200902181555.05503.jfabiani@yolo.com> Message-ID: > From: jfabiani at yolo.com > To: tutor at python.org > Date: Wed, 18 Feb 2009 15:55:05 -0800 > Subject: Re: [Tutor] confused with dates and which way to start > > On Wednesday 18 February 2009 03:10:41 pm johnf wrote: > > Hi, > > > > I need to develope a routine that will provide the some dates between a > > starting date and an ending date. The dates will be used to schedule > > instructors for specific class dates from the list of available dates. > > Class is normally on Monday, Wedesday, and Friday (or any days of the week > > including Sat and Sun). If the length of the class is 6 months (01/01/09 - > > 06/30/09). I need to generate all the dates that would match the Monday, > > Wedesday, and Friday (or whatever days are used for the class) for the > > entire period. > > > > I have done this is FoxPro in the past. Now I'm in python 2.5. > > > > Now the problem is there appears many ways to deal with dates in python. > > time(), calendar(), datetime(), dateutil(). Which is the easy way guys??? > > And is there something already written I should be using???? Also there is > > something called 'mx'. > > > > Thanks in advance. > > Kent Johnson provided the following: > > This is pretty easy using datetime.date and timedelta. For example, > this shows all the M, W, F between (more or less) your given dates: > > In [1]: from datetime import date, timedelta > In [3]: end = date(2009, 6, 30) > In [4]: start = date(2009, 1, 4) # a Sunday > In [7]: offsets = [timedelta(days=offset) for offset in (1, 3, 5) ] # > Mon, Wed, Fri > In [8]: current = start > > In [9]: while current < end: > ...: for offset in offsets: > ...: print current + offset > ...: current += timedelta(days=7) > > 2009-01-05 > 2009-01-07 > 2009-01-09 > 2009-01-12 > 2009-01-14 > 2009-01-16 > ...etc > > Kent > > > thanks Kent. This appears to work. I was not aware of datetime.timedelta(). > I really think there should be a place to find this type of information. > I'll study the module. Again, thanks. Well, if you Google "dates Python", three page-downs down the first hit and it shows about datetime.timedelta(). It's also mentioned in the second hit. Of course, it does require scanning and reading, since you start unsure of what to be on the lookout for. I'd also recommend you look at dateutil, because it is expressly for doing what you need, in case you need to do more and more complex date work. The page includes a ton of example code: http://labix.org/python-dateutil _________________________________________________________________ Stay up to date on your PC, the Web, and your mobile phone with Windows Live. http://clk.atdmt.com/MRT/go/msnnkwxp1020093185mrt/direct/01/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Thu Feb 19 08:53:57 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Wed, 18 Feb 2009 23:53:57 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <499CD50D.4020305@sbcglobal.net> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> Message-ID: <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> On Wed, Feb 18, 2009 at 7:42 PM, Wayne Watson wrote: > I took your "starter" code, and formatted it to be what I hope is an > acceptable program, Gobal_Config.py. See attached. I'm using Python 2.5.2. > I put the two modules in the same folder with it, and executed it in IDLE. I > got this: > ... > File > "C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\configobj.py", > line 1637, in _parse > ParseError, infile, cur_index) > File > "C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\configobj.py", > line 1748, in _handle_error > raise error > ParseError: Invalid line at line "1". > > As far as I can tell, line 1 of config.obj looks OK. It's a comment. > Something is amiss. > I hate to say it, but IDLE is really holding you back. It's convenient because it installs automagically with Python, but it does funky, confusing things - as in this case, where it's somehow stepped on the real error and assigned blame in the wrong place; you've already experienced its internal conflicts with Tkinter... I use wxPython for my GUI goodness, and swear by SPE (Stani's Python Editor). I don't want to re-ignite the IDE wars, but I definitely think you need to do yourself a favor and move away from IDLE. Anyway, I didn't mean for that to be a standalone program, but to be picked apart into chunks and dropped into an existing program (or, actually, just to be used as an example - maybe of what _not_ to do, but an example...) First error: if argv is None: argv = sys.argv <<== you haven't imported "sys" Second error: app = MyApp(0) <<== you haven't defined a class called "MyApp", so you can't do this... So I cut it down to just this bit: test = Global.cfgFile.validate(Global.vtor, copy=True) Global.cfgFile.write() (unindented all the way to the left, so that it executes as the main body of the program) and it works just fine... except: Third error (well, issue not error): Take all my comments out! They weren't meant to be included in final code. ConfigObj allows inline comments in your config file, and in the configspec - so my comments show up in there too. Here's what Initial.sen ends up looking like: mask_file_name = None gray_scale = True post_event_stack = False post_event_format = Tiff 2 show_real_time = False hourly_rate = 0 slowdown = 1 # I don't know what # this value is/does, so this is probably wrong start_time = 00:00:00 # or you could make the default None? stop_time = 00:00:00 # as a default latitude, if any... I've cut everything down; I'm attaching it as Global_Config1.py (just to avoid confusion with the earlier version). If you do actually want to use it as the basis of anything, you'll want to place the call to .validate() somewhere near the beginning of the action - remember, the call to .write() just afterward is completely optional; I had it in there for testing and have kept it in there for the same reason. > Does PYTHONPATH apply in Win XP? I haven't played at the level of paths for > a long time in any OS. We can worry about an install "package" later for the > modules. It might be best for the users of this program. > Ya know, I have no idea anymore. I thought I knew - but I just did a SET from a command prompt, and I don't have a PYTHONPATH variable. I seem to reacall something from a year or two ago... (looking now) Oh yes - there's a directory under your Python directory (Python25 in my case) called "Lib", and a folder under that called "site-packages"; any text files with the extension ".pth" will be scaned for the names of folders to add to the search path. As much as I love Python, I wish they'd get all this together... -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Global_Config1.py Type: text/x-python Size: 975 bytes Desc: not available URL: From denis.spir at free.fr Thu Feb 19 09:56:11 2009 From: denis.spir at free.fr (spir) Date: Thu, 19 Feb 2009 09:56:11 +0100 Subject: [Tutor] Proxies/Interceptors for file-like objects In-Reply-To: <1c2a2c590902181901x6d1e5f93r38494ebc0ba10402@mail.gmail.com> References: <2096a7260902181543o7b6847ffj9c830407d0bfb94d@mail.gmail.com> <1c2a2c590902181901x6d1e5f93r38494ebc0ba10402@mail.gmail.com> Message-ID: <20090219095611.4af42b41@o> Le Wed, 18 Feb 2009 22:01:34 -0500, Kent Johnson s'exprima ainsi: > Hmm. I guess this is Python 3? In 2.6, open is a function and trying > to subclass it gives an error: > > In [10]: open > Out[10]: > > In [11]: class myopen(open): pass > > ....: > > TypeError: Error when calling the metaclass bases > cannot create 'builtin_function_or_method' instances But... why not use the proper type instead: class F(file): def __init__(self, file_name): self.file_name = file_name f = F("/home/prog/io/test.py") print dir(f) print isinstance(f,types.FileType) ==> ['__class__', '__delattr__', '__dict__', '__doc__', '__enter__', '__exit__', '__getattribute__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'close', 'closed', 'encoding', 'file_name', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines'] True Then, overload the proper method the call of which you need to catch. Or there is a "detail" I do not "catch" ;-) Denis ------ la vita e estrany From moron.oxy at gmail.com Thu Feb 19 10:12:57 2009 From: moron.oxy at gmail.com (Oxymoron) Date: Thu, 19 Feb 2009 20:12:57 +1100 Subject: [Tutor] Proxies/Interceptors for file-like objects In-Reply-To: <20090219095611.4af42b41@o> References: <2096a7260902181543o7b6847ffj9c830407d0bfb94d@mail.gmail.com> <1c2a2c590902181901x6d1e5f93r38494ebc0ba10402@mail.gmail.com> <20090219095611.4af42b41@o> Message-ID: <2096a7260902190112l2256d670i257628186eeeefb3@mail.gmail.com> Thanks for the answers everyone. Denis, I wish to wrap an already open file handle basically, so simply extending and overriding doesn't help - my proxy won't be instantiated like a file, just used like one and if not intercepting I need to delegate down to the proxied "real" handle. If I'm missing something, please let me know. Here's the actual scenario: 1. The script is called within a CGI environment, so I get sys.stdin which I wish to wrap 2. On calls to read, I wish to perform certain actions (I am not the one doing the reading - I pass my proxy to the reader process - very trojan horse like), but the read is still done by the sys.stdin object. So far I've gone with Kent's suggestion, I have been a bit lazy and did not look up new-style classes, got it working with the old-style get attr, like so: class FileProxy: def __init__(self, wrappedfp, readhook): """wrappedfp is the fp we delegate down to, readhook is a callable(proxy) which is called on read operations""" self.fp = wrappedfp self.readhook = readhook self.bytecount = 0 def __getattr__(self, attrib): return getattr(self.fp, attrib) def read(self, size=-1): d = self.fp.read(size) self.readhook(self) return d def readline(self, size=-1): d = self.fp.readline(size) self.readhook(self) return d It seems to do what I want. I suppose extending from the actual type is 'safer' in that code that relies on it being a subtype won't break... hmm, fairly narrow scenario I have here though :-). Thanks. -- Kamal On Thu, Feb 19, 2009 at 7:56 PM, spir wrote: > > But... why not use the proper type instead: > > class F(file): > def __init__(self, file_name): > self.file_name = file_name > f = F("/home/prog/io/test.py") > print dir(f) > print isinstance(f,types.FileType) > ==> > ['__class__', '__delattr__', '__dict__', '__doc__', '__enter__', '__exit__', '__getattribute__', '__hash__', '__init__', '__iter__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'close', 'closed', 'encoding', 'file_name', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines'] > True > > Then, overload the proper method the call of which you need to catch. Or there is a "detail" I do not "catch" ;-) > > Denis > ------ > la vita e estrany > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From bala.biophysics at gmail.com Thu Feb 19 11:41:40 2009 From: bala.biophysics at gmail.com (Bala subramanian) Date: Thu, 19 Feb 2009 11:41:40 +0100 Subject: [Tutor] extracting a column from many files Message-ID: <288df32a0902190241u65182efckc99d3f27141c556d@mail.gmail.com> Dear friends, I want to extract certain 6 different columns from a many files and write it to 6 separate output files. I took some help from the following link http://mail.python.org/pipermail/tutor/2004-November/033475.html to write one column from many input files to a particular output file. Since i have to extract 6 such columns, i wanted to loop the output file writing part. This block of the script is shown in bold below. I see some odd output file names. Kindly suggest me i ) how best or should i do this loop part ii) explanation of the working *row=map(None,*value) *below which i adopted from the above tutor-mail list link. Thanks in advance, Bala #!/usr/bin/env python from sys import argv lst_files=argv[1:] sh=[];st=[];sta=[];buc=[];pro=[];ope=[] def extract(fname)*:* A=[];B=[];C=[];D=[];E=[];F=[] data=open(fname).readlines() for number, line in enumerate(data): if " Duplex" and " Shear" in line: number=number+3 for x in range(0,8): new=data[number] A.append(new[19:26]) B.append(new[27:34]) C.append(new[37:42]) D.append(new[44:54]) E.append(new[56:63]) F.append(new[69:75]) number = number + 1 sh.append(A) st.append(B) sta.append(C) buc.append(D) pro.append(E) ope.append(F) for x in lst_files: extract(x) *list=[sh,st,sta,buc,pro,ope]* *for value in list:* *row=map(None,*value)* *out=open(str(value) + '.txt','w') for num in row: out.write('\t'.join(num)) out.write('\n') out.close()* -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Thu Feb 19 12:03:24 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 19 Feb 2009 11:03:24 +0000 (UTC) Subject: [Tutor] Proxies/Interceptors for file-like objects References: <2096a7260902181543o7b6847ffj9c830407d0bfb94d@mail.gmail.com> <1c2a2c590902181901x6d1e5f93r38494ebc0ba10402@mail.gmail.com> <20090219095611.4af42b41@o> <2096a7260902190112l2256d670i257628186eeeefb3@mail.gmail.com> Message-ID: On Thu, 19 Feb 2009 20:12:57 +1100, Oxymoron wrote: > Thanks for the answers everyone. > > Denis, I wish to wrap an already open file handle basically, so simply > extending and overriding doesn't help - my proxy won't be instantiated > like a file, just used like one and if not intercepting I need to > delegate down to the proxied "real" handle. If I'm missing something, > please let me know. Here's the actual scenario: > If you replace sys.stdin with your own file object, you don't need to define all of the file object interface, just the one that generates an error if not defined (i.e. the ones that you use). Alternatively, you may also consider using subprocess. From kent37 at tds.net Thu Feb 19 12:38:03 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Feb 2009 06:38:03 -0500 Subject: [Tutor] extracting a column from many files In-Reply-To: <288df32a0902190241u65182efckc99d3f27141c556d@mail.gmail.com> References: <288df32a0902190241u65182efckc99d3f27141c556d@mail.gmail.com> Message-ID: <1c2a2c590902190338uc901ba8o39cd79c22e817b6d@mail.gmail.com> On Thu, Feb 19, 2009 at 5:41 AM, Bala subramanian wrote: > Dear friends, > > I want to extract certain 6 different columns from a many files and write it > to 6 separate output files. I took some help from the following link > > http://mail.python.org/pipermail/tutor/2004-November/033475.html > > to write one column from many input files to a particular output file. Since > i have to extract 6 such columns, i wanted to loop the output file writing > part. Do you want the resulting files to have a single column, or one column per input file? The mail you cite has one column per file. > This block of the script is shown in bold below. I see some odd output > file names. You are using the string representation of the values as the file name! What do you want to call the files? > Kindly suggest me i ) how best or should i do this loop part > ii) explanation of the working row=map(None,*value) below which i adopted > from the above tutor-mail list link. Please clarify what you want to do first. Kent > > Thanks in advance, > Bala > > #!/usr/bin/env python > from sys import argv > lst_files=argv[1:] > > sh=[];st=[];sta=[];buc=[];pro=[];ope=[] > > def extract(fname): > A=[];B=[];C=[];D=[];E=[];F=[] > data=open(fname).readlines() > for number, line in enumerate(data): > if " Duplex" and " Shear" in line: > number=number+3 > for x in range(0,8): > new=data[number] > A.append(new[19:26]) > B.append(new[27:34]) > C.append(new[37:42]) > D.append(new[44:54]) > E.append(new[56:63]) > F.append(new[69:75]) > number = number + 1 > sh.append(A) > st.append(B) > sta.append(C) > buc.append(D) > pro.append(E) > ope.append(F) > > for x in lst_files: > extract(x) > > list=[sh,st,sta,buc,pro,ope] > for value in list: > row=map(None,*value) > out=open(str(value) + '.txt','w') > for num in row: > out.write('\t'.join(num)) > out.write('\n') > out.close() > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Thu Feb 19 12:46:26 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Feb 2009 06:46:26 -0500 Subject: [Tutor] Proxies/Interceptors for file-like objects In-Reply-To: References: <2096a7260902181543o7b6847ffj9c830407d0bfb94d@mail.gmail.com> <1c2a2c590902181901x6d1e5f93r38494ebc0ba10402@mail.gmail.com> <20090219095611.4af42b41@o> <2096a7260902190112l2256d670i257628186eeeefb3@mail.gmail.com> Message-ID: <1c2a2c590902190346t3b0e823cp4a679d060a314645@mail.gmail.com> On Thu, Feb 19, 2009 at 6:03 AM, Lie Ryan wrote: > If you replace sys.stdin with your own file object, you don't need to > define all of the file object interface, just the one that generates an > error if not defined (i.e. the ones that you use). Yes, probably just defining read() and readline() are enough, you might be able to leave __getattr__() out of your wrapper class. Kent From bala.biophysics at gmail.com Thu Feb 19 12:58:37 2009 From: bala.biophysics at gmail.com (Bala subramanian) Date: Thu, 19 Feb 2009 12:58:37 +0100 Subject: [Tutor] extracting a column from many files In-Reply-To: <1c2a2c590902190338uc901ba8o39cd79c22e817b6d@mail.gmail.com> References: <288df32a0902190241u65182efckc99d3f27141c556d@mail.gmail.com> <1c2a2c590902190338uc901ba8o39cd79c22e817b6d@mail.gmail.com> Message-ID: <288df32a0902190358y331b7471y59a477042c71758e@mail.gmail.com> Hi, I have to extract say column 1, column 2 ..... column 6 (six different columns) from 10 different input files. The function "extract" to extract the columns works fine. For each column extracted from the input files, i have to write it in one output file. I have to make 6 output files correspondingly. How should i loop the writing of output files. Also, you had suggested previously the following way of creating list of row lists from the list of column lists rows = map(None, *listOfColumns) I am not getting how this works. Thanks, Bala On Thu, Feb 19, 2009 at 12:38 PM, Kent Johnson wrote: > On Thu, Feb 19, 2009 at 5:41 AM, Bala subramanian > wrote: > > Dear friends, > > > > I want to extract certain 6 different columns from a many files and write > it > > to 6 separate output files. I took some help from the following link > > > > http://mail.python.org/pipermail/tutor/2004-November/033475.html > > > > to write one column from many input files to a particular output file. > Since > > i have to extract 6 such columns, i wanted to loop the output file > writing > > part. > > Do you want the resulting files to have a single column, or one column > per input file? The mail you cite has one column per file. > > > This block of the script is shown in bold below. I see some odd output > > file names. > > You are using the string representation of the values as the file > name! What do you want to call the files? > > > Kindly suggest me i ) how best or should i do this loop part > > ii) explanation of the working row=map(None,*value) below which i adopted > > from the above tutor-mail list link. > > Please clarify what you want to do first. > Kent > > > > > Thanks in advance, > > Bala > > > > #!/usr/bin/env python > > from sys import argv > > lst_files=argv[1:] > > > > sh=[];st=[];sta=[];buc=[];pro=[];ope=[] > > > > def extract(fname): > > A=[];B=[];C=[];D=[];E=[];F=[] > > data=open(fname).readlines() > > for number, line in enumerate(data): > > if " Duplex" and " Shear" in line: > > number=number+3 > > for x in range(0,8): > > new=data[number] > > A.append(new[19:26]) > > B.append(new[27:34]) > > C.append(new[37:42]) > > D.append(new[44:54]) > > E.append(new[56:63]) > > F.append(new[69:75]) > > number = number + 1 > > sh.append(A) > > st.append(B) > > sta.append(C) > > buc.append(D) > > pro.append(E) > > ope.append(F) > > > > for x in lst_files: > > extract(x) > > > > list=[sh,st,sta,buc,pro,ope] > > for value in list: > > row=map(None,*value) > > out=open(str(value) + '.txt','w') > > for num in row: > > out.write('\t'.join(num)) > > out.write('\n') > > out.close() > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor at python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Feb 19 13:51:43 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 19 Feb 2009 04:51:43 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> Message-ID: <499D55DF.50202@sbcglobal.net> An HTML attachment was scrubbed... URL: From jitu.icfai at gmail.com Thu Feb 19 14:17:24 2009 From: jitu.icfai at gmail.com (jitendra gupta) Date: Thu, 19 Feb 2009 18:47:24 +0530 Subject: [Tutor] verify the email Message-ID: hello here is my code for sending the mail, using this code email is going ''''''''''''''''''''''''''''''''''''''''''''''''''''''''' CODE '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' import smtplib from time import strftime from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.Utils import COMMASPACE, formatdate # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart('alternative') msg['Subject'] = " is sending the mail" msg['From'] = 'jitu.icfai at domain.com' msg['Date'] = formatdate(localtime=True) msg['To'] = 'jitu.icfai at gmail.com' # Create the body of the message (a plain-text and an HTML version). #text = "jitendra kya huy a!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org" html = """\

Hi!
How are you?
This mail is send by wjitenrda Here is the link you wanted.

""" part2 = MIMEText(html, 'html') msg.attach(part2) # Send the message via local SMTP server. s = smtplib.SMTP('smtp.domain name.com') s.login("user","password") s.sendmail(msg['From'], msg['To'], msg.as_string()) s.close() ''''''''''''''''''''''''''''''''''''''''''''''''''''''''' CODE END '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' using this code i am able to send the email , but problem is when i am changing msg['To'] = "wronguser at wrongdomain.comddsdjsdsdsjdh" some wrong email then i am getting back failure notice in my inbox, which i dont want.. is there any way so that i can identify wrong email during the run time (when i am sending the email) -------------- next part -------------- An HTML attachment was scrubbed... URL: From dineshbvadhia at hotmail.com Thu Feb 19 16:14:59 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Thu, 19 Feb 2009 07:14:59 -0800 Subject: [Tutor] Removing control characters Message-ID: I want a regex to remove control characters (< chr(32) and > chr(126)) from strings ie. line = re.sub(r"[^a-z0-9-';.]", " ", line) # replace all chars NOT A-Z, a-z, 0-9, [-';.] with " " 1. What is the best way to include all the required chars rather than list them all within the r"" ? 2. How do you handle the inclusion of the quotation mark " ? Cheers Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Feb 19 17:03:55 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Feb 2009 11:03:55 -0500 Subject: [Tutor] Removing control characters In-Reply-To: References: Message-ID: <1c2a2c590902190803s3d4adc72ta35468faf433718c@mail.gmail.com> On Thu, Feb 19, 2009 at 10:14 AM, Dinesh B Vadhia wrote: > I want a regex to remove control characters (< chr(32) and > chr(126)) from > strings ie. > > line = re.sub(r"[^a-z0-9-';.]", " ", line) # replace all chars NOT A-Z, > a-z, 0-9, [-';.] with " " > > 1. What is the best way to include all the required chars rather than list > them all within the r"" ? You have to list either the chars you want, as you have done, or the ones you don't want. You could use r'[\x00-\x1f\x7f-\xff]' or r'[^\x20-\x7e]' > 2. How do you handle the inclusion of the quotation mark " ? Use \", that works even in a raw string. By the way string.translate() is likely to be faster for this purpose than re.sub(). This recipe might help: http://code.activestate.com/recipes/303342/ Kent From metolone+gmane at gmail.com Thu Feb 19 18:34:14 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Thu, 19 Feb 2009 09:34:14 -0800 Subject: [Tutor] Removing control characters References: Message-ID: A regex isn't always the best solution: >>> a=''.join(chr(n) for n in range(256)) >>> a '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' >>> b=''.join(n for n in a if ord(n) >= 32 and ord(n) <= 126) >>> b ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~' -Mark "Dinesh B Vadhia" wrote in message news:COL103-DS55714842811FEBEB4A97CA3B20 at phx.gbl... I want a regex to remove control characters (< chr(32) and > chr(126)) from strings ie. line = re.sub(r"[^a-z0-9-';.]", " ", line) # replace all chars NOT A-Z, a-z, 0-9, [-';.] with " " 1. What is the best way to include all the required chars rather than list them all within the r"" ? 2. How do you handle the inclusion of the quotation mark " ? Cheers Dinesh ------------------------------------------------------------------------------ _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Thu Feb 19 18:58:44 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 19 Feb 2009 09:58:44 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <499D55DF.50202@sbcglobal.net> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499D55DF.50202@sbcglobal.net> Message-ID: <499D9DD4.9060109@sbcglobal.net> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Thu Feb 19 18:58:21 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 19 Feb 2009 09:58:21 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <499D55DF.50202@sbcglobal.net> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499D55DF.50202@sbcglobal.net> Message-ID: <40af687b0902190958x764d5e71l6b013d3eeb3f3c08@mail.gmail.com> On Thu, Feb 19, 2009 at 4:51 AM, Wayne Watson wrote: > Hi, actually I had two aims with the pseudo code, 1. print it, and 2. > check to see if it would pull in the two modules. I pulled it into Word, and > quickly formatted it to get the line wrap out, and put it in some sort of > readable format. After that, I thought why not just take it as it was, and > scoop it into IDLE. My plan was to right a test program to get a better > understanding of how to use ConfigObj rather than just try it through the > program I plan to use it in. > > I've tried to keep to IDLE for no reason other than the author recommended > it. Well, OK, I had gotten comfortable with the editor. I'll try wxPython. > I wasn't very clear (and I shouldn't have mentioned wx at all, for clarity!) wxPython is not an alternative to IDLE, it's an alternative to Tkinter. SPE happens to have been written using wx (as IDLE uses Tkinter). As I say, I should have left wx out of that... my point was that IDLE was messing with the error somewhow and leading you to think it was a problem with ConfigObj, when in fact it was probably the missing "import sys". Since IDLE does that sort of thing A LOT, and also has known issues with Tkinter (which you've experienced firsthand), I thought I'd slip in a gentle suggestion to change tools. > > I took a quick look look at where Python was installed and found it was > directly under C:, and not under Program Files. That's a surprise. Now I > recall where I found something about classes and paths. It's on the File > menu of IDLE, Class Browser and Path Browser. > > I thought, in the last post, I asked about items like: show_real_time = > boolean(default=False) and hourly_rate = integer(min=0, default=0); but, > apparently, I accidentally knocked it out. Anyway, here's the question. > Where is the syntax for items like boolean, integer, and others described? > The doc I have barely refers to them. > I posted it a few messages back - here's the link again: http://www.voidspace.org.uk/python/validate.html In particular you want this section: http://www.voidspace.org.uk/python/validate.html#the-standard-functions -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Thu Feb 19 19:19:21 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 19 Feb 2009 10:19:21 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <499D9DD4.9060109@sbcglobal.net> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499D55DF.50202@sbcglobal.net> <499D9DD4.9060109@sbcglobal.net> Message-ID: <40af687b0902191019v59c756a3wf8f03328e6821356@mail.gmail.com> On Thu, Feb 19, 2009 at 9:58 AM, Wayne Watson wrote: > I now have wxPython, IDLE and Vim installed. IDLE didn't disappear during > the wx install. It looks as though wxPython re-compiled library files. I'll > be exploring vim now. > wxPython doesn't replace or remove anything - I still have IDLE on my machine, I just don't use it. The wxPython installer wasn't re-compiling Python - it was using Python to compile its own scripts for use on your machine. Once again, to be clear: wxPython is an alternative to Tkinter, not to IDLE - it's a different toolkit for creating GUI applications. The upsides: - it's a good deal more sophisticated and powerful (I feel) than Tkinter, and the apps you produce using it will look a lot more "native" (on Windows, they'll look like Windows apps; on OS X they'll have the Apple look and feel, etc.) and therefore more professional/less hobbyist-like. - the syntax of working with wxPython widgets feels more Pythonic (to me). It's a matter of personal taste, but I tried Tkinter for a few days and hated it; I tried wxPython and got hooked. The downsides: - it's not part of Python proper, so it's an extra dependency (although there's a great install-package creator called Gui2Exe that will bundle your program along with Python and all other dependencies into a Windows-style installer, so you can distribute just one file to your potential users.) - it's not part of Python proper, so most tutorials/Python books barely mention its existence. There's (1) excellent book, "wxPython in Action", a couple of very active mailing lists, an excellent and gigantic demo program with sample code for almost every widget, and Google. Other than that, you're on your own. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Feb 19 19:46:29 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Feb 2009 13:46:29 -0500 Subject: [Tutor] extracting a column from many files In-Reply-To: <288df32a0902190241u65182efckc99d3f27141c556d@mail.gmail.com> References: <288df32a0902190241u65182efckc99d3f27141c556d@mail.gmail.com> Message-ID: <1c2a2c590902191046k3d840f44m1406b9181ff89a87@mail.gmail.com> On Thu, Feb 19, 2009 at 5:41 AM, Bala subramanian wrote: > Dear friends, > > I want to extract certain 6 different columns from a many files and write it > to 6 separate output files. > > #!/usr/bin/env python > from sys import argv > lst_files=argv[1:] > > sh=[];st=[];sta=[];buc=[];pro=[];ope=[] > > def extract(fname): > A=[];B=[];C=[];D=[];E=[];F=[] > data=open(fname).readlines() > for number, line in enumerate(data): > if " Duplex" and " Shear" in line: > number=number+3 > for x in range(0,8): > new=data[number] > A.append(new[19:26]) > B.append(new[27:34]) > C.append(new[37:42]) > D.append(new[44:54]) > E.append(new[56:63]) > F.append(new[69:75]) > number = number + 1 > sh.append(A) > st.append(B) > sta.append(C) > buc.append(D) > pro.append(E) > ope.append(F) I think you want to use extend() rather than append() here so you end up with flat lists of values. Using append() creates lists of lists which I don't think you want. > > for x in lst_files: > extract(x) > > list=[sh,st,sta,buc,pro,ope] Don't use the names of built-ins (e.g. 'list') as variable names, it shadows the built-in name. > for value in list: > row=map(None,*value) Don't do this. You just want one column of data. The program you took this from was writing one column *per input file* which I don't think you want. > out=open(str(value) + '.txt','w') Value is a list, not a file name. I think you want something like this: # List of pairs of (value list, name) lists = [ (sh, 'sh'), (st, 'st'), ...] for values, name in lists: out = open(name + '.txt', 'w') for value in values: out.write(str(value)) out.write('\n') out.close() Kent > for num in row: > out.write('\t'.join(num)) > out.write('\n') > out.close() > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > From sierra_mtnview at sbcglobal.net Thu Feb 19 19:59:09 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 19 Feb 2009 10:59:09 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <40af687b0902191019v59c756a3wf8f03328e6821356@mail.gmail.com> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499D55DF.50202@sbcglobal.net> <499D9DD4.9060109@sbcglobal.net> <40af687b0902191019v59c756a3wf8f03328e6821356@mail.gmail.com> Message-ID: <499DABFD.5030405@sbcglobal.net> An HTML attachment was scrubbed... URL: From dorseye at gmail.com Thu Feb 19 20:24:07 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Thu, 19 Feb 2009 12:24:07 -0700 Subject: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu In-Reply-To: <20090219092734.049b3744@ubuntu> References: <20090219092734.049b3744@ubuntu> Message-ID: Still doesnt work.. I just get this when I hit the up arrow:>>> ^[[A Bah. It works in the 2.5 version that came packaged with it. Thanks for trying :) On Wed, Feb 18, 2009 at 11:27 PM, ???? ?? ????????? ??????? < ziyad.albatly at gmail.com> wrote: > On Wed, 18 Feb 2009 20:19:56 -0700 > Eric Dorsey wrote: > > I did an aptitute install of ibreadline5-dev and then > > did ./configure and make again, and still don't have any > > functionality to be able to hit up-arrow and get a command repeated > > while inside the interpreter. Any ideas? > > > > > I don't know what's wrong, Python should pickup "libreadline" and use > it automatically if it was installed. > > Try passing "--with-readline" to the "configure" script. > > If that doesn't help, then I'm sorry, I'm out of ideas. > > Hope that help. > Ziyad. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dineshbvadhia at hotmail.com Thu Feb 19 20:25:45 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Thu, 19 Feb 2009 11:25:45 -0800 Subject: [Tutor] Removing control characters In-Reply-To: <1c2a2c590902190803s3d4adc72ta35468faf433718c@mail.gmail.com> References: <1c2a2c590902190803s3d4adc72ta35468faf433718c@mail.gmail.com> Message-ID: At the bottom of the link http://code.activestate.com/recipes/303342/ there are list comprehensions for string manipulation ie. import string str = 'Chris Perkins : 224-7992' set = '0123456789' r = '$' # 1) Keeping only a given set of characters. print ''.join([c for c in str if c in set]) > '2247992' # 2) Deleting a given set of characters. print ''.join([c for c in str if c not in set]) > 'Chris Perkins : -' The missing one is # 3) Replacing a set of characters with a single character ie. for c in str: if c in set: string.replace (c, r) to give > 'Chris Perkins : $$$-$$$$' My solution is: print ''.join[string.replace(c, r) for c in str if c in set] But, this returns a syntax error. Any idea why? Ta! Dinesh From: Kent Johnson Sent: Thursday, February 19, 2009 8:03 AM To: Dinesh B Vadhia Cc: tutor at python.org Subject: Re: [Tutor] Removing control characters On Thu, Feb 19, 2009 at 10:14 AM, Dinesh B Vadhia wrote: > I want a regex to remove control characters (< chr(32) and > chr(126)) from > strings ie. > > line = re.sub(r"[^a-z0-9-';.]", " ", line) # replace all chars NOT A-Z, > a-z, 0-9, [-';.] with " " > > 1. What is the best way to include all the required chars rather than list > them all within the r"" ? You have to list either the chars you want, as you have done, or the ones you don't want. You could use r'[\x00-\x1f\x7f-\xff]' or r'[^\x20-\x7e]' > 2. How do you handle the inclusion of the quotation mark " ? Use \", that works even in a raw string. By the way string.translate() is likely to be faster for this purpose than re.sub(). This recipe might help: http://code.activestate.com/recipes/303342/ Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Thu Feb 19 20:26:25 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 19 Feb 2009 11:26:25 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <499DABFD.5030405@sbcglobal.net> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499D55DF.50202@sbcglobal.net> <499D9DD4.9060109@sbcglobal.net> <40af687b0902191019v59c756a3wf8f03328e6821356@mail.gmail.com> <499DABFD.5030405@sbcglobal.net> Message-ID: <40af687b0902191126xb975d11q5db64a70904c55ca@mail.gmail.com> On Thu, Feb 19, 2009 at 10:59 AM, Wayne Watson wrote: > I'm willing to give vim a shot. I believe in an earlier thread unrelated to > this, Alan suggested it. I'm perhaps incorrectly assuming vim will take care > of the Tkinter problem. If these editors aren't really the source of some > the error reporting problem, then I'm going to have to come up with new > thinking or some tactic that will get to the real errors. If there is an > influence of the editors, then I would think it has something to do with the > interface to Python, so it comes down to which editor has the best or most > stable interface with Python. When Alan suggested it, there was something > about the apparent awkwardness of executing the code, which made me pass on > it. I'm going back to find out what that was. > The problem is not with IDLE as an editor, but with IDLE as a shell. You can edit your code in any editor, and as long as it doesn't slip funky hidden characters into your file (not an issue with any normal text editor AFAIK, but you definitely don't want to use Word!) it will make NO difference to your code. The problem with IDLE is that it tries to be an IDE (Integrated Development Environment - in other words, you can edit the code, execute it, debug it, get rudimentary language help all in one program) and it does a p#$$-poor job of it. Alan's advice is to avoid the IDE approach and get used to editing your program in one window and running it in another - after all, that's how your users will see it. And it's good advice and a valid approach. Myself, I like using an IDE - the one thing I used to like about using Visual Studio was the integration. So I use SPE, which is an IDE and (IMHO) a good one. It does not matter in the slightest which tool you use, as long as that tool does not get in your way. (Actually, I may be misrepresenting Alan and Vim a bit - I don't use it myself. You can run external programs from inside of vim, so Alan's desktop may look more like a traditional IDE than I'm imagining.) -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Thu Feb 19 20:29:44 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 19 Feb 2009 11:29:44 -0800 Subject: [Tutor] Removing control characters In-Reply-To: References: <1c2a2c590902190803s3d4adc72ta35468faf433718c@mail.gmail.com> Message-ID: <40af687b0902191129p75d26f0bg720ced8bd812532c@mail.gmail.com> On Thu, Feb 19, 2009 at 11:25 AM, Dinesh B Vadhia wrote: > My solution is: > > print ''.join[string.replace(c, r) for c in str if c in set] > > But, this returns a syntax error. Any idea why? > Probably because you didn't use parentheses - join() is a function. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From daychilde at gmail.com Thu Feb 19 20:34:09 2009 From: daychilde at gmail.com (Isaac Eiland-Hall) Date: Thu, 19 Feb 2009 11:34:09 -0800 Subject: [Tutor] KeyError: 'DEFAULT' Message-ID: <007001c992c9$097368d0$1c5a3a70$@com> http://python.pastebin.com/m26864a1b Traceback (most recent call last): File "./loopy", line 328, in set[current_set][current_section][current_key] = current_value KeyError: 'DEFAULT' First, apologies for the formatting - I'm teaching myself python after having taught myself PHP, so I probably make amateur mistakes. I'm currently working in a 120-character-wide environment for my own purposes, with plans to perhaps change this later. The purpose of this program, as it stands now, is to read an INI file and parse it, line by line. Doing this by hand because my program will take the INI file and generate multiple INI files for another program, and loop through them (hence "Loopy" - I didn't come up with the name.) My "Loopy" commands are lines in the INI that begin with a colon, e.g. ":SET=somename" starts a new set. Lines 294-335 are where I've determined that the input line contains a key-value pair. Well, I should backtrack. "set" contains not only the various sets, but I track where I'm at in set["+current+"] - I have to track the current set and section (INI section, e.g. [DEFAULT]). So what I'm trying to do on line 328 is to store the current key/value pair in a dictionary under the proper section, which is in the proper set. Hence, set[setname][section][key]=value You can see my insanely-verbose log here: http://python.pastebin.com/m6dcfb96d That was from a run where I commented out line 328. (that dos the actual Googling "KeyError" seems to indicate problems while trying to *retrieve* values from a dictionary, whereas I'm trying to *set* values. Does anyone have any insight? Also, although I'm not formally requesting feedback on my coding style, that's mainly because I don't want to waste anyone's time. But if you have suggestions, please - I'm open. I'm self-taught and I'm sure I'm doing lots of stupid things. I just hope it's not all bad. ;-) Thank you most sincerely, -Isaac Eiland-Hall -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Thu Feb 19 20:45:52 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 19 Feb 2009 11:45:52 -0800 Subject: [Tutor] KeyError: 'DEFAULT' In-Reply-To: <007001c992c9$097368d0$1c5a3a70$@com> References: <007001c992c9$097368d0$1c5a3a70$@com> Message-ID: <40af687b0902191145ya694300weed52b45de501749@mail.gmail.com> On Thu, Feb 19, 2009 at 11:34 AM, Isaac Eiland-Hall wrote: > http://python.pastebin.com/m26864a1b > > > > Traceback (most recent call last): > > File "./loopy", line 328, in > > > set[current_set][current_section][current_key] = current_value > > KeyError: 'DEFAULT' > One thing pops out at me - I'm not quite done reviewing yet, but... Don't use reserved words as variable names! "set" is a built-in type in Python, and set() is a constructor for sets. By doing this: > set = {} > the best you can hope for is to confuse your fellow programmers - worse, there may be some ambiguity at runtime. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Feb 19 21:36:07 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Feb 2009 15:36:07 -0500 Subject: [Tutor] Removing control characters In-Reply-To: References: <1c2a2c590902190803s3d4adc72ta35468faf433718c@mail.gmail.com> Message-ID: <1c2a2c590902191236n15549d43m5f6444e97319e854@mail.gmail.com> On Thu, Feb 19, 2009 at 2:25 PM, Dinesh B Vadhia wrote: > # 3) Replacing a set of characters with a single character ie. > > for c in str: > if c in set: > string.replace (c, r) > > to give > >> 'Chris Perkins : $$$-$$$$' > My solution is: > > print ''.join[string.replace(c, r) for c in str if c in set] With the syntax corrected this will not do what you want; the "if c in set" filters the characters in the result, so the result will contain only the replacement characters. You would need something like ''.join([ (r if c in set else c) for c in str]) Note that both 'set' and 'str' are built-in names and therefore poor choices for variable names. Kent From bermanrl at cfl.rr.com Thu Feb 19 21:36:32 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 19 Feb 2009 15:36:32 -0500 Subject: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu In-Reply-To: References: <20090219092734.049b3744@ubuntu> Message-ID: <499DC2D0.3060401@cfl.rr.com> An HTML attachment was scrubbed... URL: From kent37 at tds.net Thu Feb 19 21:40:02 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Feb 2009 15:40:02 -0500 Subject: [Tutor] KeyError: 'DEFAULT' In-Reply-To: <007001c992c9$097368d0$1c5a3a70$@com> References: <007001c992c9$097368d0$1c5a3a70$@com> Message-ID: <1c2a2c590902191240t44dfde6h9c29db7a53344c82@mail.gmail.com> On Thu, Feb 19, 2009 at 2:34 PM, Isaac Eiland-Hall wrote: > http://python.pastebin.com/m26864a1b > > > > Traceback (most recent call last): > > File "./loopy", line 328, in > > > set[current_set][current_section][current_key] = current_value > > KeyError: 'DEFAULT' > So what I'm trying to do on line 328 is to store the current key/value pair > in a dictionary under the proper section, which is in the proper set. Hence, > set[setname][section][key]=value > > > > You can see my insanely-verbose log here: > > http://python.pastebin.com/m6dcfb96d > > > > That was from a run where I commented out line 328? (that dos the actual > > > > Googling "KeyError" seems to indicate problems while trying to *retrieve* > values from a dictionary, whereas I'm trying to *set* values? Yes, KeyError happens on retrieval. Maybe you don't realize you are doing two retrievals, then a set: set[current_set][current_section][current_key] = current_value means: - retrieve the value of set[current_set] - from the above value, retrieve the value associated with current_section - in the above value, set the value associated with current_key. I haven't looked at the code, but maybe current_set or current_section is 'DEFAULT From kent37 at tds.net Thu Feb 19 21:42:04 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Feb 2009 15:42:04 -0500 Subject: [Tutor] KeyError: 'DEFAULT' In-Reply-To: <1c2a2c590902191240t44dfde6h9c29db7a53344c82@mail.gmail.com> References: <007001c992c9$097368d0$1c5a3a70$@com> <1c2a2c590902191240t44dfde6h9c29db7a53344c82@mail.gmail.com> Message-ID: <1c2a2c590902191242m29cb8a7cq4057f94aa710e068@mail.gmail.com> Oops, hit send by mistake...continued below. On Thu, Feb 19, 2009 at 3:40 PM, Kent Johnson wrote: > On Thu, Feb 19, 2009 at 2:34 PM, Isaac Eiland-Hall wrote: >> http://python.pastebin.com/m26864a1b >> >> >> >> Traceback (most recent call last): >> >> File "./loopy", line 328, in >> >> >> set[current_set][current_section][current_key] = current_value >> >> KeyError: 'DEFAULT' > >> So what I'm trying to do on line 328 is to store the current key/value pair >> in a dictionary under the proper section, which is in the proper set. Hence, >> set[setname][section][key]=value >> >> >> >> You can see my insanely-verbose log here: >> >> http://python.pastebin.com/m6dcfb96d >> >> >> >> That was from a run where I commented out line 328? (that dos the actual >> >> >> >> Googling "KeyError" seems to indicate problems while trying to *retrieve* >> values from a dictionary, whereas I'm trying to *set* values? > > Yes, KeyError happens on retrieval. Maybe you don't realize you are > doing two retrievals, then a set: > set[current_set][current_section][current_key] = current_value > means: > - retrieve the value of set[current_set] > - from the above value, retrieve the value associated with current_section > - in the above value, set the value associated with current_key. > > I haven't looked at the code, but maybe current_set or current_section > is 'DEFAULT > is 'DEFAULT' and that value hasn't been added yet. You have to create/add the dicts at the top of the hierarchy before you can set values at the lower part. Take a look at dict.setdefault() or collections.defaultdict for some possible fixes. Kent From sierra_mtnview at sbcglobal.net Thu Feb 19 22:07:11 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Thu, 19 Feb 2009 13:07:11 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <40af687b0902191126xb975d11q5db64a70904c55ca@mail.gmail.com> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499D55DF.50202@sbcglobal.net> <499D9DD4.9060109@sbcglobal.net> <40af687b0902191019v59c756a3wf8f03328e6821356@mail.gmail.com> <499DABFD.5030405@sbcglobal.net> <40af687b0902191126xb975d11q5db64a70904c55ca@mail.gmail.com> Message-ID: <499DC9FF.2000809@sbcglobal.net> An HTML attachment was scrubbed... URL: From rschroev_nospam_ml at fastmail.fm Thu Feb 19 22:17:07 2009 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 19 Feb 2009 22:17:07 +0100 Subject: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu In-Reply-To: <499DC2D0.3060401@cfl.rr.com> References: <20090219092734.049b3744@ubuntu> <499DC2D0.3060401@cfl.rr.com> Message-ID: Robert Berman schreef: > Eric, > > I am running under Ubuntu 8.10. > > If I use IDLE the up arrow key gives me nothing at all. It does work > using iPython which for most testing of ideas and code snippets has > replaced IDLE. FYI, in Idle the keys for going back and forth in the history are Alt-P (previous) and Alt-N (next). -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From dineshbvadhia at hotmail.com Thu Feb 19 23:41:13 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Thu, 19 Feb 2009 14:41:13 -0800 Subject: [Tutor] Removing control characters In-Reply-To: <1c2a2c590902190803s3d4adc72ta35468faf433718c@mail.gmail.com> <1c2a2c590902191236n15549d43m5f6444e97319e854@mail.gmail.com> References: <1c2a2c590902190803s3d4adc72ta35468faf433718c@mail.gmail.com> <1c2a2c590902191236n15549d43m5f6444e97319e854@mail.gmail.com> Message-ID: Okay, here is a combination of Mark's suggestions and yours: > # string of all chars > a = ''.join([chr(n) for n in range(256)]) > a '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' > # string of wanted chars > b = ''.join([n for n in a if ord(n) >= 32 and ord(n) <= 126]) > b ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~' > # string of unwanted chars > ord(126) > c = ''.join([n for n in a if ord(n) < 32 or ord(n) > 126]) > c '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff' > # the string to process > s = "Product Concepts\xe2\x80\x94Hard candy with an innovative twist, Internet Archive: Wayback Machine. [online] Mar. 25, 2004. Retrieved from the Internet ." > # replace unwanted chars in string s with " " > t = "".join([(" " if n in c else n) for n in s if n not in c]) > t 'Product ConceptsHard candy with an innovative twist, Internet Archive: Wayback Machine. [online] Mar. 25, 2004. Retrieved from the Internet .' This last bit doesn't work ie. replacing the unwanted chars with " " - eg. 'ConceptsHard'. What's missing? Dinesh From: Kent Johnson Sent: Thursday, February 19, 2009 12:36 PM To: Dinesh B Vadhia Cc: tutor at python.org Subject: Re: [Tutor] Removing control characters On Thu, Feb 19, 2009 at 2:25 PM, Dinesh B Vadhia wrote: > # 3) Replacing a set of characters with a single character ie. > > for c in str: > if c in set: > string.replace (c, r) > > to give > >> 'Chris Perkins : $$$-$$$$' > My solution is: > > print ''.join[string.replace(c, r) for c in str if c in set] With the syntax corrected this will not do what you want; the "if c in set" filters the characters in the result, so the result will contain only the replacement characters. You would need something like ''.join([ (r if c in set else c) for c in str]) Note that both 'set' and 'str' are built-in names and therefore poor choices for variable names. Kent -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Feb 20 00:00:13 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Feb 2009 18:00:13 -0500 Subject: [Tutor] Removing control characters In-Reply-To: References: <1c2a2c590902190803s3d4adc72ta35468faf433718c@mail.gmail.com> <1c2a2c590902191236n15549d43m5f6444e97319e854@mail.gmail.com> Message-ID: <1c2a2c590902191500y71600feerff0b73a88fb49eed@mail.gmail.com> On Thu, Feb 19, 2009 at 5:41 PM, Dinesh B Vadhia wrote: > Okay, here is a combination of Mark's suggestions and yours: >> # replace unwanted chars in string s with " " >> t = "".join([(" " if n in c else n) for n in s if n not in c]) >> t > 'Product ConceptsHard candy with an innovative twist, Internet Archive: > Wayback Machine. [online] Mar. 25, 2004. Retrieved from the Internet http://www.confectionery-innovations.com>.' > > This last bit doesn't work ie. replacing the unwanted chars with " " - eg. > 'ConceptsHard'. What's missing? The "if n not in c" at the end of the list comp rejects the unwanted characters from the result immediately. What you wrote is the same as t = "".join([n for n in s if n not in c]) because "n in c" will never be true in the first conditional. BTW if you care about performance, this is the wrong approach. At least use a set for c; better would be to use translate(). Kent From metolone+gmane at gmail.com Fri Feb 20 02:16:26 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Thu, 19 Feb 2009 17:16:26 -0800 Subject: [Tutor] Removing control characters References: <1c2a2c590902190803s3d4adc72ta35468faf433718c@mail.gmail.com><1c2a2c590902191236n15549d43m5f6444e97319e854@mail.gmail.com> <1c2a2c590902191500y71600feerff0b73a88fb49eed@mail.gmail.com> Message-ID: "Kent Johnson" wrote in message news:1c2a2c590902191500y71600feerff0b73a88fb49eed at mail.gmail.com... > On Thu, Feb 19, 2009 at 5:41 PM, Dinesh B Vadhia > wrote: >> Okay, here is a combination of Mark's suggestions and yours: > >>> # replace unwanted chars in string s with " " >>> t = "".join([(" " if n in c else n) for n in s if n not in c]) >>> t >> 'Product ConceptsHard candy with an innovative twist, Internet Archive: >> Wayback Machine. [online] Mar. 25, 2004. Retrieved from the Internet >> > http://www.confectionery-innovations.com>.' >> >> This last bit doesn't work ie. replacing the unwanted chars with " " - >> eg. >> 'ConceptsHard'. What's missing? > > The "if n not in c" at the end of the list comp rejects the unwanted > characters from the result immediately. What you wrote is the same as > t = "".join([n for n in s if n not in c]) > > because "n in c" will never be true in the first conditional. > > BTW if you care about performance, this is the wrong approach. At > least use a set for c; better would be to use translate(). Sorry, I didn't catch the "replace with space" part. Kent is right, translate is what you want. The join is still nice for making the translation table: >>> table = ''.join(' ' if n < 32 or n > 126 else chr(n) for n in >>> xrange(256)) >>> string.translate('here is\x01my\xffstring',table) 'here is my string' -Mark From julianpaceqb at yahoo.com Fri Feb 20 02:29:47 2009 From: julianpaceqb at yahoo.com (rev pacce) Date: Thu, 19 Feb 2009 17:29:47 -0800 (PST) Subject: [Tutor] I have a question plz help Message-ID: <597217.32753.qm@web62007.mail.re1.yahoo.com> My mom and I have been trying to hack into the administrator account on our laptop my mom got from her job awile ago so we can update the computer and itunes and stuff but we have failed many times. We had a pro hacker from colorado try and do it and he also failed my mom told me. i dont no if the computer is hack proof or what but its getting annoying. Does anyone no an easy way to get onto the admin account and change the password???? -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Feb 20 03:48:55 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 19 Feb 2009 21:48:55 -0500 Subject: [Tutor] I have a question plz help In-Reply-To: <597217.32753.qm@web62007.mail.re1.yahoo.com> References: <597217.32753.qm@web62007.mail.re1.yahoo.com> Message-ID: <1c2a2c590902191848w6efaedcdh20e55ab7790d1e6b@mail.gmail.com> On Thu, Feb 19, 2009 at 8:29 PM, rev pacce wrote: > My mom and I have been trying to hack into the administrator account on our > laptop my mom got from her job awile ago so we can update the computer and > itunes and stuff but we have failed many times. We had a pro hacker from > colorado try and do it and he also failed my mom told me. i dont no if the > computer is hack proof or what but its getting annoying. Does anyone no an > easy way to get onto the admin account and change the password???? Sorry, wrong list. Kent From Garry.Willgoose at newcastle.edu.au Fri Feb 20 05:04:38 2009 From: Garry.Willgoose at newcastle.edu.au (Garry Willgoose) Date: Fri, 20 Feb 2009 15:04:38 +1100 Subject: [Tutor] wxPython dialog problem Message-ID: I'm just porting an old code from a GUI in Tkinter to one in wxPython and am having a problem with one of the dialog widgets. This is on OSX. The code below gives the result result= 5104 5103 5104 as expected but if I substitute the single line form that is commented out (as per the wxPython book) I get result= 2 5103 5104 can anyone enlighten me as to what is going on? I;m on OSX python 2.5.2 and wxPython 2.8.9.1 code fragment dlg=wx.MessageDialog(None,text,title,wx.YES_NO | wx.ICON_QUESTION) result=dlg.ShowModal() # result=wx.MessageBox(text,title,wx.YES_NO | wx.ICON_QUESTION) print 'result=',result,wx.ID_YES,wx.ID_NO end code fragment From lie.1296 at gmail.com Fri Feb 20 05:39:52 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 20 Feb 2009 04:39:52 +0000 (UTC) Subject: [Tutor] KeyError: 'DEFAULT' References: <007001c992c9$097368d0$1c5a3a70$@com> <40af687b0902191145ya694300weed52b45de501749@mail.gmail.com> Message-ID: On Thu, 19 Feb 2009 11:45:52 -0800, Marc Tompkins wrote: > Don't use reserved words as variable names! str, set is built-in function not reserved words. Reserved words are like if, for, from, as (see the whole list type keywords in help() ) Nevertheless, it is a bad idea to use built-in function names. From marc.tompkins at gmail.com Fri Feb 20 06:05:41 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Thu, 19 Feb 2009 21:05:41 -0800 Subject: [Tutor] KeyError: 'DEFAULT' In-Reply-To: References: <007001c992c9$097368d0$1c5a3a70$@com> <40af687b0902191145ya694300weed52b45de501749@mail.gmail.com> Message-ID: <40af687b0902192105m3e34f062hebee5738e735fc86@mail.gmail.com> On Thu, Feb 19, 2009 at 8:39 PM, Lie Ryan wrote: > On Thu, 19 Feb 2009 11:45:52 -0800, Marc Tompkins wrote: > > Don't use reserved words as variable names! > > > str, set is built-in function not reserved words. Reserved words are like > if, for, from, as (see the whole list type keywords in help() ) > > Nevertheless, it is a bad idea to use built-in function names. > > Fair 'nuff. Furthermore, there _are_ cases when you want to use built-in type or function names: when you're overloading them with your own versions. That's why Python lets you use them in the first place... but if that wasn't what you wanted to do, then avoid them like the plaque. (A little dental humor there.) -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Fri Feb 20 09:07:31 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 Feb 2009 08:07:31 -0000 Subject: [Tutor] I have a question plz help References: <597217.32753.qm@web62007.mail.re1.yahoo.com> Message-ID: "rev pacce" wrote > My mom and I have been trying to hack into the administrator > account on our laptop my mom got from her job We don't deal with that kind of hacking on this list. But consider what might happen if you succeed. Suppose Mom's PC develops a fault and her IT people try to go into administrator and find the password has been changed? She could lose her job! They don't tell you the password so you don't change anything and therefore don't mess up the PC settings. It costs businesses a heap of money fixing "broken" PCs. Many companies would consider that malicious damage of company property and sack her... Is it worth it just to play iTunes? Alan g From dineshbvadhia at hotmail.com Fri Feb 20 11:52:27 2009 From: dineshbvadhia at hotmail.com (Dinesh B Vadhia) Date: Fri, 20 Feb 2009 02:52:27 -0800 Subject: [Tutor] Standardizing on Unicode and utf8 Message-ID: We want to standardize on unicode and utf8 and would like to clarify and verify their use to minimize encode()/decode()'ing: 1. Python source files Use the header: # -*- coding: utf8 -*- 2. Reading files In most cases, we don't know the source encoding of the files being read. Do we have to decode('utf8') after reading from file? 3. Writing files We will always write to files in utf8. Do we have to encode('utf8') before writing to file? Is there anything else that we have to consider? Cheers Dinesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Fri Feb 20 12:25:12 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Feb 2009 06:25:12 -0500 Subject: [Tutor] wxPython dialog problem In-Reply-To: References: Message-ID: <1c2a2c590902200325m7350715eo7e6f6bf87416416b@mail.gmail.com> On Thu, Feb 19, 2009 at 11:04 PM, Garry Willgoose wrote: > I'm just porting an old code from a GUI in Tkinter to one in wxPython and am > having a problem with one of the dialog widgets. This is on OSX. The code > below gives the result > > result= 5104 5103 5104 > > as expected but if I substitute the single line form that is commented out > (as per the wxPython book) I get > > result= 2 5103 5104 > > can anyone enlighten me as to what is going on? I;m on OSX python 2.5.2 and > wxPython 2.8.9.1 Apparently ShowModal() returns one of wxID_OK, wxID_CANCEL, wxID_YES, wxID_NO whereas MessageBox() returns one of wxYES, wxNO, wxCANCEL, wxOK These are not the same: In [1]: import wx In [3]: wx.ID_OK, wx.ID_CANCEL, wx.ID_YES, wx.ID_NO Out[3]: (5100, 5101, 5103, 5104) In [4]: wx.YES, wx.NO, wx.CANCEL, wx.OK Out[4]: (2, 8, 16, 4) Kent > > code fragment > > dlg=wx.MessageDialog(None,text,title,wx.YES_NO | wx.ICON_QUESTION) > result=dlg.ShowModal() > # result=wx.MessageBox(text,title,wx.YES_NO | wx.ICON_QUESTION) > print 'result=',result,wx.ID_YES,wx.ID_NO > > end code fragment > > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Fri Feb 20 12:45:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Feb 2009 06:45:05 -0500 Subject: [Tutor] Standardizing on Unicode and utf8 In-Reply-To: References: Message-ID: <1c2a2c590902200345v6a440374ud24e611743f36d6@mail.gmail.com> On Fri, Feb 20, 2009 at 5:52 AM, Dinesh B Vadhia wrote: > We want to standardize on unicode and utf8 and would like to clarify and > verify their use to minimize encode()/decode()'ing: > > 1. Python source files > Use the header: # -*- coding: utf8 -*- > > 2. Reading files > In most cases, we don't know the source encoding of the files being read. > Do we have to decode('utf8') after reading from file? If you don't know the encoding of the file being read, it is difficult to handle it correctly. A simple strategy is to try several encodings and use the first one that reads without error. Note that *any* text can be decoded using iso-8859-1 (latin-1) or cp1252 so they must be last in the tests. This strategy can distinguish utf-16-be, utf-16-le, utf-8, iso-8859-1 but it can't discriminate between any of the iso-8859-x variants because they all will decode anything (they have characters at every code point). A more sophisticated strategy is to look for character patterns, see Mark Pilgrim's Universal Encoding Detector: http://chardet.feedparser.org/docs/ Best is not to get into this situation to begin with... Where are the files coming from? If they are from web pages, they often have metadata which gives the charset. > 3. Writing files > We will always write to files in utf8. Do we have to encode('utf8') before > writing to file? Yes. The codecs module can help with reading and writing files, it creates file-like objects that encode/decode on the fly. > Is there anything else that we have to consider? Console output also has to be decoded to the charset of the console (sys.stdout.encoding). Kent From denis.spir at free.fr Fri Feb 20 13:02:59 2009 From: denis.spir at free.fr (spir) Date: Fri, 20 Feb 2009 13:02:59 +0100 Subject: [Tutor] Standardizing on Unicode and utf8 In-Reply-To: References: Message-ID: <20090220130259.100639bb@o> Le Fri, 20 Feb 2009 02:52:27 -0800, "Dinesh B Vadhia" s'exprima ainsi: > We want to standardize on unicode and utf8 and would like to clarify and > verify their use to minimize encode()/decode()'ing: > > 1. Python source files > Use the header: # -*- coding: utf8 -*- You don't even need fancy decoration: # coding: utf-8 is enough. Denis ------ la vita e estrany From jenmiller7 at gmail.com Fri Feb 20 18:38:39 2009 From: jenmiller7 at gmail.com (Jennifer Miller) Date: Fri, 20 Feb 2009 12:38:39 -0500 Subject: [Tutor] Please remove me from the mailing list Message-ID: Hello, Could you please remove my address from the mailing list? Thank you, Jennifer From sierra_mtnview at sbcglobal.net Fri Feb 20 18:45:04 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 20 Feb 2009 09:45:04 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> Message-ID: <499EEC20.20807@sbcglobal.net> An HTML attachment was scrubbed... URL: From emile at fenx.com Fri Feb 20 19:00:03 2009 From: emile at fenx.com (Emile van Sebille) Date: Fri, 20 Feb 2009 10:00:03 -0800 Subject: [Tutor] verify the email In-Reply-To: References: Message-ID: jitendra gupta wrote: > is there any way so that i can identify wrong email during the run time > (when i am sending the email) As I understand things, no. You can validate the domain part, and there is the SMTPRecipientsRefused exception, but you won't get that if you're relaying. Further, mail systems (and administrators) are reluctant to provide spammers an easy way to validate email lists, so where doors may be opened, you're likely to find them closed anyway. Emile From ptmcg at austin.rr.com Fri Feb 20 19:45:51 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 20 Feb 2009 12:45:51 -0600 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: References: Message-ID: Has anyone already mentioned the article in Python Magazine, May, 2008? -- Paul From kent37 at tds.net Fri Feb 20 19:55:34 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 20 Feb 2009 13:55:34 -0500 Subject: [Tutor] Please remove me from the mailing list In-Reply-To: References: Message-ID: <1c2a2c590902201055u756fa491q79e654c57d0b23bd@mail.gmail.com> On Fri, Feb 20, 2009 at 12:38 PM, Jennifer Miller wrote: > Hello, > > Could you please remove my address from the mailing list? OK From berankin99 at yahoo.com Fri Feb 20 21:15:43 2009 From: berankin99 at yahoo.com (Bernard Rankin) Date: Fri, 20 Feb 2009 12:15:43 -0800 (PST) Subject: [Tutor] File locking: cross platform? Message-ID: <899550.48931.qm@web112215.mail.gq1.yahoo.com> Hello, What is the correct way to implement cross-platform "flock like" file locking? Specifically, how would i acquire "exclusive read-write" and "shared read-only" locks for a CGI script that I expect to run on both Windows and Linux servers. Thank you, :) From bgailer at gmail.com Fri Feb 20 21:32:09 2009 From: bgailer at gmail.com (bob gailer) Date: Fri, 20 Feb 2009 15:32:09 -0500 Subject: [Tutor] File locking: cross platform? In-Reply-To: <899550.48931.qm@web112215.mail.gq1.yahoo.com> References: <899550.48931.qm@web112215.mail.gq1.yahoo.com> Message-ID: <499F1349.5030109@gmail.com> Bernard Rankin wrote: > Hello, > > What is the correct way to implement cross-platform "flock like" file locking? > > Specifically, how would i acquire "exclusive read-write" and "shared read-only" locks for a CGI script that I expect to run on both Windows and Linux servers. Some other tutor may have a different answer. I propose you open(filename, 'r') or open(filename, 'w'). -- Bob Gailer Chapel Hill NC 919-636-4239 From marc.tompkins at gmail.com Fri Feb 20 21:58:00 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 20 Feb 2009 12:58:00 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <499EEC20.20807@sbcglobal.net> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499EEC20.20807@sbcglobal.net> Message-ID: <40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> On Fri, Feb 20, 2009 at 9:45 AM, Wayne Watson wrote: > Marc, I'm reaching back here, since something seems to have gone awry. I'm > looking at the code for Global_Config1.py. When I execute it from IDLE, I > get again: > > ... > File > "C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\configobj.py", > line 1637, in _parse > ParseError, infile, cur_index) > File > "C:\Sandia_Meteors\New_Sentinel_Development\Sentuser_Utilities_Related\sentuser\configobj.py", > line 1748, in _handle_error > raise error > ParseError: Invalid line at line "1". <<--- same old, same old > > However, we know IDLE can goof up. So I thought I'd execute the code by > double clicking on the file. A black window appears briefly, then > disappears. I have raw_input and other tricks to see if I could slow it > down. Finally, I went to the MS Command prompt window, and executed the py > file from there. I get exactly the same message (s) as above. I don't recall > if you tried the program on your system. Comments? > First: the line "1" it's talking about is the first line of the config file, not of configobj.py. Second: as written, there's no GUI here, so we _expect_ it to briefly show a black window, then close - but when it's done, there should be a file called "Initial.sen" in the current directory, which will look like this (this is the output on my machine): """ mask_file_name = None gray_scale = True post_event_stack = False post_event_format = Tiff 2 show_real_time = False hourly_rate = 0 slowdown = 1 start_time = 00:00:00 stop_time = 00:00:00 """ (I've added the triple quotes for visual clarity - they don't appear in the actual file.) I suspect that what's happening is that you already have a file called Initial.sen, and its contents don't match the configspec. So the ParseError is an expected result - we either need to tweak the configspec to match your previous file, or add exception handling, or (simplest) if you don't have any real installed base, just start from scratch. Do me two favors: - send your existing Initial.sen so I can look at modifying the configspec or adding exception handling - delete or rename it, then try the program again. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Fri Feb 20 21:59:04 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 20 Feb 2009 12:59:04 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: References: Message-ID: <40af687b0902201259h2a8ebe9x1cd685ddd8be1a59@mail.gmail.com> On Fri, Feb 20, 2009 at 10:45 AM, Paul McGuire wrote: > Has anyone already mentioned the article in Python Magazine, May, 2008? > No, I for one haven't seen it. Is it available online, or only for subscribers? -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From cfuller084 at thinkingplanet.net Fri Feb 20 19:46:09 2009 From: cfuller084 at thinkingplanet.net (Chris Fuller) Date: Fri, 20 Feb 2009 12:46:09 -0600 Subject: [Tutor] File locking: cross platform? In-Reply-To: <899550.48931.qm@web112215.mail.gq1.yahoo.com> References: <899550.48931.qm@web112215.mail.gq1.yahoo.com> Message-ID: <200902201246.10184.cfuller084@thinkingplanet.net> There's a recipe in the Python Cookbook that addresses this: http://code.activestate.com/recipes/65203/ There are probably others floating around, too. Cheers From sierra_mtnview at sbcglobal.net Fri Feb 20 23:19:04 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 20 Feb 2009 14:19:04 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499EEC20.20807@sbcglobal.net> <40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> Message-ID: <499F2C58.3060404@sbcglobal.net> An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: Initial01.sen URL: From alan.gauld at btinternet.com Sat Feb 21 00:50:55 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 20 Feb 2009 23:50:55 -0000 Subject: [Tutor] Looking for ConfigObj Documentation References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499EEC20.20807@sbcglobal.net><40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> <499F2C58.3060404@sbcglobal.net> Message-ID: "Wayne Watson" wrote > I just ran the program again straight from the py file, > and it put my the black window with my raw_input prompt. Thats why, when debugging, its often better to open the command window first and run the program from the OS prompt. That way you don't lose any text messages that may be written to the screen. Alan G From sierra_mtnview at sbcglobal.net Sat Feb 21 02:05:17 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Fri, 20 Feb 2009 17:05:17 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499EEC20.20807@sbcglobal.net><40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> <499F2C58.3060404@sbcglobal.net> Message-ID: <499F534D.7020200@sbcglobal.net> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Sat Feb 21 05:21:44 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Fri, 20 Feb 2009 20:21:44 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <499F534D.7020200@sbcglobal.net> References: <499C297E.4070300@sbcglobal.net> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499EEC20.20807@sbcglobal.net> <40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> <499F2C58.3060404@sbcglobal.net> <499F534D.7020200@sbcglobal.net> Message-ID: <40af687b0902202021o82d9533q5380f8e7b00c6116@mail.gmail.com> On Fri, Feb 20, 2009 at 5:05 PM, Wayne Watson wrote: > Not because of this particular problem, but, out of curiosity, I tried > today to give the MS command line facility a shot. I think that's what we > are discussing here. I immediately ran into something of a problem. My > assumption was is was fully a DOS window. Trying to work my way to folder > was a bit daunting, since I have not used this in a very long time, but this > wasn't the problem. > > As it turns out, there was an easier way. Drag and drop the path+program > link into the window after placing a CD in the command line. Very non-DOS*. > :-) One could then backspace to remove the program name, so the result was a > CD to the program folder, where several programs reside. Now the problem > became one of typing in the name of the program each time it was to be > executed. With a pretty long path name and the need to type in the file name > on each use, it seemed a bit tedious. Maybe there's another way? > > * But yet, no copy and paste from the folder Address area > Two tips: Command Prompt Here and tab completion. 1) If you haven't already, check out the Windows XP PowerToys: http://www.microsoft.com/windowsxp/Downloads/powertoys/Xppowertoys.mspx Most of them are useless (to me, anyway) but the two that are indispensible - I install them on every (XP) machine I work on - are TweakUI and Command Prompt Here. It adds a "Comand Prompt Here" item to the menu when you right-click on a folder. I remember seeing a few articles explaining how to do this yourself - but why bother? 2) Tab completion is turned on by default in Windows XP - just type the first few letters of the filename, and Windows will fill in the rest. If there are several files that start with what you typed, you might need to add a few letters to get the right one, but it still saves lots and lots of typing. It even intelligently handles long filenames with spaces in them, putting them in quotes when required. If it's turned off on your machine, you can turn it back on through TweakUI (see #1 above) under "Command Prompt." So for example, you would right-click on your project folder, select Command Prompt Here, type "python " followed by "G" and a tab, then Enter. (Or maybe "GL" then Tab, or whatever - you get the drift.) If you want a command prompt in your desktop folder, just right-click on a folder on your desktop, select CPH, then type "cd.." Much simpler than Start/Run/cmd followed by "cd \Documents and Settings\username\Desktop". Copy and paste DOES work, but not with keyboard shortcuts (presumably, those are intercepted by the command prompt itself) - right-click in the command window and select Paste. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Feb 21 10:42:02 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 21 Feb 2009 09:42:02 -0000 Subject: [Tutor] Looking for ConfigObj Documentation References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499EEC20.20807@sbcglobal.net><40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> <499F2C58.3060404@sbcglobal.net> <499F534D.7020200@sbcglobal.net> Message-ID: "Wayne Watson" wrote > My assumption was is was fully a DOS window. No its a DOS window on steroids! Thee are a ton of improvements to the DOS shell in XP most of which are turned off by default. Take half an hour to go through the help screens for CMD and turn on the various registry settings it mentions to access its full power. (Type HELP CMD at the prompt) > Trying to work my way to folder was a bit daunting, Cut n paste of the path works, but you can also use tab to complete the file name which speeds things up considerably. (And recall that with QuickEdit turned on you can easily cut n paste from the CMD window itself) > Now the problem became one of typing in the name of the > program each time it was to be executed. Even on DOS F3 repeated the last command but on XP (and indeed since Win95) you can use up/down arrow to step back through the command history. And you can set it to remember the history betweeen sessions (although I don't personally do that...) I think you can also search back through the history but I don't use that very often and I'm maybe confusing it with cygwin/bash! This works inside the python prompt in a CMD window too. Other tricks include environment variable expansion good for HOME, PATH, etc Definitely worth spending some time reading the HELP on the enhanced CMD features. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From mail at timgolden.me.uk Sat Feb 21 10:53:45 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 21 Feb 2009 09:53:45 +0000 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499EEC20.20807@sbcglobal.net><40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> <499F2C58.3060404@sbcglobal.net> <499F534D.7020200@sbcglobal.net> Message-ID: <499FCF29.8090701@timgolden.me.uk> Alan Gauld wrote: > Cut n paste of the path works, but you can also use tab to complete the > file name which speeds things up considerably. And you can drag a file in from explorer to a Console window to get the full path pasted in automatically. > Even on DOS F3 repeated the last command but on XP (and indeed since > Win95) you can use up/down arrow to step back through the command > history. And you can set it to remember the history betweeen sessions > (although I don't personally do that...) I think you can also search > back through the history but I don't use that very often and I'm maybe > confusing it with cygwin/bash! No, you're right: if you press a few characters and then F8 a matching line will be populated (can't remember if it's the most recent or the oldest). If you press F7, a selection list of all the lines entered pops up and you can select from there. And all the old tricks from the original DOS shells work: F3 as you mentioned (altho' up/down arrows are easier for this); F2 will copy up to a particular characters. Quite limited but still they have their possibilities. TJG From peter.anderson at internode.on.net Sat Feb 21 13:00:28 2009 From: peter.anderson at internode.on.net (Peter Anderson) Date: Sat, 21 Feb 2009 23:00:28 +1100 Subject: [Tutor] Problems with Python 3 and Tkinter Message-ID: <499FECDC.7040200@internode.on.net> I am trying to learn Python and have just installed Python 3. I am going back over some previous scripts trying to convert them to run under Python 3 (and hopefully learn a bit more in the process). I am having great problems with scripts that use Tkinter. A typical example is a script called calculator.py (the full script can be viewed at: http://openbookproject.net/pybiblio/tips/wilson/tkinterhelp.php ) I have shown some of the problem lines from the script below. 01 from Tkinter import * 02 from tkMessageBox import showerror 03 from math import sqrt ... 41 except ValueError: 42 if self.number.get() == '': 43 showerror('Entry error', 'You have to put a number in the blank.') 44 else: 45 showerror('Square root error', 46 "Can't find the square root of '%s'" % self.number.get()) ... When I run the calculator.py script I get the following error message: ---------- Python 3 ---------- Traceback (most recent call last): File "calculator.py", line 1, in from Tkinter import * ImportError: No module named Tkinter Output completed (0 sec consumed) If I change line 01 as follows: 01 from tkinter import * I get the following error message: ---------- Python 3 ---------- Traceback (most recent call last): File "calculator.py", line 2, in from tkMessageBox import showerror ImportError: No module named tkMessageBox Output completed (0 sec consumed) Clearly Python 3 needs the Tkinter library typed in lower case. Then it passes on to line 02 where it can't find the module tkMessageBox. I have a copy of Grayson's "Python and Tkinter Programming" and the original script above seems to be Ok. If I comment out line 02 01 from tkinter import * 02 # from tkMessageBox import showerror The script now runs Ok unless I try to calculate a square root with no value entered in the input field. Note: Lines 41 to 46 are there to catch such errant behaviour. With no input I get the following error message: ---------- Python 3 ---------- Exception in Tkinter callback Traceback (most recent call last): File "calculator.py", line 39, in calc (self.number.get(), sqrt(float(self.number.get()))) ) ValueError: empty string for float() During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Python30\lib\tkinter\__init__.py", line 1399, in __call__ return self.func(*args) File "calculator.py", line 43, in calc showerror('Entry error', 'You have to put a number in the blank.') NameError: global name 'showerror' is not defined As part of my 'problem resolution' process I have run scripts under Python 3 that just import the tkinter library and they run fine. It only when I try to use modules such as tkMessageBox that I get problems. I have spent hours researching and Googling this problem. Is there anyone who can help me understand how to get this script running. Additionally, is there any references to Python 3 and Tkinter other than the standard documentation (which is flimsy at best). Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From peter.anderson at internode.on.net Sat Feb 21 13:45:38 2009 From: peter.anderson at internode.on.net (Peter Anderson) Date: Sat, 21 Feb 2009 23:45:38 +1100 Subject: [Tutor] Problems with Python 3 and Tkinter In-Reply-To: <499FECDC.7040200@internode.on.net> References: <499FECDC.7040200@internode.on.net> Message-ID: <499FF772.1020503@internode.on.net> I have just re-installed Python 2.5.4 and the calculator.py script runs correctly using the original script (even when no value is entered in the data input field - the error dialog displays correctly). This is very frustrating! Clearly there is something different in the way Python 3.0.1 is handling Tkinter and tkMessageBox. Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From alan.gauld at btinternet.com Sat Feb 21 13:58:44 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 21 Feb 2009 12:58:44 -0000 Subject: [Tutor] Problems with Python 3 and Tkinter References: <499FECDC.7040200@internode.on.net> Message-ID: "Peter Anderson" wrote > Additionally, is there any references to Python 3 and Tkinter other > than the standard documentation (which is flimsy at best). There are a couple of other tutorials that have been upgraded to v3 but I suspect most, like mine, are still works in progress! Python 3 for a beginner is still pioneer country at present. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From peter.anderson at internode.on.net Sat Feb 21 14:05:57 2009 From: peter.anderson at internode.on.net (Peter Anderson) Date: Sun, 22 Feb 2009 00:05:57 +1100 Subject: [Tutor] Problems with Python 3 and Tkinter In-Reply-To: <499FECDC.7040200@internode.on.net> References: <499FECDC.7040200@internode.on.net> Message-ID: <499FFC35.6090406@internode.on.net> By George I think I've done it!!! I was looking (yet again) through the Python 3 documentation and have changed the calculator.py script to: from tkinter import * from tkinter.messagebox import showerror from math import sqrt ... And it now works! I would still appreciate any help with trying to understand how tkinter and its modules are used. For example, exactly what modules are able to be used? Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From sierra_mtnview at sbcglobal.net Sat Feb 21 14:40:36 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 21 Feb 2009 05:40:36 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <499FCF29.8090701@timgolden.me.uk> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499EEC20.20807@sbcglobal.net><40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> <499F2C58.3060404@sbcglobal.net> <499F534D.7020200@sbcglobal.net> <499FCF29.8090701@timgolden.me.uk> Message-ID: <49A00454.7000303@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Sat Feb 21 15:04:16 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 21 Feb 2009 09:04:16 -0500 Subject: [Tutor] Problems with Python 3 and Tkinter In-Reply-To: <499FFC35.6090406@internode.on.net> References: <499FECDC.7040200@internode.on.net> <499FFC35.6090406@internode.on.net> Message-ID: <1c2a2c590902210604w6a39c96epea9cfa89f6014bb7@mail.gmail.com> On Sat, Feb 21, 2009 at 8:05 AM, Peter Anderson wrote: > By George I think I've done it!!! > > I was looking (yet again) through the Python 3 documentation and have > changed the calculator.py script to: > > from tkinter import * > from tkinter.messagebox import showerror > from math import sqrt > ... > > And it now works! I would still appreciate any help with trying to > understand how tkinter and its modules are used. For example, exactly what > modules are able to be used? The docs at least list the modules, but without showing their contents: http://docs.python.org/3.0/library/tkinter.html#tkinter-modules To see what is in each package, one option is to start up a pydoc server on your local machine, that gives a convenient way to browse the modules. On Windows, for Python 2.5 at least, there is a Start menu shortcut for this - Start / All Programs / Python 2.5 / Module Docs. You can also browse the source code in Python3.0\Lib\tkinter\ Kent Kent From bgailer at gmail.com Sat Feb 21 15:43:04 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 21 Feb 2009 09:43:04 -0500 Subject: [Tutor] It's all about presentation In-Reply-To: <49A00454.7000303@sbcglobal.net> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499EEC20.20807@sbcglobal.net><40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> <499F2C58.3060404@sbcglobal.net> <499F534D.7020200@sbcglobal.net> <499FCF29.8090701@timgolden.me.uk> <49A00454.7000303@sbcglobal.net> Message-ID: <49A012F8.3000306@gmail.com> Wayne Watson wrote: > ... > I started with what I might call a (well-known) bloated book on the > subject, it took until chapter 3 for the author to say anything about > running programs. The first programming job I had found me staring at > a government issued 200 page manual printed in capitals on a then > popular language. What a huge bore. It's a wonder that I continued, or > anyone, for that matter. I guess the right start matters, or in the > words of the hero in Schindler's List (movie), "It's all about > presentation." In the 80's I taught computer classes at the Boeing Company in Seattle. On several occasions I was given handouts similar to that. One example was a Fortran course that spent the first morning on writing expressions. I imagined students wanting some context for this topic. At the first opportunity I wrote a new handout; the first topic was a program to read 2 numbers, add them and print the sum. (In that era programs were run in batch mode on a HP3000. The students edited the program at their terminals, submitted them, waited a few minutes then received listings from the printer down the hall. We did eventually cover expressions. -- Bob Gailer Chapel Hill NC 919-636-4239 From iwasroot at gmail.com Sat Feb 21 20:38:49 2009 From: iwasroot at gmail.com (Moos Heintzen) Date: Sat, 21 Feb 2009 11:38:49 -0800 Subject: [Tutor] Default list arguments in __init__ Message-ID: <49A05849.9070608@gmail.com> Hi, This behavior was totally unexpected. I only caught it because it was the only thing I changed. >>> class foo: ... def __init__(self, lst=[]): ... self.items = lst ... >>> f1 = foo() >>> f1.items [] >>> f1.items.append(1) >>> f2 = foo() >>> f2.items [1] Huh? lst is a reference to the *same list* every instance? I guess I have to do it like this. It seems to work. (i.e. every foo instance with default lst now has a unique new list.) def__init__(self, lst=None): self.items = lst or [] This is on python 2.4.4c1 From denis.spir at free.fr Sat Feb 21 20:55:10 2009 From: denis.spir at free.fr (spir) Date: Sat, 21 Feb 2009 20:55:10 +0100 Subject: [Tutor] Default list arguments in __init__ In-Reply-To: <49A05849.9070608@gmail.com> References: <49A05849.9070608@gmail.com> Message-ID: <20090221205510.55927bae@o> Le Sat, 21 Feb 2009 11:38:49 -0800, Moos Heintzen s'exprima ainsi: > Hi, > > This behavior was totally unexpected. I only caught it because it was > the only thing I changed. > > >>> class foo: > ... def __init__(self, lst=[]): > ... self.items = lst > ... > >>> f1 = foo() > >>> f1.items > [] > >>> f1.items.append(1) > >>> f2 = foo() > >>> f2.items > [1] > > Huh? lst is a reference to the *same list* every instance? Yop! Default args are evaluated once and only once at func def time. Very common trap, indeed! Note that this has nothing to do with __init__, nore with methods specifically. You can reproduce your example with a "free" function. > I guess I have to do it like this. It seems to work. (i.e. every foo > instance with default lst now has a unique new list.) > > def__init__(self, lst=None): > self.items = lst or [] This is the right remedy. Except that I would write self.items = [] if lst is None else lst to avoid "tricking" with bools (personal taste). denis ------ la vita e estrany From sierra_mtnview at sbcglobal.net Sun Feb 22 03:42:55 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 21 Feb 2009 18:42:55 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <499FCF29.8090701@timgolden.me.uk> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499EEC20.20807@sbcglobal.net><40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> <499F2C58.3060404@sbcglobal.net> <499F534D.7020200@sbcglobal.net> <499FCF29.8090701@timgolden.me.uk> Message-ID: <49A0BBAF.90201@sbcglobal.net> An HTML attachment was scrubbed... URL: From kent37 at tds.net Sun Feb 22 04:02:15 2009 From: kent37 at tds.net (Kent Johnson) Date: Sat, 21 Feb 2009 22:02:15 -0500 Subject: [Tutor] Default list arguments in __init__ In-Reply-To: <20090221205510.55927bae@o> References: <49A05849.9070608@gmail.com> <20090221205510.55927bae@o> Message-ID: <1c2a2c590902211902j183fda13h9ecf33be304cd0f9@mail.gmail.com> On Sat, Feb 21, 2009 at 2:55 PM, spir wrote: > Le Sat, 21 Feb 2009 11:38:49 -0800, > Moos Heintzen s'exprima ainsi: > >> Hi, >> >> This behavior was totally unexpected. I only caught it because it was >> the only thing I changed. Yes, it is a common trap and a FAQ: http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm >> I guess I have to do it like this. It seems to work. (i.e. every foo >> instance with default lst now has a unique new list.) >> >> def__init__(self, lst=None): >> self.items = lst or [] > > This is the right remedy. Except that I would write > self.items = [] if lst is None else lst > to avoid "tricking" with bools (personal taste). These two versions have different behaviour if an empty list is passed in. Most likely the second one will be what was intended. Kent From marc.tompkins at gmail.com Sun Feb 22 04:58:01 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sat, 21 Feb 2009 19:58:01 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <49A0BBAF.90201@sbcglobal.net> References: <499C297E.4070300@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499EEC20.20807@sbcglobal.net> <40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> <499F2C58.3060404@sbcglobal.net> <499F534D.7020200@sbcglobal.net> <499FCF29.8090701@timgolden.me.uk> <49A0BBAF.90201@sbcglobal.net> Message-ID: <40af687b0902211958l7e683430j21a9d7b6a30f11dc@mail.gmail.com> On Sat, Feb 21, 2009 at 6:42 PM, Wayne Watson wrote: > I tried XP's Help on command prompts. Not much there. Is there another > source? > There are lots, and Google knows most of them - here's a good one to start with: http://www.ss64.com/nt/ -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sun Feb 22 05:23:54 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 21 Feb 2009 20:23:54 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <40af687b0902211956h5125b74bs2a3a751d2eea72aa@mail.gmail.com> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499EEC20.20807@sbcglobal.net> <40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> <49A0BC6F.5080100@sbcglobal.net> <40af687b0902211956h5125b74bs2a3a751d2eea72aa@mail.gmail.com> Message-ID: <49A0D35A.4060506@sbcglobal.net> An HTML attachment was scrubbed... URL: From sierra_mtnview at sbcglobal.net Sun Feb 22 05:26:43 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sat, 21 Feb 2009 20:26:43 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <40af687b0902211958l7e683430j21a9d7b6a30f11dc@mail.gmail.com> References: <499C297E.4070300@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499EEC20.20807@sbcglobal.net> <40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> <499F2C58.3060404@sbcglobal.net> <499F534D.7020200@sbcglobal.net> <499FCF29.8090701@timgolden.me.uk> <49A0BBAF.90201@sbcglobal.net> <40af687b0902211958l7e683430j21a9d7b6a30f11dc@mail.gmail.com> Message-ID: <49A0D403.1090001@sbcglobal.net> An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Sun Feb 22 05:38:18 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sat, 21 Feb 2009 20:38:18 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <49A0D403.1090001@sbcglobal.net> References: <499C297E.4070300@sbcglobal.net> <40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> <499F2C58.3060404@sbcglobal.net> <499F534D.7020200@sbcglobal.net> <499FCF29.8090701@timgolden.me.uk> <49A0BBAF.90201@sbcglobal.net> <40af687b0902211958l7e683430j21a9d7b6a30f11dc@mail.gmail.com> <49A0D403.1090001@sbcglobal.net> Message-ID: <40af687b0902212038k9c5a240l93438dcd63148420@mail.gmail.com> On Sat, Feb 21, 2009 at 8:26 PM, Wayne Watson wrote: > I've found others like that, but I was looking for something more > descriptive. Things like typing fill-in, or cut/paste, use of F8, etc. I'd > guess there are more. > Click through a little further: http://www.ss64.com/nt/cmd.html Should tell you more than you could possibly want to know about the XP command prompt and its options. -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From marc.tompkins at gmail.com Sun Feb 22 06:23:30 2009 From: marc.tompkins at gmail.com (Marc Tompkins) Date: Sat, 21 Feb 2009 21:23:30 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: <499F2C58.3060404@sbcglobal.net> References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499EEC20.20807@sbcglobal.net> <40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> <499F2C58.3060404@sbcglobal.net> Message-ID: <40af687b0902212123p48ab4888ob527b1b97339ab6c@mail.gmail.com> On Fri, Feb 20, 2009 at 2:19 PM, Wayne Watson wrote: > Good. Thanks. It works fine for me now. I deleted the file. I just ran > the program again straight from the py file, and it put my the black window > with my raw_input prompt. It seems odd that it wouldn't have left text > debris when it crashed. > > I've attached a copy of an Initial file. It's still under development, but > pretty close for the immediate purposes. The "_file_" names will likely end > up as a string showing the complete path to the file. start/stop_time will > be times in > the format shown, hh:mm:ss. The first line is just a header, and currently > gets tossed when the file is read. "_name" are strings. No others have seen > the program, so development continues. > > Sentinel NC Configuration File Sentinel User 3 - 1/3/2009 (Meteor Software) > config_file_name=Initial.sen > mask_file_name=*none* > gray_scale=True > post_event_stack=False > post_event_format=Tiff 2 > show_real_time=False > hourly_rate=12 > slowdown=1 > start_time=20:00:12 > stop_time=06:03:00 > lat=40.0 > long=120.0 > utc_offset=8 > elevation=1000.0 > site_name=Unknown > clock_drift=0.0 > zenith_x_pixel=319 > zenith_y_pixel=239 > north_angle_rotation=0.0 > events=Events > post_events=Post_Events > meteors=Meteor_Tags > composites=wtw:same as events? > flat_mask_val=30 > mask_file_name=*none* > mask_file_offset=30 > flat_mask_active=False > > OK - first problem is, as the error message indicated, line 1: > Sentinel NC Configuration File Sentinel User 3 - 1/3/2009 (Meteor Software) > It's not a comment, it's not a real configuration item, so ConfigObj barfs. Put a "#" in front of that, and we run just fine until: > configobj.DuplicateError: Duplicate keyword name at line 26. > which is also correct - line 26 is a duplicate of line 3. Put a "#" in front of _that_, and we run just fine with the following result: """ config_file_name = Initial.sen mask_file_name = *none* gray_scale = True post_event_stack = False post_event_format = Tiff 2 show_real_time = False hourly_rate = 12 slowdown = 1 start_time = 20:00:12 stop_time = 06:03:00 lat = 40.0 long = 120.0 utc_offset = 8 elevation = 1000.0 site_name = Unknown clock_drift = 0.0 zenith_x_pixel = 319 zenith_y_pixel = 239 north_angle_rotation = 0.0 events = Events post_events = Post_Events meteors = Meteor_Tags composites = wtw:same as events? flat_mask_val = 30 #mask_file_name=*none* mask_file_offset = 30 flat_mask_active = False """ (Once again, those are my own triple quotes) Notice that the first line has been suppressed - if you want a comment to survive into the actual file, you'll need to add it in the configspec; however, line 26 _did_ survive... there's some mystery there, but I'm not going to kill myself over it. I haven't modified the actual program or the configspec. This illustrates that the configspec dictates the bare minimum that the config file can contain, not the maximum - any valid lines (of the format "name = value") that are in the config file but not in the spec will survive (and be available to your program). -- www.fsrtechnologies.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From ravikondamuru at gmail.com Sun Feb 22 09:16:52 2009 From: ravikondamuru at gmail.com (Ravi Kondamuru) Date: Sun, 22 Feb 2009 00:16:52 -0800 Subject: [Tutor] cgi script to start another process in background Message-ID: <36601b010902220016h397a5881vc3cdd5f9573d665f@mail.gmail.com> Hi, I am trying to write a python cgi script, that invokes another process and exists. Using the subprocess documentation on NO_WAIT, I am not having much success: pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") ==> pid = Popen(["/bin/mycmd", "myarg"]).pid The script seems to wait for the new process to exit before returning to the user. I tried doing the double-fork approach discussed here: http://code.activestate.com/recipes/66012/ I am not having much luck. Any ideas on how to accomplish this appreciated. thanks, Ravi. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Feb 22 09:48:40 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sun, 22 Feb 2009 08:48:40 -0000 Subject: [Tutor] Looking for ConfigObj Documentation References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499EEC20.20807@sbcglobal.net><40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> <499F2C58.3060404@sbcglobal.net> <499F534D.7020200@sbcglobal.net> <499FCF29.8090701@timgolden.me.uk> <49A0BBAF.90201@sbcglobal.net> Message-ID: "Wayne Watson" wrote > tried XP's Help on command prompts. Not much there. Is there another > source? When you say XPs help do you mean the GUI help tool? There isn't much in there. For DOS things use the DOS help tool. Type HELP CMD at the DOS prompt. Alan G. From sierra_mtnview at sbcglobal.net Sun Feb 22 14:01:43 2009 From: sierra_mtnview at sbcglobal.net (Wayne Watson) Date: Sun, 22 Feb 2009 05:01:43 -0800 Subject: [Tutor] Looking for ConfigObj Documentation In-Reply-To: References: <499C297E.4070300@sbcglobal.net> <40af687b0902181022x58902b06h126e3f49a90daa65@mail.gmail.com> <499C7738.5020103@sbcglobal.net> <40af687b0902181314n1810ef86j43b76509ca90bee@mail.gmail.com> <499CD50D.4020305@sbcglobal.net> <40af687b0902182353g38af5962o8700d01241919d92@mail.gmail.com> <499EEC20.20807@sbcglobal.net><40af687b0902201258l68e76f56h186318f3b3aeb8d7@mail.gmail.com> <499F2C58.3060404@sbcglobal.net> <499F534D.7020200@sbcglobal.net> <499FCF29.8090701@timgolden.me.uk> <49A0BBAF.90201@sbcglobal.net> Message-ID: <49A14CB7.3030209@sbcglobal.net> An HTML attachment was scrubbed... URL: From wormwood_3 at yahoo.com Sun Feb 22 19:36:09 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Sun, 22 Feb 2009 10:36:09 -0800 (PST) Subject: [Tutor] Simple CGI script and Apache configuration Message-ID: <920149.4759.qm@web110808.mail.gq1.yahoo.com> Hello all, I'll try to give as much detail as I can, but this is a somewhat vague problem. I have a very simple script that I would like to implement as a CGI script, just so I can hit a URL and get some output. However, after following a number of tutorials, I am still seeing some very odd results. I am almost sure it's in my Apache configuration, but I figured a few people on this list would likely know what the minimal related Apache config should be. (The Apache docs are pretty daunting...) Local version wise, I am on Ubuntu 8.10, with Apache 2.2.9 and Python 2.5.2. I have libapache2-mod-python installed. Apache config is out of the box, along with: ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" In /var/www/cgi-bin, I have hello.py: #!/usr/bin/python import cgitb cgitb.enable() print "Content-type: text/html" print print "" print "
Hello!
" print "" Reload, hit http://localhost/cgi-bin/hello.py in a browser, I get centered text just fine. Now I want to do this same process on my remote webserver. On there, I am on Ubuntu 7.10, with Apache 2.2.4 and Python 2.5.1. I add: ScriptAlias /python/ "/var/www/samuelhuckins.com/python" Reload, hit http://samuelhuckins.com/python/hello.py, and I get a 404? The perms and ownership on the file is the same as in other directories. Do I need to add some sort of handler, with mod_python.publisher? I think I am just missing one of the basics of this whole process. Thanks for any assistance, Sam _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sun Feb 22 19:51:22 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Sun, 22 Feb 2009 18:51:22 +0000 (GMT) Subject: [Tutor] Looking for ConfigObj Documentation Message-ID: <509488.44926.qm@web86704.mail.ird.yahoo.com> > Under Start there's a ? icon that says Help and Support. Minimal info. Yes, although by exploring the links and using the Microsoft Knowledgebase panel on the left you do get more than I remembered. I just think the DOS HELP command is easier to use. However I did find a good overview on Technet: http://technet.microsoft.com/en-us/library/bb490954.aspx Which has a lot of other stuff on cmd.exe too. > It seems to me that the Command Prompt window is important enough > in the use of Python to warrant a full page somewhere to its applicability. I might try to do that sometime. But its not really Python specific, if you are doing any serious programming or admin work on a PC you really should be familiar with the cmd window, its often the fastest and easiest way to do stuff. And learning the little tricks and settings that make it more productive is definitely worthwhile. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From iwasroot at gmail.com Sun Feb 22 22:17:08 2009 From: iwasroot at gmail.com (Moos Heintzen) Date: Sun, 22 Feb 2009 13:17:08 -0800 Subject: [Tutor] extracting a column from many files In-Reply-To: <288df32a0902190241u65182efckc99d3f27141c556d@mail.gmail.com> References: <288df32a0902190241u65182efckc99d3f27141c556d@mail.gmail.com> Message-ID: <7b13ba330902221317l5b9fb063rc3999500250cf898@mail.gmail.com> On Thu, Feb 19, 2009 at 2:41 AM, Bala subramanian wrote: > Dear friends, > > I want to extract certain 6 different columns from a many files and write it > to 6 separate output files. I took some help from the following link > > http://mail.python.org/pipermail/tutor/2004-November/033475.html > > to write one column from many input files to a particular output file. Let me see if I understand what you want to do. You have file1.txt, file2.txt, file3.txt ... and you want to read n columns from those files? It gets confusing. How many columns do you want to read from each file? How many columns does each output file have? Also, it would be very helpful if you give us the format of the input and output files. From roberto03 at gmail.com Sun Feb 22 22:21:22 2009 From: roberto03 at gmail.com (roberto) Date: Sun, 22 Feb 2009 22:21:22 +0100 Subject: [Tutor] calling user defined function Message-ID: <4bcde3e10902221321j7d3d71b2n66e25119a2d121f0@mail.gmail.com> hello i have a question which i didn't solved yet: i can define a function using the text editor provided by IDLE 3.0; then i'd like to call this function from the python prompt but when i try to do it, python warns me that function doesn't exist of course if i define the function directly using the >>> prompt, after that everything is fine may you tell me where i have to save the file that defines the function is order to use it later ? is it a problem of path ? my version of python is 3.0, OS windows xp thank you very much in advance -- roberto OS: GNU/Linux Debian Kubuntu, Edubuntu From iwasroot at gmail.com Sun Feb 22 22:58:31 2009 From: iwasroot at gmail.com (Moos Heintzen) Date: Sun, 22 Feb 2009 13:58:31 -0800 Subject: [Tutor] extracting a column from many files In-Reply-To: <7b13ba330902221317l5b9fb063rc3999500250cf898@mail.gmail.com> References: <288df32a0902190241u65182efckc99d3f27141c556d@mail.gmail.com> <7b13ba330902221317l5b9fb063rc3999500250cf898@mail.gmail.com> Message-ID: <7b13ba330902221358t99baf20r245e37f211c74396@mail.gmail.com> For example, if you have input files: file1: 1a1 1b1 1c1 1d1 1e1 1f1 2a1 2b1 2c1 2d1 2e1 2f1 3a1 3b1 3c1 3d1 3e1 3f1 file2: 1a2 1b2 1c2 1d2 1e2 1f2 2a2 2b2 2c2 2d2 2e2 2f2 3a2 3b2 3c2 3d2 3e2 3f2 How do you want the output files to look like? From bgailer at gmail.com Sun Feb 22 23:10:15 2009 From: bgailer at gmail.com (bob gailer) Date: Sun, 22 Feb 2009 17:10:15 -0500 Subject: [Tutor] calling user defined function In-Reply-To: <4bcde3e10902221321j7d3d71b2n66e25119a2d121f0@mail.gmail.com> References: <4bcde3e10902221321j7d3d71b2n66e25119a2d121f0@mail.gmail.com> Message-ID: <49A1CD47.9020401@gmail.com> roberto wrote: > hello > i have a question which i didn't solved yet: > i can define a function using the text editor provided by IDLE 3.0; > then i'd like to call this function from the python prompt > > but when i try to do it, python warns me that function doesn't exist > of course if i define the function directly using the >>> prompt, > after that everything is fine > > may you tell me where i have to save the file that defines the > function is order to use it later ? > is it a problem of path ? > Let's say you saved the file as foo.py. Then: >>> import foo >>> foo.afunction() -- Bob Gailer Chapel Hill NC 919-636-4239 From denis.spir at free.fr Sun Feb 22 23:23:26 2009 From: denis.spir at free.fr (spir) Date: Sun, 22 Feb 2009 23:23:26 +0100 Subject: [Tutor] calling user defined function In-Reply-To: <4bcde3e10902221321j7d3d71b2n66e25119a2d121f0@mail.gmail.com> References: <4bcde3e10902221321j7d3d71b2n66e25119a2d121f0@mail.gmail.com> Message-ID: <20090222232326.452e1ef8@o> Le Sun, 22 Feb 2009 22:21:22 +0100, roberto s'exprima ainsi: > hello > i have a question which i didn't solved yet: > i can define a function using the text editor provided by IDLE 3.0; > then i'd like to call this function from the python prompt > > but when i try to do it, python warns me that function doesn't exist > of course if i define the function directly using the >>> prompt, > after that everything is fine > > may you tell me where i have to save the file that defines the > function is order to use it later ? > is it a problem of path ? I guess what you mean is how to run your program? If you write it inside the editor (as opposed to the interactive window where you get the prompt), then all you need is save (where ever you like it) and run (menu or F5). The program's output, if any, will then happen inside the interactive window. You can also "run" a program or module by importing it from inside the interactive window, using >>> import filenamewithoutdotpy Further runs/imports during the same session must however be expressed with >>> reload(filenamewithoutdotpy) Denis ------ la vita e estrany From kent37 at tds.net Mon Feb 23 00:09:54 2009 From: kent37 at tds.net (Kent Johnson) Date: Sun, 22 Feb 2009 18:09:54 -0500 Subject: [Tutor] calling user defined function In-Reply-To: <4bcde3e10902221321j7d3d71b2n66e25119a2d121f0@mail.gmail.com> References: <4bcde3e10902221321j7d3d71b2n66e25119a2d121f0@mail.gmail.com> Message-ID: <1c2a2c590902221509n2c87a1aai651ca98222595680@mail.gmail.com> On Sun, Feb 22, 2009 at 4:21 PM, roberto wrote: > hello > i have a question which i didn't solved yet: > i can define a function using the text editor provided by IDLE 3.0; > then i'd like to call this function from the python prompt > > but when i try to do it, python warns me that function doesn't exist > of course if i define the function directly using the >>> prompt, > after that everything is fine > > may you tell me where i have to save the file that defines the > function is order to use it later ? The simplest way is to save the file in your working directory, then import as Bob showed you. Kent From alan.gauld at btinternet.com Mon Feb 23 01:06:37 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Feb 2009 00:06:37 -0000 Subject: [Tutor] calling user defined function References: <4bcde3e10902221321j7d3d71b2n66e25119a2d121f0@mail.gmail.com> Message-ID: "roberto" wrote > i can define a function using the text editor provided by IDLE 3.0; > then i'd like to call this function from the python prompt > > but when i try to do it, python warns me that function doesn't exist > of course if i define the function directly using the >>> prompt, > after that everything is fine You need to save the file containing the function in a folder in the Python search patyh. tHis is defined in sys.path: import sys print sys.path Saving your file in any folder there will allow python to import the file as a module. Thus if you save it in C:\MyProjects\Python\myFunction.py and C:\MyProjects\Python is in your sys.path You can then import your file with >>> import myFunction # notice no .py And call your function foo() with >>> myFunction.foo() You can add folders to sys.path either in a startup script or using the PYTHONPATH environment variable. Make sure its PYTHONPATH you create or modify not PATH, they are very different! HTH -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From orsenthil at gmail.com Mon Feb 23 03:03:20 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Sun, 22 Feb 2009 21:03:20 -0500 Subject: [Tutor] Exercises for Classes and OOP in Python Message-ID: <7c42eba10902221803p3e195232h1a110b4998fec49b@mail.gmail.com> Hello, I am looking for a good material that would provide exercises (and possibly solutions to demo exercises) that illustrates the Object Oriented Programming constructs in Python. Can pointers? TIA, Senthil From ish_ling at yahoo.com Mon Feb 23 04:49:09 2009 From: ish_ling at yahoo.com (ish_ling) Date: Sun, 22 Feb 2009 19:49:09 -0800 (PST) Subject: [Tutor] regex help Message-ID: <598687.74144.qm@web45007.mail.sp1.yahoo.com> I have a string: 'a b c h' I would like a regex to recursively match all alpha letters that are between . That is, I would like the following list of matches: ['d', 'e', 'f', 'i', 'j'] I do not want the 'g' or the 'k' matched. I have figured out how to do this in a multiple-step process, but I would like to do it in one step using only one regex (if possible). My multiple step process is first to use the regex '(?<=H )[a-z][^H]+(?!H)' with re.findall() in order to find two strings ['d e f ', 'i j '] I can then use another regex to extract the letters out of the strings. But, as I said above I would prefer to do this in one swoop. Another example: 'a b c' There should be no matches. Last example: 'a b c' There should be one match: ['d'] (For background, although it's probably irrelevant, the string is a possible representation of a syllable (a, b, c, etc.) to tone (H) mapping in tonal languages.) If anyone has ideas, then I would greatly appreciate it. From alan.gauld at btinternet.com Mon Feb 23 09:40:07 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Feb 2009 08:40:07 -0000 Subject: [Tutor] Exercises for Classes and OOP in Python References: <7c42eba10902221803p3e195232h1a110b4998fec49b@mail.gmail.com> Message-ID: "Senthil Kumaran" wrote > I am looking for a good material that would provide exercises (and > possibly solutions to demo exercises) that illustrates the Object > Oriented Programming constructs in Python. Can pointers? I'm not sure what exactly you have in mind but most tutorials will cover OOP and you can generally take their examples and expand them in different ways to explore the features. Similarly most software problems can have an OOP solution so you could simply find OOP altrernatives to exercises you have already done in a non OOP way. Or ar you looking for something along the line of: 1) define a Shape class 2) define a circle square and triange from the shape 3) add a class attribute to your shape class 4) use polymorphic methods to embellish your shape classes etc? Those kinds of exercises are easy enough to invent yourself. And other than practicing the syntax won't help much in real-world type scenarios. IMHO HTH, Alan G. From alan.gauld at btinternet.com Mon Feb 23 09:48:08 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Feb 2009 08:48:08 -0000 Subject: [Tutor] regex help References: <598687.74144.qm@web45007.mail.sp1.yahoo.com> Message-ID: "ish_ling" wrote > 'a b c h' > > I would like a regex to Congratulations on a cclear explanation of what you want. With regex questions that is half the battle. > I have figured out how to do this in a multiple-step process And there's nothing much wrong with multi step. > with re.findall() in order to find two strings > > ['d e f ', 'i j '] > > I can then use another regex to extract the letters But you don't need a regex to do that, it could be a list comprehension: [ch for s in yourList for ch in s if ch != ' ' ] HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From bala.biophysics at gmail.com Mon Feb 23 10:35:42 2009 From: bala.biophysics at gmail.com (Bala subramanian) Date: Mon, 23 Feb 2009 10:35:42 +0100 Subject: [Tutor] extracting a column from many files In-Reply-To: <7b13ba330902221358t99baf20r245e37f211c74396@mail.gmail.com> References: <288df32a0902190241u65182efckc99d3f27141c556d@mail.gmail.com> <7b13ba330902221317l5b9fb063rc3999500250cf898@mail.gmail.com> <7b13ba330902221358t99baf20r245e37f211c74396@mail.gmail.com> Message-ID: <288df32a0902230135rb68955cicebdb740b8cec66f@mail.gmail.com> > > > file1: > 1a1 1b1 1c1 1d1 1e1 1f1 > 2a1 2b1 2c1 2d1 2e1 2f1 > 3a1 3b1 3c1 3d1 3e1 3f1 > > file2: > 1a2 1b2 1c2 1d2 1e2 1f2 > 2a2 2b2 2c2 2d2 2e2 2f2 > 3a2 3b2 3c2 3d2 3e2 3f2 > > How do you want the output files to look like? > I want to extract 1a1 2a1 3a1 from file 1, similarly 1a2 2a2 3a2 from file 2 ( same columns) and then make a new output file of the following format 1a1 1a2 --- 2a1 2a2 --- 3a1 3a2 --- Similarly for the 2nd, 3rd, 4th..columns in the input files. Thanks, Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Mon Feb 23 12:07:18 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 23 Feb 2009 05:07:18 -0600 Subject: [Tutor] regex help In-Reply-To: References: Message-ID: I second Alan G's appreciation for a well-thought-through and well-conveyed description of your text processing task. (Is "Alan G" his gangsta name, I wonder?) This pyparsing snippet may point you to some easier-to-follow code, especially once you go beyond the immediate task and do more exhaustive parsing of your syllable syntax. from pyparsing import * LT,GT = map(Suppress,"<>") lower = oneOf(list(alphas.lower())) H = Suppress("H") # have to look ahead to only accept lowers if NOT followed by H patt = LT + H + ZeroOrMore(lower + ~H)("body") + lower + H + GT tests = """\ a b c h a b c a b c""".splitlines() for t in tests: print t print sum((list(p.body) for p in patt.searchString(t) if p.body), []) print Prints: a b c h ['d', 'e', 'f', 'i', 'j'] a b c [] a b c ['d'] There is more info on pyparsing at http://pyparsing.wikispaces.com. -- Paul From kent37 at tds.net Mon Feb 23 12:45:23 2009 From: kent37 at tds.net (Kent Johnson) Date: Mon, 23 Feb 2009 06:45:23 -0500 Subject: [Tutor] regex help In-Reply-To: <598687.74144.qm@web45007.mail.sp1.yahoo.com> References: <598687.74144.qm@web45007.mail.sp1.yahoo.com> Message-ID: <1c2a2c590902230345o60e9ac1enc7ef5c84a7692bde@mail.gmail.com> On Sun, Feb 22, 2009 at 10:49 PM, ish_ling wrote: > I have a string: > > 'a b c h' > > I would like a regex to recursively match all alpha letters that are between . That is, I would like the following list of matches: > > ['d', 'e', 'f', 'i', 'j'] > > I do not want the 'g' or the 'k' matched. > > I have figured out how to do this in a multiple-step process, but I would like to do it in one step using only one regex (if possible). My multiple step process is first to use the regex > > '(?<=H )[a-z][^H]+(?!H)' I would use a slightly different regex, it seems more explicit to me. r'' > > with re.findall() in order to find two strings > > ['d e f ', 'i j '] > > I can then use another regex to extract the letters out of the strings. str.split() will pull out the individual strings. You can still write it as a one-liner if you want: In [1]: import re In [2]: s = 'a b c h' In [3]: regex = r'' In [5]: [m.split() for m in re.findall(regex, s)] Out[5]: [['d', 'e', 'f'], ['i', 'j']] Kent From denis.spir at free.fr Mon Feb 23 14:18:14 2009 From: denis.spir at free.fr (spir) Date: Mon, 23 Feb 2009 14:18:14 +0100 Subject: [Tutor] regex help In-Reply-To: <1c2a2c590902230345o60e9ac1enc7ef5c84a7692bde@mail.gmail.com> References: <598687.74144.qm@web45007.mail.sp1.yahoo.com> <1c2a2c590902230345o60e9ac1enc7ef5c84a7692bde@mail.gmail.com> Message-ID: <20090223141814.6853b1d2@o> Le Mon, 23 Feb 2009 06:45:23 -0500, Kent Johnson s'exprima ainsi: > On Sun, Feb 22, 2009 at 10:49 PM, ish_ling wrote: > > I have a string: > > > > 'a b c h' > > > > I would like a regex to recursively match all alpha letters that are > > between . That is, I would like the following list of > > matches: > > > > ['d', 'e', 'f', 'i', 'j'] > > > > I do not want the 'g' or the 'k' matched. > > > > I have figured out how to do this in a multiple-step process, but I would > > like to do it in one step using only one regex (if possible). My multiple > > step process is first to use the regex > > > > '(?<=H )[a-z][^H]+(?!H)' > > I would use a slightly different regex, it seems more explicit to me. > r'' You can even probably exclude leading & trailing spaces from match: r'' returns ['d e f', 'i j'] > Kent > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > ------ la vita e estrany From norman at khine.net Mon Feb 23 14:41:10 2009 From: norman at khine.net (Norman Khine) Date: Mon, 23 Feb 2009 14:41:10 +0100 Subject: [Tutor] create dictionary from csv data Message-ID: <49A2A776.5090401@khine.net> Hello, I have this csv file: $ cat licences.csv "1","Air Travel Organisation Licence (ATOL)\n Operates Inclusive Tours (IT)" "2","Air Travel Organisation Licence (ATOL)\n Appointed Agents of IATA (IATA)" "3", "Association of British Travel Agents (ABTA) No. 56542\n Air Travel Organisation Licence (ATOL)\n Appointed Agents of IATA (IATA)\n Incentive Travel & Meet. Association (ITMA)" I would like to create a set of unique values for all the memberships. i.e. ATOL IT ABTA etc.. and also I would like to extract the No. 56542 and lastly I would like to map each record to the set of unique membership values, so that: I have a dictionary like: {0: ['1', '('ATOL', 'IT')'], 1: ['2','('ATOL', 'IATA')'], 2: ['3','('ABTA', 'ATOL', 'IATA', 'ITMA')']} Here is what I have so far: >>> import csv >>> inputFile = open(str("licences.csv"), 'r') >>> outputDic = {} >>> keyIndex = 0 >>> fileReader = csv.reader(inputFile) >>> for line in fileReader: ... outputDic[keyIndex] = line ... keyIndex+=1 ... >>> print outputDic {0: ['2', 'Air Travel Organisation Licence (ATOL) Appointed Agents of IATA (IATA)'], 1: ['3', ' "Association of British Travel Agents (ABTA) No. 56542 Air Travel'], 2: ['Organisation Licence (ATOL) Appointed Agents of IATA (IATA) Incentive Travel & Meet. Association (ITMA)"']} So basically I would like to keep only the data in the brackets, i.e. (ABTA) etc.. Cheers Norman From wormwood_3 at yahoo.com Mon Feb 23 15:21:27 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 23 Feb 2009 06:21:27 -0800 (PST) Subject: [Tutor] Simple CGI script and Apache configuration References: <920149.4759.qm@web110808.mail.gq1.yahoo.com> <7b13ba330902221436t1f92e883l156b0d7b30ab9ba8@mail.gmail.com> Message-ID: <515994.77479.qm@web110807.mail.gq1.yahoo.com> Well that did seem to help, at least I get an error now:-) I changed my config to: ScriptAlias /python/ /var/www/samuelhuckins.com/python/ SetHandler mod_python PythonHandler mod_python.publisher PythonDebug On So I have the / as mentioned on ScriptAlias, and I added what seems to be the lines suggested in all the tutorials I came across. Now when you hit http://trac.samuelhuckins.com/python/hello.py, you get: Environment not foundWhen I hit the script on the command line, I get back what I think should display fine: ./hello.py Content-type: text/html
Hello!
I don't see anything in the Apache error logs. Any ideas? -Sam _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins ________________________________ From: Moos Heintzen To: wormwood_3 Sent: Sunday, February 22, 2009 5:36:32 PM Subject: Re: [Tutor] Simple CGI script and Apache configuration Just noticed that ScriptAlias /python/ "/var/www/samuelhuckins.com/python" doesn't have a slash at the end. Could that be it? -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Mon Feb 23 16:31:44 2009 From: denis.spir at free.fr (spir) Date: Mon, 23 Feb 2009 16:31:44 +0100 Subject: [Tutor] create dictionary from csv data In-Reply-To: <49A2A776.5090401@khine.net> References: <49A2A776.5090401@khine.net> Message-ID: <20090223163144.271dc8ad@o> Le Mon, 23 Feb 2009 14:41:10 +0100, Norman Khine s'exprima ainsi: > Hello, > > I have this csv file: > > $ cat licences.csv > "1","Air Travel Organisation Licence (ATOL)\n Operates Inclusive Tours (IT)" > "2","Air Travel Organisation Licence (ATOL)\n Appointed Agents of IATA > (IATA)" > "3", "Association of British Travel Agents (ABTA) No. 56542\n Air Travel > Organisation Licence (ATOL)\n Appointed Agents of IATA (IATA)\n > Incentive Travel & Meet. Association (ITMA)" I have the impression that the CSV module is here helpless. Yes, it parses the data, but you need only a subset of it that may be harder to extract. I would do the following (all untested): -0- Read in the file as a single string. > I would like to create a set of unique values for all the memberships. i.e. > > ATOL > IT > ABTA > etc.. -1- Use re.findall with a pattern like r'\((\w+)\)' to get the company codes, then built a set out of the result list > and also I would like to extract the No. 56542 -2- idem, with r'No. (\d+)' (maybe set is not necessary) > and lastly I would like to map each record to the set of unique > membership values, so that: > > I have a dictionary like: > > {0: ['1', '('ATOL', 'IT')'], > 1: ['2','('ATOL', 'IATA')'], > 2: ['3','('ABTA', 'ATOL', 'IATA', 'ITMA')']} (The dict looks strange...) -3- Now "splitlines" the string, and on each line * read ordinal number (maybe useless actually) * read again the codes I dont know what your dict is worthful for, as the keys are simple ordinals. It's a masked list, actually. Unless you want instead {['1':['ATOL', 'IT'], '2':['ATOL', 'IATA'], '3':['ABTA', 'ATOL', 'IATA', 'ITMA']} But here the keys are still predictable ordinals. denis ------ la vita e estrany > Here is what I have so far: > > >>> import csv > >>> inputFile = open(str("licences.csv"), 'r') > >>> outputDic = {} > >>> keyIndex = 0 > >>> fileReader = csv.reader(inputFile) > >>> for line in fileReader: > ... outputDic[keyIndex] = line > ... keyIndex+=1 > ... > >>> print outputDic > {0: ['2', 'Air Travel Organisation Licence (ATOL) Appointed Agents of > IATA (IATA)'], 1: ['3', ' "Association of British Travel Agents (ABTA) > No. 56542 Air Travel'], 2: ['Organisation Licence (ATOL) Appointed > Agents of IATA (IATA) Incentive Travel & Meet. Association (ITMA)"']} > > So basically I would like to keep only the data in the brackets, i.e. > (ABTA) etc.. > > Cheers > > Norman > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Mon Feb 23 20:27:49 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Mon, 23 Feb 2009 19:27:49 +0000 (GMT) Subject: [Tutor] Looking for ConfigObj Documentation Message-ID: <377595.13279.qm@web86711.mail.ird.yahoo.com> > Under Start there's a ? icon that says Help and Support. Minimal info. Yes, although by exploring the links and using the Microsoft Knowledgebase panel on the left you do get more than I remembered. I just think the DOS HELP command is easier to use. However I did find a good overview on Technet: http://technet.microsoft.com/en-us/library/bb490954.aspx Which has a lot of other stuff on cmd.exe too. > It seems to me that the Command Prompt window is important enough > in the use of Python to warrant a full page somewhere to its applicability. I might try to do that sometime. But its not really Python specific, if you are doing any serious programming or admin work on a PC you really should be familiar with the cmd window, its often the fastest and easiest way to do stuff. And learning the little tricks and settings that make it more productive is definitely worthwhile. Alan G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Mon Feb 23 20:31:40 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 23 Feb 2009 19:31:40 -0000 Subject: [Tutor] extracting a column from many files References: <288df32a0902190241u65182efckc99d3f27141c556d@mail.gmail.com><7b13ba330902221317l5b9fb063rc3999500250cf898@mail.gmail.com><7b13ba330902221358t99baf20r245e37f211c74396@mail.gmail.com> <288df32a0902230135rb68955cicebdb740b8cec66f@mail.gmail.com> Message-ID: "Bala subramanian" wrote > I want to extract 1a1 2a1 3a1 from file 1, similarly 1a2 2a2 3a2 > from file > 2 ( same columns) and then make a new output file of the following > format > > 1a1 1a2 --- > 2a1 2a2 --- > 3a1 3a2 --- > > Similarly for the 2nd, 3rd, 4th..columns in the input files. OK, So you want separate output files per column? And each file contains the same column from each of the input files? So output1.txt contains all of the column 1 data output2.txt contains all of the column 2 data and so on? Alan G From iwasroot at gmail.com Tue Feb 24 00:46:07 2009 From: iwasroot at gmail.com (Moos Heintzen) Date: Mon, 23 Feb 2009 15:46:07 -0800 Subject: [Tutor] extracting a column from many files In-Reply-To: <7b13ba330902231048j72d5efe7m8dc9b85573564da2@mail.gmail.com> References: <288df32a0902190241u65182efckc99d3f27141c556d@mail.gmail.com> <7b13ba330902221317l5b9fb063rc3999500250cf898@mail.gmail.com> <7b13ba330902221358t99baf20r245e37f211c74396@mail.gmail.com> <288df32a0902230135rb68955cicebdb740b8cec66f@mail.gmail.com> <7b13ba330902231048j72d5efe7m8dc9b85573564da2@mail.gmail.com> Message-ID: <7b13ba330902231546h41af5c9ayf81f197075f6a319@mail.gmail.com> Here's a simple repositioning code given that you already have the fields extracted. All files have to have equal dimensions. file1 = [["1a1", "1b1", "1c1",], ["2a1", "2b1", "2c1"],] file2 = [["1a2", "1b2", "1c2",], ["2a2", "2b2", "2c2"],] files = [file1, file2] out_lines = [] for column in range(len(files[0][0])): for fileno in range(len(files)): out_lines.append([]) for row in range(len(files[0])): out_lines[-1].append(files[fileno][row][column]) # write out_lines to file "file%s" % column print out_lines out_lines = [] No offense, but your extracting code looks a bit inflexible. It has a lot of magic numbers, and most of it is hardcoded. From mwalsh at mwalsh.org Tue Feb 24 06:33:35 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Mon, 23 Feb 2009 23:33:35 -0600 Subject: [Tutor] Simple CGI script and Apache configuration In-Reply-To: <920149.4759.qm@web110808.mail.gq1.yahoo.com> References: <920149.4759.qm@web110808.mail.gq1.yahoo.com> Message-ID: <49A386AF.8040501@mwalsh.org> wormwood_3 wrote: > Hello all, Hi Sam, > I'll try to give as much detail as I can, but this is a somewhat vague > problem. I have a very simple script that I would like to implement as a > CGI script, just so I can hit a URL and get some output. However, after > following a number of tutorials, I am still seeing some very odd > results. I am almost sure it's in my Apache configuration, but I figured > a few people on this list would likely know what the minimal related > Apache config should be. (The Apache docs are pretty daunting...) > > Local version wise, I am on Ubuntu 8.10, with Apache 2.2.9 and Python > 2.5.2. I have libapache2-mod-python installed. Apache config is out of > the box, along with: > > ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" You need more than this to make apache cgi work, I think. Firstly, mod_cgi should be loaded -- look for a symlink named cgi.load or some such, in /etc/apache2/mods-enabled. Run 'a2enmod cgi' if you don't have one. Secondly, ExecCGI is usually enabled using the Options directive within a Directory definition -- but, less commonly, you might see something like 'AddHandler cgi-program .py' in an apache or site config. Of course, the script needs to be executable by the apache user (which would be 'www-data' on ubuntu, IIRC), and contain an appropriate shebang (#!) on the first line -- but it sounds like you have that covered. Both 'Options ExecCGI' and 'Addhandler cgi-program .py' are allowed in .htaccess also, given an appropriate AllowOverride directive for the path in question. Something to look for on the working system, if all else fails. You do *not* need mod python to run python cgi scripts. > In /var/www/cgi-bin, I have hello.py : > > #!/usr/bin/python > import cgitb > cgitb.enable() > > print "Content-type: text/html" > print > print "" > print "
Hello!
" > print "" > > Reload, hit http://localhost/cgi-bin/hello.py in a browser, I get > centered text just fine. Now I want to do this same process on my remote > webserver. On there, I am on Ubuntu 7.10, with Apache 2.2.4 and Python > 2.5.1. I add: > > ScriptAlias /python/ "/var/www/samuelhuckins.com/python" You can try appending something like this (untested): AllowOverride None Options ExecCGI # or, Options +ExecCGI to merge # with options from parent dir(s) Order allow,deny Allow from all > > Reload, hit http://samuelhuckins.com/python/hello.py, and I get a 404? > The perms and ownership on the file is the same as in other directories. > Do I need to add some sort of handler, with mod_python.publisher? I > think I am just missing one of the basics of this whole process. Hmmm, interesting. It's unlikely that any of my advice will help you with a 404. With an incomplete apache cgi config, the response I'd expect would be either a 403 (Forbidden), or the script itself in plain text. Do the logs provide any additional information? Re-check your spelling. A 404 with vanilla apache config might just indicate a typo. When you say 'Reload', I assume you mean the apache daemon (ie. /etc/init.d/apache2 reload or apache2ctl reload)? Again, you do *not* need mod python to run python cgi scripts. HTH, Marty From wormwood_3 at yahoo.com Tue Feb 24 07:14:24 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Mon, 23 Feb 2009 22:14:24 -0800 (PST) Subject: [Tutor] Simple CGI script and Apache configuration References: <920149.4759.qm@web110808.mail.gq1.yahoo.com> <49A386AF.8040501@mwalsh.org> Message-ID: <691471.62310.qm@web110807.mail.gq1.yahoo.com> Thanks for all the suggestions! I tried to go through them, and will relate what results I encountered. I changed my Apache config to: AllowOverride None Options ExecCGI Order allow,deny Allow from all I in fact did not have the cgi module enabled, so I did that. Then I ran "sudo /etc/init.d/apache2 reload", and hit http://samuelhuckins.com/cgi-bin/hello.py, which contains simply: #!/usr/bin/python print "Content-type: text/html" print print "" print "
Hello!
" print "" I get prompted to download the file, but it does not execute or appear in plain text. The logs just show the request being made. What is the missing element to get this script to execute? Thanks, Sam ________________________________ From: Martin Walsh To: Python Tutorlist Sent: Tuesday, February 24, 2009 12:33:35 AM Subject: Re: [Tutor] Simple CGI script and Apache configuration wormwood_3 wrote: > Hello all, Hi Sam, > I'll try to give as much detail as I can, but this is a somewhat vague > problem. I have a very simple script that I would like to implement as a > CGI script, just so I can hit a URL and get some output. However, after > following a number of tutorials, I am still seeing some very odd > results. I am almost sure it's in my Apache configuration, but I figured > a few people on this list would likely know what the minimal related > Apache config should be. (The Apache docs are pretty daunting...) > > Local version wise, I am on Ubuntu 8.10, with Apache 2.2.9 and Python > 2.5.2. I have libapache2-mod-python installed. Apache config is out of > the box, along with: > > ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" You need more than this to make apache cgi work, I think. Firstly, mod_cgi should be loaded -- look for a symlink named cgi.load or some such, in /etc/apache2/mods-enabled. Run 'a2enmod cgi' if you don't have one. Secondly, ExecCGI is usually enabled using the Options directive within a Directory definition -- but, less commonly, you might see something like 'AddHandler cgi-program .py' in an apache or site config. Of course, the script needs to be executable by the apache user (which would be 'www-data' on ubuntu, IIRC), and contain an appropriate shebang (#!) on the first line -- but it sounds like you have that covered. Both 'Options ExecCGI' and 'Addhandler cgi-program .py' are allowed in .htaccess also, given an appropriate AllowOverride directive for the path in question. Something to look for on the working system, if all else fails. You do *not* need mod python to run python cgi scripts. > In /var/www/cgi-bin, I have hello.py : > > #!/usr/bin/python > import cgitb > cgitb.enable() > > print "Content-type: text/html" > print > print "" > print "
Hello!
" > print "" > > Reload, hit http://localhost/cgi-bin/hello.py in a browser, I get > centered text just fine. Now I want to do this same process on my remote > webserver. On there, I am on Ubuntu 7.10, with Apache 2.2.4 and Python > 2.5.1. I add: > > ScriptAlias /python/ "/var/www/samuelhuckins.com/python" You can try appending something like this (untested): AllowOverride None Options ExecCGI # or, Options +ExecCGI to merge # with options from parent dir(s) Order allow,deny Allow from all > > Reload, hit http://samuelhuckins.com/python/hello.py, and I get a 404? > The perms and ownership on the file is the same as in other directories. > Do I need to add some sort of handler, with mod_python.publisher? I > think I am just missing one of the basics of this whole process. Hmmm, interesting. It's unlikely that any of my advice will help you with a 404. With an incomplete apache cgi config, the response I'd expect would be either a 403 (Forbidden), or the script itself in plain text. Do the logs provide any additional information? Re-check your spelling. A 404 with vanilla apache config might just indicate a typo. When you say 'Reload', I assume you mean the apache daemon (ie. /etc/init.d/apache2 reload or apache2ctl reload)? Again, you do *not* need mod python to run python cgi scripts. HTH, Marty _______________________________________________ Tutor maillist - Tutor at python.org http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwalsh at mwalsh.org Tue Feb 24 08:32:48 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Tue, 24 Feb 2009 01:32:48 -0600 Subject: [Tutor] Simple CGI script and Apache configuration In-Reply-To: <691471.62310.qm@web110807.mail.gq1.yahoo.com> References: <920149.4759.qm@web110808.mail.gq1.yahoo.com> <49A386AF.8040501@mwalsh.org> <691471.62310.qm@web110807.mail.gq1.yahoo.com> Message-ID: <49A3A2A0.3050602@mwalsh.org> wormwood_3 wrote: > Thanks for all the suggestions! I tried to go through them, and will > relate what results I encountered. I changed my Apache config to: > > > AllowOverride None > Options ExecCGI > Order allow,deny > Allow from all > > > I in fact did not have the cgi module enabled, so I did that. Then I ran > "sudo /etc/init.d/apache2 reload", and hit > http://samuelhuckins.com/cgi-bin/hello.py, which contains simply: > > #!/usr/bin/python > print "Content-type: text/html" > print > print "" > print "
Hello!
" > print "" > > I get prompted to download the file, but it does not execute or appear > in plain text. The logs just show the request being made. What is the > missing element to get this script to execute? > When you look at the downloaded file, is it your python script? Looks like you changed the path where you're keeping your cgi script, did you update the ScriptAlias directive to suit? You may find this more helpful ... http://httpd.apache.org/docs/2.0/howto/cgi.html HTH, Marty From norman at khine.net Tue Feb 24 12:48:51 2009 From: norman at khine.net (Norman Khine) Date: Tue, 24 Feb 2009 12:48:51 +0100 Subject: [Tutor] using re to build dictionary Message-ID: <49A3DEA3.30707@khine.net> Hello, From my previous post on create dictionary from csv, i have broken the problem further and wanted the lists feedback if it could be done better: >>> s = 'Association of British Travel Agents (ABTA) No. 56542\nAir Travel Organisation Licence (ATOL)\nAppointed Agents of IATA (IATA)\nIncentive Travel & Meet. Association (ITMA)' >>> licences = re.split("\n+", s) >>> licence_list = [re.split("\((\w+)\)", licence) for licence in licences] >>> association = [] >>> for x in licence_list: ... for y in x: ... if y.isupper(): ... association.append(y) ... >>> association ['ABTA', 'ATOL', 'IATA', 'ITMA'] In my string 's', I have 'No. 56542', how would I extract the '56542' and map it against the 'ABTA' so that I can have a dictionary for example: >>> my_dictionary = {'ABTA': '56542', 'ATOL': '', 'IATA': '', 'ITMA': ''} >>> Here is what I have so far: >>> my_dictionary = {} >>> for x in licence_list: ... for y in x: ... if y.isupper(): ... my_dictionary[y] = y ... >>> my_dictionary {'ABTA': 'ABTA', 'IATA': 'IATA', 'ITMA': 'ITMA', 'ATOL': 'ATOL'} This is wrong as the values should be the 'decimal' i.e. 56542 that is in the licence_list. here is where I miss the point as in my licence_list, not all items have a code, all but one are empty, for my usecase, I still need to create the dictionary so that it is in the form: >>> my_dictionary = {'ABTA': '56542', 'ATOL': '', 'IATA': '', 'ITMA': ''} Any advise much appreciated. Norman From wormwood_3 at yahoo.com Tue Feb 24 13:28:41 2009 From: wormwood_3 at yahoo.com (wormwood_3) Date: Tue, 24 Feb 2009 04:28:41 -0800 (PST) Subject: [Tutor] Simple CGI script and Apache configuration References: <920149.4759.qm@web110808.mail.gq1.yahoo.com> <49A386AF.8040501@mwalsh.org> <691471.62310.qm@web110807.mail.gq1.yahoo.com> <49A3A2A0.3050602@mwalsh.org> Message-ID: <921091.61735.qm@web110812.mail.gq1.yahoo.com> I wasn't sure if that was needed, so I took it out, sorry about that. I put ScriptAlias /cgi-bin/ "/var/www/samuelhuckins.com/cgi-bin/" in place, reloaded, and it works! I think the problem throughout was that I was mixing up what was necessary between CGI and mod_python. If you'd like a random programming epigram served up by this new config, check out: http://samuelhuckins.com/cgi-bin/qotd.py -Sam _______________________ Samuel Huckins Homepage - http://samuelhuckins.com Tech blog - http://dancingpenguinsoflight.com/ Photos - http://www.flickr.com/photos/samuelhuckins/ AIM - samushack | Gtalk - samushack | Skype - shuckins ________________________________ From: Martin Walsh To: wormwood_3 Cc: Python Tutorlist Sent: Tuesday, February 24, 2009 2:32:48 AM Subject: Re: [Tutor] Simple CGI script and Apache configuration wormwood_3 wrote: > Thanks for all the suggestions! I tried to go through them, and will > relate what results I encountered. I changed my Apache config to: > > > AllowOverride None > Options ExecCGI > Order allow,deny > Allow from all > > > I in fact did not have the cgi module enabled, so I did that. Then I ran > "sudo /etc/init.d/apache2 reload", and hit > http://samuelhuckins.com/cgi-bin/hello.py, which contains simply: > > #!/usr/bin/python > print "Content-type: text/html" > print > print "" > print "
Hello!
" > print "" > > I get prompted to download the file, but it does not execute or appear > in plain text. The logs just show the request being made. What is the > missing element to get this script to execute? > When you look at the downloaded file, is it your python script? Looks like you changed the path where you're keeping your cgi script, did you update the ScriptAlias directive to suit? You may find this more helpful ... http://httpd.apache.org/docs/2.0/howto/cgi.html HTH, Marty -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Tue Feb 24 13:40:06 2009 From: denis.spir at free.fr (spir) Date: Tue, 24 Feb 2009 13:40:06 +0100 Subject: [Tutor] using re to build dictionary In-Reply-To: <49A3DEA3.30707@khine.net> References: <49A3DEA3.30707@khine.net> Message-ID: <20090224134006.5090b842@o> Le Tue, 24 Feb 2009 12:48:51 +0100, Norman Khine s'exprima ainsi: > Hello, > From my previous post on create dictionary from csv, i have broken the > problem further and wanted the lists feedback if it could be done better: > > >>> s = 'Association of British Travel Agents (ABTA) No. 56542\nAir > Travel Organisation Licence (ATOL)\nAppointed Agents of IATA > (IATA)\nIncentive Travel & Meet. Association (ITMA)' > >>> licences = re.split("\n+", s) > >>> licence_list = [re.split("\((\w+)\)", licence) for licence in licences] > >>> association = [] > >>> for x in licence_list: > ... for y in x: > ... if y.isupper(): > ... association.append(y) > ... > >>> association > ['ABTA', 'ATOL', 'IATA', 'ITMA'] > > > In my string 's', I have 'No. 56542', how would I extract the '56542' > and map it against the 'ABTA' so that I can have a dictionary for example: > > >>> my_dictionary = {'ABTA': '56542', 'ATOL': '', 'IATA': '', 'ITMA': ''} > >>> > > > Here is what I have so far: > > >>> my_dictionary = {} > > >>> for x in licence_list: > ... for y in x: > ... if y.isupper(): > ... my_dictionary[y] = y > ... > >>> my_dictionary > {'ABTA': 'ABTA', 'IATA': 'IATA', 'ITMA': 'ITMA', 'ATOL': 'ATOL'} > > This is wrong as the values should be the 'decimal' i.e. 56542 that is > in the licence_list. > > here is where I miss the point as in my licence_list, not all items have > a code, all but one are empty, for my usecase, I still need to create > the dictionary so that it is in the form: > > >>> my_dictionary = {'ABTA': '56542', 'ATOL': '', 'IATA': '', 'ITMA': ''} > > Any advise much appreciated. > > Norman I had a similar problem once. The nice solution was -- I think, don't take this for granted I have no time to verify -- simply using multiple group with re.findall again. Build a rule like: r'.+(code-pattern).+(number_pattern).+\n+' Then the results will be a list of tuples like [ (code1, n1), (code2, n2), ... ] where some numbers will be missing. from this it's straightforward to instantiate a dict, maybe using a default None value for n/a numbers. Someone will probably infirm or confirm this method. denis ------ la vita e estrany From kent37 at tds.net Tue Feb 24 13:41:11 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Feb 2009 07:41:11 -0500 Subject: [Tutor] using re to build dictionary In-Reply-To: <49A3DEA3.30707@khine.net> References: <49A3DEA3.30707@khine.net> Message-ID: <1c2a2c590902240441g525d1d5bp12a877cdc9e525b5@mail.gmail.com> On Tue, Feb 24, 2009 at 6:48 AM, Norman Khine wrote: > Hello, > From my previous post on create dictionary from csv, i have broken the > problem further and wanted the lists feedback if it could be done better: > >>>> s = 'Association of British Travel Agents (ABTA) No. 56542\nAir Travel >>>> Organisation Licence (ATOL)\nAppointed Agents of IATA (IATA)\nIncentive >>>> Travel & Meet. Association (ITMA)' >>>> licences = re.split("\n+", s) >>>> licence_list = [re.split("\((\w+)\)", licence) for licence in licences] This is awkward. You can match directly on what you want: In [7]: import re In [8]: s = 'Association of British Travel Agents (ABTA) No. 56542\nAir Travel Organisation Licence (ATOL)\nAppointed Agents of IATA (IATA)\nIncentive Travel & Meet. Association (ITMA)' In [9]: licenses = re.split("\n+", s) In [10]: licenseRe = re.compile(r'\(([A-Z]+)\)( No. (\d+))?') In [11]: for license in licenses: ....: m = licenseRe.search(license) ....: print m.group(1, 3) ('ABTA', '56542') ('ATOL', None) ('IATA', None) ('ITMA', None) Kent From norman at khine.net Tue Feb 24 14:56:19 2009 From: norman at khine.net (Norman Khine) Date: Tue, 24 Feb 2009 14:56:19 +0100 Subject: [Tutor] using re to build dictionary In-Reply-To: <1c2a2c590902240441g525d1d5bp12a877cdc9e525b5@mail.gmail.com> References: <49A3DEA3.30707@khine.net> <1c2a2c590902240441g525d1d5bp12a877cdc9e525b5@mail.gmail.com> Message-ID: <49A3FC83.2090404@khine.net> Thank you all, this is great. Kent Johnson wrote: > On Tue, Feb 24, 2009 at 6:48 AM, Norman Khine wrote: >> Hello, >> From my previous post on create dictionary from csv, i have broken the >> problem further and wanted the lists feedback if it could be done better: >> >>>>> s = 'Association of British Travel Agents (ABTA) No. 56542\nAir Travel >>>>> Organisation Licence (ATOL)\nAppointed Agents of IATA (IATA)\nIncentive >>>>> Travel & Meet. Association (ITMA)' >>>>> licences = re.split("\n+", s) >>>>> licence_list = [re.split("\((\w+)\)", licence) for licence in licences] > > This is awkward. You can match directly on what you want: > > In [7]: import re > > In [8]: s = 'Association of British Travel Agents (ABTA) No. > 56542\nAir Travel Organisation Licence (ATOL)\nAppointed Agents of > IATA (IATA)\nIncentive Travel & Meet. Association (ITMA)' > > In [9]: licenses = re.split("\n+", s) > > In [10]: licenseRe = re.compile(r'\(([A-Z]+)\)( No. (\d+))?') > > In [11]: for license in licenses: > ....: m = licenseRe.search(license) > ....: print m.group(1, 3) > > ('ABTA', '56542') > ('ATOL', None) > ('IATA', None) > ('ITMA', None) > > Kent > From taylankaraman at gmail.com Tue Feb 24 16:16:00 2009 From: taylankaraman at gmail.com (Taylan Karaman) Date: Tue, 24 Feb 2009 17:16:00 +0200 Subject: [Tutor] String to list conversion Message-ID: <9b8e52190902240716n1eab1026j48deee4a35952535@mail.gmail.com> Hello, I am a beginner. And I am trying to get a user input converted to a list. print 'Enter your first name :' firstname = raw_input() So if the user input is firstname = 'foo' ----------->should become--------> firstlist['f','o','o'] thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Tue Feb 24 16:21:38 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Tue, 24 Feb 2009 10:21:38 -0500 Subject: [Tutor] String to list conversion In-Reply-To: <9b8e52190902240716n1eab1026j48deee4a35952535@mail.gmail.com> References: <9b8e52190902240716n1eab1026j48deee4a35952535@mail.gmail.com> Message-ID: <652641e90902240721x4c17c897v73aa404ed2c0e3b0@mail.gmail.com> On Tue, Feb 24, 2009 at 10:16 AM, Taylan Karaman wrote: > Hello, > > I am a beginner. And I am trying to get a user input converted to a list. > > print 'Enter your first name :' > firstname = raw_input() > > So if the user input is > > firstname = 'foo' ----------->should become--------> > firstlist['f','o','o'] > > > thanks in advance > if I understand this correctly, you want a name like "foo" to be changed to ['f', 'o','o'] This is what the list function does. for example, >>> name = "foo" >>> list(name) ['f', 'o', 'o'] >>> > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington http://emnawfal.googlepages.com -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Tue Feb 24 16:33:44 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Feb 2009 10:33:44 -0500 Subject: [Tutor] String to list conversion In-Reply-To: <9b8e52190902240716n1eab1026j48deee4a35952535@mail.gmail.com> References: <9b8e52190902240716n1eab1026j48deee4a35952535@mail.gmail.com> Message-ID: <1c2a2c590902240733l5b385cf1k7676311cc7fba621@mail.gmail.com> On Tue, Feb 24, 2009 at 10:16 AM, Taylan Karaman wrote: > Hello, > > I am a beginner. And I am trying to get a user input converted to a list. > > print 'Enter your first name :' > firstname = raw_input() > > So if the user input is > > firstname = 'foo'??? ----------->should become--------> > firstlist['f','o','o'] Strings behave as sequences of characters, so you can just do firstname = 'foo' firstlist = list(firstname) If you just want to iterate over the letters, there is no need to create a separate list, you can iterate over the string directly, e.g. for letter in firstname: print letter Kent From mwalsh at mwalsh.org Tue Feb 24 19:13:32 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Tue, 24 Feb 2009 12:13:32 -0600 Subject: [Tutor] Simple CGI script and Apache configuration In-Reply-To: <921091.61735.qm@web110812.mail.gq1.yahoo.com> References: <920149.4759.qm@web110808.mail.gq1.yahoo.com> <49A386AF.8040501@mwalsh.org> <691471.62310.qm@web110807.mail.gq1.yahoo.com> <49A3A2A0.3050602@mwalsh.org> <921091.61735.qm@web110812.mail.gq1.yahoo.com> Message-ID: <49A438CC.6050909@mwalsh.org> wormwood_3 wrote: > I wasn't sure if that was needed, so I took it out, sorry about that. I put > > ScriptAlias /cgi-bin/ "/var/www/samuelhuckins.com/cgi-bin/" > > in place, reloaded, and it works! I think the problem throughout was > that I was mixing up what was necessary between CGI and mod_python. The apache2 documentation isn't clear about the relationship between ExecCGI and ScriptAlias (rather, it's not clear to me) and unless I've missed something, seems to imply that either ScriptAlias or ExecCGI alone should be sufficient. Unfortunately, I don't have time to experiment. IIRC, all of the vanilla apache configs I've worked with recently include both in definitions for cgi-bin. In any case, glad it worked. > > If you'd like a random programming epigram served up by this new config, > check out: http://samuelhuckins.com/cgi-bin/qotd.py Very cool, thanks. > > -Sam > wormwood_3 wrote: >> Thanks for all the suggestions! I tried to go through them, and will >> relate what results I encountered. I changed my Apache config to: >> >> >> AllowOverride None >> Options ExecCGI >> Order allow,deny >> Allow from all >> >> >> I in fact did not have the cgi module enabled, so I did that. Then I ran >> "sudo /etc/init.d/apache2 reload", and hit >> http://samuelhuckins.com/cgi-bin/hello.py, which contains simply: >> >> #!/usr/bin/python >> print "Content-type: text/html" >> print >> print "" >> print "
Hello!
" >> print "" >> >> I get prompted to download the file, but it does not execute or appear >> in plain text. The logs just show the request being made. What is the >> missing element to get this script to execute? >> > > When you look at the downloaded file, is it your python script? > > Looks like you changed the path where you're keeping your cgi script, > did you update the ScriptAlias directive to suit? > > You may find this more helpful ... > http://httpd.apache.org/docs/2.0/howto/cgi.html > From bermanrl at cfl.rr.com Tue Feb 24 19:14:13 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Tue, 24 Feb 2009 13:14:13 -0500 Subject: [Tutor] String to list conversion In-Reply-To: <1c2a2c590902240733l5b385cf1k7676311cc7fba621@mail.gmail.com> References: <9b8e52190902240716n1eab1026j48deee4a35952535@mail.gmail.com> <1c2a2c590902240733l5b385cf1k7676311cc7fba621@mail.gmail.com> Message-ID: <49A438F5.8080202@cfl.rr.com> An HTML attachment was scrubbed... URL: From mobiledreamers at gmail.com Tue Feb 24 19:53:29 2009 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Tue, 24 Feb 2009 10:53:29 -0800 Subject: [Tutor] Accessing callers context from callee method Message-ID: when i call a method foo from another method func. can i access func context variables or locals() from foo so def func(): i=10 foo() in foo, can i access func's local variables on in this case i Thanks a lot -- Bidegg worlds best auction site http://bidegg.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From sdragon1984 at gmail.com Tue Feb 24 20:03:09 2009 From: sdragon1984 at gmail.com (nathan virgil) Date: Tue, 24 Feb 2009 14:03:09 -0500 Subject: [Tutor] Passing perimeters in dictionary values? Message-ID: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> I'm experimenting with OOP using the Critter Caretaker script from Python Programming for the Absolute Beginner as my basis. I've noticed that a dictionary/function combo is a great way to handle menus, and so I've adapted the menu to read as: selection = raw_input("Choice: ") choices = {"0":quit, "1":crit.talk, "2":crit.eat, "3":crit.play} choice = choices[selection] choice() so that I can call methods from a dictionary, instead of having an excruciatingly long if structure. Unfortunately, the problem I'm running into with this is that I can't pass any perimeters through the dictionary. I can't figure out how, for example, I could have an option that calls crit.eat(2) and another that calls crit.eat(4). The only thing I can think of is going back to the if structure, but my instinct tells me that this is a Bad Idea. What can I do? -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Tue Feb 24 20:15:50 2009 From: denis.spir at free.fr (spir) Date: Tue, 24 Feb 2009 20:15:50 +0100 Subject: [Tutor] Accessing callers context from callee method In-Reply-To: References: Message-ID: <20090224201550.7083a572@o> Le Tue, 24 Feb 2009 10:53:29 -0800, mobiledreamers at gmail.com s'exprima ainsi: > when i call a method foo from another method func. can i access func context > variables or locals() from foo > so > def func(): > i=10 > foo() > > in foo, can i access func's local variables on in this case i > Thanks a lot def func(): i=10 foo(i) ------ la vita e estrany From justin.mailinglists at gmail.com Tue Feb 24 20:25:59 2009 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Wed, 25 Feb 2009 03:25:59 +0800 Subject: [Tutor] Passing parameters in dictionary values? Message-ID: <3c6718980902241125q409abfc7gef694b4ab4189af1@mail.gmail.com> From: nathan virgil > selection = raw_input("Choice: ") > choices = {"0":quit, "1":crit.talk, "2":crit.eat, "3":crit.play} > choice = choices[selection] > choice() > > ...so that I can call methods from a dictionary > the problem I'm running into with this is that > I can't pass any perimeters through the dictionary. > What can I do? choices = {'a': lambda: crit.eat(2), 'b': lambda: crit.eat(4), ...} choice = choices[selection] choice() http://www.diveintopython.org/power_of_introspection/lambda_functions.html From clp2 at rebertia.com Tue Feb 24 19:56:36 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 24 Feb 2009 10:56:36 -0800 Subject: [Tutor] Accessing callers context from callee method In-Reply-To: References: Message-ID: <50697b2c0902241056h14e92b8cu3ea2270d3c1b5bd3@mail.gmail.com> On Tue, Feb 24, 2009 at 10:53 AM, wrote: > when i call a method foo from another method func.?can i access func context > variables or locals() from foo > so > def func(): > ??i=10 > ??foo() > > in foo, can i access func's local variables on in this case i You can, but it's an evil hack that I would avoid if at all possible; there are almost certainly better ways to accomplish whatever your goal is. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com From denis.spir at free.fr Tue Feb 24 20:35:24 2009 From: denis.spir at free.fr (spir) Date: Tue, 24 Feb 2009 20:35:24 +0100 Subject: [Tutor] Passing perimeters in dictionary values? In-Reply-To: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> Message-ID: <20090224203524.55dbef2f@o> Le Tue, 24 Feb 2009 14:03:09 -0500, nathan virgil s'exprima ainsi: > I'm experimenting with OOP using the Critter Caretaker script from Python > Programming for the Absolute Beginner as my basis. I've noticed that a > dictionary/function combo is a great way to handle menus, and so I've > adapted the menu to read as: > > > selection = raw_input("Choice: ") > choices = {"0":quit, "1":crit.talk, "2":crit.eat, "3":crit.play} > choice = choices[selection] > choice() This is (to my taste) very good programming practice. The only detail is that in this precise case, as keys are ordinals starting at 0, you can use a simple list instead ;-) and choice = choices[int(selection)] > so that I can call methods from a dictionary, instead of having an > excruciatingly long if structure. Unfortunately, the problem I'm running > into with this is that I can't pass any perimeters through the dictionary. I > can't figure out how, for example, I could have an option that calls > crit.eat(2) and another that calls crit.eat(4). The only thing I can think > of is going back to the if structure, but my instinct tells me that this is > a Bad Idea. What can I do? There is a syntactic trick for this, commonly called *args. You can call a function and pass it a variable holding a 'pack' of arguments prefixed with '*' so that the args will be automagically unpacked into the call message. Below an example: def sum(a,b): return a+b arg_list = (1,2) func_calls = {1:sum(*arg_list)} print func_calls[1] ==> 3 Like if I had written sum(1,2) -- except that the arg_list can now be unknown at design time! Conversely, when you want a function to accept an arbitrary number of args, you can write its def using the * trick: def sum(*values): s = 0 for v in values : s+= v return s print sum(1), sum(1,2), sum(1,2,3) ==> 1, 3, 6 There is a similar trick for named arguments using ** denis ------ la vita e estrany From kent37 at tds.net Tue Feb 24 20:42:39 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Feb 2009 14:42:39 -0500 Subject: [Tutor] Passing perimeters in dictionary values? In-Reply-To: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> Message-ID: <1c2a2c590902241142h342a8355mab72b1c3f883d7c6@mail.gmail.com> On Tue, Feb 24, 2009 at 2:03 PM, nathan virgil wrote: > I'm experimenting with OOP using the Critter Caretaker script from Python > Programming for the Absolute Beginner as my basis. I've noticed that a > dictionary/function combo is a great way to handle menus, and so I've > adapted the menu to read as: > > > selection = raw_input("Choice: ") > choices = {"0":quit, "1":crit.talk, "2":crit.eat, "3":crit.play} > choice = choices[selection] > choice() > > so that I can call methods from a dictionary, instead of having an > excruciatingly long if structure. Unfortunately, the problem I'm running > into with this is that I can't pass any perimeters through the dictionary. I > can't figure out how, for example, I could have an option that calls > crit.eat(2) and another that calls crit.eat(4). The only thing I can think > of is going back to the if structure, but my instinct tells me that this is > a Bad Idea. What can I do? You can define a function that does what you want: def eat2(): crit.eat(2) Then put eat2 in your dictionary: choices = { '2': eat2, ...} Alternately you can use lambda expressions to do the same thing without an explicit def: choices = { '2': lambda: crit.eat(2), ... } Kent From kent37 at tds.net Tue Feb 24 20:45:02 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Feb 2009 14:45:02 -0500 Subject: [Tutor] Passing perimeters in dictionary values? In-Reply-To: <20090224203524.55dbef2f@o> References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> <20090224203524.55dbef2f@o> Message-ID: <1c2a2c590902241145i8a5527fq6e6cbef59e820cc5@mail.gmail.com> On Tue, Feb 24, 2009 at 2:35 PM, spir wrote: > Le Tue, 24 Feb 2009 14:03:09 -0500, > nathan virgil s'exprima ainsi: >> so that I can call methods from a dictionary, instead of having an >> excruciatingly long if structure. Unfortunately, the problem I'm running >> into with this is that I can't pass any perimeters through the dictionary. I >> can't figure out how, for example, I could have an option that calls >> crit.eat(2) and another that calls crit.eat(4). The only thing I can think >> of is going back to the if structure, but my instinct tells me that this is >> a Bad Idea. What can I do? > > There is a syntactic trick for this, commonly called *args. You can call a function and pass it a variable holding a 'pack' of arguments prefixed with '*' so that the args will be automagically unpacked into the call message. Below an example: > > def sum(a,b): > ? ? ? ?return a+b > arg_list = (1,2) > func_calls = {1:sum(*arg_list)} > print func_calls[1] > ==> 3 > > Like if I had written sum(1,2) -- except that the arg_list can now be unknown at design time! I don't think this is addressing the OP's question. Your dict will contain the result of calling sum(1, 2). He wants a callable which he can call later. Kent From wescpy at gmail.com Tue Feb 24 20:59:03 2009 From: wescpy at gmail.com (wesley chun) Date: Tue, 24 Feb 2009 11:59:03 -0800 Subject: [Tutor] Accessing callers context from callee method In-Reply-To: References: Message-ID: <78b3a9580902241159g3add4898na23151ebe6c0f987@mail.gmail.com> > when i call a method foo from another method func.?can i access func context > variables or locals() from foo > so > def func(): > ??i=10 > ??foo() > > in foo, can i access func's local variables A. python has statically-nested scoping, so you can do it as long as you: 1. define foo() as an inner function -- its def is contained within func()'s def: def func(): i = 10 def foo(): print i 2. you don't define a variable with the same name locally. in other words, you do have access to func()'s 'i' as long as you don't create another 'i' within foo() -- if you do, only your new local 'i' will be within your scope. B. another alterative is to pass in all of func()'s local variables to foo(): foo(**locals()) this will require you to accept the incoming dictionary in foo() and access the variables from it instead of having them be in foo()'s scope. C. in a related note, your question is similar to that of global vs. local variables. inside a function, you have access to the global as long as you don't define a local using the same name. should you only wish to manipulate the global one, i.e. assign a new value to it instead of creating a new local variable with that name, you would need to use the "global" keyword to specify that you only desire to use and update the global one. i = 0 def func(): i = 10 in this example, the local 'i' in func() hides access to the global 'i'. in the next code snippet, you state you only want to access/update the global 'i'... IOW, don't create a local one: i = 0 def func(): global i i = 10 D. this doesn't work well for inner functions yet: i = 0 def func(): i = 10 def foo(): i = 20 the 'i' in foo() shadows/hides access to func()'s 'i' as well as the global 'i'. if you issue the 'global' keyword, that only gives you access to the global one: i = 0 def func(): i = 10 def foo(): global i i = 20 you cannot get access to func()'s 'i' in this case. E. however, starting in Python 3.x, you'll be able to do somewhat better with the new 'nonlocal' keyword: i = 0 print('globally, i ==', i) def func(): i = 10 print('in func(), i ==', i) def foo(): nonlocal i i = 20 print('in foo(), i ==', i) foo() print('in func() after calling foo(), i ==', i) func() in this case, foo() modified func()'s 'i'. hope this helps! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From sdragon1984 at gmail.com Tue Feb 24 23:13:37 2009 From: sdragon1984 at gmail.com (nathan virgil) Date: Tue, 24 Feb 2009 17:13:37 -0500 Subject: [Tutor] Passing perimeters in dictionary values? In-Reply-To: <1c2a2c590902241142h342a8355mab72b1c3f883d7c6@mail.gmail.com> References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> <1c2a2c590902241142h342a8355mab72b1c3f883d7c6@mail.gmail.com> Message-ID: <111a9ddb0902241413v79e25368jd8be81397976f70f@mail.gmail.com> I'm not familiar with lambdas yet, and I don't think this book will introduce me to them; they aren't listed in the index, anyway. Adding a bunch of single-line functions would work, but I'm not sure how much better that is then the if structure. I think it's what I'm going to go with, anyway. At least until I can learn about lambdas, or even some other solution. On Tue, Feb 24, 2009 at 2:42 PM, Kent Johnson wrote: > On Tue, Feb 24, 2009 at 2:03 PM, nathan virgil > wrote: > > I'm experimenting with OOP using the Critter Caretaker script from Python > > Programming for the Absolute Beginner as my basis. I've noticed that a > > dictionary/function combo is a great way to handle menus, and so I've > > adapted the menu to read as: > > > > > > selection = raw_input("Choice: ") > > choices = {"0":quit, "1":crit.talk, "2":crit.eat, "3":crit.play} > > choice = choices[selection] > > choice() > > > > so that I can call methods from a dictionary, instead of having an > > excruciatingly long if structure. Unfortunately, the problem I'm running > > into with this is that I can't pass any perimeters through the > dictionary. I > > can't figure out how, for example, I could have an option that calls > > crit.eat(2) and another that calls crit.eat(4). The only thing I can > think > > of is going back to the if structure, but my instinct tells me that this > is > > a Bad Idea. What can I do? > > You can define a function that does what you want: > def eat2(): > crit.eat(2) > > Then put eat2 in your dictionary: > choices = { '2': eat2, ...} > > Alternately you can use lambda expressions to do the same thing > without an explicit def: > choices = { '2': lambda: crit.eat(2), ... } > > Kent > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent37 at tds.net Wed Feb 25 00:26:29 2009 From: kent37 at tds.net (Kent Johnson) Date: Tue, 24 Feb 2009 18:26:29 -0500 Subject: [Tutor] Passing perimeters in dictionary values? In-Reply-To: <111a9ddb0902241413v79e25368jd8be81397976f70f@mail.gmail.com> References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> <1c2a2c590902241142h342a8355mab72b1c3f883d7c6@mail.gmail.com> <111a9ddb0902241413v79e25368jd8be81397976f70f@mail.gmail.com> Message-ID: <1c2a2c590902241526k598ceb52kfc22fa9f09233602@mail.gmail.com> On Tue, Feb 24, 2009 at 5:13 PM, nathan virgil wrote: > I'm not familiar with lambdas yet, and I don't think this book will > introduce me to them; they aren't listed in the index, anyway. Here are two brief introductions: http://docs.python.org/tutorial/controlflow.html#lambda-forms http://www.ibiblio.org/swaroopch/byteofpython/read/lambda-forms.html Kent From alan.gauld at btinternet.com Wed Feb 25 00:41:12 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 24 Feb 2009 23:41:12 -0000 Subject: [Tutor] Accessing callers context from callee method References: Message-ID: wrote > when i call a method foo from another method func. can i access func > context > variables or locals() from foo Yes and there are several ways to do it, but nearly always this is a bad idea. It will make foo almost totally unusable in any other context since it will rely on the calling function having local variables of a specific name (and possibly type). It is usually much better to pass the variables into foo at call time. Or even to use global variables! > def func(): > i=10 > foo() How would you write foo? Would you require the variable in func() to be called i? Or would you assign a referece to it using a dictionary to access it? Can you explain what you really want to do with this? What is the motivation behind the request? There is probably a better alternative... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From andreengels at gmail.com Wed Feb 25 00:47:02 2009 From: andreengels at gmail.com (Andre Engels) Date: Wed, 25 Feb 2009 00:47:02 +0100 Subject: [Tutor] Passing perimeters in dictionary values? In-Reply-To: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> Message-ID: <6faf39c90902241547s36fd8becu7c24afded442d60@mail.gmail.com> On Tue, Feb 24, 2009 at 8:03 PM, nathan virgil wrote: > I'm experimenting with OOP using the Critter Caretaker script from Python > Programming for the Absolute Beginner as my basis. I've noticed that a > dictionary/function combo is a great way to handle menus, and so I've > adapted the menu to read as: > > > selection = raw_input("Choice: ") > choices = {"0":quit, "1":crit.talk, "2":crit.eat, "3":crit.play} > choice = choices[selection] > choice() > > so that I can call methods from a dictionary, instead of having an > excruciatingly long if structure. Unfortunately, the problem I'm running > into with this is that I can't pass any perimeters through the dictionary. I > can't figure out how, for example, I could have an option that calls > crit.eat(2) and another that calls crit.eat(4). The only thing I can think > of is going back to the if structure, but my instinct tells me that this is > a Bad Idea. What can I do? You could use a tuple, consisting of the function and its parameter: choices = {"0": (quit,), "1": (eat,2), "2": (eat,4)} choice = choices[selection] choice[0](*choice[1:]) But as said by someone else, if the choices are the lowest n natural numbers, a list feels more natural: choices = [(quit,), (eat,2), (eat,4)] choices = choice[int(selection)] choice[0](*choice[1:]) -- Andr? Engels, andreengels at gmail.com From andreengels at gmail.com Wed Feb 25 00:47:53 2009 From: andreengels at gmail.com (Andre Engels) Date: Wed, 25 Feb 2009 00:47:53 +0100 Subject: [Tutor] Passing perimeters in dictionary values? In-Reply-To: <6faf39c90902241547s36fd8becu7c24afded442d60@mail.gmail.com> References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> <6faf39c90902241547s36fd8becu7c24afded442d60@mail.gmail.com> Message-ID: <6faf39c90902241547m2eb237a2ia82ee0faf02233@mail.gmail.com> On Wed, Feb 25, 2009 at 12:47 AM, Andre Engels wrote: > - Show quoted text - > On Tue, Feb 24, 2009 at 8:03 PM, nathan virgil wrote: >> I'm experimenting with OOP using the Critter Caretaker script from Python >> Programming for the Absolute Beginner as my basis. I've noticed that a >> dictionary/function combo is a great way to handle menus, and so I've >> adapted the menu to read as: >> >> >> selection = raw_input("Choice: ") >> choices = {"0":quit, "1":crit.talk, "2":crit.eat, "3":crit.play} >> choice = choices[selection] >> choice() >> >> so that I can call methods from a dictionary, instead of having an >> excruciatingly long if structure. Unfortunately, the problem I'm running >> into with this is that I can't pass any perimeters through the dictionary. I >> can't figure out how, for example, I could have an option that calls >> crit.eat(2) and another that calls crit.eat(4). The only thing I can think >> of is going back to the if structure, but my instinct tells me that this is >> a Bad Idea. What can I do? > > You could use a tuple, consisting of the function and its parameter: > > choices = {"0": (quit,), "1": (eat,2), "2": (eat,4)} > choice = choices[selection] > choice[0](*choice[1:]) > > But as said by someone else, if the choices are the lowest n natural > numbers, a list feels more natural: > > choices = [(quit,), (eat,2), (eat,4)] > choices = choice[int(selection)] > choice[0](*choice[1:]) That last one should of course be: choices = [(quit,), (eat,2), (eat,4)] choice = choices[int(selection)] choice[0](*choice[1:]) -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Wed Feb 25 00:50:53 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Tue, 24 Feb 2009 23:50:53 -0000 Subject: [Tutor] Passing perimeters in dictionary values? References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> Message-ID: "nathan virgil" wrote in > selection = raw_input("Choice: ") > choices = {"0":quit, "1":crit.talk, "2":crit.eat, "3":crit.play} > choice = choices[selection] > choice() > > so that I can call methods from a dictionary, instead of having an > excruciatingly long if structure. Unfortunately, the problem I'm > running > into with this is that I can't pass any perimeters through the > dictionary. Yes you can. choice(x) will work as will choices[selection](param) So you can do something like: selection = raw_input("Choice: ") param = raw_input('Value: ') choices = {"0":quit, "1":crit.talk, "2":crit.eat, "3":crit.play} choice = choices[selection] choice(param) Or you can build the param value into the dictionary: selection = raw_input("Choice: ") choices = { "0":(quit, None), "1":(crit.talk, "Hi there"), "2":(crit.eat, "Nuts"), "3": (crit.play, "Soccer") "4": (crit.play, "Baseball")} # same func different param choice = choices[selection] choice[0](choice[1]) There are plenty other ways too. I > can't figure out how, for example, I could have an option that calls > crit.eat(2) and another that calls crit.eat(4). The question is where are the 2 and 4 coming from? You could read them from the user or a file in option 1 above or store them with the function under a different menu in option 2. Or of course you could just hard code them at call time... It depends how you want to use it... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Wed Feb 25 01:01:49 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 25 Feb 2009 00:01:49 -0000 Subject: [Tutor] Passing perimeters in dictionary values? References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com><1c2a2c590902241142h342a8355mab72b1c3f883d7c6@mail.gmail.com> <111a9ddb0902241413v79e25368jd8be81397976f70f@mail.gmail.com> Message-ID: "nathan virgil" wrote > I'm not familiar with lambdas yet, and I don't think this book will > introduce me to them; they aren't listed in the index, anyway. lambda is just a fancy mathematical name for a simple concept - its a block of code, like the body of a function. In Python its even simpler, it is an expression. And we store that expression and make it callable. def funcname(aParam): return is the same as funcname = lambda aParam: In some languages, including some Lisp dialects function definitions are syntactic sugar for exactly that kind of lambda assignment. Some even make it explicit as in: (define func ( lambda (aParam) (expression using aParam))) In Python its more like the other way around, functions are defined using def and lambdas are really syntax wrapped around that. lambdas are often offputting to beginners but they are useful in avoiding lots of small oneliner type functions (and the resultant namespace clutter) and they are very important in understanding the theory behind computing (ie. Lambda calculus). HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From sdragon1984 at gmail.com Wed Feb 25 01:25:02 2009 From: sdragon1984 at gmail.com (nathan virgil) Date: Tue, 24 Feb 2009 19:25:02 -0500 Subject: [Tutor] Passing perimeters in dictionary values? In-Reply-To: References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> Message-ID: <111a9ddb0902241625h71b9402bq7a9c7efc726c6038@mail.gmail.com> On Tue, Feb 24, 2009 at 6:50 PM, Alan Gauld wrote: > > > Or you can build the param value into the dictionary: > > selection = raw_input("Choice: ") > choices = { > "0":(quit, None), > "1":(crit.talk, "Hi there"), > "2":(crit.eat, "Nuts"), > "3": (crit.play, "Soccer") > "4": (crit.play, "Baseball")} # same func different param > choice = choices[selection] > choice[0](choice[1]) > This actually suits my needs wonderfully. Thanks! > > I > >> can't figure out how, for example, I could have an option that calls >> crit.eat(2) and another that calls crit.eat(4). >> > > The question is where are the 2 and 4 coming from? > You could read them from the user or a file in option 1 above > or store them with the function under a different menu in option 2. > Or of course you could just hard code them at call time... > > It depends how you want to use it... > The "critter" has attributes for hunger and boredom; if you do anything but eat (for hunger) or play (for boredom), the attribute value goes up, and affects the critter's mood. If you access the right method, the corresponding attribute will go down by a certain value. As it is right now, it only uses the default value, but I was thinking of having different options for the method. Maybe the critter finds cabbage more tasty/filling then lettuce, or maybe it prefers playing baseball over playing soccer. This could be represented by having cabbage represented by crit.eat(4) and lettuce by crit.eat(2). In this case, getting the perimeters directly from the user would be a Very Bad Idea, but I'm sure there's some scenarios where it wouldn't be. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sdragon1984 at gmail.com Wed Feb 25 02:32:10 2009 From: sdragon1984 at gmail.com (nathan virgil) Date: Tue, 24 Feb 2009 20:32:10 -0500 Subject: [Tutor] Passing perimeters in dictionary values? In-Reply-To: <111a9ddb0902241625h71b9402bq7a9c7efc726c6038@mail.gmail.com> References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> <111a9ddb0902241625h71b9402bq7a9c7efc726c6038@mail.gmail.com> Message-ID: <111a9ddb0902241732l1be7d6dcwf65ffb463bcf941a@mail.gmail.com> Erm, it's still not working... Whenever I try to use the talk method (which reports the mood, and doesn't take parameters), it says I gave it too many parameters. Maybe it might help if I posted the code in it's entirety.... # Critter Caretaker # A virtual pet to care for class Critter(object): """A virtual pet""" def __init__(self, name, hunger = 0, boredom = 0): self.name = name self.hunger = hunger self.boredom = boredom def __pass_time(self): self.hunger += 1 self.boredom += 1 def __get_mood(self): unhappiness = self.hunger + self.boredom if unhappiness < 5: mood = "happy" elif 5 <= unhappiness <= 10: mood = "okay" elif 11 <= unhappiness <= 15: mood = "frustrated" else: mood = "mad" return mood mood = property(__get_mood) def talk(self): print "I'm", self.name, "and I feel", self.mood, "now.\n" self.__pass_time() def eat(self, food = 4): print "Brruppp. Thank you." self.hunger -= food if self.hunger < 0: self.hunger = 0 self.__pass_time() def play(self, fun = 4): print "Wheee!" self.boredom -= fun if self.boredom < 0: self.boredom = 0 self.__pass_time() def backdoor(self): print "hunger:", self.hunger, "boredom:", self.boredom def quit(): print "God-bye!" def main(): crit_name = raw_input("What do you want to name your critter?: ") crit = Critter(crit_name) selection = None while selection != "0": print \ """ Critter Caretaker 0 - Quit 1 - Listen to your critter 2 - Feed your critter 3 - Play with your critter """ selection = raw_input("Choice: ") choices = {"0":(quit, None), "1":(crit.talk, None), "2":(crit.eat, 3), "3":(crit.play, 3), "Xyzzy":(crit.backdoor, None)} if selection in choices: choice = choices[selection] choice[0](choice[1]) main() ("\n\nPress the enter key to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: From emile at fenx.com Wed Feb 25 02:50:27 2009 From: emile at fenx.com (Emile van Sebille) Date: Tue, 24 Feb 2009 17:50:27 -0800 Subject: [Tutor] Passing perimeters in dictionary values? In-Reply-To: <111a9ddb0902241732l1be7d6dcwf65ffb463bcf941a@mail.gmail.com> References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> <111a9ddb0902241625h71b9402bq7a9c7efc726c6038@mail.gmail.com> <111a9ddb0902241732l1be7d6dcwf65ffb463bcf941a@mail.gmail.com> Message-ID: nathan virgil wrote: > Erm, it's still not working... > if selection in choices: > choice = choices[selection] > choice[0](choice[1]) s/b choice[0]() > > main() > ("\n\nPress the enter key to exit.") hth, Emile From lie.1296 at gmail.com Wed Feb 25 05:07:11 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 25 Feb 2009 04:07:11 +0000 (UTC) Subject: [Tutor] calling user defined function References: <4bcde3e10902221321j7d3d71b2n66e25119a2d121f0@mail.gmail.com> Message-ID: On Sun, 22 Feb 2009 22:21:22 +0100, roberto wrote: > hello > i have a question which i didn't solved yet: i can define a function > using the text editor provided by IDLE 3.0; then i'd like to call this > function from the python prompt > > but when i try to do it, python warns me that function doesn't exist of > course if i define the function directly using the >>> prompt, after > that everything is fine > > may you tell me where i have to save the file that defines the function > is order to use it later ? > is it a problem of path ? > > my version of python is 3.0, OS windows xp > > thank you very much in advance or you can also run your module with -i (interactive) argument, which means to put you into the interactive mode after the module ends. # mycode.py def foo(): print 'bar' print 'output of program (if any)' # then run this in your shell: $ python -i mycode.py output of program (if any) >>> foo() bar From lie.1296 at gmail.com Wed Feb 25 05:11:29 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 25 Feb 2009 04:11:29 +0000 (UTC) Subject: [Tutor] Passing perimeters in dictionary values? References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> <1c2a2c590902241142h342a8355mab72b1c3f883d7c6@mail.gmail.com> <111a9ddb0902241413v79e25368jd8be81397976f70f@mail.gmail.com> <1c2a2c590902241526k598ceb52kfc22fa9f09233602@mail.gmail.com> Message-ID: On Tue, 24 Feb 2009 18:26:29 -0500, Kent Johnson wrote: > On Tue, Feb 24, 2009 at 5:13 PM, nathan virgil > wrote: >> I'm not familiar with lambdas yet, and I don't think this book will >> introduce me to them; they aren't listed in the index, anyway. Nobody remembers partial? from functools import partial newfunc = partial(myfunc, 1, 2, 3) newfunc() {'eatgrass': partial(eat, 'grass'), 'eatcarrot': partial(eat, 'carrot')} From lie.1296 at gmail.com Wed Feb 25 05:36:28 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Wed, 25 Feb 2009 04:36:28 +0000 (UTC) Subject: [Tutor] String to list conversion References: <9b8e52190902240716n1eab1026j48deee4a35952535@mail.gmail.com> <652641e90902240721x4c17c897v73aa404ed2c0e3b0@mail.gmail.com> Message-ID: > name like "foo" to be changed Nitpick: "foo" is a string, not a name... From prasadaraon50 at gmail.com Wed Feb 25 06:07:25 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Wed, 25 Feb 2009 10:37:25 +0530 Subject: [Tutor] Formatting Message-ID: <9e3fac840902242107i100b02aauc034592cb2079124@mail.gmail.com> hi. s = 'Association of British Travel Agents (ABTA) No.56542\nAir Travel Organisation Licence (ATOL)\nAppointed Agents ofIATA (IATA)\nIncentive Travel & Meet. Association (ITMA)' licenses = re.split("\n+", s) licenseRe = re.compile(r'\(([A-Z]+)\)( No. (\d+))?') >>> for license in licenses: m = licenseRe.search(license) print m.group(1, 3) ('ABTA', None) ('ATOL', None) ('IATA', None) ('ITMA', None) The no 56542 is not getting into m.group() -------------- next part -------------- An HTML attachment was scrubbed... URL: From orsenthil at gmail.com Wed Feb 25 06:30:25 2009 From: orsenthil at gmail.com (Senthil Kumaran) Date: Wed, 25 Feb 2009 11:00:25 +0530 Subject: [Tutor] Formatting In-Reply-To: <9e3fac840902242107i100b02aauc034592cb2079124@mail.gmail.com> References: <9e3fac840902242107i100b02aauc034592cb2079124@mail.gmail.com> Message-ID: <7c42eba10902242130p7b72b810rbd6585cebb15a7d8@mail.gmail.com> On Wed, Feb 25, 2009 at 10:37 AM, prasad rao wrote: > > licenseRe = re.compile(r'\(([A-Z]+)\)( No. (\d+))?') Change that to: licenseRe = re.compile(r'\(([A-Z]+)\)\s*(No.\d+)?') It now works. Thanks, Senthil From a.t.hofkamp at tue.nl Wed Feb 25 08:21:13 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Wed, 25 Feb 2009 08:21:13 +0100 Subject: [Tutor] Accessing callers context from callee method In-Reply-To: References: Message-ID: <49A4F169.3010907@tue.nl> mobiledreamers at gmail.com wrote: > when i call a method foo from another method func. can i access func context > variables or locals() from foo > so > def func(): > i=10 > foo() > > in foo, can i access func's local variables on in this case i As others have already pointed out, this is a really bad idea. Instead you can do: def func(): i = 10 i = foo(i) def foo(i): i = i + 1 return i Sincerely, Albert From denis.spir at free.fr Wed Feb 25 09:00:47 2009 From: denis.spir at free.fr (spir) Date: Wed, 25 Feb 2009 09:00:47 +0100 Subject: [Tutor] Passing perimeters in dictionary values? In-Reply-To: References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> <1c2a2c590902241142h342a8355mab72b1c3f883d7c6@mail.gmail.com> <111a9ddb0902241413v79e25368jd8be81397976f70f@mail.gmail.com> Message-ID: <20090225090047.547db780@o> Le Wed, 25 Feb 2009 00:01:49 -0000, "Alan Gauld" s'exprima ainsi: > > "nathan virgil" wrote > > > I'm not familiar with lambdas yet, and I don't think this book will > > introduce me to them; they aren't listed in the index, anyway. > > lambda is just a fancy mathematical name for a simple > concept - its a block of code, like the body of a function. > In Python its even simpler, it is an expression. And we > store that expression and make it callable. > > > def funcname(aParam): > return > > is the same as > > funcname = lambda aParam: > > In some languages, including some Lisp dialects function > definitions are syntactic sugar for exactly that kind of lambda > assignment. Some even make it explicit as in: > > (define func > ( lambda (aParam) > (expression using aParam))) In io (a wonderful prototype-based languages which syntax reflects the code structure (read: parse tree) like in Lisp), you would have: method_name := method(aParam, ) for instance: perimeter := method(radius, 2 * PI * radius) average := method(values, sum := values sum sum / values count ) [Above: there is not '.' -- return value needs not be explicit] > In Python its more like the other way around, functions are > defined using def and lambdas are really syntax wrapped > around that. > > lambdas are often offputting to beginners but they are useful > in avoiding lots of small oneliner type functions (and the resultant > namespace clutter) and they are very important in understanding > the theory behind computing (ie. Lambda calculus). > > HTH, > > ------ la vita e estrany From andreengels at gmail.com Wed Feb 25 09:21:47 2009 From: andreengels at gmail.com (Andre Engels) Date: Wed, 25 Feb 2009 09:21:47 +0100 Subject: [Tutor] Passing perimeters in dictionary values? In-Reply-To: <111a9ddb0902241732l1be7d6dcwf65ffb463bcf941a@mail.gmail.com> References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> <111a9ddb0902241625h71b9402bq7a9c7efc726c6038@mail.gmail.com> <111a9ddb0902241732l1be7d6dcwf65ffb463bcf941a@mail.gmail.com> Message-ID: <6faf39c90902250021j2b9f63eey3e3c611c97496b49@mail.gmail.com> On Wed, Feb 25, 2009 at 2:32 AM, nathan virgil wrote: > Erm, it's still not working... > > Whenever I try to use the talk method (which reports the mood, and doesn't > take parameters), it says I gave it too many parameters. Maybe it might help > if I posted the code in it's entirety.... > > > # Critter Caretaker > # A virtual pet to care for > > class Critter(object): > ??? """A virtual pet""" > ??? def __init__(self, name, hunger = 0, boredom = 0): > ??????? self.name = name > ??????? self.hunger = hunger > ??????? self.boredom = boredom > > ??? def __pass_time(self): > ??????? self.hunger += 1 > ??????? self.boredom += 1 > > ??? def __get_mood(self): > ??????? unhappiness = self.hunger + self.boredom > ??????? if unhappiness < 5: > ??????????? mood = "happy" > ??????? elif 5 <= unhappiness <= 10: > ??????????? mood = "okay" > ??????? elif 11 <= unhappiness <= 15: > ??????????? mood = "frustrated" > ??????? else: > ??????????? mood = "mad" > ??????? return mood > > ??? mood = property(__get_mood) > > ??? def talk(self): > ??????? print "I'm", self.name, "and I feel", self.mood, "now.\n" > ??????? self.__pass_time() > > ??? def eat(self, food = 4): > ??????? print "Brruppp.? Thank you." > ??????? self.hunger -= food > ??????? if self.hunger < 0: > ??????????? self.hunger = 0 > ??????? self.__pass_time() > > ??? def play(self, fun = 4): > ??????? print "Wheee!" > ??????? self.boredom -= fun > ??????? if self.boredom < 0: > ??????????? self.boredom = 0 > ??????? self.__pass_time() > > ??? def backdoor(self): > ??????? print "hunger:", self.hunger, "boredom:", self.boredom > > def quit(): > ??? print "God-bye!" > > > def main(): > ??? crit_name = raw_input("What do you want to name your critter?: ") > ??? crit = Critter(crit_name) > > ??? selection = None > ??? while selection != "0": > ??????? print \ > ??????? """ > ??????? Critter Caretaker > > ??????? 0 - Quit > ??????? 1 - Listen to your critter > ??????? 2 - Feed your critter > ??????? 3 - Play with your critter > ??????? """ > > ??????? selection = raw_input("Choice: ") > ??????? choices = {"0":(quit, None), "1":(crit.talk, None), "2":(crit.eat, > 3), "3":(crit.play, 3), "Xyzzy":(crit.backdoor, None)} > ??????? if selection in choices: > ?????????? choice = choices[selection] > ?????????? choice[0](choice[1]) Yes, that won't work - you are now calling 'quit' and 'talk' with the argument 'None' rather than without an argument. One way to resolve this would be to use my proposal: take out the "None"s (but keep the comma before it) and chance this line to choice[0](*choice[1:]) which also has the advantage of still working with more than one argument Another would be to not change the definition of choices, but replace choice[0](choice[1]) by: if not choice[1] is None: choice[0](choice[1]) -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Wed Feb 25 10:16:08 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 25 Feb 2009 09:16:08 -0000 Subject: [Tutor] Passing perimeters in dictionary values? References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com><111a9ddb0902241625h71b9402bq7a9c7efc726c6038@mail.gmail.com> <111a9ddb0902241732l1be7d6dcwf65ffb463bcf941a@mail.gmail.com> Message-ID: "nathan virgil" wrote > Whenever I try to use the talk method (which reports the mood, and > doesn't > take parameters), it says I gave it too many parameters. Sorry, I should have pointed out that you will need to redefine all your functions to accept a parameter. Alan G From bala.biophysics at gmail.com Wed Feb 25 13:44:04 2009 From: bala.biophysics at gmail.com (Bala subramanian) Date: Wed, 25 Feb 2009 13:44:04 +0100 Subject: [Tutor] overwriting input file Message-ID: <288df32a0902250444w675a4f91i1d6b4aa72afaa62e@mail.gmail.com> Hello all, query 1) How should i overwrite the input file I want to open 5 files one by one, do some operation on the lines and write the modified lines on the same file (overwritting). Can some please tell me how to do it. pat1=" R" pat2="U5" pat3="A3" from sys import argv files=argv[1:] for names in files: out=open(names + '_new','w') # Here i creat new files to write the content which i dnt want for line in open(names): if pat1 in line: line=line.replace(pat1," ") if pat2 in line: line=line.replace(pat2,"U ") if pat3 in line: line=line.replace(pat3,"A ") out.write(line) query 2) How should I use wild cards to open files in python. Say I have files with names *.dat in a directory, i want the program to open every file with extension .dat and do the process. Thanks in advance, Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From prasadaraon50 at gmail.com Wed Feb 25 13:46:17 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Wed, 25 Feb 2009 18:16:17 +0530 Subject: [Tutor] re Formating Message-ID: <9e3fac840902250446j633d7a2fj9ed917b277777013@mail.gmail.com> hi >>> licenseRe = re.compile(r'\(([A-Z]+)\)\s*(No.\d+)?') >>> for license in licenses: m = licenseRe.search(license) print m.group(1, 3) Traceback (most recent call last): File "", line 3, in print m.group(1, 3) IndexError: no such group Something wrong with this code. -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Wed Feb 25 13:55:43 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Wed, 25 Feb 2009 13:55:43 +0100 Subject: [Tutor] overwriting input file In-Reply-To: <288df32a0902250444w675a4f91i1d6b4aa72afaa62e@mail.gmail.com> References: <288df32a0902250444w675a4f91i1d6b4aa72afaa62e@mail.gmail.com> Message-ID: <49A53FCF.60701@tue.nl> Bala subramanian wrote: > Hello all, > > query 1) How should i overwrite the input file > I want to open 5 files one by one, do some operation on the lines and write > the modified lines on the same file (overwritting). Can some please tell me > how to do it. You cannot write output to a file if you need the data in the file for input first. You'll have to do it in sequence. Either first read all input into memory, then open the file for output, or write the output to a temporary file while reading the input, then rename the temporary file. To prevent problems, be sure to close the input files after reading and before you overwrite them. > query 2) How should I use wild cards to open files in python. Say I have > files with names *.dat in a directory, i want the program to open every > file with extension .dat and do the process. The glob module should be able to solve that problem for you. Sincerely, Albert From prasadaraon50 at gmail.com Wed Feb 25 13:55:54 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Wed, 25 Feb 2009 18:25:54 +0530 Subject: [Tutor] Formatting Message-ID: <9e3fac840902250455r57b593e8rc05e097e3ff7ad7a@mail.gmail.com> hi for license in licenses: m = licenseRe.search(license) print m.group(1, 2) ('ABTA', 'No.56542') ('ATOL', None) ('IATA', None) ('ITMA', None) Yes It is working Thank you Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From noufal at nibrahim.net.in Wed Feb 25 14:26:30 2009 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Wed, 25 Feb 2009 18:56:30 +0530 Subject: [Tutor] overwriting input file In-Reply-To: <288df32a0902250444w675a4f91i1d6b4aa72afaa62e@mail.gmail.com> References: <288df32a0902250444w675a4f91i1d6b4aa72afaa62e@mail.gmail.com> Message-ID: <49A54706.1060202@nibrahim.net.in> Bala subramanian wrote: > Hello all, > > query 1) How should i overwrite the input file > I want to open 5 files one by one, do some operation on the lines and > write the modified lines on the same file (overwritting). Can some > please tell me how to do it. import fileinput pat1=" R" pat2="U5" pat3="A3" files = fileinput.Fileinput(sys.argv[1:], inplace = 1) for i in files: if pat1 in i: print i.replace(pat1," ") if pat2 in i: print i.replace(pat2,"U ") if pat3 in i: print i.replace(pat3,"A ") files.close() should work for you. Check out the fileinput documentation for details especially the 'inplace' argument. It's untested though. Personally speaking, I think the stdout redirection business violates the 'explicit is better than implicit' rule. > query 2) How should I use wild cards to open files in python. Say I have > files with names *.dat in a directory, i want the program to open every > file with extension .dat and do the process. import glob glob.glob(r"*.dat") should do that for you. -- ~noufal http://nibrahim.net.in/ From noufal at nibrahim.net.in Wed Feb 25 14:27:39 2009 From: noufal at nibrahim.net.in (Noufal Ibrahim) Date: Wed, 25 Feb 2009 18:57:39 +0530 Subject: [Tutor] overwriting input file In-Reply-To: <49A53FCF.60701@tue.nl> References: <288df32a0902250444w675a4f91i1d6b4aa72afaa62e@mail.gmail.com> <49A53FCF.60701@tue.nl> Message-ID: <49A5474B.4020800@nibrahim.net.in> A.T.Hofkamp wrote: > write the output to a temporary file while reading the input, then > rename the temporary file. This I believe is what the fileinput module does when you use it with the inplace parameter set to 1. -- ~noufal http://nibrahim.net.in/ From kent37 at tds.net Wed Feb 25 14:38:55 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Feb 2009 08:38:55 -0500 Subject: [Tutor] re Formating In-Reply-To: <9e3fac840902250446j633d7a2fj9ed917b277777013@mail.gmail.com> References: <9e3fac840902250446j633d7a2fj9ed917b277777013@mail.gmail.com> Message-ID: <1c2a2c590902250538w50e38bf3x69967eac1f062d49@mail.gmail.com> On Wed, Feb 25, 2009 at 7:46 AM, prasad rao wrote: > hi >>>> licenseRe = re.compile(r'\(([A-Z]+)\)\s*(No.\d+)?') >>>> for license in licenses: > ?? ? ?m = licenseRe.search(license) > ?? ? ?print m.group(1, 3) > > Traceback (most recent call last): > ??File "", line 3, in > ?? ?print m.group(1, 3) > IndexError: no such group > Something wrong with this code. There are only two groups in the re, try print m.group(1, 2) Kent From kent37 at tds.net Wed Feb 25 14:44:43 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Feb 2009 08:44:43 -0500 Subject: [Tutor] overwriting input file In-Reply-To: <49A54706.1060202@nibrahim.net.in> References: <288df32a0902250444w675a4f91i1d6b4aa72afaa62e@mail.gmail.com> <49A54706.1060202@nibrahim.net.in> Message-ID: <1c2a2c590902250544p1b24c3aetebe4fa78601e2fe8@mail.gmail.com> On Wed, Feb 25, 2009 at 8:26 AM, Noufal Ibrahim wrote: > Bala subramanian wrote: >> >> Hello all, >> >> query 1) How should i overwrite the input file >> I want to open 5 files one by one, do some operation on the lines and >> write the modified lines on the same file (overwritting). Can some please >> tell me how to do it. > > import fileinput > pat1=" R" > pat2="U5" > pat3="A3" > files = fileinput.Fileinput(sys.argv[1:], inplace = 1) > for i in files: > ?if pat1 in i: print i.replace(pat1," ") > ?if pat2 in i: print i.replace(pat2,"U ") > ?if pat3 in i: print i.replace(pat3,"A ") > files.close() > > should work for you. Check out the fileinput documentation for details > especially the 'inplace' argument. It's untested though. This doesn't do quite the same as the original, it only writes modified lines. Also I think it will add extra newlines, you should use sys.stdout.write(i) instead of print i. I would put the patterns in a list and use a loop. I think the test for the pattern is not needed, the replace does the same search. patterns = [ (' R', ' '), ('U5', 'U '), ('A3', 'A ') ] files = fileinput.Fileinput(sys.argv[1:], inplace = 1) for line in files: for pat, repl in patterns: line = line.replace(pat, repl) sys.stdout.write(line) Kent From thorsten at thorstenkampe.de Wed Feb 25 18:44:22 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Wed, 25 Feb 2009 18:44:22 +0100 Subject: [Tutor] Standardizing on Unicode and utf8 References: Message-ID: * Dinesh B Vadhia (Fri, 20 Feb 2009 02:52:27 -0800) > We want to standardize on unicode and utf8 Very good idea. > and would like to clarify and verify their use to minimize encode > ()/decode()'ing: > > 1. Python source files > Use the header: # -*- coding: utf8 -*- Good idea (although only valid for comments and "inline" strings > 2. Reading files > In most cases, we don't know the source encoding of the files being > read. Do we have to decode('utf8') after reading from file? No. If you don't know the encoding of the file you can't decode it, of course. You can read() it of course, but you can't process it (as text). > 3. Writing files > We will always write to files in utf8. Do we have to encode('utf8') > before writing to file? Yes, sure. > Is there anything else that we have to consider? Hm, in general nothing I'm aware of. Thorsten From thorsten at thorstenkampe.de Wed Feb 25 18:46:13 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Wed, 25 Feb 2009 18:46:13 +0100 Subject: [Tutor] Standardizing on Unicode and utf8 References: <20090220130259.100639bb@o> Message-ID: * spir (Fri, 20 Feb 2009 13:02:59 +0100) > Le Fri, 20 Feb 2009 02:52:27 -0800, > "Dinesh B Vadhia" s'exprima ainsi: > > > We want to standardize on unicode and utf8 and would like to clarify and > > verify their use to minimize encode()/decode()'ing: > > > > 1. Python source files > > Use the header: # -*- coding: utf8 -*- > > You don't even need fancy decoration: > > # coding: utf-8 > > is enough. Sure? Never heard of that. Interesting... Thorsten From thorsten at thorstenkampe.de Wed Feb 25 18:51:10 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Wed, 25 Feb 2009 18:51:10 +0100 Subject: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu References: <20090219092734.049b3744@ubuntu> Message-ID: * Eric Dorsey (Thu, 19 Feb 2009 12:24:07 -0700) > Still doesnt work.. I just get this when I hit the up arrow:>>> ^[[A > > Bah. It works in the 2.5 version that came packaged with it. Thanks for > trying :) There's a log for the ./configure. See if the configure script can find readline. Thorsten From alan.gauld at btinternet.com Wed Feb 25 19:53:49 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Wed, 25 Feb 2009 18:53:49 -0000 Subject: [Tutor] overwriting input file References: <288df32a0902250444w675a4f91i1d6b4aa72afaa62e@mail.gmail.com> Message-ID: "Bala subramanian" wrote > query 1) How should i overwrite the input file > I want to open 5 files one by one, do some operation on the lines > and write > the modified lines on the same file (overwritting). Can some please > tell me > how to do it. You don't really want to do that! Too risky. Better to do what you are doing and then when it has all worked and you close both input and output files you can delete the original and rename the outfile to the original input file name. In fact to be really safe don't delete the old file but rename it to .bak... For copying and renaming filers see the os and shutil modules and the Using the OS topic in my tutorial. > query 2) How should I use wild cards to open files in python. Look at the glob module. It uses wildcards to build lists of matching file names. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Wed Feb 25 20:26:14 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Feb 2009 14:26:14 -0500 Subject: [Tutor] Standardizing on Unicode and utf8 In-Reply-To: References: <20090220130259.100639bb@o> Message-ID: <1c2a2c590902251126y2b782117n50496f971859d2a3@mail.gmail.com> On Wed, Feb 25, 2009 at 12:46 PM, Thorsten Kampe wrote: > * spir (Fri, 20 Feb 2009 13:02:59 +0100) >> > Use the header: # -*- coding: utf8 -*- >> >> You don't even need fancy decoration: >> >> # coding: utf-8 >> >> is enough. > > Sure? Never heard of that. Interesting... >From PEP 263 (http://www.python.org/dev/peps/pep-0263/): To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding= or (using formats recognized by popular editors) #!/usr/bin/python # -*- coding: -*- or #!/usr/bin/python # vim: set fileencoding= : More precisely, the first or second line must match the regular expression "coding[:=]\s*([-\w.]+)". The -*- style is also recognized by some editors. Kent From kent37 at tds.net Wed Feb 25 20:33:17 2009 From: kent37 at tds.net (Kent Johnson) Date: Wed, 25 Feb 2009 14:33:17 -0500 Subject: [Tutor] overwriting input file In-Reply-To: References: <288df32a0902250444w675a4f91i1d6b4aa72afaa62e@mail.gmail.com> Message-ID: <1c2a2c590902251133p6e47e400mfc02088ecdf335f6@mail.gmail.com> On Wed, Feb 25, 2009 at 1:53 PM, Alan Gauld wrote: > > "Bala subramanian" wrote > >> query 1) How should i overwrite the input file >> I want to open 5 files one by one, do some operation on the lines and >> write >> the modified lines on the same file (overwritting). Can some please tell >> me >> how to do it. > > You don't really want to do that! Too risky. > Better to do what you are doing and then when it has all worked > and you close both input and output files you can delete the > original and rename the outfile to the original input file name. > In fact to be really safe don't delete the old file but rename > it to .bak... The fileinput module with inplace=1, backup='.bak' does close to what you are describing. It renames the input file before opening it, so if there is a failure it will be renamed. Kent From mobiledreamers at gmail.com Wed Feb 25 23:24:27 2009 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Wed, 25 Feb 2009 14:24:27 -0800 Subject: [Tutor] Accessing callers context from callee method In-Reply-To: <49A4F169.3010907@tue.nl> References: <49A4F169.3010907@tue.nl> Message-ID: i found the solution This is my first attempt at memcaching html page using cheetah since cheetah render needs locals() i use getCallerInfo() to get the locals() and send to memcached let me know if it is possible to better do this *notice getCallerInfo * *utils.py* @log_time_func def renderpage(key, htmlfile, deleteafter=3600): from globaldb import mc try:page = mc.get(key) except: page=None clogger.info('except error mc.get '+ key) if not page: clogger.info(key+ ' rendering cheetah page') terms = getCallerInfo(1) #print terms page = str(web.render(htmlfile, asTemplate=True, terms=terms)) try:mc.set(key, page, deleteafter) except: clogger.info('except error mc.set '+ key) return page @log_time_func @memcachethis def mcrenderpage(key, htmlfile, deleteafter=3600): terms = getCallerInfo(2) #print terms return str(web.render(htmlfile, asTemplate=True, terms=terms)) def getCallerInfo(decorators=0): '''returns locals of caller using frame.optional pass number of decorators\nFrom Dig deep into python internals http://www.devx.com/opensource/Article/31593/1954' '' f = sys._getframe(2+decorators) args = inspect.getargvalues(f) return args[3] *Usage* key=facebookstuff.APP_NAME+'newstart'+str(uid) return utils.renderpage(key, 'pick.html') -- Bidegg worlds best auction site http://bidegg.com On Tue, Feb 24, 2009 at 11:21 PM, A.T.Hofkamp wrote: > mobiledreamers at gmail.com wrote: > >> when i call a method foo from another method func. can i access func >> context >> variables or locals() from foo >> so >> def func(): >> i=10 >> foo() >> >> in foo, can i access func's local variables on in this case i >> > > As others have already pointed out, this is a really bad idea. > Instead you can do: > > > def func(): > i = 10 > i = foo(i) > > def foo(i): > i = i + 1 > return i > > Sincerely, > Albert > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mobiledreamers at gmail.com Wed Feb 25 23:24:55 2009 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Wed, 25 Feb 2009 14:24:55 -0800 Subject: [Tutor] Accessing callers context from callee method In-Reply-To: <78b3a9580902241159g3add4898na23151ebe6c0f987@mail.gmail.com> References: <78b3a9580902241159g3add4898na23151ebe6c0f987@mail.gmail.com> Message-ID: i found the solution This is my first attempt at memcaching html page using cheetah since cheetah render needs locals() i use getCallerInfo() to get the locals() and send to memcached let me know if it is possible to better do this *notice getCallerInfo * *utils.py* @log_time_func def renderpage(key, htmlfile, deleteafter=3600): from globaldb import mc try:page = mc.get(key) except: page=None clogger.info('except error mc.get '+ key) if not page: clogger.info(key+ ' rendering cheetah page') terms = getCallerInfo(1) #print terms page = str(web.render(htmlfile, asTemplate=True, terms=terms)) try:mc.set(key, page, deleteafter) except: clogger.info('except error mc.set '+ key) return page @log_time_func @memcachethis def mcrenderpage(key, htmlfile, deleteafter=3600): terms = getCallerInfo(2) #print terms return str(web.render(htmlfile, asTemplate=True, terms=terms)) def getCallerInfo(decorators=0): '''returns locals of caller using frame.optional pass number of decorators\nFrom Dig deep into python internals http://www.devx.com/opensource/Article/31593/1954' '' f = sys._getframe(2+decorators) args = inspect.getargvalues(f) return args[3] *Usage* key=facebookstuff.APP_NAME+'newstart'+str(uid) return utils.renderpage(key, 'pick.html') -- Bidegg worlds best auction site http://bidegg.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Thu Feb 26 06:01:34 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 26 Feb 2009 05:01:34 +0000 (UTC) Subject: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu References: <20090219092734.049b3744@ubuntu> Message-ID: On Thu, 19 Feb 2009 09:27:34 +0300, ???? ?? ????????? ??????? wrote: > On Wed, 18 Feb 2009 20:19:56 -0700 > Eric Dorsey wrote: >> I did an aptitute install of ibreadline5-dev and then did ./configure >> and make again, and still don't have any functionality to be able to >> hit up-arrow and get a command repeated while inside the interpreter. >> Any ideas? >> >> > I don't know what's wrong, Python should pickup "libreadline" and use it > automatically if it was installed. > > Try passing "--with-readline" to the "configure" script. > > If that doesn't help, then I'm sorry, I'm out of ideas. > Try installing other readline modules that looks suspicious. In my Ubuntu machine (these are all readline-related modules in my machine, not only the ones that is needed for python), I have these packages installed: v lib32readline-dev - v libghc6-readline-dev - v libghc6-readline-doc - v libghc6-readline-prof- v libreadline-dbg - v libreadline-dev - i libreadline5 - GNU readline and history libraries, run-ti i A libreadline5-dev - GNU readline and history libraries, develo i readline-common - GNU readline and history libraries, common try matching that and ./configure then make. From dorseye at gmail.com Thu Feb 26 06:23:01 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Wed, 25 Feb 2009 22:23:01 -0700 Subject: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu In-Reply-To: References: <20090219092734.049b3744@ubuntu> Message-ID: Thanks for all your continued insights on this. I'm going to investigate the .configure log, as well as look around at other readline packages.. But, noob question, did you just go into something like synaptic to find out what readline type packages are installed? (Sorry if this is annoying anyone on the list, but its all in the name of getting the Python inerpreter to be happy !) Or did you do some kind of command line aptitude "list out readine stuff"? On Wed, Feb 25, 2009 at 10:01 PM, Lie Ryan wrote: > On Thu, 19 Feb 2009 09:27:34 +0300, ???? ?? ????????? ??????? wrote: > > > On Wed, 18 Feb 2009 20:19:56 -0700 > > Eric Dorsey wrote: > >> I did an aptitute install of ibreadline5-dev and then did ./configure > >> and make again, and still don't have any functionality to be able to > >> hit up-arrow and get a command repeated while inside the interpreter. > >> Any ideas? > >> > >> > > I don't know what's wrong, Python should pickup "libreadline" and use it > > automatically if it was installed. > > > > Try passing "--with-readline" to the "configure" script. > > > > If that doesn't help, then I'm sorry, I'm out of ideas. > > > > Try installing other readline modules that looks suspicious. In my Ubuntu > machine (these are all readline-related modules in my machine, not only > the ones that is needed for python), I have these packages installed: > v lib32readline-dev - > v libghc6-readline-dev - > v libghc6-readline-doc - > v libghc6-readline-prof- > v libreadline-dbg - > v libreadline-dev - > i libreadline5 - GNU readline and history libraries, run-ti > i A libreadline5-dev - GNU readline and history libraries, develo > i readline-common - GNU readline and history libraries, common > > try matching that and ./configure then make. > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Thu Feb 26 07:00:39 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 26 Feb 2009 17:00:39 +1100 Subject: [Tutor] Add readline capabilities to a Python build 2.6 on Ubuntu In-Reply-To: References: <20090219092734.049b3744@ubuntu> Message-ID: <1235628039.6909.5.camel@lieryan-laptop> On Wed, 2009-02-25 at 22:23 -0700, Eric Dorsey wrote: > Thanks for all your continued insights on this. I'm going to > investigate the .configure log, as well as look around at other > readline packages.. But, noob question, did you just go into something > like synaptic to find out what readline type packages are installed? > (Sorry if this is annoying anyone on the list, but its all in the name > of getting the Python inerpreter to be happy !) Or did you do some > kind of command line aptitude "list out readine stuff"? Yeah, you can go to synaptic and and do a search. Alternatively, you type "aptitude search readline" on the terminal (no need for sudo/root access for search). If you found what you want to install, you can use "sudo apt-get install " or "sudo aptitude install ". Synaptic is fine too, but not the "Add/Remove Application", the "Add/Remove Application" allows you to install applications not single packages. From abhishek.luck at gmail.com Thu Feb 26 08:08:27 2009 From: abhishek.luck at gmail.com (Abhishek Kumar) Date: Thu, 26 Feb 2009 12:38:27 +0530 Subject: [Tutor] how to instantiate a class Message-ID: <74abbcd30902252308n6ddd70a0i246a55bc1be0bc0f@mail.gmail.com> hello list, Below is the sample code of a class. import Class ABC: def __init__(self,a,b,c): statement 1 statement 2 def func(x,y): statement 1 statement 2 Here is the question: how to make an object of this class and how to use the methods listed in the class. do i need to create the object in a separate file or in the same file it can be done ?? From lie.1296 at gmail.com Thu Feb 26 08:22:25 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 26 Feb 2009 07:22:25 +0000 (UTC) Subject: [Tutor] how to instantiate a class References: <74abbcd30902252308n6ddd70a0i246a55bc1be0bc0f@mail.gmail.com> Message-ID: On Thu, 26 Feb 2009 12:38:27 +0530, Abhishek Kumar wrote: > hello list, > You need to read through the tutorial first: http://docs.python.org/ tutorial/ If there are still things you don't understand, please ask again. As for your question, here is a sample useless python code: class MyClass(object): def __init__(self, arg): self.a = arg def foo(self, b): return self.a + b myinstance = MyClass(5) print myinstance.foo(6) # output 11 From lie.1296 at gmail.com Thu Feb 26 08:22:32 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 26 Feb 2009 07:22:32 +0000 (UTC) Subject: [Tutor] how to instantiate a class References: <74abbcd30902252308n6ddd70a0i246a55bc1be0bc0f@mail.gmail.com> Message-ID: On Thu, 26 Feb 2009 12:38:27 +0530, Abhishek Kumar wrote: > hello list, > You need to read through the tutorial first: http://docs.python.org/ tutorial/ If there are still things you don't understand, please ask again. As for your question, here is a sample useless python code: class MyClass(object): def __init__(self, arg): self.a = arg def foo(self, b): return self.a + b myinstance = MyClass(5) print myinstance.foo(6) # output 11 From tomar.arun at gmail.com Thu Feb 26 08:25:43 2009 From: tomar.arun at gmail.com (Arun Tomar) Date: Thu, 26 Feb 2009 12:55:43 +0530 Subject: [Tutor] how to instantiate a class In-Reply-To: <74abbcd30902252308n6ddd70a0i246a55bc1be0bc0f@mail.gmail.com> References: <74abbcd30902252308n6ddd70a0i246a55bc1be0bc0f@mail.gmail.com> Message-ID: <202c460902252325m357cd6d1s54922d82c0eb76f6@mail.gmail.com> @Abhishek, On 2/26/09, Abhishek Kumar wrote: > hello list, > > Below is the sample code of a class. > > > import > > Class ABC: > def __init__(self,a,b,c): > statement 1 > statement 2 > def func(x,y): > statement 1 > statement 2 > > Here is the question: > > how to make an object of this class and how to use the methods listed > in the class. you can make object newobj = ABC() using the methods would be newobj.func() > do i need to create the object in a separate file or in the same file > it can be done ?? It's upto you. You can create the object in the same file or separate file, both works. kindly read the documentation, especially the tutorial section. It's one of the best available resources for learning python. http://docs.python.org/ > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -- Regards, Arun Tomar blog: http://linuxguy.in website: http://www.solutionenterprises.co.in From iwasroot at gmail.com Thu Feb 26 08:44:32 2009 From: iwasroot at gmail.com (Moos Heintzen) Date: Wed, 25 Feb 2009 23:44:32 -0800 Subject: [Tutor] how to instantiate a class In-Reply-To: <74abbcd30902252308n6ddd70a0i246a55bc1be0bc0f@mail.gmail.com> References: <74abbcd30902252308n6ddd70a0i246a55bc1be0bc0f@mail.gmail.com> Message-ID: <7b13ba330902252344h7d8d0afm575ae3c7f3a3f082@mail.gmail.com> Here is a good book if you are already familiar with other languages. http://diveintopython.org/object_oriented_framework/instantiating_classes.html From denis.spir at free.fr Thu Feb 26 09:04:37 2009 From: denis.spir at free.fr (spir) Date: Thu, 26 Feb 2009 09:04:37 +0100 Subject: [Tutor] how to instantiate a class In-Reply-To: <74abbcd30902252308n6ddd70a0i246a55bc1be0bc0f@mail.gmail.com> References: <74abbcd30902252308n6ddd70a0i246a55bc1be0bc0f@mail.gmail.com> Message-ID: <20090226090437.61d1f3af@o> Le Thu, 26 Feb 2009 12:38:27 +0530, Abhishek Kumar s'exprima ainsi: > hello list, > > Below is the sample code of a class. > > > import > > Class ABC: > def __init__(self,a,b,c): > statement 1 > statement 2 > def func(x,y): > statement 1 > statement 2 > > Here is the question: > > how to make an object of this class abc = ABC(1,2,3) >and how to use the methods listed > in the class. abc.func(foo,bar) > do i need to create the object in a separate file or in the same file > it can be done ?? Both are possible. If not in the same file, you must first import the file (module) where ABC is defined, then ABC will behave like an attribute of the module; or just the name ABC from this file, in which case ABC will be locally know: import ABCFile abc = ABCFile.ABC(1,2,3) or from ABCFile import ABC abc = ABC(1,2,3) denis ------ la vita e estrany From prasadaraon50 at gmail.com Thu Feb 26 10:09:07 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Thu, 26 Feb 2009 14:39:07 +0530 Subject: [Tutor] format a file Message-ID: <9e3fac840902260109x52bb957fsb81c3154d39461bf@mail.gmail.com> hello I find it difficult to use horizontal scroll bar to read text documents. So I want to split lines in the text file in to two lines. def myforrmat(source,desty): ???? so=open(source) ???? de=open(desty,'w') ???? for line in so: ????????? if len(line)<60:de.write(line) ????????? if len(line)>60: ????????????de.write(''.join(list(line)[:60])) ????????????de.write(''.join(list(line)[60:])) ????so.close() ????de.close() This code is not working.Destination file have the same length of lines to source file Some one please show where the problem is. I tried to do it using fileinput module and inplace flag. in vain. please some one show me how to do it. Thank you Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From lie.1296 at gmail.com Thu Feb 26 12:00:01 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Thu, 26 Feb 2009 11:00:01 +0000 (UTC) Subject: [Tutor] format a file References: <9e3fac840902260109x52bb957fsb81c3154d39461bf@mail.gmail.com> Message-ID: Try thinking what happens when you do this: line = 'this is a reaaaaaaaaaaaaaaaaaaaallly long lineeeee\n' first = line[:20] second = line[20:] print first print second . . . . . . . . . . Have you got it? The first would contain "this is a reaaaaaaaa" and the second "aaaaaaaaaaaallly long lineeeee\n" When you try to write to the file: de.write(first) de.write(second) why isn't there a new line between the first and second? Also, I think you should realize that with how you do it now, you may put line breaks in between words. Better to split on space line.split(' ') then ' '.join(first) + '\n' it together again. From gerard.kelly at uqconnect.edu.au Thu Feb 26 06:32:30 2009 From: gerard.kelly at uqconnect.edu.au (Mr Gerard Kelly) Date: Thu, 26 Feb 2009 05:32:30 +0000 Subject: [Tutor] Linear Algebra weirdness Message-ID: <3F23748B015E23448EDE65E6411239F115220FCC68@BL2PRD0101MB010.prod.exchangelabs.com> I am getting some very strange behaviour from the Linear Algebra module. Look at this code: from LinearAlgebra import * a=5 print a And look at the output that I get when I run it: 50.0 0.0 0.25 0.0 0.5 0.0 0.75 0.0 1.0 [[ 2.50000000e-01 -2.50000000e-01 -4.99993750e-01 ..., 3.73459082e+01 3.75116710e+01 3.76764961e+01] [ 5.00000000e-01 -5.00000000e-01 -6.25000000e-06 ..., -4.99993797e-01 -2.49373966e-03 4.99993766e-01] [ 7.50000000e-01 -7.50000000e-01 0.00000000e+00 ..., -7.50000000e-01 0.00000000e+00 7.50000000e-01] [ 1.00000000e+00 -1.00000000e+00 0.00000000e+00 ..., -1.00000000e+00 0.00000000e+00 1.00000000e+00]] 5 Apparently Linear Algebra is giving me the output of another program along with the output for this one. Of course I don't need Linear Algebra to print the number 5, but I've been trying to make a program that uses Linear Algebra, and I'm always having the output come out twice each time I run it. When I edit the program, it always gives me the old output before the new output, even if I edit it right down to something as simple as "a=5, print a". Is anybody familiar with this module and why it is doing this? I've used it before and never had this issue. -Gerard. From kkwaiser at umich.edu Thu Feb 26 08:00:37 2009 From: kkwaiser at umich.edu (kkwaiser at umich.edu) Date: Thu, 26 Feb 2009 02:00:37 -0500 Subject: [Tutor] Convert a string of numbers to a list Message-ID: <20090226020037.14827f8djp59brsw@web.mail.umich.edu> Hi, I am trying to convert an output from subprocess.Popen() from a byte string to a list of numbers. This is what Popen returns: print SAL.stdout.readlines() ['[335, 180, 201, 241, 199]\r\n'] Except the string will be much longer in practice. I've experimented with .rstrip and .split and I've looked over the csv module but have not been able to figure anything out. My only restriction is to avoid writing to a file. I have a feeling I'm missing something incredibly simple. Any help would be greatly appreciated, kbk From kent37 at tds.net Thu Feb 26 12:28:20 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Feb 2009 06:28:20 -0500 Subject: [Tutor] format a file In-Reply-To: <9e3fac840902260109x52bb957fsb81c3154d39461bf@mail.gmail.com> References: <9e3fac840902260109x52bb957fsb81c3154d39461bf@mail.gmail.com> Message-ID: <1c2a2c590902260328l35f1ece8q3280cbe8a0466a2e@mail.gmail.com> On Thu, Feb 26, 2009 at 4:09 AM, prasad rao wrote: > hello > I find it difficult to use horizontal scroll bar to read text documents. > So I want to split lines in the text file in to two lines. > > def ?myforrmat(source,desty): > ???? so=open(source) > ???? de=open(desty,'w') > ???? for line in so: > ????????? if len(line)<60:de.write(line) > ????????? if len(line)>60: > ????????????de.write(''.join(list(line)[:60])) > ????????????de.write(''.join(list(line)[60:])) You don't have to convert to list, strings are sequences and support slicing directly. As Lie notes, you have to write a newline between the lines! de.write(line[:60]) de.write('\n') de.write(line[60:]) Kent From bala.biophysics at gmail.com Thu Feb 26 12:28:55 2009 From: bala.biophysics at gmail.com (Bala subramanian) Date: Thu, 26 Feb 2009 12:28:55 +0100 Subject: [Tutor] learning new features of python Message-ID: <288df32a0902260328g2c275a51ucaa490190edb5f2@mail.gmail.com> Dear Friends, Is there any website/tutorial that explains new features that are constantly getting embedded in python. This would be helpful for python lovers to grow with python and adopt new styles of codes. Just for an example, i read in Mark Luts "learning python" book, the various forms of except statements except name except name, value <-- present style except name as value <-- expected to be available in python 3.0 Similaraly in Alan Guald Learn to program link, he has given information on opening a file with file() and open() functions. Thanks, Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Thu Feb 26 12:40:04 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Thu, 26 Feb 2009 12:40:04 +0100 Subject: [Tutor] Convert a string of numbers to a list In-Reply-To: <20090226020037.14827f8djp59brsw@web.mail.umich.edu> References: <20090226020037.14827f8djp59brsw@web.mail.umich.edu> Message-ID: <49A67F94.1020804@tue.nl> kkwaiser at umich.edu wrote: > Hi, > > I am trying to convert an output from subprocess.Popen() from a byte > string to a list of numbers. This is what Popen returns: > > print SAL.stdout.readlines() > > ['[335, 180, 201, 241, 199]\r\n'] > > Except the string will be much longer in practice. > > I've experimented with .rstrip and .split and I've looked over the csv > module but have not been able to figure anything out. My only > restriction is to avoid writing to a file. Don't know about the csv module, but if you want to do it in plain Python: readlines() returns a list of lines, so do the following for each line in the list: 1. chop off the "[" and "]\r\n" 2. split on "," 3. convert to integer values by means of int() > I have a feeling I'm missing something incredibly simple. Any help > would be greatly appreciated, Please post what you have, and what you are stuck on, then we can guide you through the problem. Sincerely, Albert From kent37 at tds.net Thu Feb 26 12:42:11 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Feb 2009 06:42:11 -0500 Subject: [Tutor] Linear Algebra weirdness In-Reply-To: <3F23748B015E23448EDE65E6411239F115220FCC68@BL2PRD0101MB010.prod.exchangelabs.com> References: <3F23748B015E23448EDE65E6411239F115220FCC68@BL2PRD0101MB010.prod.exchangelabs.com> Message-ID: <1c2a2c590902260342t3c09bcbw9edec7d9b4ed0735@mail.gmail.com> On Thu, Feb 26, 2009 at 12:32 AM, Mr Gerard Kelly wrote: > I am getting some very strange behaviour from the Linear Algebra module. > > Look at this code: > > from LinearAlgebra import * > > a=5 > print a > > And look at the output that I get when I run it: > > 50.0 > 0.0 > 0.25 > 0.0 > 0.5 > 0.0 > 0.75 > 0.0 > 1.0 > [[ ?2.50000000e-01 ?-2.50000000e-01 ?-4.99993750e-01 ..., > ? ?3.73459082e+01 ? 3.75116710e+01 ? 3.76764961e+01] > ?[ ?5.00000000e-01 ?-5.00000000e-01 ?-6.25000000e-06 ..., > ? -4.99993797e-01 ?-2.49373966e-03 ? 4.99993766e-01] > ?[ ?7.50000000e-01 ?-7.50000000e-01 ? 0.00000000e+00 ..., > ? -7.50000000e-01 ? 0.00000000e+00 ? 7.50000000e-01] > ?[ ?1.00000000e+00 ?-1.00000000e+00 ? 0.00000000e+00 ..., > ? -1.00000000e+00 ? 0.00000000e+00 ? 1.00000000e+00]] > 5 > > > Apparently Linear Algebra is giving me the output of another program along with the output for this one. Of course I don't need Linear Algebra to print the number 5, but I've been trying to make a program that uses Linear Algebra, and I'm always having the output come out twice each time I run it. When I edit the program, it always gives me the old output before the new output, even if I edit it right down to something as simple as "a=5, print a". Is this the LinearAlgebra package from Numeric? It's helpful if you don't assume we know what you are talking about :-) If so, shouldn't it be something like from Numeric.LinearAlgebra import * ? Anyway my guess is that you have another program called LinearAlgebra.py in your python path. *That* program probably has the correct import, but it also does some calculations and prints the result. Try this: import LinearAlgebra print LinearAlgebra.__file__ to find out what you are really importing. Kent From kent37 at tds.net Thu Feb 26 12:45:05 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Feb 2009 06:45:05 -0500 Subject: [Tutor] Convert a string of numbers to a list In-Reply-To: <20090226020037.14827f8djp59brsw@web.mail.umich.edu> References: <20090226020037.14827f8djp59brsw@web.mail.umich.edu> Message-ID: <1c2a2c590902260345l5e51801foe68c48197ae28685@mail.gmail.com> On Thu, Feb 26, 2009 at 2:00 AM, wrote: > Hi, > > I am trying to convert an output from subprocess.Popen() from a byte string > to a list of numbers. ?This is what Popen returns: > > print SAL.stdout.readlines() > > ['[335, 180, 201, 241, 199]\r\n'] For one line: In [11]: s = '[335, 180, 201, 241, 199]\r\n' In [12]: map(int, s.strip('[]\r\n').split(', ')) Out[12]: [335, 180, 201, 241, 199] Modify appropriately to handle a list of lines. Kent From kent37 at tds.net Thu Feb 26 12:47:23 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Feb 2009 06:47:23 -0500 Subject: [Tutor] learning new features of python In-Reply-To: <288df32a0902260328g2c275a51ucaa490190edb5f2@mail.gmail.com> References: <288df32a0902260328g2c275a51ucaa490190edb5f2@mail.gmail.com> Message-ID: <1c2a2c590902260347x21145670g969df51bb68004c0@mail.gmail.com> On Thu, Feb 26, 2009 at 6:28 AM, Bala subramanian wrote: > Dear Friends, > > Is there any website/tutorial that explains new features that are constantly > getting embedded in python. Every new release comes with a "What's New in Python xx" document. This is often the best, and sometimes the only, available documentation for new features. For example: http://docs.python.org/whatsnew/2.6.html http://docs.python.org/3.0/whatsnew/3.0.html Kent From bermanrl at cfl.rr.com Thu Feb 26 14:03:35 2009 From: bermanrl at cfl.rr.com (Robert Berman) Date: Thu, 26 Feb 2009 08:03:35 -0500 Subject: [Tutor] Linear Algebra weirdness In-Reply-To: <3F23748B015E23448EDE65E6411239F115220FCC68@BL2PRD0101MB010.prod.exchangelabs.com> References: <3F23748B015E23448EDE65E6411239F115220FCC68@BL2PRD0101MB010.prod.exchangelabs.com> Message-ID: <49A69327.1040201@cfl.rr.com> An HTML attachment was scrubbed... URL: From prasadaraon50 at gmail.com Thu Feb 26 14:43:59 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Thu, 26 Feb 2009 19:13:59 +0530 Subject: [Tutor] re.format a file Message-ID: <9e3fac840902260543l557989abl34c01b677468d6f8@mail.gmail.com> helloThank you Lie and Kent. I forgot about newline character and the fact that string can be sliced. Thanks for your timely help BTW I have gone through the Python library reference and find no examples in fileinput module. z=fileinput.input(file,inplace=1) for line in z: ???if len(line)<60:pass ???if len(line)>60: ??????line=line[:60]+'\n'+line[60:] Is it the right way to do? Thank you Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.t.hofkamp at tue.nl Thu Feb 26 15:16:35 2009 From: a.t.hofkamp at tue.nl (A.T.Hofkamp) Date: Thu, 26 Feb 2009 15:16:35 +0100 Subject: [Tutor] re.format a file In-Reply-To: <9e3fac840902260543l557989abl34c01b677468d6f8@mail.gmail.com> References: <9e3fac840902260543l557989abl34c01b677468d6f8@mail.gmail.com> Message-ID: <49A6A443.9090209@tue.nl> prasad rao wrote: > helloThank you Lie and Kent. > I forgot about newline character and the fact that string can be sliced. > Thanks for your timely help > BTW I have gone through the Python library reference and find no examples > in fileinput module. The fileinput module only deals with reading and writing data from/to files, it does not deal with manipulating that data. How to manipulate strings is in the 'strings' or 'text' section of a tutorial. > z=fileinput.input(file,inplace=1) > for line in z: > ???if len(line)<60:pass > ???if len(line)>60: > ??????line=line[:60]+'\n'+line[60:] > Is it the right way to do? A nice step forward, I'd say. Did you consider what to do with ridiculous long lines, eg 200, 500, 1000 or 10000 characters long? If you want to deal with them, you'd need to repeatedly split the line. You could use a while loop for it. Sincerely, Albert From kent37 at tds.net Thu Feb 26 16:06:22 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Feb 2009 10:06:22 -0500 Subject: [Tutor] re.format a file In-Reply-To: <9e3fac840902260543l557989abl34c01b677468d6f8@mail.gmail.com> References: <9e3fac840902260543l557989abl34c01b677468d6f8@mail.gmail.com> Message-ID: <1c2a2c590902260706s32f22f17l33858c3b2ac4a527@mail.gmail.com> On Thu, Feb 26, 2009 at 8:43 AM, prasad rao wrote: > hello > Thank you Lie and Kent. > I forgot ?about newline character and the fact that string can be sliced. > Thanks for your timely help > BTW I have gone through ?the Python library reference and find no examples > in fileinput module. > z=fileinput.input(file,inplace=1) > for line in ?z: > ???if len(line)<60:pass No need for the above line, it does nothing. Kent > ???if len(line)>60: > ??????line=line[:60]+'\n'+line[60:] > Is it the right way to do? > Thank you > Prasad From alan.gauld at btinternet.com Thu Feb 26 16:35:17 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Feb 2009 15:35:17 -0000 Subject: [Tutor] learning new features of python References: <288df32a0902260328g2c275a51ucaa490190edb5f2@mail.gmail.com> Message-ID: "Bala subramanian" wrote > Is there any website/tutorial that explains new features that are > constantly > getting embedded in python. The documentation for each release has a whats new document that is always worth reading. > Similaraly in Alan Guald Learn to program link, he has given > information on > opening a file with file() and open() functions. And in V3 they took that back out again :-( Alan G. From kent37 at tds.net Thu Feb 26 17:42:58 2009 From: kent37 at tds.net (Kent Johnson) Date: Thu, 26 Feb 2009 11:42:58 -0500 Subject: [Tutor] learning new features of python In-Reply-To: References: <288df32a0902260328g2c275a51ucaa490190edb5f2@mail.gmail.com> Message-ID: <1c2a2c590902260842v3a582b23ob22641f5ba90065c@mail.gmail.com> On Thu, Feb 26, 2009 at 10:35 AM, Alan Gauld wrote: > > "Bala subramanian" wrote >> Similaraly in Alan Guald Learn to program link, he has given information >> on >> opening a file with file() and open() functions. > > And in V3 they took that back out again :-( ?? open() is in V3. file() is not. Kent From jay at splitstreams.com Thu Feb 26 18:39:26 2009 From: jay at splitstreams.com (Jay Deiman) Date: Thu, 26 Feb 2009 11:39:26 -0600 Subject: [Tutor] cgi script to start another process in background In-Reply-To: <36601b010902220016h397a5881vc3cdd5f9573d665f@mail.gmail.com> References: <36601b010902220016h397a5881vc3cdd5f9573d665f@mail.gmail.com> Message-ID: <49A6D3CE.4060303@splitstreams.com> Ravi Kondamuru wrote: > Hi, > > I am trying to write a python cgi script, that invokes another process > and exists. > Using the subprocess documentation on NO_WAIT, I am not having much success: > > pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") > ==> > pid = Popen(["/bin/mycmd", "myarg"]).pid > > The script seems to wait for the new process to exit before returning to > the user. > > I tried doing the double-fork approach discussed here: > http://code.activestate.com/recipes/66012/ Are you on some kind of Unix box here? The fork approach should definitely work for you. An even simpler example, which should still work for you, is here: ======================== import os , time , sys print 'hello before the fork' if os.fork(): print 'parent exiting' sys.exit() print 'hello from child: %d' % os.getpid() time.sleep(30) os._exit(0) ======================== You should be able to verify that you have that process still running after the main process exits. -- Jay Deiman \033:wq! From jay at splitstreams.com Thu Feb 26 18:39:11 2009 From: jay at splitstreams.com (Jay Deiman) Date: Thu, 26 Feb 2009 11:39:11 -0600 Subject: [Tutor] passig parameter with CGI... In-Reply-To: References: Message-ID: <49A6D3BF.9030904@splitstreams.com> Spencer Parker wrote: > I am looking for a little instruction on how one would process a set of > parameters being sent to it through CGI. I have a script that sends > info to another script that lives on another server. The second script > would then process the information that is passed to it through a > parameters list in a URL. It would then trigger the script to do some > things via XMLRPC. I have the portion that connects to the XMLRPC > server, but not the 1st part. I can send it a list of command line > parameters, but the spec has changed. We want to do it with just curl > and send it parameters with a URL string. Not really looking for direct > code...just some ideas on how this is done for the most part. I looked > around, but nothing really fit what I wanted...mostly form > processing...thanks! I assume the receiving script is going to be a cgi or something like that. It sounds like all you want to do here is construct a GET request to send to a web server. ===================== import urllib options = {'optone': '1' , 'opttwo': '2' , 'optthree': '3'} url = 'http://www.example.com/path/to/script.cgi?%s' % \ urllib.urlencode(options) u = urllib.urlopen(url) # Here you can read the response if needs be response = u.read() u.close() ===================== That's about it. -- Jay Deiman \033:wq! From inthefridge at gmail.com Thu Feb 26 19:07:04 2009 From: inthefridge at gmail.com (Spencer Parker) Date: Thu, 26 Feb 2009 11:07:04 -0700 Subject: [Tutor] Class definition... Message-ID: I am looking for a good tutorial to walk through that really explains class definition. This has been one sticking point that always messes me up for the most part. That and when people use "self". For some reason I just can't grasp what people say. Any good pointers to throw at me? I really want to get this down so I can move forward in Python. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Thu Feb 26 19:16:59 2009 From: alan.gauld at btinternet.com (ALAN GAULD) Date: Thu, 26 Feb 2009 18:16:59 +0000 (GMT) Subject: [Tutor] learning new features of python References: <288df32a0902260328g2c275a51ucaa490190edb5f2@mail.gmail.com> <1c2a2c590902260842v3a582b23ob22641f5ba90065c@mail.gmail.com> Message-ID: <110717.84018.qm@web86709.mail.ird.yahoo.com> > >> Similaraly in Alan Guald Learn to program link, he has given information > >> on opening a file with file() and open() functions. > > > > And in V3 they took that back out again :-( > > ?? open() is in V3. file() is not. That's right, they have reverted to how it was in Python 1.X I changed all my pages to use file() in v2.2 then changed them to use a mixtyuure of file() and open() in 2.4 and now I'm changing them all back to open() for v3! :-( Alan G. From alan.gauld at btinternet.com Thu Feb 26 19:42:24 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 26 Feb 2009 18:42:24 -0000 Subject: [Tutor] Class definition... References: Message-ID: "Spencer Parker" wrote >I am looking for a good tutorial to walk through that really explains >class > definition. This has been one sticking point that always messes me > up I assume from that you have been through the basic tutors like mine? Have you tried the deeper material in Dive into Python and the official tutorial? If so then it is probnably better for you to give us some specific questions you have. Or post a bit of a tutorialyou don't understand and we can collectively try to clarify it. Specific questions are always easier to answer than generalities. > the most part. That and when people use "self". For some reason I > just > can't grasp what people say. Any good pointers to throw at me? OK, I explain self in my OOP tutor topic ( a sub heading under "Using Classes"), but again if thats not sufficient then you probably need to give us explicit examples of what you don't understand and your concerns. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From denis.spir at free.fr Thu Feb 26 19:43:29 2009 From: denis.spir at free.fr (spir) Date: Thu, 26 Feb 2009 19:43:29 +0100 Subject: [Tutor] learning new features of python In-Reply-To: <110717.84018.qm@web86709.mail.ird.yahoo.com> References: <288df32a0902260328g2c275a51ucaa490190edb5f2@mail.gmail.com> <1c2a2c590902260842v3a582b23ob22641f5ba90065c@mail.gmail.com> <110717.84018.qm@web86709.mail.ird.yahoo.com> Message-ID: <20090226194329.06fde3c2@o> Le Thu, 26 Feb 2009 18:16:59 +0000 (GMT), ALAN GAULD s'exprima ainsi: > > > >> Similaraly in Alan Guald Learn to program link, he has given > > >> information on opening a file with file() and open() functions. > > > > > > And in V3 they took that back out again :-( > > > > ?? open() is in V3. file() is not. > > That's right, they have reverted to how it was in Python 1.X > I changed all my pages to use file() in v2.2 then changed them > to use a mixtyuure of file() and open() in 2.4 and now I'm changing > them all back to open() for v3! :-( > > Alan G. Does someone know why this choice has been made? After all, the result is a file object, so imo it's consistent to use file() like for any other type. Denis ------ la vita e estrany From srilyk at gmail.com Thu Feb 26 20:24:56 2009 From: srilyk at gmail.com (W W) Date: Thu, 26 Feb 2009 13:24:56 -0600 Subject: [Tutor] Tkinter Grid, Listbox expand Message-ID: <333efb450902261124y4152e7f1u1c3a4ce50fed0fda@mail.gmail.com> Hi, I'm writing a Tkinter program and having severe problems with getting my listbox to expand when I resize the window. Here's my code so far: 1 from Tkinter import * 2 import os, shutil, tkFileDialog, tkMessageBox 3 4 class TkSync: 5 def __init__(self, root): 6 self.sbox = Listbox(root) 7 self.sbox.grid(row=0, column=0, sticky=N+S+E+W) 8 root.grid_rowconfigure(0, minsize=400) 9 root.grid_columnconfigure(0, minsize=400) 10 11 root = Tk() 12 TkSync(root) 13 root.mainloop() When I run that, it sizes right to start out... but then it won't get any bigger. I've tried various different combinations and nothing has worked quite right. TIA, Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi From ravikondamuru at gmail.com Thu Feb 26 20:30:05 2009 From: ravikondamuru at gmail.com (Ravi Kondamuru) Date: Thu, 26 Feb 2009 11:30:05 -0800 Subject: [Tutor] cgi script to start another process in background In-Reply-To: <49A6CCCE.2070709@splitstreams.com> References: <36601b010902220016h397a5881vc3cdd5f9573d665f@mail.gmail.com> <49A6CCCE.2070709@splitstreams.com> Message-ID: <36601b010902261130l27b092d0kd30495f08cbe44a8@mail.gmail.com> I am running this on a freebsd 4.9 system running apache server. I started with code that was as simple as yours. But the problem is apache does not print "hello before the fork" until the child exists.I have read at various forums that apache buffers till the script exists and in this case till the child exists and then the parent itself. So "hello before the fork" is printed after 30 secs on the browser. This approach I believe works when executed from the shell but not in the apache context. I finally got the script working after using the following recipe to make the process a daemon. http://code.activestate.com/recipes/278731/ In place of os.fork() in the script I called createDaemon mention from the module in the recipe and that did the trick. I had to convert the os._exit() to sys.exit() in the createDaemon function otherwise the was giving "Premature end of script headers" error. thanks, Ravi. On Thu, Feb 26, 2009 at 9:09 AM, Jay Deiman wrote: > Ravi Kondamuru wrote: > >> Hi, >> >> I am trying to write a python cgi script, that invokes another process and >> exists. >> Using the subprocess documentation on NO_WAIT, I am not having much >> success: >> >> pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg") >> ==> >> pid = Popen(["/bin/mycmd", "myarg"]).pid >> >> The script seems to wait for the new process to exit before returning to >> the user. >> >> I tried doing the double-fork approach discussed here: >> http://code.activestate.com/recipes/66012/ >> > > Are you on some kind of Unix box here? The fork approach should definitely > work for you. An even simpler example, which should still work for you, is > here: > > ======================== > import os , time , sys > > print 'hello before the fork' > > if os.fork(): > print 'parent exiting' > sys.exit() > > print 'hello from child: %d' % os.getpid() > time.sleep(30) > os._exit(0) > ======================== > > You should be able to verify that you have that process still running after > the main process exits. > > -- > Jay Deiman > > \033:wq! > -------------- next part -------------- An HTML attachment was scrubbed... URL: From srilyk at gmail.com Thu Feb 26 20:45:17 2009 From: srilyk at gmail.com (W W) Date: Thu, 26 Feb 2009 13:45:17 -0600 Subject: [Tutor] Tkinter Grid, Listbox expand Message-ID: <333efb450902261145x522b06a5u71210a86926d7e46@mail.gmail.com> Aha! I found the key - I was missing the weight argument: 1 from Tkinter import * 2 import os, shutil, tkFileDialog, tkMessageBox 3 4 class TkSync: 5 def __init__(self, root): 6 self.sbox = Listbox(root) 7 self.sbox.grid(row=0, column=0, sticky=N+S+E+W) 8 root.grid_rowconfigure(0, minsize=400, weight=1) 9 root.grid_columnconfigure(0, minsize=400, weight=1) 10 11 root = Tk() 12 TkSync(root) 13 root.mainloop() Works perfectly. -Wayne -- To be considered stupid and to be told so is more painful than being called gluttonous, mendacious, violent, lascivious, lazy, cowardly: every weakness, every vice, has found its defenders, its rhetoric, its ennoblement and exaltation, but stupidity hasn?t. - Primo Levi From mwalsh at mwalsh.org Thu Feb 26 20:59:25 2009 From: mwalsh at mwalsh.org (Martin Walsh) Date: Thu, 26 Feb 2009 13:59:25 -0600 Subject: [Tutor] re.format a file In-Reply-To: <49A6A443.9090209@tue.nl> References: <9e3fac840902260543l557989abl34c01b677468d6f8@mail.gmail.com> <49A6A443.9090209@tue.nl> Message-ID: <49A6F49D.90207@mwalsh.org> A.T.Hofkamp wrote: > prasad rao wrote: >> helloThank you Lie and Kent. >> I forgot about newline character and the fact that string can be sliced. >> Thanks for your timely help >> BTW I have gone through the Python library reference and find no >> examples >> in fileinput module. > > The fileinput module only deals with reading and writing data from/to > files, it does not deal with manipulating that data. > > How to manipulate strings is in the 'strings' or 'text' section of a > tutorial. > >> z=fileinput.input(file,inplace=1) >> for line in z: >> ???if len(line)<60:pass >> ???if len(line)>60: >> ??????line=line[:60]+'\n'+line[60:] >> Is it the right way to do? > > A nice step forward, I'd say. > > Did you consider what to do with ridiculous long lines, eg 200, 500, > 1000 or 10000 characters long? > If you want to deal with them, you'd need to repeatedly split the line. > You could use a while loop for it. Or if the lines resemble paragraphs, then one might use the textwrap module which breaks on word boundaries by default I think, and provides several options for tweaking -- perhaps not what the OP is looking for. # untested import textwrap for line in z: line = textwrap.fill(line, width=60) HTH, Marty From bmoll70 at att.net Fri Feb 27 03:43:52 2009 From: bmoll70 at att.net (bmoll70 at att.net) Date: Thu, 26 Feb 2009 21:43:52 -0500 Subject: [Tutor] setting PYTHONPATH on mac In-Reply-To: References: Message-ID: <278E2E21-9115-44F3-9E14-0F07A1190C0C@att.net> > how does one go about setting a PYTHON path environment variable on > Mac OS X 10.4? i set up my .profile in the Terminal.app (UNIX) with a text file with the following line: PATH=$PATH:/Applications/Autodesk/maya8.5/Maya.app/Contents/bin thanks, -b -------------- next part -------------- An HTML attachment was scrubbed... URL: From prasadaraon50 at gmail.com Fri Feb 27 05:29:40 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Fri, 27 Feb 2009 09:59:40 +0530 Subject: [Tutor] re Format a file Message-ID: <9e3fac840902262029k5f1cc9c4t5ae31435d48decf2@mail.gmail.com> HelloI don't know why, but this I think going into infinite loop. I cant see anything wrong in it. Please show me where the problem is. def myform(s): ???? import os ???? so=open(s) ???? d=os.path.dirname(s)+os.sep+'temp.txt' ???? de=open(d,'w') ???? for line in so: ???????? while len(line)>60: ????????????tem=line[60:] ????????????try: ??????????????? a,b=tem.split(' ',1) ??????????????? de.write(line[:60]+a+'\n') ??????????????? line=b ????????????except ValueError:pass ???????? de.write(line+'\n') ???? so.close() ???? de.close() ???? os.remove(s) ???? os.rename(d,s) Thank you Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at fouhy.net Fri Feb 27 05:53:48 2009 From: john at fouhy.net (John Fouhy) Date: Fri, 27 Feb 2009 17:53:48 +1300 Subject: [Tutor] re Format a file In-Reply-To: <9e3fac840902262029k5f1cc9c4t5ae31435d48decf2@mail.gmail.com> References: <9e3fac840902262029k5f1cc9c4t5ae31435d48decf2@mail.gmail.com> Message-ID: <5e58f2e40902262053l17e5513fp6720c464eb7396fd@mail.gmail.com> 2009/2/27 prasad rao : > Hello > I don't know why, but this I think going into infinite loop. > I cant see anything wrong in it. > Please show me where ?the problem is. [...] > ???????? while len(line)>60: > ????????????tem=line[60:] > ????????????try: > ????????????????a,b=tem.split(' ',1) > ????????????????de.write(line[:60]+a+'\n') > ????????????????line=b > ????????????except ValueError:pass So you have a while loop, whose condition depends on line. This will loop infinitely if the body of the loop does not change the value of line. Can you see how that could happen? -- John. From david at abbottdavid.com Fri Feb 27 06:06:59 2009 From: david at abbottdavid.com (David) Date: Fri, 27 Feb 2009 00:06:59 -0500 Subject: [Tutor] Class instance understanding = None Message-ID: <49A774F3.2060203@abbottdavid.com> Hi Everyone, I go through the archived [Tutor] mail list to find programs others have tried to do. I found one that would keep track of a petty cash fund. please point out my misunderstanding. Here is what I started with; #!/usr/bin/python from reportlab.lib.normalDate import ND #import cPickle as p #import pprint today = ND() class Account: def __init__(self, initial): self.balance = initial def deposit(self, amt): self.balance = self.balance + amt def withdraw(self, amt): self.balance = self.balance - amt def getbalance(self): return self.balance print 'The current date is: ', today.formatUS() data = float('100.00') a = Account(data) p = a.getbalance() print 'balance = ', p remove_data = float('50.00') w = a.withdraw(remove_data) print "withdraw = ", w add_data = float('50.00') add = a.deposit(add_data) print "deposit = ", add results; The current date is: 02/27/09 balance = 100.0 withdraw = None deposit = None expected results; The current date is: 02/27/09 balance = 100.0 withdraw = 50.0 deposit = 100.0 thanks, -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From valdemaras.jonikas at mac.com Fri Feb 27 05:45:07 2009 From: valdemaras.jonikas at mac.com (Valdemaras Jonikas) Date: Fri, 27 Feb 2009 06:45:07 +0200 Subject: [Tutor] setting PYTHONPATH on mac Message-ID: <150283243439569199884222623474014311977-Webmail@me.com> >> how does one go about setting a PYTHON path environment variable on >> Mac OS X 10.4? > >i set up my .profile in the Terminal.app (UNIX) with a text file with >the following line: >PATH=$PATH:/Applications/Autodesk/maya8.5/Maya.app/Contents/bin You should do more or less the same -- edit .bash_profile file and add these lines (replace [...] with actual path): PATH="[/absolute/path/to/folder/you/want]:${PATH}" export PATH Please note that if you add your new directory at the end of PATH (as in your example), then this new directory will be searched for executables last. In my example, when you add new directory at the beginning, this new new directory will be searched first. This could be useful if you have several version of Python on you computer. Good luck, Valdas From linuxlover00 at gmail.com Fri Feb 27 06:53:43 2009 From: linuxlover00 at gmail.com (Mohamed Hassan) Date: Thu, 26 Feb 2009 21:53:43 -0800 Subject: [Tutor] Extract strings from a text file Message-ID: <3f3eb0bd0902262153p21cfe972j705c490aa7c00aaf@mail.gmail.com> Hi all, I am new to Python and still trying to figure out some things. Here is the situation: There is a text file that looks like this: text text text Joseph text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text Joseph Smith text text text 1 text text text 0 This text file is very long, however all the entries in it looks the same at the above. What I am trying to do is: 1. I need to extract the name and the full name from this text file. For example: ( ID is Joseph & Full name is Joseph Smith). - I am thinking I need to write something that will check the whole text file line by line which I have done already. - Now what I am trying to figure out is : How can I write a function that will check to see if the line contains the word ID between < > then copy the letter after > until > and dump it to a text file. Can somebody help please. I know this might soudn easy for some people, but again I am new to Python and still figuring out things. Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Fri Feb 27 07:51:53 2009 From: denis.spir at free.fr (spir) Date: Fri, 27 Feb 2009 07:51:53 +0100 Subject: [Tutor] Class instance understanding = None In-Reply-To: <49A774F3.2060203@abbottdavid.com> References: <49A774F3.2060203@abbottdavid.com> Message-ID: <20090227075153.310054e9@o> Le Fri, 27 Feb 2009 00:06:59 -0500, David s'exprima ainsi: > Hi Everyone, > I go through the archived [Tutor] mail list to find programs others have > tried to do. I found one that would keep track of a petty cash fund. > please point out my misunderstanding. > Here is what I started with; > [...] > > > results; > The current date is: 02/27/09 > balance = 100.0 > withdraw = None > deposit = None > > expected results; > The current date is: 02/27/09 > balance = 100.0 > withdraw = 50.0 > deposit = 100.0 > > thanks, > -david So, what is your question, actually? If you do not want None, replace it with 0.0. None is good as a flag value. Denis ------ la vita e estrany From denis.spir at free.fr Fri Feb 27 07:58:19 2009 From: denis.spir at free.fr (spir) Date: Fri, 27 Feb 2009 07:58:19 +0100 Subject: [Tutor] Class instance understanding = None In-Reply-To: <49A774F3.2060203@abbottdavid.com> References: <49A774F3.2060203@abbottdavid.com> Message-ID: <20090227075819.2d516c4e@o> Le Fri, 27 Feb 2009 00:06:59 -0500, David s'exprima ainsi: > Hi Everyone, > I go through the archived [Tutor] mail list to find programs others have > tried to do. I found one that would keep track of a petty cash fund. > please point out my misunderstanding. > Here is what I started with; > > #!/usr/bin/python > > from reportlab.lib.normalDate import ND > #import cPickle as p > #import pprint > > today = ND() > > class Account: > def __init__(self, initial): > self.balance = initial > def deposit(self, amt): > self.balance = self.balance + amt > def withdraw(self, amt): > self.balance = self.balance - amt > def getbalance(self): > return self.balance > print 'The current date is: ', today.formatUS() > > > data = float('100.00') > a = Account(data) > p = a.getbalance() > print 'balance = ', p > remove_data = float('50.00') > w = a.withdraw(remove_data) > print "withdraw = ", w > add_data = float('50.00') > add = a.deposit(add_data) > print "deposit = ", add > > > results; > The current date is: 02/27/09 > balance = 100.0 > withdraw = None > deposit = None > > expected results; > The current date is: 02/27/09 > balance = 100.0 > withdraw = 50.0 > deposit = 100.0 > > thanks, > -david PS: I guess you misunderstand the methods withdraw and deposit: If you read the code (read it again), they *do* something, meaning they process an *action*. Understand they name as verbs. As a consequence they do not return anything result (they do not *make* anything). They are like Pascal procedures. So that you should state instead: w = float('50.00') ###w = a.withdraw(remove_data) print "withdraw = ", w denis ------ la vita e estrany From denis.spir at free.fr Fri Feb 27 08:22:32 2009 From: denis.spir at free.fr (spir) Date: Fri, 27 Feb 2009 08:22:32 +0100 Subject: [Tutor] Extract strings from a text file In-Reply-To: <3f3eb0bd0902262153p21cfe972j705c490aa7c00aaf@mail.gmail.com> References: <3f3eb0bd0902262153p21cfe972j705c490aa7c00aaf@mail.gmail.com> Message-ID: <20090227082232.092a5764@o> Le Thu, 26 Feb 2009 21:53:43 -0800, Mohamed Hassan s'exprima ainsi: > Hi all, > > I am new to Python and still trying to figure out some things. Here is the > situation: > > There is a text file that looks like this: > > text text text Joseph > text text text text text text text text text text text > text text text text text text text text text text text > text text text text text text text text text text text > text text text text text text text text text text text > text text text text text text text text text text text > text text text text text text text text text text text > text text text text text text text text text text text > text text text Joseph Smith > text text text 1 > text text text 0 > > > This text file is very long, however all the entries in it looks the same at > the above. > > What I am trying to do is: > > 1. I need to extract the name and the full name from this text file. For > example: ( ID is Joseph & Full name is Joseph Smith). > > > - I am thinking I need to write something that will check the whole text > file line by line which I have done already. > - Now what I am trying to figure out is : How can I write a function that > will check to see if the line contains the word ID between < > then copy the > letters after > until > and dump it to a text file. > > Can somebody help please. I know this might soudn easy for some people, but > again I am new to Python and still figuring out things. > > Thank you This is a typical text parsing job. There are tools for that. However, probably we would need a bit more information about the real text structure, and first of all what you wish to do with it later, to point you to the most appropriate tool. I guess that there is a higher level structure that nests IDs, names, rights etc in a section and that you will need to keep them together for further process. Anyway for a startup exploration you can use regular expressions (regex) to extract individual data item. For instance: from re import compile as Pattern pattern = Pattern(r""".*(.+)<.+>.*""") line = "text text text Joseph" print pattern.findall(line) text = """\ text text text Joseph text text text Jodia text text text Joobawap """ print pattern.findall(text) ==> ['Joseph'] ['Joseph', 'Jodia', 'Joobawap'] There is a nice tutorial on regexes somewhere (you will easily find). Key points on this example are: r""".*(.+)<.+>.*""" * the pattern between """...""" expresses the overall format to be matched * all what is between (...) will be extracted by findall * '.' mean 'any character'; '*' means zero or more of what is just before; '+' mean one or more of what is just before. So the pattern will look for chains that contains a sequence formed of: 1. possible start chars 2. literally 3. one or more chars -- to return 4. something between <...> 5. possible end chars Denis ------ la vita e estrany From lie.1296 at gmail.com Fri Feb 27 08:29:16 2009 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 27 Feb 2009 07:29:16 +0000 (UTC) Subject: [Tutor] re Format a file References: <9e3fac840902262029k5f1cc9c4t5ae31435d48decf2@mail.gmail.com> Message-ID: On Fri, 27 Feb 2009 09:59:40 +0530, prasad rao wrote: > def myform(s): > import os > so=open(s) > d=os.path.dirname(s)+os.sep+'temp.txt' > de=open(d,'w') > for line in so: > while len(line)>60: > item=line[60:] > try: > a,b=tem.split(' ',1) what is tem here? It must be a global, since I can't see any other reference to tem in the function definition. If tem is global, then the value of b (a.k.a. line) will never change (except for the first iteration) > de.write(line[:60]+a+'\n') > line=b > except ValueError: > pass > de.write(line+'\n') > so.close() > de.close() > os.remove(s) > os.rename(d,s) From wescpy at gmail.com Fri Feb 27 08:59:44 2009 From: wescpy at gmail.com (wesley chun) Date: Thu, 26 Feb 2009 23:59:44 -0800 Subject: [Tutor] Extract strings from a text file In-Reply-To: <3f3eb0bd0902262153p21cfe972j705c490aa7c00aaf@mail.gmail.com> References: <3f3eb0bd0902262153p21cfe972j705c490aa7c00aaf@mail.gmail.com> Message-ID: <78b3a9580902262359g5ffca594y760fd4f31426e88b@mail.gmail.com> > There is a text file that looks like this: > > text text text Joseph > text text text text text text text text text text text > text text text text text text text text text text text > text text text text text text text text text text text > text text text text text text text text text text text > text text text text text text text text text text text > text text text text text text text text text text text > text text text text text text text text text text text > text text text Joseph Smith > text text text 1 > text text text 0 > > What I am trying to do is: > > 1. I need to extract the name and the full name from this text file. For > example: ( ID is Joseph & Full name is Joseph Smith). in addition to denis' suggestion of using regular expressions, you can also look at the xml.etree module and have ElementTree parse them into tags for you, so all you have to do is ask for the ID and "Full name" tags to get your data. good luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From andreengels at gmail.com Fri Feb 27 09:00:39 2009 From: andreengels at gmail.com (Andre Engels) Date: Fri, 27 Feb 2009 09:00:39 +0100 Subject: [Tutor] Class instance understanding = None In-Reply-To: <6faf39c90902270000tf6f6836p88e1262bcda9ceca@mail.gmail.com> References: <49A774F3.2060203@abbottdavid.com> <6faf39c90902270000tf6f6836p88e1262bcda9ceca@mail.gmail.com> Message-ID: <6faf39c90902270000i3e6379b0yb8b932464f00c7b0@mail.gmail.com> On Fri, Feb 27, 2009 at 6:06 AM, David wrote: > Hi Everyone, > I go through the archived [Tutor] mail list to find programs others have > tried to do. I found one that would keep track of a petty cash fund. please > point out my misunderstanding. > Here is what I started with; > > #!/usr/bin/python > > from reportlab.lib.normalDate import ND > #import cPickle as p > #import pprint > > today = ND() > > class Account: > ? ?def __init__(self, initial): > ? ? ? ?self.balance = initial > ? ?def deposit(self, amt): > ? ? ? ?self.balance = self.balance + amt > ? ?def withdraw(self, amt): > ? ? ? ?self.balance = self.balance - amt > ? ?def getbalance(self): > ? ? ? ?return self.balance > print 'The current date is: ', today.formatUS() > > > data = float('100.00') > a = Account(data) > p = a.getbalance() > print 'balance = ', p > remove_data = float('50.00') > w = a.withdraw(remove_data) > print "withdraw = ", w > add_data = float('50.00') > add = a.deposit(add_data) > print "deposit = ", add > > > results; > The current date is: ?02/27/09 > balance = ?100.0 > withdraw = ?None > deposit = ?None > > expected results; > The current date is: ?02/27/09 > balance = ?100.0 > withdraw = ?50.0 > deposit = ?100.0 A method only returns a value if you do so explicitly, that is, end it with return value That's what happens in getbalance: return self.balance deposit and withdraw however do not return a value. If, like you do, you still try to extract their return value, it gives None. There are two ways to resolve this. The first gets closer to what you are trying to do, but is considered less proper programming, because it mixes functions of methods. In it, you add the returns to the methods: class Account: ? def __init__(self, initial): ? ? ? self.balance = initial ? def deposit(self, amt): ? ? ? self.balance = self.balance + amt ? ? ? return self.balance ? def withdraw(self, amt): ? ? ? self.balance = self.balance - amt ? ? ? return self.balance ? def getbalance(self): ? ? ? return self.balance The more preferable method is to leave the class alone, and call getbalance by hand: data = float('100.00') a = Account(data) p = a.getbalance() print 'balance = ', p remove_data = float('50.00') a.withdraw(remove_data) w = a.getbalance() print "withdraw = ", w add_data = float('50.00') a.deposit(add_data) add = a.getbalance() print "deposit = ", add Some other things: 1. data = float('100.00') is unnecessarily clumsy - you can specify floats directly without creating a string first by doing data = 100.0 2. You are creating a lot of variables only to use them for the one and only time on the next line. That's not necessarily bad, it sometimes improves readability especially if a lot is being done (which can then be split up in more readable parts), but doing it this much mostly causes your coding to look more complicated than it actually is. I would either prefer something like this: data = 100.0 remove_data = 50.0 add_data = 50.0 ? ? ? ?# first all input-like elements, so I know where to go when I want to change something trivial a = Account(data) print 'balance = ',a.getbalance() a.withdraw(remove_data) print 'balance after withdraw = ',a.getbalance() a.deposit(add_data) print 'balance after deposit = ',a.getbalance() doing away with p, w and add, or the even shorter variant where data, remove_data and add_data are also removed: a = Account(100.0) print 'balance = ',a.getbalance() a.withdraw(50.0) print 'balance after withdraw = ',a.getbalance() a.deposit(50.0) print 'balance after deposit = ',a.getbalance() -- Andr? Engels, andreengels at gmail.com From alan.gauld at btinternet.com Fri Feb 27 10:16:28 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Feb 2009 09:16:28 -0000 Subject: [Tutor] setting PYTHONPATH on mac References: <278E2E21-9115-44F3-9E14-0F07A1190C0C@att.net> Message-ID: wrote >> how does one go about setting a PYTHON path environment variable on >> Mac OS X 10.4? Your subject asks about PYTHONPATH, your text asks about PATH. These are two different things. Which do you want to know about? PATH is how Unix (ie MacOS aka Darwin) finds your Python interpreter PYTHONPATH is how python finds modules to import > i set up my .profile in the Terminal.app (UNIX) with a text file > with > the following line: > PATH=$PATH:/Applications/Autodesk/maya8.5/Maya.app/Contents/bin They are both set that way but you need to export them to take effect outside .profile You can use: export PATH=.... export PYTHONPATH=.... or PATH=.... export PATH PYTHONPATH=... export PYTHONPATH You might find this page helpful http://club.mandriva.com/xwiki/bin/view/KB/BasicsBshell5 Or search the Apple help files there is a page there describing the use of bash and bash_profile settings. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l From prasadaraon50 at gmail.com Fri Feb 27 11:09:35 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Fri, 27 Feb 2009 15:39:35 +0530 Subject: [Tutor] re Format a file Message-ID: <9e3fac840902270209t1aff9be3l9198e535c3434618@mail.gmail.com> HelloFinally I managed to writ a function to format a file. Thank to everybody for their tips. def mmm(a): ???? import os,textwrap ???? so=open(a) ???? d=os.path.dirname(a)+os.sep+'temp.txt' ???? de=open(d,'w') ???? import textwrap ???? for line in so: ???????? if len(line)<70:de.write(line+'\n') ???????? if len(line)>70: ???????????? da=textwrap.fill(line,width=60) ???????????? de.write(da+'\n') ???? so.close() ???? de.close() Any improvements and suggestions are welcome. Thanks Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From emadnawfal at gmail.com Fri Feb 27 12:49:10 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Fri, 27 Feb 2009 06:49:10 -0500 Subject: [Tutor] Extract strings from a text file In-Reply-To: <78b3a9580902262359g5ffca594y760fd4f31426e88b@mail.gmail.com> References: <3f3eb0bd0902262153p21cfe972j705c490aa7c00aaf@mail.gmail.com> <78b3a9580902262359g5ffca594y760fd4f31426e88b@mail.gmail.com> Message-ID: <652641e90902270349v760409exb318b7f9371ee55d@mail.gmail.com> On Fri, Feb 27, 2009 at 2:59 AM, wesley chun wrote: > > There is a text file that looks like this: > > > > text text text Joseph > > text text text text text text text text text text text > > text text text text text text text text text text text > > text text text text text text text text text text text > > text text text text text text text text text text text > > text text text text text text text text text text text > > text text text text text text text text text text text > > text text text text text text text text text text text > > text text text Joseph Smith > > text text text 1 > > text text text 0 > > > > What I am trying to do is: > > > > 1. I need to extract the name and the full name from this text file. For > > example: ( ID is Joseph & Full name is Joseph Smith). > > > in addition to denis' suggestion of using regular expressions, you can > also look at the xml.etree module and have ElementTree parse them into > tags for you, so all you have to do is ask for the ID and "Full name" > tags to get your data. > > good luck! > -- wesley > - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - > "Core Python Programming", Prentice Hall, (c)2007,2001 > "Python Fundamentals", Prentice Hall, (c)2009 > http://corepython.com > > wesley.j.chun :: wescpy-at-gmail.com > python training and technical consulting > cyberweb.consulting : silicon valley, ca > http://cyberwebconsulting.com > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Since I'm learning Pyparsing, this was a nice excercise. I've written this elementary script which does the job well in light of the data we have from pyparsing import * ID_TAG = Literal("") FULL_NAME_TAG1 = Literal("") END_TAG = Literal("', 'Joseph', '', 'Joseph', 'Smith', ' From alan.gauld at btinternet.com Fri Feb 27 12:53:41 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Fri, 27 Feb 2009 11:53:41 -0000 Subject: [Tutor] re Format a file References: <9e3fac840902270209t1aff9be3l9198e535c3434618@mail.gmail.com> Message-ID: "prasad rao" wrote > ???? for line in so: > ???????? if len(line)<70:de.write(line+'\n') > ???????? if len(line)>70: > ???????????? da=textwrap.fill(line,width=60) > ???????????? de.write(da+'\n') What happens if the line is exactly 70 characters long? I think you want an else instead of the second if.... -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From kent37 at tds.net Fri Feb 27 13:07:21 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Feb 2009 07:07:21 -0500 Subject: [Tutor] Extract strings from a text file In-Reply-To: <20090227082232.092a5764@o> References: <3f3eb0bd0902262153p21cfe972j705c490aa7c00aaf@mail.gmail.com> <20090227082232.092a5764@o> Message-ID: <1c2a2c590902270407l131e2246i5777924c952a70b4@mail.gmail.com> On Fri, Feb 27, 2009 at 2:22 AM, spir wrote: > Anyway for a startup exploration you can use regular expressions (regex) to extract individual data item. For instance: > > from re import compile as Pattern > pattern = Pattern(r""".*(.+)<.+>.*""") > line = "text text text Joseph" > print pattern.findall(line) > text = """\ > text text text Joseph > text text text Jodia > text text text Joobawap > """ > print pattern.findall(text) > ==> > ['Joseph'] > ['Joseph', 'Jodia', 'Joobawap'] You need to be a bit careful with wildcards, your regex doesn't work correctly if there are two s on a line: In [7]: re.findall(r""".*(.+)<.+>.*""", 'text JosephMary') Out[7]: ['Mary'] The problem is that the initial .* matches the whole line; the regex then backtracks to the second , finds a match and stops. Taking out the initial .* shows another problem: In [8]: re.findall(r"""(.+)<.+>""", 'text JosephMary') Out[8]: ['JosephMary'] Now (.+) is matching to the end of the line, then backing up to find the last <. One way to fix this is to use non-greedy matching: In [10]: re.findall(r"""(.+?)<""", 'text JosephMary') Out[10]: ['Joseph', 'Mary'] Another way is to specifically exclude the character you are matching from the wildcard match: In [11]: re.findall(r"""([^[<]+)<""", 'text JosephMary') Out[11]: ['Joseph', 'Mary'] Kent From roadierich at googlemail.com Fri Feb 27 14:54:50 2009 From: roadierich at googlemail.com (Richard Lovely) Date: Fri, 27 Feb 2009 13:54:50 +0000 Subject: [Tutor] Passing perimeters in dictionary values? In-Reply-To: References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com> <111a9ddb0902241625h71b9402bq7a9c7efc726c6038@mail.gmail.com> <111a9ddb0902241732l1be7d6dcwf65ffb463bcf941a@mail.gmail.com> Message-ID: On 25/02/2009, Alan Gauld wrote: > > "nathan virgil" wrote > > > Whenever I try to use the talk method (which reports the mood, and doesn't > > take parameters), it says I gave it too many parameters. > > > > Sorry, I should have pointed out that you will need to redefine > all your functions to accept a parameter. > > Alan G > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > Always makes me smile when (experienced) people redesign the wheel... >From the docs (http://www.python.org/doc/2.6/library/functools.html): "The partial() is used for partial function application which ?freezes? some portion of a function?s arguments and/or keywords resulting in a new object with a simplified signature." -- Richard "Roadie Rich" Lovely, part of the JNP|UK Famile www.theJNP.com From david at abbottdavid.com Fri Feb 27 15:24:10 2009 From: david at abbottdavid.com (David) Date: Fri, 27 Feb 2009 09:24:10 -0500 Subject: [Tutor] Class instance understanding = None In-Reply-To: <6faf39c90902270000i3e6379b0yb8b932464f00c7b0@mail.gmail.com> References: <49A774F3.2060203@abbottdavid.com> <6faf39c90902270000tf6f6836p88e1262bcda9ceca@mail.gmail.com> <6faf39c90902270000i3e6379b0yb8b932464f00c7b0@mail.gmail.com> Message-ID: <49A7F78A.4000609@abbottdavid.com> Thank you spir and Andre for the explanation. You are very good teachers. I can now continue. I am sure I will be back. Next I am going to set up a menu to enter amounts and also a way to store the resulting balance. Is cPickle a good way to do this? -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From bala.biophysics at gmail.com Fri Feb 27 15:33:24 2009 From: bala.biophysics at gmail.com (Bala subramanian) Date: Fri, 27 Feb 2009 15:33:24 +0100 Subject: [Tutor] concatenating files Message-ID: <288df32a0902270633h1a687077ke614ba1535f4ea20@mail.gmail.com> Hai, I have file1.dat,file2.dat...file 300.dat in one directory. I want to concatenate all the files in a single file (total.dat) with a string "END" separating the file contents. my total.dat should be file1.dat contents END file2.dat contents END ---- ---- file300.dat. now i have another 400 such *.dat files in another directory whose contents i hve to append to "total.dat", how can i do this task. i need to do something like, updating the file total.dat without overwritting it. Thanks, Bala -------------- next part -------------- An HTML attachment was scrubbed... URL: From david at abbottdavid.com Fri Feb 27 15:37:54 2009 From: david at abbottdavid.com (David) Date: Fri, 27 Feb 2009 09:37:54 -0500 Subject: [Tutor] Class instance understanding = None In-Reply-To: <6faf39c90902270000i3e6379b0yb8b932464f00c7b0@mail.gmail.com> References: <49A774F3.2060203@abbottdavid.com> <6faf39c90902270000tf6f6836p88e1262bcda9ceca@mail.gmail.com> <6faf39c90902270000i3e6379b0yb8b932464f00c7b0@mail.gmail.com> Message-ID: <49A7FAC2.7040408@abbottdavid.com> Thank you spir and Andre for the explanation. You are very good teachers. I can now continue. I am sure I will be back. Next I am going to set up a menu to enter amounts and also a way to store the resulting balance. Is cPickle a good way to do this? -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From ptmcg at austin.rr.com Fri Feb 27 16:01:44 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 27 Feb 2009 09:01:44 -0600 Subject: [Tutor] Extract strings from a text file In-Reply-To: References: Message-ID: <4FB511C6321F45FF9D99AEC07FB7352F@AWA2> Emad wrote: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Since I'm learning Pyparsing, this was a nice excercise. I've written this elementary script which does the job well in light of the data we have from pyparsing import * ID_TAG = Literal("") FULL_NAME_TAG1 = Literal("") END_TAG = Literal("', 'Joseph', '', 'Joseph', 'Smith', '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Welcome to the world of pyparsing! Your program is a very good first cut at this problem. Let me add some suggestions (more like hints toward more advanced concepts in your pyparsing learning): - Look into Group, as in Group(OneOrMore(word)), this will add organization and structure to the returned results. - Results names will make it easier to access the separate parsed fields. - Check out the makeHTMLTags and makeXMLTags helper methods - these do more than just wrap angle brackets around a tag name, but also handle attributes in varying order, case variability, and (of course) varying whitespace - the OP didn't explicitly say this XML data, but the sample does look suspicious. If you only easy_install'ed pyparsing or used the binary windows installer, please go back to SourceForge and download the source .ZIP or tarball package - these have the full examples and htmldoc directories that the auto-installers omit. Good luck in your continued studies! -- Paul From emadnawfal at gmail.com Fri Feb 27 16:08:07 2009 From: emadnawfal at gmail.com (=?windows-1256?B?RW1hZCBOYXdmYWwgKNrjx88g5Obd4Sk=?=) Date: Fri, 27 Feb 2009 10:08:07 -0500 Subject: [Tutor] Extract strings from a text file In-Reply-To: <4FB511C6321F45FF9D99AEC07FB7352F@AWA2> References: <4FB511C6321F45FF9D99AEC07FB7352F@AWA2> Message-ID: <652641e90902270708k3855abadn496b444f4c71f9b0@mail.gmail.com> On Fri, Feb 27, 2009 at 10:01 AM, Paul McGuire wrote: > Emad wrote: > >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> > Since I'm learning Pyparsing, this was a nice excercise. I've written this > elementary script which does the job well in light of the data we have > > from pyparsing import * > ID_TAG = Literal("") > FULL_NAME_TAG1 = Literal(" FULL_NAME_TAG2 = Literal("name>") > END_TAG = Literal(" word = Word(alphas) > pattern1 = ID_TAG + word + END_TAG > pattern2 = FULL_NAME_TAG1 + FULL_NAME_TAG2 + OneOrMore(word) + END_TAG > result = pattern1 | pattern2 > > lines = open("lines.txt")# This is your file name > for line in lines: > myresult = result.searchString(line) > if myresult: > print myresult[0] > > > # This prints out > ['', 'Joseph', ' ['', 'Joseph', 'Smith', ' > # You can access the individual elements of the lists to pick whatever you > want > > Emad - > >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> > > Welcome to the world of pyparsing! Your program is a very good first cut > at > this problem. Let me add some suggestions (more like hints toward more > advanced concepts in your pyparsing learning): > - Look into Group, as in Group(OneOrMore(word)), this will add organization > and structure to the returned results. > - Results names will make it easier to access the separate parsed fields. > - Check out the makeHTMLTags and makeXMLTags helper methods - these do more > than just wrap angle brackets around a tag name, but also handle attributes > in varying order, case variability, and (of course) varying whitespace - > the > OP didn't explicitly say this XML data, but the sample does look > suspicious. > > If you only easy_install'ed pyparsing or used the binary windows installer, > please go back to SourceForge and download the source .ZIP or tarball > package - these have the full examples and htmldoc directories that the > auto-installers omit. > > Good luck in your continued studies! > -- Paul > > Thanks Paul. I've read lots ABOUT pyparsing, but doing is different. Programming is mostly fun just for fun for me. I'm a linguist surrounded by many programmers. I enjoy Python and Pyparsing a lot. -- ?? ???? ?????? ????? ????? ??? ???? ??? ????? ?? ?????? ????????.....???? ??????? "No victim has ever been more repressed and alienated than the truth" Emad Soliman Nawfal Indiana University, Bloomington -------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From inthefridge at gmail.com Fri Feb 27 18:19:23 2009 From: inthefridge at gmail.com (Spencer Parker) Date: Fri, 27 Feb 2009 10:19:23 -0700 Subject: [Tutor] Class definition... In-Reply-To: References: Message-ID: Your tutorial is awesome...thanks again... The biggest confusion I have just had is the self.balance kind of thing. I need to just remember how it is treating each individual statement is all. Remember how everything is basically an object...just wrapping my brain around it for the most part. On Thu, Feb 26, 2009 at 11:42 AM, Alan Gauld wrote: > > "Spencer Parker" wrote > > I am looking for a good tutorial to walk through that really explains >> class >> definition. This has been one sticking point that always messes me up >> > > I assume from that you have been through the basic tutors like mine? > > Have you tried the deeper material in Dive into Python and the official > tutorial? > > If so then it is probnably better for you to give us some specific > questions you have. Or post a bit of a tutorialyou don't understand > and we can collectively try to clarify it. Specific questions are always > easier to answer than generalities. > > the most part. That and when people use "self". For some reason I just >> can't grasp what people say. Any good pointers to throw at me? >> > > OK, I explain self in my OOP tutor topic ( a sub heading under > "Using Classes"), but again if thats not sufficient then you probably > need to give us explicit examples of what you don't understand and > your concerns. > > HTH, > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > -------------- next part -------------- An HTML attachment was scrubbed... URL: From administrador.de.red at gmail.com Fri Feb 27 18:19:50 2009 From: administrador.de.red at gmail.com (Network Administrator) Date: Fri, 27 Feb 2009 11:19:50 -0600 Subject: [Tutor] Add elements to list and display it [Very newbie question] Message-ID: I am beggining to learn Python and I appreciate if you help me with this: "I want a piece of a program to request the user to input "elements" (numbers, text, etc) and store them into a list. Then, I want to display all the elements one-per-line." I started using this code: #!/usr/bin/env python ##################### # This function fills any given list # and display its content. # x = 0 # Variable "x" initiallized to zero, just because Python required it while (x != 't2' ): # On user's input "t2", no more input must be required list = [] # I start a zero-elements list x = raw_input('Enter your number or text: ') # Software asks for user's input. list.append(x) # User's input is append to the list "list" for x in list: # It asks to enter the list and... print x # print their elements. Unfortunately, this code fails to do what I expect. I notice that user's input is not being append to the list, so, when I require to print the elements of the list only "t2" is displayed. I don't know how to append elements to a list on user's input. I appreciate your clearence. Regards, Will. -------------- next part -------------- An HTML attachment was scrubbed... URL: From denis.spir at free.fr Fri Feb 27 18:44:11 2009 From: denis.spir at free.fr (spir) Date: Fri, 27 Feb 2009 18:44:11 +0100 Subject: [Tutor] Add elements to list and display it [Very newbie question] In-Reply-To: References: Message-ID: <20090227184411.70084c71@o> Le Fri, 27 Feb 2009 11:19:50 -0600, Network Administrator s'exprima ainsi: > I am beggining to learn Python and I appreciate if you help me with this: > > "I want a piece of a program to request the user to input "elements" > (numbers, text, etc) and store them into a list. Then, I want to display all > the elements one-per-line." > > I started using this code: > > #!/usr/bin/env python > ##################### > # This function fills any given list > # and display its content. > # > x = 0 # Variable "x" initiallized to zero, just > because Python required it > while (x != 't2' ): # On user's input "t2", no more input must be > required > list = [] # I start a zero-elements list > x = raw_input('Enter your number or text: ') # Software > asks for user's input. > > list.append(x) > # User's input is append to the list "list" > > for x in list: # It asks to enter the list and... > print x # print their elements. > > Unfortunately, this code fails to do what I expect. I notice that user's > input is not being append to the list, so, when I require to print the > elements of the list only "t2" is displayed. I don't know how to append > elements to a list on user's input. Hello Will, Just watch the algorithm you designed for the task -- pretty sure you will find the issue yourself: -0- init a variable that will store individual input === enter a loop -- will be quit on "flag" input -1- set input list empty -2- get user input -3- append it to the list -4- print list An additional question: should 't2' be stored into the list? denis ------ la vita e estrany From david at abbottdavid.com Fri Feb 27 18:51:56 2009 From: david at abbottdavid.com (David) Date: Fri, 27 Feb 2009 12:51:56 -0500 Subject: [Tutor] Class instance understanding = None In-Reply-To: <6faf39c90902270000tf6f6836p88e1262bcda9ceca@mail.gmail.com> References: <49A774F3.2060203@abbottdavid.com> <6faf39c90902270000tf6f6836p88e1262bcda9ceca@mail.gmail.com> Message-ID: <49A8283C.8020502@abbottdavid.com> Andre Engels wrote: > > The more preferable method is to leave the class alone, and call > getbalance by hand: > > data = float('100.00') > a = Account(data) > p = a.getbalance() > print 'balance = ', p > remove_data = float('50.00') > a.withdraw(remove_data) > w = a.getbalance() > print "withdraw = ", w > add_data = float('50.00') > a.deposit(add_data) > add = a.getbalance() > print "deposit = ", add > > Some other things: > 1. data = float('100.00') is unnecessarily clumsy - you can specify > floats directly without creating a string first by doing data = 100.0 > 2. You are creating a lot of variables only to use them for the one > and only time on the next line. That's not necessarily bad, it > sometimes improves readability especially if a lot is being done > (which can then be split up in more readable parts), but doing it this > much mostly causes your coding to look more complicated than it > actually is. I would either prefer something like this: > > data = 100.0 > remove_data = 50.0 > add_data = 50.0 # first all input-like elements, so I know > where to go when I want to change something trivial > a = Account(data) > print 'balance = ',a.getbalance() > a.withdraw(remove_data) > print 'balance after withdraw = ',a.getbalance() > a.deposit(add_data) > print 'balance after deposit = ',a.getbalance() > > doing away with p, w and add, or the even shorter variant where data, > remove_data and add_data are also removed: > > a = Account(100.0) > print 'balance = ',a.getbalance() > a.withdraw(50.0) > print 'balance after withdraw = ',a.getbalance() > a.deposit(50.0) > print 'balance after deposit = ',a.getbalance() > Ok almost there, here is what i have now; http://linuxcrazy.pastebin.com/m6b090d2d My problem now is the balance is updated from the file that is pickled fine, but the first entry goes is not added to that total. I know it is in this part; start_total() start = 0 a = Account(start) but when I change it to; start_total() start = start_total() a = Account(start) here is the error; Enter Amount: 100 Traceback (most recent call last): File "./py_pettycash.py", line 77, in menu() File "./py_pettycash.py", line 53, in menu a.deposit(cash) File "./py_pettycash.py", line 15, in deposit self.balance = self.balance + amt TypeError: unsupported operand type(s) for +: 'NoneType' and 'Decimal' -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From jay at splitstreams.com Fri Feb 27 18:54:28 2009 From: jay at splitstreams.com (Jay Deiman) Date: Fri, 27 Feb 2009 11:54:28 -0600 Subject: [Tutor] concatenating files In-Reply-To: <288df32a0902270633h1a687077ke614ba1535f4ea20@mail.gmail.com> References: <288df32a0902270633h1a687077ke614ba1535f4ea20@mail.gmail.com> Message-ID: <49A828D4.4050309@splitstreams.com> Bala subramanian wrote: > Hai, > > I have file1.dat,file2.dat...file 300.dat in one directory. I want to > concatenate all the files in a single file (total.dat) with a string > "END" separating the file contents. > my total.dat should be > file1.dat contents > END > file2.dat contents > END > ---- > ---- > file300.dat. > > now i have another 400 such *.dat files in another directory whose > contents i hve to append to "total.dat", how can i do this task. i need > to do something like, updating the file total.dat without overwritting it. > > Thanks, > Bala This should about do it: ------------------------------------- #!/usr/bin/env python import sys , os , glob startDir = '' totalFile = '/path/to/total.dat' if len(sys.argv) > 1 and os.path.isdir(sys.argv[1]): startDir = sys.argv[1] else: print 'Usage: %s ' % os.path.basename(sys.argv[0]) sys.exit(1) tfh = open(totalFile , 'a') for f in glob.glob(os.path.join(startDir , '*.dat')): tfh.write('%s contents\n' % f) tfh.write(open(f).read()) tfh.write('\nEND\n') tfh.close() ------------------------------------- All you have to do is set "totalFile" to your main output file and then call the script as "scriptname.py /path/to/datfile/directory". -- Jay Deiman \033:wq! From david at abbottdavid.com Fri Feb 27 19:27:32 2009 From: david at abbottdavid.com (David) Date: Fri, 27 Feb 2009 13:27:32 -0500 Subject: [Tutor] Class instance understanding = None In-Reply-To: <49A8283C.8020502@abbottdavid.com> References: <49A774F3.2060203@abbottdavid.com> <6faf39c90902270000tf6f6836p88e1262bcda9ceca@mail.gmail.com> <49A8283C.8020502@abbottdavid.com> Message-ID: <49A83094.2060102@abbottdavid.com> David wrote: > but when I change it to; > start_total() > start = start_total() > a = Account(start) > > here is the error; > Enter Amount: 100 > Traceback (most recent call last): > File "./py_pettycash.py", line 77, in > menu() > File "./py_pettycash.py", line 53, in menu > a.deposit(cash) > File "./py_pettycash.py", line 15, in deposit > self.balance = self.balance + amt > TypeError: unsupported operand type(s) for +: 'NoneType' and 'Decimal' > > -david > > Ok I got it, same problem I had before no return :) def start_total(): fname = open("cash.dat", "r") contents = cPickle.Unpickler(fname) data = contents.load() print "The current balance is", data fname.close() return data start = start_total() a = Account(start) Thanks all, any other comments?, I am going to add some error checking but, I am so happy, woopee -david -- Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com pgp.mit.edu From haztang17 at gmail.com Fri Feb 27 19:38:55 2009 From: haztang17 at gmail.com (Hi) Date: Fri, 27 Feb 2009 10:38:55 -0800 Subject: [Tutor] Auto Refresh Message-ID: I am trying to read a value in a variable from a different class every time I click on a refresh button for my GUI program. The problem is I am using statictext so when I refresh, it displays the new value on top of the old one. In my main GUI: def refresh(self, event): x = refresh_var() value = wx.StaticText(self, -1, str(x.var_rate)) In my refresh class: class refresh_var(): def var_rate(self): random_var = random.randint(5, 100) return random_var So each time I click on the button, which runs refresh, the new value generated by random.randint will be on top of the old number. Is there any commands I can use to remove the old value that is on the GUI window before I put the new one on there? Or is there a better command/syntax that does the same job? I am ultimately trying to make it so the GUI program refreshes and rereads random_var on a set interval. Can anyone offer any advice on how to do it or any commands I can read up on the Internet? -------------- next part -------------- An HTML attachment was scrubbed... URL: From wescpy at gmail.com Fri Feb 27 22:44:45 2009 From: wescpy at gmail.com (wesley chun) Date: Fri, 27 Feb 2009 13:44:45 -0800 Subject: [Tutor] Class definition... In-Reply-To: References: Message-ID: <78b3a9580902271344v40a6c83cy64d2ef8f545f3925@mail.gmail.com> >> I am looking for a good tutorial to walk through that really explains class >> definition. > > I assume from that you have been through the basic tutors like mine? > : > OK, I explain self in my OOP tutor topic ( a sub heading under > "Using Classes"), but again if thats not sufficient then you probably > need to give us explicit ?examples of what you don't understand and > your concerns. similarly, i go through a deep and comprehensive treatment of all aspects of object-oriented programming in Python, from the highest-level intro all the way through metaclasses in the OOP chapter (13) of Core Python (see below). when you're beyond alan's great tutorial as well as mark's dive, i hope you'll find Core Python a useful resource to putting it all together. best of luck! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 "Python Fundamentals", Prentice Hall, (c)2009 http://corepython.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From sanelson at gmail.com Fri Feb 27 22:58:08 2009 From: sanelson at gmail.com (Stephen Nelson-Smith) Date: Fri, 27 Feb 2009 21:58:08 +0000 Subject: [Tutor] Not Storing State Message-ID: Hi, This is both a general question and a specific one. I want to iterate over a bunch of lines; If any line contains a certain string, I want to do something, otherwise do something else. I can store state - eg line 1 - did it contain the string? no.. ok we're cool, next line.... But, I'd like to avoid keeping state. How can I do this? S. From kent37 at tds.net Fri Feb 27 23:01:12 2009 From: kent37 at tds.net (Kent Johnson) Date: Fri, 27 Feb 2009 17:01:12 -0500 Subject: [Tutor] re Format a file In-Reply-To: <9e3fac840902270209t1aff9be3l9198e535c3434618@mail.gmail.com> References: <9e3fac840902270209t1aff9be3l9198e535c3434618@mail.gmail.com> Message-ID: <1c2a2c590902271401jaa58472j717bcf2c334975c3@mail.gmail.com> On Fri, Feb 27, 2009 at 5:09 AM, prasad rao wrote: > Hello > Finally I ?managed to writ a function to format a file. > Thank to everybody for their tips. > > def mmm(a): > ???? import os,textwrap > ???? so=open(a) > ???? d=os.path.dirname(a)+os.sep+'temp.txt' > ???? de=open(d,'w') > ???? import textwrap > ???? for line in so: > ???????? if len(line)<70:de.write(line+'\n') You are introducing an extra newline here, line already ends in a newline. > ???????? ?if len(line)>70: > ?????????????da=textwrap.fill(line,width=60) > ?????????????de.write(da+'\n') Not sure if textwrap strips the trailing newline, if not, this is also double-spacing. Kent From kkwaiser at umich.edu Fri Feb 27 22:40:31 2009 From: kkwaiser at umich.edu (Kyle Kwaiser) Date: Fri, 27 Feb 2009 16:40:31 -0500 Subject: [Tutor] Convert a string of numbers to a list In-Reply-To: <1c2a2c590902260345l5e51801foe68c48197ae28685@mail.gmail.com> References: <20090226020037.14827f8djp59brsw@web.mail.umich.edu> <1c2a2c590902260345l5e51801foe68c48197ae28685@mail.gmail.com> Message-ID: <49A85DCF.8070401@umich.edu> Turns out I was close but had not combined everything. I never would have picked up on the map() function. Much more efficient than looping through the whole mess and converting to int. x = ['[335, 180, 201, 241, 199]\r\n'] y = map( int, x[0].strip( '[]\r\n' ).split( ', ' ) ) #need an index here print y [335, 180, 201, 241, 199] Thanks for your help! kbk Kent Johnson wrote: > For one line: > In [11]: s = '[335, 180, 201, 241, 199]\r\n' > > In [12]: map(int, s.strip('[]\r\n').split(', ')) > Out[12]: [335, 180, 201, 241, 199] > > Modify appropriately to handle a list of lines. > > Kent From alan.gauld at btinternet.com Sat Feb 28 01:33:09 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Feb 2009 00:33:09 -0000 Subject: [Tutor] Passing perimeters in dictionary values? References: <111a9ddb0902241103jb046840kf87ba8d442f5f458@mail.gmail.com><111a9ddb0902241625h71b9402bq7a9c7efc726c6038@mail.gmail.com><111a9ddb0902241732l1be7d6dcwf65ffb463bcf941a@mail.gmail.com> Message-ID: "Richard Lovely" wrote > > Sorry, I should have pointed out that you will need to redefine > > all your functions to accept a parameter. > >Always makes me smile when (experienced) people redesign the wheel... > >From the docs (http://www.python.org/doc/2.6/library/functools.html): > > "The partial() is used for partial function application which > ?freezes? some portion of a function?s arguments and/or keywords > resulting in a new object with a simplified signature." I'm not sure how you would use partial in this case, I still think you'd need to add a parameter to the function definitions. partial would remove the need for lambda in some of the other solutions though. But an interesting module that I've not seen before. Although since it was only introduced in 2.5 I'm not surprised, I've been focussing more on v3 lately rather than the new stuff in 2.5/2.6 (in fact I don't even have 2.6 loaded yet and only have 2.5 on one PC...) Thanks for highlighting it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Feb 28 01:46:14 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Feb 2009 00:46:14 -0000 Subject: [Tutor] concatenating files References: <288df32a0902270633h1a687077ke614ba1535f4ea20@mail.gmail.com> Message-ID: "Bala subramanian" wrote > I have file1.dat,file2.dat...file 300.dat in one directory. I want > to > concatenate all the files in a single file (total.dat) with a > string "END" > separating the file contents. > my total.dat should be > file1.dat contents > END > file2.dat contents > END > ---- > ---- > file300.dat. > > now i have another 400 such *.dat files in another directory whose > contents > i hve to append to "total.dat", how can i do this task. i need to do > something like, updating the file total.dat without overwritting it. > > Thanks, > Bala > -------------------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at btinternet.com Sat Feb 28 01:52:44 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Feb 2009 00:52:44 -0000 Subject: [Tutor] concatenating files References: <288df32a0902270633h1a687077ke614ba1535f4ea20@mail.gmail.com> Message-ID: "Bala subramanian" wrote > I have file1.dat,file2.dat...file 300.dat in one directory. I want > to > concatenate all the files in a single file (total.dat) with a > string "END" > separating the file contents. If you are on Linux (or other *nix variant) you may be better off using the shell... for f in *.dat do cat $f >> total.dat echo "END" >> total.dat done Will do it for you. If you are on Windoze then you need to write a batch file and then execute it within the for loop so I'd just stick with Python there. (Or install cygwin :-) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Feb 28 02:00:21 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Feb 2009 01:00:21 -0000 Subject: [Tutor] Auto Refresh References: Message-ID: "Hi" wrote > In my main GUI: > > def refresh(self, event): > x = refresh_var() > value = wx.StaticText(self, -1, str(x.var_rate)) Its not clear how you are positioning Static Text, I suspect you need it as a opart of your main GUI and then reference it in here and use the SetLabel() method to update its contents. But I also not that you are not calling the var_rate method of x. Or does your code really look like value = wx.StaticText(self, -1, str(x.var_rate())) Notice the extra parens... > So each time I click on the button, which runs refresh, the new > value > generated by random.randint will be on top of the old number. Is > there any > commands I can use to remove the old value that is on the GUI window > before > I put the new one on there? I think you can just update the content of the original Text widget using SetLabel() -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From alan.gauld at btinternet.com Sat Feb 28 02:03:35 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Feb 2009 01:03:35 -0000 Subject: [Tutor] Not Storing State References: Message-ID: "Stephen Nelson-Smith" wrote > I want to iterate over a bunch of lines; for line in > If any line contains a certain string, I want to do something, > otherwise do something else. if in line: doSomething() else: doSomethingElse() > I can store state - eg line 1 - did it contain the string? no.. ok > we're cool, next line.... No need, just translate what you asked into Python code directly. You don't say what kind of "bunch" your lines are in but the above will work with an open file or a list or a tuple etc. HTH, -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ From vceder at canterburyschool.org Sat Feb 28 03:32:02 2009 From: vceder at canterburyschool.org (Vern Ceder) Date: Fri, 27 Feb 2009 21:32:02 -0500 Subject: [Tutor] Convert a string of numbers to a list In-Reply-To: <49A85DCF.8070401@umich.edu> References: <20090226020037.14827f8djp59brsw@web.mail.umich.edu> <1c2a2c590902260345l5e51801foe68c48197ae28685@mail.gmail.com> <49A85DCF.8070401@umich.edu> Message-ID: <49A8A222.1030107@canterburyschool.org> Kyle Kwaiser wrote: > x = ['[335, 180, 201, 241, 199]\r\n'] > y = map( int, x[0].strip( '[]\r\n' ).split( ', ' ) ) #need an index here > print y > [335, 180, 201, 241, 199] I realize it's not totally secure, but if your string really is in that format (i.e., a representation of a list), you COULD just use eval(): >>> x = '[335, 180, 201, 241, 199]\r\n' >>> y = eval(x.strip()) >>> print y [335, 180, 201, 241, 199] >>> Regards, Vern Ceder From geoterium at gmail.com Sat Feb 28 05:34:07 2009 From: geoterium at gmail.com (George Wahid) Date: Sat, 28 Feb 2009 06:34:07 +0200 Subject: [Tutor] new print statement + time module Message-ID: I downloaded python 3.0.1 today and started experimenting with the new print statement. >>>import time >>>for l in 'the answer': ... print(l,end='') ... time.sleep(0.1) the code is supposed to print "the answer" with a 0.1 second long pause between the letters. instead, it waits for 1 second ( 0.1*len("the answer") seconds ) and then prints "the answer". what am I doing wrong ? both replacing print(l,end='') with print(l) or using the msvcrt module instead of the print function work fine. From denis.spir at free.fr Sat Feb 28 08:16:29 2009 From: denis.spir at free.fr (spir) Date: Sat, 28 Feb 2009 08:16:29 +0100 Subject: [Tutor] new print statement + time module In-Reply-To: References: Message-ID: <20090228081629.36a244b4@o> Le Sat, 28 Feb 2009 06:34:07 +0200, George Wahid s'exprima ainsi: > I downloaded python 3.0.1 today and started experimenting with the new > print statement. > > >>>import time > >>>for l in 'the answer': > ... print(l,end='') > ... time.sleep(0.1) > > the code is supposed to print "the answer" with a 0.1 second long > pause between the letters. instead, it waits for 1 second ( > 0.1*len("the answer") seconds ) and then prints "the answer". what am > I doing wrong ? Indeed, it does the same for me with python 2.5: from time import sleep for c in "1234567890": sleep(0.25) print c, I guess python underlying outputs are managed like a queue that is flushed at certain points, eg whan a newline comes. Already noticed weird outputs messing up ordinary prints (~ sys.stdout) and exceptions messages (sys.stderr). I'd like to know more about that. > both replacing print(l,end='') with print(l) or using the msvcrt > module instead of the print function work fine. The same with py2.5. Without the ',', all is fine. Maybe there is a trick to force python printing ot in due time, but I have no idea, sorry. Denis ------ la vita e estrany From dorseye at gmail.com Sat Feb 28 08:36:08 2009 From: dorseye at gmail.com (Eric Dorsey) Date: Sat, 28 Feb 2009 00:36:08 -0700 Subject: [Tutor] Add elements to list and display it [Very newbie question] In-Reply-To: References: Message-ID: Here is one possible implementation of your project. *Code:* #Dont use list as a variable name, its one of the reserved words. mylist = [] #realize any values captured here are strings x = raw_input('Enter num or text: ') mylist.append(x) x = raw_input('Enter num or text: ') mylist.append(x) #output the type of objects you've entered (hint: they'll always be strings.. ;) print type(mylist[0]) print type(mylist[1]) #print the list of items for i in mylist: print i *When you run the program:* Enter num or text: 27 Enter num or text: Eric 27 Eric On Fri, Feb 27, 2009 at 10:19 AM, Network Administrator < administrador.de.red at gmail.com> wrote: > I am beggining to learn Python and I appreciate if you help me with this: > > "I want a piece of a program to request the user to input "elements" > (numbers, text, etc) and store them into a list. Then, I want to display all > the elements one-per-line." > > I started using this code: > > #!/usr/bin/env python > ##################### > # This function fills any given list > # and display its content. > # > x = 0 # Variable "x" initiallized to zero, just > because Python required it > while (x != 't2' ): # On user's input "t2", no more input must be > required > list = [] # I start a zero-elements list > x = raw_input('Enter your number or text: ') # Software > asks for user's input. > > list.append(x) > # User's input is append to the list "list" > > for x in list: # It asks to enter the list and... > print x # print their elements. > > Unfortunately, this code fails to do what I expect. I notice that user's > input is not being append to the list, so, when I require to print the > elements of the list only "t2" is displayed. I don't know how to append > elements to a list on user's input. > > I appreciate your clearence. > > Regards, > > > Will. > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From metolone+gmane at gmail.com Sat Feb 28 08:53:04 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Fri, 27 Feb 2009 23:53:04 -0800 Subject: [Tutor] new print statement + time module References: <20090228081629.36a244b4@o> Message-ID: "spir" wrote in message news:20090228081629.36a244b4 at o... > Le Sat, 28 Feb 2009 06:34:07 +0200, > George Wahid s'exprima ainsi: > >> I downloaded python 3.0.1 today and started experimenting with the new >> print statement. >> >> >>>import time >> >>>for l in 'the answer': >> ... print(l,end='') >> ... time.sleep(0.1) >> >> the code is supposed to print "the answer" with a 0.1 second long >> pause between the letters. instead, it waits for 1 second ( >> 0.1*len("the answer") seconds ) and then prints "the answer". what am >> I doing wrong ? > > Indeed, it does the same for me with python 2.5: > > from time import sleep > for c in "1234567890": > sleep(0.25) > print c, > > I guess python underlying outputs are managed like a queue that is flushed > at certain points, eg whan a newline comes. > Already noticed weird outputs messing up ordinary prints (~ sys.stdout) > and exceptions messages (sys.stderr). I'd like to know more about that. > >> both replacing print(l,end='') with print(l) or using the msvcrt >> module instead of the print function work fine. > > The same with py2.5. Without the ',', all is fine. Maybe there is a trick > to force python printing ot in due time, but I have no idea, sorry. stdout is line-buffered. Here's the trick: import time import sys for l in 'the answer': print(l,end='') sys.stdout.flush() time.sleep(0.1) -Mark From ksterling at mindspring.com Sat Feb 28 09:01:16 2009 From: ksterling at mindspring.com (Ken Oliver) Date: Sat, 28 Feb 2009 03:01:16 -0500 (EST) Subject: [Tutor] new print statement + time module Message-ID: <16839352.1235808077207.JavaMail.root@mswamui-chipeau.atl.sa.earthlink.net> -----Original Message----- >From: spir >Sent: Feb 28, 2009 2:16 AM >To: tutor at python.org >Subject: Re: [Tutor] new print statement + time module > >Le Sat, 28 Feb 2009 06:34:07 +0200, >George Wahid s'exprima ainsi: > >> I downloaded python 3.0.1 today and started experimenting with the new >> print statement. >> >> >>>import time >> >>>for l in 'the answer': >> ... print(l,end='') >> ... time.sleep(0.1) >> >> the code is supposed to print "the answer" with a 0.1 second long >> pause between the letters. instead, it waits for 1 second ( >> 0.1*len("the answer") seconds ) and then prints "the answer". what am >> I doing wrong ? > >Indeed, it does the same for me with python 2.5: > >from time import sleep >for c in "1234567890": > sleep(0.25) > print c, > >I guess python underlying outputs are managed like a queue that is flushed at certain points, eg whan a newline comes. >Already noticed weird outputs messing up ordinary prints (~ sys.stdout) and exceptions messages (sys.stderr). I'd like to know more about that. > >> both replacing print(l,end='') with print(l) or using the msvcrt >> module instead of the print function work fine. > >The same with py2.5. Without the ',', all is fine. Maybe there is a trick to force python printing ot in due time, but I have no idea, sorry. > >Denis >------ >la vita e estrany >_______________________________________________ >Tutor maillist - Tutor at python.org >http://mail.python.org/mailman/listinfo/tutor The above code for the 2.5 version appears to work as expected in the command line versions of 2.5. . From geoterium at gmail.com Sat Feb 28 09:56:27 2009 From: geoterium at gmail.com (George Wahid) Date: Sat, 28 Feb 2009 10:56:27 +0200 Subject: [Tutor] new print statement + time module Message-ID: Thanks for the answers. I didn't have this problem with python 2.5. I know I can use stdout instead, but I want to know what I'm doing wrong. From prasadaraon50 at gmail.com Sat Feb 28 13:40:29 2009 From: prasadaraon50 at gmail.com (prasad rao) Date: Sat, 28 Feb 2009 18:10:29 +0530 Subject: [Tutor] re Format a file Message-ID: <9e3fac840902280440s6cf376dcr2dbf8141e8e4778b@mail.gmail.com> Hello >> ???? for line in so: >> ???????? if len(line)<70:de.write(line+'\n') >> ???????? if len(line)>70: >> ???????????? da=textwrap.fill(line,width=60) >> ???????????? de.write(da+'\n') >What happens if the line is exactly 70 characters long? >I think you want an else instead of the second if.... >Alan G >Author of the Learn to Program web site True.Thanks for pointing out the folly. I might have lost bits of data. Thank you Prasad -------------- next part -------------- An HTML attachment was scrubbed... URL: From alan.gauld at btinternet.com Sat Feb 28 18:25:31 2009 From: alan.gauld at btinternet.com (Alan Gauld) Date: Sat, 28 Feb 2009 17:25:31 -0000 Subject: [Tutor] new print statement + time module References: Message-ID: "George Wahid" wrote > Thanks for the answers. I didn't have this problem with python 2.5. > I > know I can use stdout instead, but I want to know what I'm doing > wrong. You aren't doing anything wrong. The print function writes to sys.stdout. sys.stdout is a buffered file which means it doesn''t write to its output immediately but waits until enough data is in its buffer to make it worthwhile - or until explicitly told to flush itself. Because you are trying to write only one character at a time it's not enough to make stdout write so you need to explicitly flush() it. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/l2p/ From geoterium at gmail.com Sat Feb 28 20:11:54 2009 From: geoterium at gmail.com (George Wahid) Date: Sat, 28 Feb 2009 21:11:54 +0200 Subject: [Tutor] new print statement + time module Message-ID: > You aren't doing anything wrong. The print function writes to > sys.stdout. > sys.stdout is a buffered file which means it doesn''t write to its > output > immediately but waits until enough data is in its buffer to make it > worthwhile - or until explicitly told to flush itself. > > Because you are trying to write only one character at a time it's not > enough to make stdout write so you need to explicitly flush() it. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/l2p/ Thanks for the explanation. From bgailer at gmail.com Sat Feb 28 22:09:02 2009 From: bgailer at gmail.com (bob gailer) Date: Sat, 28 Feb 2009 16:09:02 -0500 Subject: [Tutor] new print statement + time module In-Reply-To: References: Message-ID: <49A9A7EE.9040802@gmail.com> George Wahid wrote: > I downloaded python 3.0.1 today and started experimenting with the new > print statement. print is a function, not a statement. -- Bob Gailer Chapel Hill NC 919-636-4239 From haztang17 at gmail.com Sat Feb 28 22:41:14 2009 From: haztang17 at gmail.com (Hi) Date: Sat, 28 Feb 2009 13:41:14 -0800 Subject: [Tutor] Auto Refresh Message-ID: Thank you for the reply, SetLabel is exactly what I am looking for. And yes, you were correct, I just typoed the var_rate() when I was composing the email. So what I did is in my main GUI class: wx.StaticText(self, -1, sampling rate':', (107, 150)) self.rate_status = wx.StaticText(self, -1, '', (190, 150)) #just to initialize rate_status to some location def refresh(self, event): x = rate() rate_text = self.rate_status.SetLabel(str(x.rate_var())) and in my class that contains the variable (which will change every so often at the end, so right now I'm modeling this with a random generator): class rate(): def rate_var(self): samp_rate = random.randint(44100, 48000) return samp_rate I want to make it so once def refresh ran, it will continuously update and display the new value in samp_rate in my main GUI at some time interval, say every 10 seconds. I have looked up Timer, but I have not been able to make it work. I looked up the documentation in Python's website to no avail. Can anyone suggeste anything to help me? On Fri, Feb 27, 2009 at 5:05 PM, wrote: > > Message: 7 > Date: Sat, 28 Feb 2009 01:00:21 -0000 > From: "Alan Gauld" > Subject: Re: [Tutor] Auto Refresh > To: tutor at python.org > Message-ID: > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "Hi" wrote > > > > In my main GUI: > > > > def refresh(self, event): > > x = refresh_var() > > value = wx.StaticText(self, -1, str(x.var_rate)) > > Its not clear how you are positioning Static Text, I suspect you > need it as a opart of your main GUI and then reference it in > here and use the SetLabel() method to update its contents. > > But I also not that you are not calling the var_rate method of x. > Or does your code really look like > > value = wx.StaticText(self, -1, str(x.var_rate())) > > Notice the extra parens... > > > So each time I click on the button, which runs refresh, the new > > value > > generated by random.randint will be on top of the old number. Is > > there any > > commands I can use to remove the old value that is on the GUI window > > before > > I put the new one on there? > > I think you can just update the content of the original Text widget > using SetLabel() > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > End of Tutor Digest, Vol 60, Issue 143 > ************************************** > -------------- next part -------------- An HTML attachment was scrubbed... URL: