Re: [Tutor] Communication between classes
Greg Perry liveammo.com> writes: > Is it safe to say that classes are only useful for instances where reuse is a key consideration? From my very > limited perspective, it seems that classes are in most cases overkill for simple tasks (such as reading > the command line then calculating a hash/checksum to verify integrity). Alan has already adressed your questions, I just have one addition on this point. If this is *all* your application does, a class is indeed overkill. However, if this functionality is part of a larger application, it could become a small class. Imagine an application that would offer some file operations, like: - calculate hash - split into chunks of 1.44 MB - compress - encrypt You could have a generic ancestor class, say FileOperation and inherit from it different classes implementing specific operations. class FileOperation(object): def __init__(self, filename): self._filename = filename def Perform(self): pass # should be implemented in children def ShowHelp(self): pass # should be implemented in children class HashFileOperation(FileOperation): def Perform(self): # calculate hash of self._filename def ShowHelp(self): print "Calculates MD5 hash of the file" Depending on a command line option, the application could instantiate one of the operation classes and work with it. Assuming the command line would be 'app.py ' (e.g. 'app.py hash myfile.txt'), the application code could look something like this: # register all known operation classes and bind them # to specific command line options operations = {'hash': HashFileOperation, 'split': SplitFileOperation, } opname = sys.argv[1] # determine what operation class is necessary opclass = operations[opname] # instantiate that operation (make a file operation object) fileop = opclass(sys.argv[2]) # check if it should display help or run the operation if sys.argv[2] == '?': fileop.ShowHelp() else: fileop.Perform() Adding new operations would be a matter of implementing an appropriate class and adding it to the operations dictionary. With a bit of Python magic you could even get the operation classes to auto-register, so just writing an operation class would automatically make it available in the application. -- Yours, Andrei = Mail address in header catches spam. Real contact info: ''.join([''.join(s) for s in zip( "poet aao.l pmfe!Pes ontuei ulcpss edtels,s hr' one oC.", "rjc5wndon.Sa-re laed o s npbi ot.Ira h it oteesn edt C")]) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] datetime.timedelta Output Format
"R. Alan Monroe" <[EMAIL PROTECTED]> wrote >> Is there a way to have the output of "print tis" in the same format >> as >> "print now" and "print tafmsd" in the code below? >> >>> now = datetime.date.today() >> >>> print now >> 2007-04-01 >> >>> tis = now - tafmsd >> >>> print tis >> 4785 days, 0:00:00 > That's kind of like asking how to say "128 shopping days left until > Christmas" in the format of "2007-04-01 shopping days left until > Christmas". It doesn't work, somehow. I assume that what Will really means is how does he get the number of days expressed as a number of years/months and days. As in: There are 4 months, 8 days to Xmas. I don't use datetime so don't know whether/how that would be done but it seems like a reasonable request. And if that's not what Will wants can someone tell me because I'm now curious! Its a non trivial conversion and would require knowledge of the context - ie start or end date. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] datetime.timedelta Output Format
Alan Gauld wrote: > "R. Alan Monroe" <[EMAIL PROTECTED]> wrote > > >>> Is there a way to have the output of "print tis" in the same format >>> as >>> "print now" and "print tafmsd" in the code below? >>> > > >>> >>> now = datetime.date.today() >>> >>> print now >>> 2007-04-01 >>> >>> tis = now - tafmsd >>> >>> print tis >>> 4785 days, 0:00:00 >>> > > >> That's kind of like asking how to say "128 shopping days left until >> Christmas" in the format of "2007-04-01 shopping days left until >> Christmas". It doesn't work, somehow. >> > > I assume that what Will really means is how does he > get the number of days expressed as a number of > years/months and days. > > As in: There are 4 months, 8 days to Xmas. > Yes, that's correct. Sorry I didn't express myself clearly. Thanks again, Will ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] A bug or a feature - complex arguments in special
Alan G wrote: >It would be good if you could include the error text. >However, did you try putting the complex number in parens? >or assigning to a variable and then pass the variable into the call? Well, the error message is not from Pytho but from the operating system (windows XP). It says "pythonw.exe has encountered a problem and needs to close. We are sorry for the inconvenience." The IDLE does not close but it is restarted: There appears a line: >>> RESTART I tried to assign the argument to a variable: >>>from scipy import * >>> x=.5 >>> special.jv(0,x) 0.938469807241 >>> y=.5+1.j >>> y (0.5+1j) >>> special.jv(0,y) >>> RESTART >>> The results are still the same: when the variable is real, the result is correct. When the variable is comlex, the program crashes. Is it a bug ? Thanks Eli ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] datetime.timedelta Output Format
William Allison wrote: > Is there a way to have the output of "print tis" in the same format as > "print now" and "print tafmsd" in the code below? > Thanks, > Will > > > savage:~ wallison$ python > Python 2.5 (r25:51918, Sep 19 2006, 08:49:13) > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import datetime > >>> now = datetime.date.today() > >>> print now > 2007-04-01 > >>> tafmsd = datetime.date(1994, 2, 23) > >>> print tafmsd > 1994-02-23 > >>> tis = now - tafmsd > >>> print tis > 4785 days, 0:00:00 It looks like Gustavo Niemeyer's dateutil module will at least do the year/month/day calculation if not the formatting: In [1]: from datetime import date In [2]: from dateutil import relativedelta In [3]: now = date.today() In [9]: rd = relativedelta.relativedelta(now, tafmsd) In [10]: rd Out[10]: relativedelta(years=+13, months=+1, days=+10) http://labix.org/python-dateutil Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tokenizing a imple string with split()
The split method in the "re" module does what you want here. This is a method on compiled re_patterns, so first you construct a regular expression that matches any of the desired separators: >>> s = "spam;egg mail" >>> x_re = re.compile(r'[; ]') >>> s.split("; ") ['spam;egg mail'] >>> x_re.split(s) ['spam', 'egg', 'mail'] >>> > > Message: 1 > Date: Sat, 31 Mar 2007 18:00:47 -0400 > From: Rafael Garcia <[EMAIL PROTECTED]> > Subject: Re: [Tutor] tokenizing a simple string with split() > To: tutor@python.org > Message-ID: <[EMAIL PROTECTED]> > Content-Type: text/plain; charset="iso-8859-1" > > I think by "multiple characters" they mean more than one character for > ONE separator. I don't know how to specify multiple separators. You > could try something like this: > > s = "spam;egg mail" > list = [] > for t in s.split(";"): > for u in t.split(" "): > list.append(u) > > which yields: > list = ['spam', 'egg', 'mail'] > > > Rafael > > On 3/31/07 5:43 PM, Andrei Petre wrote: >> I want to split a string like "C:\My\Doc\;D:\backup\" with two >> separators: \ and ; >> I found that \ is handled with /raw string/ notation r"". But the >> problem i encountered is with split() function. >> In the 2.5 reference is said that "The sep argument of the split() >> function may consist of multiple characters". But I cannot figured >> out >> why this simple example not working: >> >> s = "spam;egg mail" >> s.split("; ") >> >> output: ['spam;egg mail'] >> >> instead of ['spam', 'egg', 'mail'] >> >> any suggestion is welcome, >> andrei >> >> - >> --- >> >> ___ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > -- next part -- > An HTML attachment was scrubbed... > URL: http://mail.python.org/pipermail/tutor/attachments/ > 20070331/8e1bedb4/attachment.html > > -- > > Message: 2 > Date: Sat, 31 Mar 2007 17:20:02 -0500 > From: "Greg Corradini" <[EMAIL PROTECTED]> > Subject: [Tutor] Create an Access table w/ mxODBC module > To: tutor@python.org > Message-ID: > <[EMAIL PROTECTED]> > Content-Type: text/plain; charset="utf-8" > > Hello all, > I'm brand new to the mxODBC module from egenix (like yesterday). I > currently > use the module for data laundering. I connect to a Microsoft > Access .mdb and > perform some SQL queries on tables. Almost everything is going fine. > However, I can't find out how to create a new table. Even other > examples > that I've found on the web that use the "create table" SQL command > aren't > working for me. When I run mycursor.execute('create table TEST (nr > Integer, > val Integer)'), i only get a return value of -1. I was hoping > somebody with > more mxODBC experience could give me a hand with this minor problem. > > Thanks > Greg > -- next part -- > An HTML attachment was scrubbed... > URL: http://mail.python.org/pipermail/tutor/attachments/20070331/ > cfd322a8/attachment.htm > > -- > > Message: 3 > Date: Sat, 31 Mar 2007 23:20:21 +0100 > From: Dave S <[EMAIL PROTECTED]> > Subject: Re: [Tutor] My Python project - an update > To: tutor@python.org > Message-ID: <[EMAIL PROTECTED]> > Content-Type: text/plain; charset="iso-8859-15" > > Very valid points, I was not aware that MD5 had been cracked :) > > Dave > > > -- > > Message: 4 > Date: Sun, 1 Apr 2007 00:01:49 +0100 > From: "Alan Gauld" <[EMAIL PROTECTED]> > Subject: Re: [Tutor] Detect errors when using os.popen.readlines() > To: tutor@python.org > Message-ID: <[EMAIL PROTECTED]> > Content-Type: text/plain; format=flowed; charset="iso-8859-1"; > reply-type=original > > > "Peter" <[EMAIL PROTECTED]> wrote > >> Is there a way to detect errors when running shell commands using >> os.popen? > > You have to parse the programs output. > Usually errors will appear on stderr so you need to read that as > well as stdout. > > This may be slightly easier using the new subprocess module > and the Popen class. > >> if an interface doesn't exist I get an error from the shell command. >> I tried using try and except, but that did seem to work. > > Even if the program returns an error popen is still working just > fine so no exception gets raised. You must parse the output > (or check the status value, but thats not reliable in all programs) > > HTH, > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.freenetpages.co.uk/hp/alan.gauld > > > > > -- > > Message: 5 > Date: Sat, 31 Mar 2007 20:45:21 -0400 > From: Jay Mutter III <[EMAIL PROTECTED]> > Subject: Re: [Tutor] Another parsing question > To: Kent Johnson <[EMAIL PROTECTED]> > Cc: tutor@python.org > Message-ID: <[EMAIL PROTECTED]> > Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed > > Ken
Re: [Tutor] Tokenizing a imple string with split()
Alternativly, one might consider the standard shlex module. Depending what one ones to achieve this might be the better or worse choice. Andreas ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A bug or a feature - complex arguments in special
On Monday 02 April 2007 11:33, Eli Brosh wrote: > from scipy import * > >>> > >>> x=.5 > >>> special.jv(0,x) > > 0.938469807241 > > >>> y=.5+1.j > >>> y > > (0.5+1j) > > >>> special.jv(0,y) > >>> RESTART > >>> > > The results are still the same: when the variable is real, the > result is correct. When the variable is comlex, the program > crashes. > Is it a bug ? I think it is a bug, the function should definitely not crash the python session. You should go to the SciPy mailing list: http://projects.scipy.org/mailman/listinfo/scipy-user Maybe there someone knows a workaround for you. On my computer it does not crash: In [1]:import scipy In [2]:from scipy import * In [3]:y=.5+1.j In [4]:special.jv(0,y) Out[4]:(1.1798566304-0.273726785591j) In [5]:scipy.__version__ Out[5]:'0.5.2' Regards, Eike. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] A string-manipulation question
>>The only "hitch" I see is how one tells that an initial >>consonant is a vowel sound or not. (honor vs home)? The above is exactly what I was thinking about, theres no way I could think of besides creating a dict for the few thousand English words that have this trait. Then run a search against the dict (the one for words like honor), then something like if the words on this list then just add ay to the end of the word and jump to the next word in the sequence. And if the word's not on that list then just following the regular pig latin rules. I apologize if what I'm saying doesn't make too much sense. I've been teaching myself python for all of 3 weeks. Its been long days and even longer nights of pure confusion at some times...but only because I NEED to know everything I can. Imaginary numbers blew my mind lol. -- Original message -- From: Bob Gailer <[EMAIL PROTECTED]> > [EMAIL PROTECTED] wrote: > > Alan Gilfoy wrote: > > > > > Is there a way in Python to separate a string into its component words. > > you could do something like this: > > >>> x = Is there a way in Python to seperate a string into its > > compontent words. > > >>> x.split() > > that would yield: > > ['Is', 'there', 'a', 'way', 'in', 'Python', 'to', 'separate', 'a', > > 'string', 'into', 'its', 'component', 'words.'] > > As far as teh translating to pig latin.well I honestly don't know. > From Wikipedia, the rules are: > > 1. For words that begin with consonant > sounds, move the initial > consonant or consonant cluster > to the end of the > word and add "ay." Examples: > * fatso â atso-fay > * button â /utton-bay/ > * star â /ar-stay/ > * three â /ee-thray/ > * question â /estion-quay/ > 2. For words that begin with vowel > sounds (including silent > consonants ), simply > add the syllable "ay" to the end of the word. > * eagle â /eagle-ay/ > * America â /America-ay/ > * honor â /honor-ay/ > > Seems pretty straightforward to translate to Python (or any other > language). The only "hitch" I see is how one tells that an initial > consonant is a vowel sound or not. (honor vs home)? > > opehay isthay elphay > > -- > Bob Gailer > 510-978-4454 > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] C coded extinsion question
I am writing a c type extension for Python deriving from the list class (using PyList_Type.tp_init). I have the need to overload the + operator (To add two numbers stored as binary lists instead of concatenation). I have tried the following: static PyMethodDef BinaryList_methods[] = { ... {"__add__", (PyCFunction)BinaryList___add__, METH_VARARGS, PyDoc_STR("__add__(self,other) -> BinaryList")}, ... {NULL, NULL}, }; This the BinaryList___add__ function is called if I use the __add__ explicitly but the list base class __add__ is called for the + operator, for example: a = BinaryList([1,0,0,0]) b = BinaryList([0,0,0,1]) print a.__add__(b) #prints [1,0,0,1] print a + b #prints [1,0,0,0,0,0,0,1] I read this: object.h -- Added tp_call member to the typeobject struct This along with a minor change to the ceval.c allows overloading of the function call operator for any class. Can anyone either tell me what I am doing wrong and or give me an example of how to properly overload an operator in a c coded extension? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fw: 2) 'WHICH MULTI'
On Fri, 30 Mar 2007, ALAN GAULD wrote: > One of my tutorial users has come upon a really weird bug. > > He has sent a transcript oif his session. Notice that wx > is not defined yet doing help(wx) produces a strange message. Very weird. Here's what I get, weird in a different way... ___ ActivePython 2.5.0.0 (ActiveState Software Inc.) based on Python 2.5 (r25:51908, Mar 9 2007, 17:40:28) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> print wx Traceback (most recent call last): File "", line 1, in NameError: name 'wx' is not defined >>> dir(wx) Traceback (most recent call last): File "", line 1, in NameError: name 'wx' is not defined >>> help Type help() for interactive help, or help(object) for help about object. >>> help() Welcome to Python 2.5! This is the online help utility. [etc.] help> wx [pause of about 6 seconds] Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\site.py", line 355, in __call__ return pydoc.help(*args, **kwds) File "C:\Python25\Lib\pydoc.py", line 1649, in __call__ self.interact() File "C:\Python25\Lib\pydoc.py", line 1667, in interact self.help(request) File "C:\Python25\Lib\pydoc.py", line 1688, in help elif request: doc(request, 'Help on %s:') File "C:\Python25\Lib\pydoc.py", line 1481, in doc pager(title % desc + '\n\n' + text.document(object, name)) File "C:\Python25\Lib\pydoc.py", line 324, in document if inspect.ismodule(object): return self.docmodule(*args) File "C:\Python25\Lib\pydoc.py", line 1084, in docmodule contents.append(self.docother(value, key, name, maxlen=70)) File "C:\Python25\Lib\pydoc.py", line 1283, in docother repr = self.repr(object) File "C:\Python25\Lib\repr.py", line 24, in repr return self.repr1(x, self.maxlevel) File "C:\Python25\Lib\pydoc.py", line 951, in repr1 return cram(stripid(repr(x)), self.maxother) File "C:\Python25\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 242, in __repr__ def __repr__(self): return 'wx.Colour' + str(self.Get(True)) File "C:\Python25\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 230, in Get return _gdi_.Colour_Get(*args, **kwargs) TypeError: in method 'Colour_Get', expected argument 1 of type 'wxColour *' >>> ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hashlib weirdness
On 30 Mar 2007, Greg Perry wrote: > Here's one that has me stumped. > > I am writing a forensic analysis tool that takes either a file or a > directory as input, then calculates a hash digest based on the contents > of each file. > > I have created an instance of the hashlib class: > > m = hashlib.md5() > > I then load in a file in binary mode: > > f = open("c:\python25\python.exe", "rb") > > According to the docs, the hashlib update function will update the hash > object with the string arg. So: > > m.update(f.read()) > m.hexdigest() > > The md5 hash is not correct for the file. Odd. It's correct for me: In Python: >>> import hashlib >>> m = hashlib.md5() >>> f = open("c:\python25\python.exe", "rb") >>> m.update(f.read()) >>> m.hexdigest() '7e7c8ae25d268636a3794f16c0c21d7c' Now, check against the md5 as calculated by the md5sum utility: >md5sum c:\Python25\python.exe \7e7c8ae25d268636a3794f16c0c21d7c *c:\\Python25\\python.exe > f.seek(0) > hashlib.md5(f.read()).hexdigest() No difference here: >>> f.close() >>> f = open("c:\python25\python.exe", "rb") >>> hashlib.md5(f.read()).hexdigest() '7e7c8ae25d268636a3794f16c0c21d7c' ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hashlib weirdness
Thanks Terry, others have pointed out the same thing. The stock Python 2.5 interpreter functions properly; my issue seems to be with the IDE I am using, that is where I've been able to nail down the problem so far. -Original Message- From: Terry Carroll On 30 Mar 2007, Greg Perry wrote: > >> Here's one that has me stumped. > > I am writing a forensic analysis tool that takes either a file or a > directory as input, then calculates a hash digest based on the contents > of each file. > > I have created an instance of the hashlib class: > > m = hashlib.md5() > > I then load in a file in binary mode: > > f = open("c:\python25\python.exe", "rb") > > According to the docs, the hashlib update function will update the hash > object with the string arg. So: > > m.update(f.read()) > m.hexdigest() > > The md5 hash is not correct for the file. > >Odd. It's correct for me: > >In Python: > import hashlib >>> m = hashlib.md5() >>> f = open("c:\python25\python.exe", "rb") >>> m.update(f.read()) >>> m.hexdigest() >'7e7c8ae25d268636a3794f16c0c21d7c' > >Now, check against the md5 as calculated by the md5sum utility: > >>md5sum c:\Python25\python.exe >\7e7c8ae25d268636a3794f16c0c21d7c *c:\\Python25\\python.exe > > >> f.seek(0) > hashlib.md5(f.read()).hexdigest() > >No difference here: > f.close() >>> f = open("c:\python25\python.exe", "rb") >>> hashlib.md5(f.read()).hexdigest() >'7e7c8ae25d268636a3794f16c0c21d7c' > >___ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] datetime.timedelta Output Format
Kent Johnson wrote: > > It looks like Gustavo Niemeyer's dateutil module will at least do the > year/month/day calculation if not the formatting: > > In [1]: from datetime import date > In [2]: from dateutil import relativedelta > In [3]: now = date.today() > In [9]: rd = relativedelta.relativedelta(now, tafmsd) > In [10]: rd > Out[10]: relativedelta(years=+13, months=+1, days=+10) > > http://labix.org/python-dateutil > > Kent > Thank you, seems to be just what I was looking for! Will ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] hashlib weirdness
On 2 Apr 2007, Greg Perry wrote: > Thanks Terry, others have pointed out the same thing. The stock Python > 2.5 interpreter functions properly; my issue seems to be with the IDE I > am using, that is where I've been able to nail down the problem so far. Just curious, what's the IDE? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] apihelper module for python
i have looked and been unable to find this module anywhere, can somebody please direct me to where i can download it, thanks _ Message offline contacts without any fire risk! http://www.communicationevolved.com/en-ie/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] apihelper module for python
Brian McDermott wrote: > i have looked and been unable to find this module anywhere, can somebody > please direct me to where i can download it, thanks A little context might help here, but I guess you are looking for the apihelper referenced in Chapter 4 of Dive Into Python. This module is included in the download for the book: http://diveintopython.org/download/diveintopython-examples-5.4.zip Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor