ANN: eric 4.1.4 released
Hi, this is to inform all of you about the immediate availability of eric 4.1.4. It includes a fix for an API change of Qt 4.4, that caused eric4 to crash. Please update immediately. As usual, it is available via http://www.die-offenbachs.de/eric/index.html. What is eric? - Eric is a Python (and Ruby) IDE, that comes with all batteries included. For more details please see the above link. Regards, Detlev -- Detlev Offenbach [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Reading Java byte[] data stream over standard input
I should also mention that for some reason there are several binay values popping in between for some reason. This behavior (for the inputr stream) is not expected Now, the incoming data is binary(though mine is actually merely ascii text) but the output is not what is expected. I expect for e.g all/86000/114.310.151.209.60370-121.110.5.176.113\n62485.9718 118.010.241.12 60370 128.210.5.176 However i get a 1 before all and a 4 just after \n and before the 6. My question is : how do i read binary data(Java's byte stream) from stdin? Or is this actually what i'm getting? Thanks Sapsi -- http://mail.python.org/mailman/listinfo/python-list
Re: How do *you* use Python in non-GUI work?
On May 18, 7:25 pm, John Salerno [EMAIL PROTECTED] wrote: On Sun, 18 May 2008 16:17:55 -0700 (PDT) Mensanator [EMAIL PROTECTED] wrote: I see no need for GUI in any of these applications. Yeah, I try to find little projects to write in Python that don't involve a GUI. It's quicker, for one thing, and I also find that there is much more of a focus on the actual problem rather than wasting time trying to get a button positioned just right. :) Even back when I was using Windows 3.1 and 95, I enjoyed doing stuff in DOS because it made me feel like I was actually getting work done. :) I do mostly Internet protocol server/proxy-side applications. One of the fun things about those kinds of programs is that you get away from the whole user interface design concept, because you normally don't have to do any kind of user interface (neither command-line-based, GUI- based, web-based, nor anything), since you're not designing something to serve an end user, but to work as a lonely daemon and serve some kind of Internet service. So I think that'd be a good alternative for you. Every now and then, however, I do build some interface (mostly GUI), such as a monitor, notification mechanism, etc. But I never feel like I'm losing focus on the actual problem; maybe because I develop the core program first and the think about a possible and optional interface. Maybe a good suggestion is to put the GUI stuff on another module or package, and make interface functions or methods to handle the needed GUI controls, so that the GUI stuff shows up as little as possible in the core part of the program. -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading Java byte[] data stream over standard input
On Sun, 18 May 2008 22:11:33 -0700, sapsi wrote: I am using HadoopStreaming using a BinaryInputStream. What this basically does is send a stream of bytes ( the java type is : private byte[] bytes) to my python program. I have done a test like this, while 1: x=sys.stdin.read(100) if x: print x else: break Now, the incoming data is binary(though mine is actually merely ascii text) but the output is not what is expected. I expect for e.g all/86000/114.310.151.209.60370-121.110.5.176.113\n62485.9718 118.010.241.12 60370 128.210.5.176 However i get a 1 before all and a 4 just after \n and before the 6. My question is : how do i read binary data(Java's byte stream) from stdin? Or is this actually what i'm getting? If there's extra data in `x` then it was sent to stdin. Maybe there's some extra information like string length, Java type information, or checksums encoded in that data!? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading Java byte[] data stream over standard input
Yes, that could be the case. Browsing through hadoop's source, i see stdin in the above code is reading from piped Java DataOutputStream. I read of a libray on the net Javadata.py that reads this but it has disappeared. What is involved in reading from a Dataoutputstream? Thank you Sapsi -- http://mail.python.org/mailman/listinfo/python-list
python script to windows exe
hi all i am very much a newbie to python but has some experience of development.i am trying to write a script which will loop through the outlook 2003 inbox and save the email data in an simple data.html page and save all the attachments in a folder name emails.after some initial struggling i am able to write this script.but now i want to create the exe file of this script.i have used py2exe for this job and created the exe. but when i run the exe my program in not behaving as it supposed to be.its generating some errors.i dont know why this thing is happening as when i run my script it works fine.can some one put some light here. i am using python2.5 and is using py2exe-0.6.6.win32-py2.5.exe of py2exe. My os is windows xp with service pack2. thanks and reagrds sandeep kumar sharma -- http://mail.python.org/mailman/listinfo/python-list
unpack() exploration!
All: I've got a script that runs really slow because I'm reading from a stream a byte at a time: // TERRIBLE for y in range( height ): for color in range(4): for x in range( width ): pixelComponent = fileIO.read(4) buffer = unpack(!f,pixelComponent) unpacks ONE float, but we now can do something with that pixel component. I can speed this up dramatically if I did this: // MUCH FASTER for y in range( height ): for color in range(4): pixelComponent = fileIO.read(4*width) GET a LOT more data from the stream into memory FIRST!! for x in range( width ): buffer = unpack( ?? ) how do I get each float from the pixelComponent??? -M _ Windows Live SkyDrive lets you share files with faraway friends. http://www.windowslive.com/skydrive/overview.html?ocid=TXT_TAGLM_WL_Refresh_skydrive_052008-- http://mail.python.org/mailman/listinfo/python-list
Rearranging elements (cont..)
All: Say I have an array: a = ([''],['']) How do I make it so that I now have: starting with first element (a[0]) new_arr[0] = 'r' new_arr[1] = 'g' new_arr[2] = 'b' new_arr[3] = 'a' new_arr[4] = 'r' . continuing through a[1] with the same new_arr new_arr[N] = 'r' new_arr[N+1] = 'g' -M _ Keep your kids safer online with Windows Live Family Safety. http://www.windowslive.com/family_safety/overview.html?ocid=TXT_TAGLM_WL_Refresh_family_safety_052008-- http://mail.python.org/mailman/listinfo/python-list
More on numpy trickiness.
All: Say I have an array: a = ([''],['']) How do I make it so that I now have: starting with first element (a[0])new_arr[0] = 'r'new_arr[1] = 'g'new_arr[2] = 'b'new_arr[3] = 'a'new_arr[4] = 'r'. continuing through a[1] with the same new_arrnew_arr[N] = 'r'new_arr[N+1] = 'g' -M _ E-mail for the greater good. Join the i’m Initiative from Microsoft. http://im.live.com/Messenger/IM/Join/Default.aspx?source=EML_WL_ GreaterGood-- http://mail.python.org/mailman/listinfo/python-list
arrays
All: Say I have an array: a = ([''],['']) How do I make it so that I now have: starting with first element (a[0])new_arr[0] = 'r'new_arr[1] = 'g'new_arr[2] = 'b'new_arr[3] = 'a'new_arr[4] = 'r'. continuing through a[1] with the same new_arrnew_arr[N] = 'r'new_arr[N+1] = 'g' -M _ Give to a good cause with every e-mail. Join the i’m Initiative from Microsoft. http://im.live.com/Messenger/IM/Join/Default.aspx?souce=EML_WL_ GoodCause-- http://mail.python.org/mailman/listinfo/python-list
Re: Classmethods are evil
Hans Nowak [EMAIL PROTECTED] wrote: The way I see it, a class method is really just sugar for a function operating on the class, living in the class namespace. As such, they are basically redundant, and as you point out, they can always be replaced by a function outside the class (and in fact, this was what people did before they came along in 2.2). Personally, I don't use them... but some people like them. Different strokes, and all that... In exactly the same way you could claim that a method is just sugar for a function operating on the instance living in the instance namespace. As such, you might think that they too are basically redundant, but they aren't: with instance methods you get the ability to override the method in a subclass without the caller needing to know whether they are calling the original method or an overridden version. With class methods you also get the ability to override the method in a subclass, and again the caller doesn't need to know or care which variant when they call it. Say you have a class hierarchy with a from_keys() class method. If you want to construct a new Foo you might call Foo.from_keys() without caring whether the method is the original one defined in one of Foo's base classes or a modified version specific to a Foo. If you were using functions then you would need to define a new from_keys() function for every class in a hierarchy, or at least for every different implementation in the hierarchy and the caller would need to be careful to call the correct one. So we end up with functions from_keys_Foo_or_Baz(cls) and from_keys_Bar() which is an unmaintainable mess. -- Duncan Booth http://kupuguy.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: default object comparison considered harmful?
On 2008-05-16, Kay Schluehr [EMAIL PROTECTED] wrote: On 16 Mai, 10:03, A.T.Hofkamp [EMAIL PROTECTED] wrote: Hello all, Yesterday we found the cause of a bug that has caused problems for a long time. It appeared to be the following: class A(object): pass print min(1.0, A()) which is accepted by Python even though the A() object is not numerical in nature. The cause of this behavior seems to be the compare operation of the object class. Is there a way to disable this behavior in Python (other than deriving a new 'object-like' class that doesn't do comparisons?) Sincerely, Albert Are you sure you don't want to use a statically typed language that captures all type errors just by inspecting your source code? yes. The problem here is that it isn't caught at all, neither at 'compile' time nor at run-time. That means that the Python language considers this proper code. Whether you make that decision by inspecting source code or at run-time is irrelevant here. Unfortunaly, we have to maintain Python 2.3 compability. As a solution, I have created a new BaseObject class as follows: class BaseObject(object): Generic base class without default compare and hashing functions. def __cmp__(self, other): Disable default compare method raise NotImplementedError def __hash__(self): Disable default hashing method raise NotImplementedError(Implement me in class '%s' % self.__class__.__name__) Sincerely, Albert -- http://mail.python.org/mailman/listinfo/python-list
Professional Grant Proposal Writing Workshop (August 2008: Manchester, New Hampshire)
The Grant Institute's Grants 101: Professional Grant Proposal Writing Workshop will be heldin Manchester, New Hampshire on August 6 - 8, 2008. Interested development professionals, researchers, faculty, and graduate students should register as soon as possible, as demand means that seats will fill up quickly. Please forward, post, and distribute this e-mail to your colleagues and listservs. All participants will receive certification in professional grant writing from the Institute. For more information call (888) 824 - 4424 (213-817-5308 outside US) or visit The Grant Institute at www.thegrantinstitute.com. Please find the program description below: The Grant Institute Grants 101: Professional Grant Proposal Writing Workshop will be held in Manchester, New Hampshire August 6 - 8, 2008 8:00 AM - 5:00 PM The Grant Institute's Grants 101 course is an intensive and detailed introduction to the process, structure, and skill of professional proposal writing. This course is characterized by its ability to act as a thorough overview, introduction, and refresher at the same time. In this course, participants will learn the entire proposal writing process and complete the course with a solid understanding of not only the ideal proposal structure, but a holistic understanding of the essential factors, which determine whether or not a program gets funded. Through the completion of interactive exercises and activities, participants will complement expert lectures by putting proven techniques into practice. This course is designed for both the beginner looking for a thorough introduction and the intermediate looking for a refresher course that will strengthen their grant acquisition skills. This class, simply put, is designed to get results by creating professional grant proposal writers. Participants will become competent program planning and proposal writing professionals after successful completion of the Grants 101 course. In three active and informative days, students will be exposed to the art of successful grant writing practices, and led on a journey that ends with a masterful grant proposal. Grants 101 consists of three (3) courses that will be completed during the three-day workshop. (1) Fundamentals of Program Planning This course is centered on the belief that "it's all about the program." This intensive course will teach professional program development essentials and program evaluation. While most grant writing "workshops" treat program development and evaluation as separate from the writing of a proposal, this class will teach students the relationship between overall program planning and grant writing. (2) Professional Grant Writing Designed for both the novice and experienced grant writer, this course will make each student an overall proposal writing specialist. In addition to teaching the basic components of a grant proposal, successful approaches, and the do's and don'ts of grant writing, this course is infused with expert principles that will lead to a mastery of the process. Strategy resides at the forefront of this course's intent to illustrate grant writing as an integrated, multidimensional, and dynamic endeavor. Each student will learn to stop writing the grant and to start writing the story. Ultimately, this class will illustrate how each component of the grant proposal represents an opportunity to use proven techniques for generating support. (3) Grant Research At its foundation, this course will address the basics of foundation, corporation, and government grant research. However, this course will teach a strategic funding research approach that encourages students to see research not as something they do before they write a proposal, but as an integrated part of the grant seeking process. Students will be exposed to online and database research tools, as well as publications and directories that contain information about foundation, corporation, and government grant opportunities. Focusing on funding sources and basic social science research, this course teaches students how to use research as part of a strategic grant acquisition effort. Registration $597.00 tuition includes all materials and certificates. Each student will receive: *The Grant Institute Certificate in Professional Grant Writing *The Grant Institute's Guide to Successful Grant Writing *The Grant Institute Grant Writer's Workbook with sample proposals, forms, and outlines Registration Methods 1) On-Line- Complete the online registration form at www.thegrantinstitute.com under Register Now. We'll send your confirmation by e-mail. 2) By Phone - Call (888) 824 - 4424 (213-817-5308 outside US)to register by phone. Our friendly Program Coordinators will be happy to assist you and answer your questions. 3) By E-mail - Send an e-mail with your name, organization, and basic contact information to [EMAIL PROTECTED] and we will reserve your slot and send your Confirmation Packet. You have
Re: how would you...?
inhahe == inhahe [EMAIL PROTECTED] writes: inhahe Btw, use float() to convert a textual GPA to a number. It would be much better to use Decimal() instead of float(). A GPA of 3.6001 probably doesn't make much sense; this problem doesn't arise when using the Decimal type. Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Organizing a Python project
On 2008-05-19, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Hello all, I'm starting work on what is going to become a fairly substantial Python project, and I'm trying to find the best way to organize everything. The project will consist of: - A few applications - Several small scripts and utilities - Unit tests and small interactive test programs - A number of custom libraries and modules that may be shared and referenced among all of the above I have the following general structure in mind: myproject/ app1/ main.py file1.py file2.py tests/ test_abc.py test_xyz.py app2/ ... scripts/ script1.py script2.py shared/ mylib1/ file1.py file2.py tests/ test_foo.py test_bar.py mylib2/ ... The files that you might want to execute directly are: - Any of the main.py files under app*/ - Any of the files under shared/ - Any of the files under app*/tests or shared/mylib*/tests So, my questions: First of all, does this look like a reasonable overall structure, or are there better alternatives? You could make a 'bin' directory next to 'myproject' with executable programs which would usually do something like #!/usr/bin/env python from myproject.app1 import main main.run() to make a more clear seperation between code that can be executed and code that is imported in an application. Also, why do you make a distinction between shared and non-shared code? You could simply eliminate 'shared' directory, and put its contents directly under myproject. Second (and the thing I'm primarily interested in), what is the best way to deal with importing the shared modules in the applications, scripts, test programs, and possibly other shared modules? I think the most obvious solution is to add /path/to/myproject to PYTHONPATH. However, this seems like an annoying little dependency that you are likely to forget whenever you move your workspace to a new path, open up a branch of the project in a different directory, or download and work on the project using a different computer. What I am missing here is how you plan to do the development. If you want to do branch-based development, you may want to have a look at Combinator (at divmod.org). It handles branch management, adds executable programs from bin to your path (in your current branch), and extends PYTHONPATH (with your current branch). Even if you have just 1 branch (namely 'trunk') it may be useful. Is there a way to set this up that is a bit more self contained? For example, at first I was somewhat hopeful that Python could ascend parent directories until it reached a directory that did not include an __init__.py file, and it could use this as a root for referring to packages and modules from any file contained within. (e.g. in the example project above, any file could refer to myproject.shared.mylib1 so long as 'myproject' and all subdirectories contained an __init__.py, and the parent of 'myproject' didn't contain such a file). Evidently this is not the case, but it seems like it could be a useful feature in these situations. Work is being done on relative imports. Not sure of its state. Anyway, I'm sure this is not an unusual situation, so I'm curious to hear how other people have handled it. Most people probably run scripts from the root, ie where 'myproject' is a sub-directory. Since Python automatically adds '.' to its path, it will work. Sincerely, Albert -- http://mail.python.org/mailman/listinfo/python-list
Re: arrays
Marlin Rowley wrote: All: Say I have an array: a = ([''],['']) How do I make it so that I now have: starting with first element (a[0]) new_arr[0] = 'r' new_arr[1] = 'g' new_arr[2] = 'b' new_arr[3] = 'a' new_arr[4] = 'r' . continuing through a[1] with the same new_arr new_arr[N] = 'r' new_arr[N+1] = 'g' -M Give to a good cause with every e-mail. Join the i’m Initiative from Microsoft. http://im.live.com/Messenger/IM/Join/Default.aspx?souce=EML_WL_%20GoodCause -- http://mail.python.org/mailman/listinfo/python-list 2 questions: 1. Why have you flooded this news group with three identical copies of a question under three different subject? This is a (mild) bit of abuse of the newsgroup. One copy with a reasonable subject line is enough. 2. Haven't I answered this question for you often enough already? Was my answer not clear enough, or has the problem again changed slightly enough to require a new answer? Having solved 3 or 4 versions of this problem for you already, I'm wondering why I'm seeing it posed yet one more time. If this is *exactly* the same problem I solved once already (and I believe it is), why are we seeing it again, and if it is not the *exact* same problem, why are we seeing so many similar version of it? It's starting to feel like a slight abuse of my time to see this problem on the newsgroup again. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
Re: explain this function to me, lambda confusion
On May 19, 5:22 am, Terry Reedy [EMAIL PROTECTED] wrote: Arnaud Delobelle [EMAIL PROTECTED] wrote in message [...] | Note that the same thing can be said about generator expressions, | which are nothing more than anonymous, non-reusable, generator | functions. Right. So if someone posted on genexp confusion, I would suggest 'write a full generator function'. I was just arguing against arguing for the removal of lambda on the basis that it doesn't add any functionality to the language! | Instead these were _added_ to the language! As a convenience. Actually, if one uses more that one for-clause in a generator expression, there is a potential gotcha in relation to name capture. So if that bites, the genexp is not so much a convenience, and one might better write the full function. tjr Yes, IMHO this is a bug, and I wish I had the time to dive into the code to see if I can fix it. -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: python script to windows exe
but when i run the exe my program in not behaving as it supposed to be.its generating some errors.i dont know why this thing is happening as when i run my script it works fine.can some one put some light here. There is nothing special in executables produced by py2exe. I mean that the debugging strategy is as always. A good start might be in adding logging\tracing facilities both to script and the executable. Comparing two trace files could give you some clue. -- http://mail.python.org/mailman/listinfo/python-list
Re: TPCServer and xdrlib
It is possible to change the serialization used by Pyro http://pyro.sourceforge.net/manual/9-security.html#pickle to the the 'gnosis' XML Pickler. As I said earlier, I would not use XML. Just an example - I need to be able to transfer image files, word and excel documents. How silly it would be to base64encode a binary file, then put it into an XML. L -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading Java byte[] data stream over standard input
On Mon, 19 May 2008 00:14:25 -0700, sapsi wrote: Yes, that could be the case. Browsing through hadoop's source, i see stdin in the above code is reading from piped Java DataOutputStream. I read of a libray on the net Javadata.py that reads this but it has disappeared. What is involved in reading from a Dataoutputstream? According to the Java docs of `DataInput` and `DataOutput` it is quite simple. Most methods just seem to write the necessary bytes for the primitive types except `writeUTF()` which prefixes the string data with length information. So if it is not Strings you are writing then hadoop seems to throw in some information into the stream. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Classmethods are evil
Ivan Illarionov a écrit : After re-reading Python is not Java I finally came to conclusion that classmethods in Python are a very Bad Thing. I can't see any use-case of them that couldn't be re-written more clearly with methods of metaclass or plain functions. Plain functions don't give you polymorphic dispatch and can't be overriden. Using metaclass methods requires a custom metaclass, which 1/ adds boilerplate code and cognitive load and 2/may bring problems, specially wrt/ MI. They have the following issues: 1. You mix instance-level and class-level functionality in one place making your code a mess. May I remind you that every name defined at the top-level of a class statement becomes a class attribute ? Anyway : most of the use case I've had so far for classmethods required collaboration between the instance and the class, and I definitively prefer to have related functionalities defined in one place. 2. They are slower than metaclass methods or plain functions. Slower than plain functions, indeed - but so are instancemethods. Slower that metaclass methods ? I never benchmarked this, but I don't see any reason that should be the case. Anyway, you could also argue that properties are slower than plain attributes, which are slower than local vars etc... I really want to hear your opinions on the subject. Mine is that classmethods are a GoodThing that make simple thing easy. -- http://mail.python.org/mailman/listinfo/python-list
Re: python script to windows exe
On Mon, May 19, 2008 at 3:32 AM, sandeep [EMAIL PROTECTED] wrote: hi all i am very much a newbie to python but has some experience of development.i am trying to write a script which will loop through the outlook 2003 inbox and save the email data in an simple data.html page and save all the attachments in a folder name emails.after some initial struggling i am able to write this script.but now i want to create the exe file of this script.i have used py2exe for this job and created the exe. but when i run the exe my program in not behaving as it supposed to be.its generating some errors.i dont know why this thing is happening as when i run my script it works fine.can some one put some light here. i am using python2.5 and is using py2exe-0.6.6.win32-py2.5.exe of py2exe. My os is windows xp with service pack2. thanks and reagrds sandeep kumar sharma -- http://mail.python.org/mailman/listinfo/python-list What exactly are those errors? You can get more help if we know more about the problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: python script to windows exe
On May 19, 1:39 pm, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: but when i run the exe my program in not behaving as it supposed to be.its generating some errors.i dont know why this thing is happening as when i run my script it works fine.can some one put some light here. There is nothing special in executables produced by py2exe. I mean that the debugging strategy is as always. A good start might be in adding logging\tracing facilities both to script and the executable. Comparing two trace files could give you some clue. hi here is my code.i wont get any errors when i run this script.it may not be the best pycode as i am very much new to python development. import win32com,win32com.client import os,os.path import codecs import zipfile [EMAIL PROTECTED]:::Sandeep Kumar Sharma #outlook2003 application refrence outlook_app=0 #outlook ids to access different folders look into msdn for more info. not a preffered way as i am hardcoding data here OlDefaultFolders={'olFolderCalendar':9,'olFolderConflicts': 19,'olFolderContacts':10,'olFolderDeletedItems':3,'olFolderDrafts': 16,'olFolderInbox':6,'olFolderJournal':11,'olFolderJunk': 23,'olFolderLocalFailures':21,'olFolderNotes':12,'olFolderOutbox': 4,'olFolderSentMail':5,'olFolderServerFailures': 22,'olFolderSyncIssues':20,'olFolderTasks': 13,'olPublicFoldersAllPublicFolders':18} #outlook types to save mailItem look into msdn for more info #although doesnot work for me :-( OlSaveAsType={'olTXT': 0,'olRTF':1,'olTemplate': 2,'olMSG': 3,'olDoc': 4,'olHTML':5,'olVCard': 6,'olVCal':7,'olICal': 8}; #refrence to content in inbox inbox_obj=0 #function which will initialise outlook and return its reference def getAppRef(): temp=win32com.client.Dispatch(OutLook.Application) return temp.GetNamespace(MAPI) #function to return the folders in the outlook def getOutLookFolders(a,b=OlDefaultFolders['olFolderInbox']): return a.GetDefaultFolder(b) #function to get email content def getMailContent(obj): txt_file=codecs.open('data.html',encoding='utf-8',mode='w') for kk in range(len(obj.Items),1,-1): #for kk in range(len(obj.Items-1),0,-1): #print 'hello' print 'writting file='+str(kk) mailItem=obj.Items[kk] writeData(mailItem,txt_file) #print mailItem.OlSaveAsType.olMSG #saveCopy(mailItem) #print sender=+mailItem.SenderName+' SenderEmailId='+str(mailItem.SenderEmailAddress)+' Time='+str(mailItem.ReceivedTime) #print 'Subject='+mailItem.Subject+' size='+str(mailItem.Size) txt_file.close() ''' file_zip=zipfile.ZipFile(txt_file,w,zipfile.ZIP_DEFLATED) file_zip.write('data.log') file_zip.close() ''' #function to create a directory #obviously not a best way :-( but i think can expected this sort of mistakes from beginners def createDir(): path=os.path.abspath(\email) if(os.path.exists(path)): print Directory already exists else: os.system(md +path) #function to save a copy of email def writeData(mailItem,file): data=p sender='h4SenderName/ h4'+checkStringType(mailItem.SenderName) time='brh4Time/ h4'+checkStringType(str(mailItem.ReceivedTime)) attachment='brh5Attachments Count/ h5'+str(len(mailItem.Attachments)) edata='h4Email Content/h4'+checkStringType(mailItem.Body)+/ phr/ dataToWrite=data+sender+time+attachment+edata getAttachmentInfo(mailItem.Attachments) file.write(getHTMLString(dataToWrite)) #checkStringType(dataToWrite) def getAttachmentInfo(atmts): for kk in range(1,len(atmts)): atmt=atmts[kk] #print File Name=+atmt.FileName+' DisplayName='+atmt.DisplayName+' PathName='+atmt.PathName+' ' abc=os.path.isdir(os.getcwd()+'\email') if(abc==True): print 'directory exists' else: os.mkdir(os.getcwd()+'\email') path=os.path.abspath(os.getcwd()+'\email') atmt.SaveAsFile(path+\\+atmt.DisplayName) # function to check whether the character encoding is ascii or smthing else def checkStringType(a): if isinstance(a,str): b='not a unicode string' else: a.encode('utf-8') #print 'unicode type' return a #function to save the coopy of an email #:-( but smhow it generate error whenever i make a call to it def saveCopy(mailItem): name=\\+mailItem.Subject+__+str(mailItem.ReceivedTime) print name #global outlook_app try: mailItem.SaveAs(path+name+.txt,OlSaveAsType['olTXT']) except BaseException: print BaseException def getHTMLString(b): a='htmlheadtitleYour Email Data log is here/title/ headbody'+b+'/body/html' return a #main entrance to the program def main(): global outlook_app,inbox_obj outlook_app=getAppRef() #print outlook_app.OlSaveAsType.olMSG print '==' print dir(outlook_app) print '==' inbox_obj=getOutLookFolders(outlook_app) print dir(inbox_obj) print
ANN: eric 4.1.4 released
Hi, this is to inform all of you about the immediate availability of eric 4.1.4. It includes a fix for an API change of Qt 4.4, that caused eric4 to crash. Please update immediately. As usual, it is available via http://www.die-offenbachs.de/eric/index.html. What is eric? - Eric is a Python (and Ruby) IDE, that comes with all batteries included. For more details please see the above link. Regards, Detlev -- Detlev Offenbach [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for programming algorithms
Henrique Dante de Almeida a écrit : On May 17, 7:32 pm, Vicent Giner [EMAIL PROTECTED] wrote: Hello. (snip) However, it is usually said that Python is not a compiled but interpreted programming language —I mean, it is not like C, in that sense. (snip) I guess that python is not a good language for that. (snip) My opinion: choose compiled or byte compiled languages. Slightly OT (ie : not talking about computation-heavy alorgithm being better implemented in C then wrapped in Python - this seems quite obvious) but just a couple facts: 1/ being interpreted or compiled (for whatever definition of these terms) is not a property of a language, but a property of an implementation of a language. 2/ actually, all known Python implementations compile to byte-code. -- http://mail.python.org/mailman/listinfo/python-list
Disabling raw string to print newlines
Hello, *** import urllib2 import re import string import sys url = http://www.macgyver.com/; request = urllib2.Request(url) opener = urllib2.build_opener() html = opener.open(request).read() match = re.compile(PRE(.+)/PRE, re.DOTALL) out = match.findall(html) print out ** I would like to print out string with formatting, but as I read, the string is made into a raw string when using re. How could I disable or bypass this? I googled for an hour and couldn't find a solution. Thank you in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: Showing the method's class in expection's traceback
En Sun, 18 May 2008 17:31:44 -0300, Diez B. Roggisch [EMAIL PROTECTED] escribió: Agustin Villena schrieb: is there anyway to show the class of a method in an exception's traceback? I want to improve the line File G:\dev\exceptions\sample.py, line 3, in foo to File G:\dev\exceptions\sample.py, line 3, in Some.foo Is this improvement feasible It should be. You can get a dictionary of the locals of an exception stack frame, of which you could extract the self-parameter's class. That by itself is not enough, the method could be inherited; one should walk the base classes in the MRO to find the right one. And deal with classmethods and staticmethods. And decorators that don't preserve meta information... Hmmm, I think it isn't so trivial as it seems. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: python script to windows exe
hi the py code that i have written is here.when i run this code i wont get any errors it just works fine for me.but when i created the exe i start getting an error in my 'getMailContent' function. The error description is TypeError:unsupported operand type(s) for :- 'instance' and 'int' i dont know why i am start getting this error when i run it through the exe. import win32com,win32com.client import os,os.path import codecs import zipfile [EMAIL PROTECTED]:::Sandeep Kumar Sharma #outlook application refrence outlook_app=0 #outlook ids to access different folders look into msdn for more info. not a preffered way as i am hardcoding data here OlDefaultFolders={'olFolderCalendar':9,'olFolderConflicts': 19,'olFolderContacts':10,'olFolderDeletedItems':3,'olFolderDrafts': 16,'olFolderInbox':6,'olFolderJournal':11,'olFolderJunk': 23,'olFolderLocalFailures':21,'olFolderNotes':12,'olFolderOutbox': 4,'olFolderSentMail':5,'olFolderServerFailures': 22,'olFolderSyncIssues':20,'olFolderTasks': 13,'olPublicFoldersAllPublicFolders':18} #outlook types to save mailItem look into msdn for more info #although doesnot work for me :-( OlSaveAsType={'olTXT': 0,'olRTF':1,'olTemplate': 2,'olMSG': 3,'olDoc': 4,'olHTML':5,'olVCard': 6,'olVCal':7,'olICal': 8}; #refrence to content in inbox inbox_obj=0 #function which will initialise outlook and return its reference def getAppRef(): temp=win32com.client.Dispatch(OutLook.Application) return temp.GetNamespace(MAPI) #function to return the folders in the outlook def getOutLookFolders(a,b=OlDefaultFolders['olFolderInbox']): return a.GetDefaultFolder(b) #function to get email content def getMailContent(obj): txt_file=codecs.open('data.html',encoding='utf-8',mode='w') for kk in range(len(obj.Items),1,-1): #for kk in range(len(obj.Items-1),0,-1): #print 'hello' print 'writting file='+str(kk) mailItem=obj.Items[kk] writeData(mailItem,txt_file) #print mailItem.OlSaveAsType.olMSG #saveCopy(mailItem) #print sender=+mailItem.SenderName+' SenderEmailId='+str(mailItem.SenderEmailAddress)+' Time='+str(mailItem.ReceivedTime) #print 'Subject='+mailItem.Subject+' size='+str(mailItem.Size) txt_file.close() ''' file_zip=zipfile.ZipFile(txt_file,w,zipfile.ZIP_DEFLATED) file_zip.write('data.log') file_zip.close() ''' #function to create a directory #obviously not a best way :-( but i think can expected this sort of mistakes from beginners def createDir(): path=os.path.abspath(\email) if(os.path.exists(path)): print Directory already exists else: os.system(md +path) #function to save a copy of email def writeData(mailItem,file): data=p sender='h4SenderName/ h4'+checkStringType(mailItem.SenderName) time='brh4Time/ h4'+checkStringType(str(mailItem.ReceivedTime)) attachment='brh5Attachments Count/ h5'+str(len(mailItem.Attachments)) edata='h4Email Content/h4'+checkStringType(mailItem.Body)+/ phr/ dataToWrite=data+sender+time+attachment+edata getAttachmentInfo(mailItem.Attachments) file.write(getHTMLString(dataToWrite)) #checkStringType(dataToWrite) def getAttachmentInfo(atmts): for kk in range(1,len(atmts)): atmt=atmts[kk] #print File Name=+atmt.FileName+' DisplayName='+atmt.DisplayName+' PathName='+atmt.PathName+' ' abc=os.path.isdir(os.getcwd()+'\email') if(abc==True): print 'directory exists' else: os.mkdir(os.getcwd()+'\email') path=os.path.abspath(os.getcwd()+'\email') atmt.SaveAsFile(path+\\+atmt.DisplayName) # function to check whether the character encoding is ascii or smthing else def checkStringType(a): if isinstance(a,str): b='not a unicode string' else: a.encode('utf-8') #print 'unicode type' return a #function to save the coopy of an email #:-( but smhow it generate error whenever i make a call to it def saveCopy(mailItem): name=\\+mailItem.Subject+__+str(mailItem.ReceivedTime) print name #global outlook_app try: mailItem.SaveAs(path+name+.txt,OlSaveAsType['olTXT']) except BaseException: print BaseException def getHTMLString(b): a='htmlheadtitleYour Email Data log is here/title/ headbody'+b+'/body/html' return a #main entrance to the program def main(): global outlook_app,inbox_obj outlook_app=getAppRef() #print outlook_app.OlSaveAsType.olMSG print '==' print dir(outlook_app) print '==' inbox_obj=getOutLookFolders(outlook_app) print dir(inbox_obj) print (inbox_obj.Items) #saveCopy(inbox_obj.Items[1]) getMailContent(inbox_obj) main() my setup file has this code from distutils.core import setup import py2exe setup(console=['outlook.py']) i have just copied and pasted it from the tutorial available at the py2exe site and changed the filename with mine
Re: Disabling raw string to print newlines
[EMAIL PROTECTED] wrote: Hello, *** import urllib2 import re import string import sys url = http://www.macgyver.com/; request = urllib2.Request(url) opener = urllib2.build_opener() html = opener.open(request).read() match = re.compile(PRE(.+)/PRE, re.DOTALL) out = match.findall(html) print out ** I would like to print out string with formatting, but as I read, the string is made into a raw string when using re. How could I disable or bypass this? You have a misconception here. A raw-string in python is *only* different as literal - that is, you can write rfooo\bar where you'd have to write fooo\\bar with normal string-literals. However, the result of both is a byte-string object that is exactly equal. So whatever out contains, it has nothing to do with raw-string or not. But what you probably mean is that putting out a list using print will use the repr()-call on the contained objects. So instead of doing print out do print \n.join(out) or such. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for programming algorithms
Vicent Giner a écrit : Hello. I am new to Python. It seems a very interesting language to me. Its simplicity is very attractive. However, it is usually said that Python is not a compiled but interpreted programming language cf my answer to you and Henrique on this. I am working on my PhD Thesis, which is about Operations Research, heuristic algorithms, etc., and I am considering the possibility of programming all my algorithms in Python. The usual alternative is C, but I like Python more. Then use it. The main drawbacks I see to using Python are these: * As far as I understand, the fact that Python is not a compiled language makes it slower than C, when performing huge amounts of computations within an algorithm or program. In which way is this a problem here ? I thought your thesis was about algorithm, not about implementation optimisation ? And if it's the later, then even C might sometimes be too high level - you should drop to assembly language. * I don't know how likely it is to find libraries in Python related to my research field. I can't tell but you'd be surprised by the quantity of available Python libs. * I know Python is a serious and mature programming language, of course. But I do not know if it is seen as just funny in a research context. Is Python considered as a good programming language for implementing Operations Research algorithms, such as heuristics and other soft-computing algorithms? Don't know if this answers your question, but it seems that at least some authors consider it a good choice: http://www.oreilly.com/catalog/9780596529321/ All code examples in this books are in Python - very badly written Python, alas... Maybe this is not the right forum, but maybe you can give me some hints or tips... Hem... Obviously, most people here will have a little biased, you know ?-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for programming algorithms
Bruno Desthuilliers wrote: 2/ actually, all known Python implementations compile to byte-code. In curiosity, did your actually mean, in the French sense, at the moment or, in the English sense, in contrast to something stated earlier? Or maybe both? TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: How do *you* use Python in non-GUI work?
John Salerno a écrit : Hey all. Just thought I'd ask a general question for my own interest. Every time I think of something I might do in Python, it usually involves creating a GUI interface, so I was wondering what kind of work you all do with Python that does *not* involve any GUI work. This could be any little scripts you write for your own benefit, or what you do at work, if you feel like talking about that! :) web apps, command line utilities, and of course libraries. -- http://mail.python.org/mailman/listinfo/python-list
Re: explain this function to me, lambda confusion
inhahe a écrit : Both the responses offer lambda free alternatives. That's fine, and given the terse documentation and problems that I had understanding them, I would agree. So what applications are lambdas suited to? I think the parameterised function model is one. What else? i've hardly ever used lambdas since map() and filter() were replaced by list comprehension. two other uses I can think of for it are: using it as a sorting key (which takes a function and lambdas are perfect for that when a direct function isn't available. for example, lambda x: x.myName), import operator foos.sort(key=operator.attrgetter('myName')) -- http://mail.python.org/mailman/listinfo/python-list
Re: Showing the method's class in expection's traceback
That by itself is not enough, the method could be inherited; one should walk the base classes in the MRO to find the right one. And deal with classmethods and staticmethods. And decorators that don't preserve meta information... Hmmm, I think it isn't so trivial as it seems. You might even have an instance-unique method. But I think the OP is satisfied with a 90%-solution. Diez -- http://mail.python.org/mailman/listinfo/python-list
pickle internals
I am trying to understand pickle internals. This involves: -- the algorithm(s) used for traversal arbitrary structures -- the pickle format -- the use if any of introspection I'll be thankful for any pointers PS Should this question be put on some other list?/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Get all the instances of one class
Matt Nordhoff [EMAIL PROTECTED] wrote: Tommy Nordgren wrote: class MyClass : a_base_class memberlist=[] # Insert object in memberlist when created; # note: objects won't be garbage collected until removed from memberlist. Just to say, if you wanted to go about it that way, you could avoid the garbage collection problem by using weakrefs: http://docs.python.org/lib/module-weakref.html Eg... from weakref import WeakKeyDictionary class Test(object): _instances = WeakKeyDictionary() def __init__(self): self._instances[self] = True # your normal init stuff here @classmethod def instances(cls): return cls._instances.keys() print Test.instances() a = Test() b = Test() print Test.instances() del a print Test.instances() del b print Test.instances() Which prints [] [__main__.Test object at 0xb7d4eb6c, __main__.Test object at 0xb7d4eb4c] [__main__.Test object at 0xb7d4eb6c] [] -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for programming algorithms
Tim Golden a écrit : Bruno Desthuilliers wrote: 2/ actually, all known Python implementations compile to byte-code. In curiosity, did your actually mean, in the French sense, at the moment or, in the English sense, in contrast to something stated earlier? Or maybe both? I mainly intented it to be understood in the English sense - but taking it the French way would be ok too. -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading Java byte[] data stream over standard input
On 19 May, 06:11, sapsi [EMAIL PROTECTED] wrote: Hello, I am using HadoopStreaming using a BinaryInputStream. What this basically does is send a stream of bytes ( the java type is : private byte[] bytes) to my python program. I have done a test like this, while 1: x=sys.stdin.read(100) if x: print x else: break Now, the incoming data is binary(though mine is actually merely ascii text) but the output is not what is expected. I expect for e.g all/86000/114.310.151.209.60370-121.110.5.176.113\n62485.9718 118.010.241.12 60370 128.210.5.176 However i get a 1 before all and a 4 just after \n and before the 6. My question is : how do i read binary data(Java's byte stream) from stdin? Or is this actually what i'm getting? Thanks Sapsi In the past I've sent binary data to a java applet reading DataInputStream using xdrlib from the standard library. I'd expect that it would work in the reverse direction so I suggest you have a look at that. Giles -- http://mail.python.org/mailman/listinfo/python-list
Re: Organizing a Python project
A.T.Hofkamp wrote: Also, why do you make a distinction between shared and non-shared code? You could simply eliminate 'shared' directory, and put its contents directly under myproject. I would go further and make them individual projects, with their own version control, code repository and then install them as eggs using setuptools. This has been working fine for me in some projects and has the advantage of being reusable in different big projects. Also, using setuptools on each big project I don't have to worry with dependencies because it downloads and installs everything to me when I install the main project. Is there a way to set this up that is a bit more self contained? For example, at first I was somewhat hopeful that Python could ascend parent directories until it reached a directory that did not include an __init__.py file, and it could use this as a root for referring to packages and modules from any file contained within. (e.g. in the example project above, any file could refer to myproject.shared.mylib1 so long as 'myproject' and all subdirectories contained an __init__.py, and the parent of 'myproject' didn't contain such a file). Evidently this is not the case, but it seems like it could be a useful feature in these situations. Eggs would solve that as well. They would behave like any other installed library on your system. -- Jorge Godoy [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
ftplib returns EOFError
Hi All, I've written a little method to connect to an ftpserver which works well, however when I send a file using this ftp connection oddly I _sometimes_ get returned an EOFError from ftplib.getline even though my file is actually transferred. Here's my script: def uploadViaFtp(self, file, filename): '''A method to upload a file via ftp''' ftpserverloc = self.getItunesUftpServer() ftpserverusername = self.getItunesUftpUser() ftpserverpassword = self.getItunesUftpPsswd() ftp = ftplib.FTP(ftpserverloc) ftp.login(ftpserverusername, ftpserverpassword) try: ftp.storbinary(STOR + filename, file, 1024) finally: file.close() ftp.quit() And here's the traceback: Traceback (innermost last): Module ZPublisher.Publish, line 114, in publish Module ZPublisher.mapply, line 88, in mapply Module ZPublisher.Publish, line 40, in call_object Module Products.FileSystemSite.FSPythonScript, line 108, in __call__ Module Shared.DC.Scripts.Bindings, line 311, in __call__ Module Shared.DC.Scripts.Bindings, line 348, in _bindAndExec Module Products.FileSystemSite.FSPythonScript, line 164, in _exec Module None, line 28, in upload_submit - FSPythonScript at /silva/service_views/UCLItunesUPodcast/edit/Asset/UCLItunesUTrack/upload_sub mit - Line 28 Module Products.UCLItunesUPodcast.UCLItunesUService, line 138, in uploadViaFtp Module ftplib, line 523, in quit Module ftplib, line 246, in voidcmd Module ftplib, line 221, in voidresp Module ftplib, line 207, in getresp Module ftplib, line 193, in getmultiline Module ftplib, line 183, in getline EOFError Any help in catching and ignoring this error would be greatly appreciated. Regards Jon -- http://mail.python.org/mailman/listinfo/python-list
Re: indexed properties...
On Sun, 18 May 2008 18:18:34 +0200, pataphor [EMAIL PROTECTED] wrote: In article [EMAIL PROTECTED], [EMAIL PROTECTED] says... Is there some reason that would be better? It would make a lot of the code more complicated. Ok, it would require only one bit of added code, I suppose, but I don't see the plus side. The plus side is you give up an untenable position :-) Maybe you could be more specific? Various positions I've taken in all this may well be untenable, but I can't think of any that have anything to do with whether the data should be a single list instead of a list of lists. (The only way I can parse this to make it relevant is to assume that the position you're referring to is that a list of lists is better than a single list. If so: First, I haven't said that it was. Second, saying B is untenable is not much of an answer when someone asks why you say A is better than B.) And to address an item in a matrix costs two lookups, row and column, while an array needs only one. The phrase premature optimization springs to mind. This is _Python_ we're talking about. Supposing you're right that doing two lookups _in Python_ is faster than doing one lookup plus the calculuation col + row*width _in Python_, it can't make enough difference to matter. In the sort of application I have in mind things already happen instantaneously. The point is not to improve on NumPy. Trying to improve on NumPy in pure Python code would be silly - if I wanted optimized large matrices I'd _use_ NumPy. The point is just to give a simple intuitive way to manipulate rows and columns in small matrices. So I'm not looking ahead to the future, things are not scalable? The thing is not _supposed_ to scale up to large matricies. If a person were dealing with large matricies then almost all of it would need to be rewritten (and if a person were dealing with really large matrices then trying to do the thing in pure Python would be silly in the first place, and insisting on being able to write things like m.row[0] = m.row[1] + m.row[2] could very well be a totally wrong approach to begin with - I'd figure out the operations I expected to need to do and write functions to do them.) Really. In one of the intended applications the matrix entries are going to be home-made Rationals. Just adding two of those guys takes a long time. It's still more than fast enough for the intended application, but [oh, never mind. Sorry about the argumentative tone - I _would_ like to know which untenable position you're referring to... P. David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: New to Python, Discussion Groups.
On May 19, 1:34 am, cmoller [EMAIL PROTECTED] wrote: Hi, I am new to Python and the use of discussion groups. Is there a FAQ for basic information so certain questions are not repeated? I am NOT an experienced programmer, but have decided to write a data logger for sensors sending data via an internal ethernet work to machines running OS X (Intel). The program should store data and allow real time plotting. It does not need a beautiful GUI, but I may want to share the program with others, so it should be somewhat intuitive. It looks like I could use Python to access MS Excel, which would significantly reduce the effort, but I am not sure if this is practical. I am not in a hurry and would approach the problem as a way to learn. You could also use Resolver One, a spreadsheet program that lets you put Python code inside your spreadsheets (effectively providing a 'spreadsheet-like' front end to the code you write). http://www.resolversystems.com/ http://www.resolverhacks.net/ All the best, Michael Foord http://www.ironpythoninaction.com/ The data I am processing is readily seen via telnet so I know it's there. Is Python a good choice or should I invest in learning a language well known to be best for applications like this? Are there other key topics in addition to network programing that I should be focusing on? Thanks, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: indexed properties...
On Mon, 19 May 2008 06:29:18 -0500 David C. Ullrich [EMAIL PROTECTED] wrote: Maybe you could be more specific? Various positions I've taken in all this may well be untenable, but I can't think of any that have anything to do with whether the data should be a single list instead of a list of lists. What's 'untenable' (hey, I tried to get away with a smiley, remember) is that a matrix is a list of rows. Suppose you do the transpose trick with the zip(*M) routine, now it's a list of columns. Both views are equal, there is no getting around the fact that you're holding an unnatural predisposition towards seeing the matrix as a list of rows, which it is most definitely not ... I was holding the brakes for this argument because I realize it's intuitive and also because Gabriel seems to want a list stay a list if he assigns something a list. But that's untenable too. Suppose you assign a column to a list? The list is torn to shreds and placed over multiple rows. (The only way I can parse this to make it relevant is to assume that the position you're referring to is that a list of lists is better than a single list. If so: First, I haven't said that it was. Second, saying B is untenable is not much of an answer when someone asks why you say A is better than B.) Yes, it was not much of an answer but I was afraid of ending up in this quagmire. I now see that it is unavoidable anyway if I want to explain myself. Why couldn't you just see it the same way as me and leave it at that without waking up all the creatures of hell :-) And to address an item in a matrix costs two lookups, row and column, while an array needs only one. The phrase premature optimization springs to mind. Well, I really liked your slicing idea ... This is _Python_ we're talking about. Supposing you're right that doing two lookups _in Python_ is faster than doing one lookup plus the calculuation col + row*width _in Python_, it can't make enough difference to matter. In the sort of application I have in mind things already happen instantaneously. The computation is almost certainly faster. Lookups are expensive. However I concede the point because we're not supposed to worry about such stuff. But it *is* a simpler format. The point is not to improve on NumPy. Trying to improve on NumPy in pure Python code would be silly - if I wanted optimized large matrices I'd _use_ NumPy. The point is just to give a simple intuitive way to manipulate rows and columns in small matrices. Yes, me too. This is all about intuition. So I'm not looking ahead to the future, things are not scalable? The thing is not _supposed_ to scale up to large matricies. If a person were dealing with large matricies then almost all of it would need to be rewritten (and if a person were dealing with really large matrices then trying to do the thing in pure Python would be silly in the first place, and insisting on being able to write things like m.row[0] = m.row[1] + m.row[2] could very well be a totally wrong approach to begin with - I'd figure out the operations I expected to need to do and write functions to do them.) The reason why I am interested in this is that since I was writing sudoku algorithms some time ago I have been looking for ways to interact with data according to different views. I want the data to update even when I have made changes to them according to another view. In my case things are even more complex than they are with matrices because I tend to view sudoku as subcases of binary cubes. Imagine a 3d 9*9*9 chessboard and try to place 81 non-threatening rooks in it. This is not quite a solution to a sudoku but every sudoku is also a solution to this problem. One of the solution strategies I thought of was forgetting about the 3d binary cube's content at all, and just update row, column and file totals (I start with a 'filled' cube and wipe away fields that are covered by the 'rooks') to drive the optimization. Somehow this seems possible even though I do not use the cube itself anymore. It just exists as a figment of my imagination but still it defines the context. I hope you understand how this was driving me crazy and why I would be more than happy to return to a safe and sound, actually 'existing' cube, if only there was a way to access rows, columns and files (for example sum their elements) as shared data. In the end I realized that everything I was doing was an abstraction anyway and if that is the case why not use the simplest possible representation for the data and let any matrices, rows, columns, files, cubes and so on exist somewhere higher up in the levels of abstraction of the code. Really. In one of the intended applications the matrix entries are going to be home-made Rationals. Just adding two of those guys takes a long time. It's still more than fast enough for the intended application, but [oh, never mind. Too late :-) Sorry about the argumentative tone - I _would_ like to
Re: python script to windows exe
On May 19, 8:32 am, sandeep [EMAIL PROTECTED] wrote: hi all i am very much a newbie to python but has some experience of development.i am trying to write a script which will loop through the outlook 2003 inbox and save the email data in an simple data.html page and save all the attachments in a folder name emails.after some initial struggling i am able to write this script.but now i want to create the exe file of this script.i have used py2exe for this job and created the exe. but when i run the exe my program in not behaving as it supposed to be.its generating some errors.i dont know why this thing is happening as when i run my script it works fine.can some one put some light here. i am using python2.5 and is using py2exe-0.6.6.win32-py2.5.exe of py2exe. My os is windows xp with service pack2. thanks and reagrds sandeep kumar sharma You'll need to post the actual errors you get for people to be able to help. You might find posting to the py2exe mailing list useful. All the best, Michael Foord http://www.ironpythoninaction.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How do *you* use Python in non-GUI work?
On May 19, 12:20 am, John Salerno [EMAIL PROTECTED] wrote: Hey all. Just thought I'd ask a general question for my own interest. Every time I think of something I might do in Python, it usually involves creating a GUI interface, so I was wondering what kind of work you all do with Python that does *not* involve any GUI work. This could be any little scripts you write for your own benefit, or what you do at work, if you feel like talking about that! :) Thanks. - Programs creating C and VHDL source files - Scipy scripts generating charts Jan Wicijowski -- http://mail.python.org/mailman/listinfo/python-list
Re: Disabling raw string to print newlines
On May 19, 4:54 am, [EMAIL PROTECTED] wrote: Hello, *** import urllib2 import re import string import sys url = http://www.macgyver.com/; request = urllib2.Request(url) opener = urllib2.build_opener() html = opener.open(request).read() match = re.compile(PRE(.+)/PRE, re.DOTALL) out = match.findall(html) print out ** I would like to print out string with formatting, but as I read, the string is made into a raw string when using re. How could I disable or bypass this? I googled for an hour and couldn't find a solution. Thank you in advance. Change your print statement to: print out[0] -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: explain this function to me, lambda confusion
Arnaud Delobelle [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | On May 19, 5:22 am, Terry Reedy [EMAIL PROTECTED] wrote: | Arnaud Delobelle [EMAIL PROTECTED] wrote in message | [...] | | Note that the same thing can be said about generator expressions, | | which are nothing more than anonymous, non-reusable, generator | | functions. | | Right. So if someone posted on genexp confusion, I would suggest | 'write a full generator function'. | | I was just arguing against arguing for the removal of lambda on the | basis that it doesn't add any functionality to the language! I sort of understood that ;-) Like Guido, I am split on keep/remove. However, I have decided to leave lambda out of my Python-subset executable-pseudocode algorithm language. I have not decided whether or not to include genexps. | | Instead these were _added_ to the language! | | As a convenience. | Actually, if one uses more that one for-clause in a generator expression, | there is a potential gotcha in relation to name capture. So if that bites, | the genexp is not so much a convenience, and one might better write | the full function. | Yes, IMHO this is a bug, and I wish I had the time to dive into the | code to see if I can fix it. If I do include them, I might restrict them to one for-clause because of that glitch, whose details I keep forgetting. tjr | -- http://mail.python.org/mailman/listinfo/python-list
Re: Disabling raw string to print newlines
On May 19, 4:54 am, [EMAIL PROTECTED] wrote: Hello, snip code example scraping a QOTD from www.mcgyver.com print out ** Since you have no control over spacing and line breaks in the input, you can reformat using the textwrap module. First replace all \ns with , then use re.sub to replace multiple spaces with a single space, then call textwrap.fill to reformat the line into lines up to 'n' characters long (I chose 50 in the sample below, but you can choose any line length you like). out = match.findall(html) out = out[0].replace(\n, ) out = re.sub(\s+, ,out) print textwrap.fill(out,50) -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Disabling raw string to print newlines
On May 19, 8:09 am, Paul McGuire [EMAIL PROTECTED] wrote: On May 19, 4:54 am, [EMAIL PROTECTED] wrote: Hello, snip code example scraping a QOTD fromwww.mcgyver.com print out ** Since you have no control over spacing and line breaks in the input, you can reformat using the textwrap module. First replace all \ns with , then use re.sub to replace multiple spaces with a single space, then call textwrap.fill to reformat the line into lines up to 'n' characters long (I chose 50 in the sample below, but you can choose any line length you like). out = match.findall(html) out = out[0].replace(\n, ) out = re.sub(\s+, ,out) print textwrap.fill(out,50) -- Paul One last try - .replace(\n, ) is unnecessary, textwrap.fill takes care of removing extra newlines already. out = match.findall(html) out = out[0] out = re.sub(\s+, ,out) print textwrap.fill(out,50) -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: python script to windows exe
En Mon, 19 May 2008 06:59:22 -0300, sandeep [EMAIL PROTECTED] escribió: the py code that i have written is here.when i run this code i wont get any errors it just works fine for me.but when i created the exe i start getting an error in my 'getMailContent' function. The error description is TypeError:unsupported operand type(s) for :- 'instance' and 'int' i dont know why i am start getting this error when i run it through the exe. By example, your code uses os.getcwd() - so it depends on the current dir. Try running it from a different directory. Don't focus too much on the .exe vs .py difference: it might not be relevant, the error may reside elsewhere. Please post the complete exception message *and* traceback. Don't retype it; copy and paste the message from the console. Your message above doesn't appear to be correctly typed, it says `:-` but Python would print `-:` and I don't see any `-` operation in your code that could fail in that way. Also, don't do this: try: mailItem.SaveAs(path+name+.txt,OlSaveAsType['olTXT']) except BaseException: print BaseException because you're completely hiding important information about *what* happened. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading Java byte[] data stream over standard input
sapsi wrote: I should also mention that for some reason there are several binay values popping in between for some reason. This behavior (for the inputr stream) is not expected Now, the incoming data is binary(though mine is actually merely ascii text) but the output is not what is expected. I expect for e.g all/86000/114.310.151.209.60370-121.110.5.176.113\n62485.9718 118.010.241.12 60370 128.210.5.176 However i get a 1 before all and a 4 just after \n and before the 6. My question is : how do i read binary data(Java's byte stream) from stdin? Or is this actually what i'm getting? Consider changing print x to print repr(x) ... this would mean that you have a better chance of understanding what the extra or unexpected popping-in bytes are. -- http://mail.python.org/mailman/listinfo/python-list
Re: TPCServer and xdrlib
I'm trying to write a multi threaded TPC server. I have used xmlrpc How exactly did you come to the conclusion that your server must be multi threaded ? I don't think that it is important. But if you are interested: - yes, the server will probably be I/O bound, not CPU bound - I'm have experience with thread programming, but not with twisted - I have to send larger amounts of data, the overhead of converting to XML and parsing XML back would be too much pain - What's the expected amount of data you have to transfer ? I cannot predict. But I will be trasferring image files which would be silly to do with XML. - What's the expected network bandwidth ? It cannot be determined in advance. - What's the expected acceptable transfer time ? Not known. - How many users are expected to be transfering data at the same time ? The server should be scaleable up to hundreds of users. (I'm just trying to answer your questions, if that helps to answer mine.) Did you consider gzipping your XML (or YAML) packets ? Would the transfer time be acceptable in this case ? No. Image binary data - base64encode - XML - gzip - looks very silly. It cannot be efficient. Do you have better ideas? BTW I do not care about the clients - they must trust the server side. Oh, he said he _doesn't care about the clients_ ! ;-) I meant *safety* here: clients are going to download program updates from the server. So if they do not trust the server then they should not use it. The server is different: it must be safe against external attacks. Maybe it was my bad English? Sorry for the misunderstanding. In general I would avoid that. Try to better estimate the speed requirements, to see if you really need do to this. I cannot predict acceptable speed requirements, but I can tell that there will be some clients downloading 100MB report files from the server, so I presume that I will need a progress bar. I think that I need to develop my own protocol for this, and probably the underlying layer should use binary representation. Before I start re-inventing the wheel: - Is there another (already existing) higher level framework that I can try? It should be safe and fast, that is the only restriction. There's Twisted. http://twistedmatrix.com/projects/core/documentation/howto/servers.html Yes, I tried twisted before and I did not like it. It forces me to things that I do not want to do. (I cannot tell what it was - it was two years ago.) - Do you think that it is a good idea to use xdrlib? I haven't seen projects using it directly. For me it is like the rotor module was - it It's probably the best way to send binary stuff over the network. But, again, I would avoid doing so. It is NOT the best way. Just to tell one example: big endian / little endian integers. Definitely I need some encoding. (But if you are right and this is the best way, why would you avoid?) L -- http://mail.python.org/mailman/listinfo/python-list
Re: pickle internals
En Mon, 19 May 2008 07:52:25 -0300, Rustom Mody [EMAIL PROTECTED] escribió: I am trying to understand pickle internals. This involves: -- the algorithm(s) used for traversal arbitrary structures -- the pickle format -- the use if any of introspection I'll be thankful for any pointers Use The Source, Luke! See pickle.py and pickletools.py - you may post here any questions you have then. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for programming algorithms
Bruno Desthuilliers schreef: 1/ being interpreted or compiled (for whatever definition of these terms) is not a property of a language, but a property of an implementation of a language. 2/ actually, all known Python implementations compile to byte-code. You keep saying that, and in theory you're right. But I'm still inclined to disagree with it, since the practical reality is different. Python is indeed compiled to byte code, but if you compare that byte code with assembly code you'll see that there's a whole world of difference between the two, largely because of the dynamical nature of Python. Fact is that Python was designed from the start to run on a virtual machine, not on the native hardware. C OTOH was designed to be compiled to assembly code (or directly to machine code) and as a result there are no (or virtually) no implementations that interpret C or compile it to bytecode. I love Python, but IMHO it's a bit silly to maintain that the fact that Python compiles to byte code instead of assembly code/machine code is purely a matter of implementation; on the contrary, I believe it's a result of its design. I also think that there's a large difference between byte code and machine code (in Python's case; I haven't looked at other languages), and that it's a bit silly to try to trivialize that difference. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven -- http://mail.python.org/mailman/listinfo/python-list
Re: Organizing a Python project
[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | Hello all, | | I'm starting work on what is going to become a fairly substantial | Python project, and I'm trying to find the best way to organize | everything. The project will consist of: | | - A few applications | - Several small scripts and utilities | - Unit tests and small interactive test programs | - A number of custom libraries and modules that may be shared and | referenced among all of the above | | I have the following general structure in mind: | | myproject/ | app1/ |main.py If you put myproject in Pythonxy/Lib/site-packages, there is no need to fiddle with PYTHONPATH or sys.path. In 3.0a5 I tried a relative import and got a message that relative imports only work within packages, not modules. I presume that means package.__init__.py. Maybe I just miswrote the import, but I decided to stick with what dependably works whether from within or without the package from package.subpackage import module #or from package.subpackage.module import object. I agree with the comment about removing the 'shared' package layer. Two packages deep is enough typing unless the deeper hierarchy is needed (like possibly the 'tests' subsubpackages, if they make running the tests easier). tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: How do *you* use Python in non-GUI work?
John Salerno wrote: Hey all. Just thought I'd ask a general question for my own interest. Every time I think of something I might do in Python, it usually involves creating a GUI interface, so I was wondering what kind of work you all do with Python that does *not* involve any GUI work. This could be any little scripts you write for your own benefit, or what you do at work, if you feel like talking about that! :) Thanks. The vast majority of my Python work is Non-GUI. As an example, this weekend, I wrote a script to help in making a 'Lyrics' track in an audacity file, which is (more-or-less) an XML variety. In audacity, I created 'markers' in the file (as the song played) at the start of each line. The result was 'blank' markers at the correct times: labeltrack name=Lyrics numlabels=25 label t=18.50121034 t1=18.50121034 title=/ label t=24.34844390 t1=24.34844390 title=/ !-- Etc -- /labeltrackl My Python script took a text file, and inserted the words, as well as a title for the whole song. labeltrack name=Lyrics numlabels=26 label t=0.25 t1=0.25 title=Katie Melua. 'Nine million bicycles in Beijing' / label t=18.50121034 t1=18.50121034 title=There are nine million bicycles in Beijing,/ label t=24.34844390 t1=24.34844390 title=Thatapos;s a fact,/ label t=27.12436227 t1=27.12436227 title=Itapos;s a thing we canapos;t deny,/ !-- Etc -- /labeltrackl (The script used FourSuite) You can do this in FourSuite itself, but it can be error-prone if you miss out one. I can this in 'Scite' a text editor which puts your input in one window, and the output in another. Scite is a text editor that comes free with Ruby, by the way. -- http://mail.python.org/mailman/listinfo/python-list
Re: explain this function to me, lambda confusion
On May 18, 10:41 am, inhahe [EMAIL PROTECTED] wrote: Both the responses offer lambda free alternatives. That's fine, and given the terse documentation and problems that I had understanding them, I would agree. So what applications are lambdas suited to? I think the parameterised function model is one. What else? i've hardly ever used lambdas since map() and filter() were replaced by list comprehension. two other uses I can think of for it are: using it as a sorting key (which takes a function and lambdas are perfect for that when a direct function isn't available. for example, lambda x: x.myName), and I made an irc bot once that certain events had a list of fuctions that would be called after that event. it was like being able to dynamically add and remove event handlers. for example what if you asked the user a question and you wanted to know for the next input whether it was from that user and was an answer to that question. sometimes the function to add would be very simple, so writing a def for it would just be ugly. lambda is handy in defining parse actions in pyparsing. Parse actions are callbacks to be run when an expression within a larger grammar is matched. A common use for parse actions is to do some sort of text or type conversion. The simplest parse actions are called using the list of matched tokens. Here is a subexpression that will convert numeric strings found in a larger grammar to ints: integer = Word(0123456789).setParseAction(lambda tokens: int(tokens[0]) ) Since this returns an actual int, there is no need to junk up the post- parsing code with calls to int(), float(), etc. for these simple conversions. Here is an example parse action that just converts a set of matched words to title case: title = OneOrMore(Word(alphas)).setParseAction(lambda tokens: .join([ t.title() for t in tokens ]) ) print title.parseString(the sun also rises)[0] prints: The Sun Also Rises This second example is about as complex as I'd like to get in a lambda, though. Anything more elaborate than that, and I'd go with a separately defined function. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for programming algorithms
Roel Schroeven wrote: Bruno Desthuilliers schreef: 1/ being interpreted or compiled (for whatever definition of these terms) is not a property of a language, but a property of an implementation of a language. 2/ actually, all known Python implementations compile to byte-code. You keep saying that, and in theory you're right. But I'm still inclined to disagree with it, since the practical reality is different. Python is indeed compiled to byte code, but if you compare that byte code with assembly code you'll see that there's a whole world of difference between the two, largely because of the dynamical nature of Python. Fact is that Python was designed from the start to run on a virtual machine, not on the native hardware. C OTOH was designed to be compiled to assembly code (or directly to machine code) and as a result there are no (or virtually) no implementations that interpret C or compile it to bytecode. I love Python, but IMHO it's a bit silly to maintain that the fact that Python compiles to byte code instead of assembly code/machine code is purely a matter of implementation; on the contrary, I believe it's a result of its design. I also think that there's a large difference between byte code and machine code (in Python's case; I haven't looked at other languages), and that it's a bit silly to try to trivialize that difference. I strongly disagree. See the Java which is compiled to bytecode *explicitly*, jet the JVM-bytecode is closer to Python than to what C++ is compiled to. But then, it's possible to have JIT-compilers that bring machine code back into the picture. And see python + psyco as JIT. And OTOH see Objective-C and it's runtime for an example of a machine-code-compiled language that still has huge dynamic runtime parts. All these blur the image extremely and make Bruno's point: compilation is an artifact, not some inherent property of a language. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Showing the method's class in expection's traceback
On May 18, 4:31 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote: Agustin Villena schrieb: Hi! is there anyway to show the class of amethodin an exception's traceback? For example, the next code class Some(object): def foo(self,x): raise Exception(x) obj = Some() obj.foo(some arg) produces the next traceback Traceback (most recent call last): File string, line 231, in run_nodebug File G:\dev\exceptions\sample.py, line 7, in module obj.foo(some arg) File G:\dev\exceptions\sample.py, line 3, in foo raise Exception(x) Exception: some arg I want to improve the line File G:\dev\exceptions\sample.py, line 3, in foo to File G:\dev\exceptions\sample.py, line 3, in Some.foo Is this improvement feasible It should be. You can get a dictionary of the locals of an exception stack frame, of which you could extract the self-parameter's class. Diez Hi! I digged on sys.exc_info() object and the traceback module and I could't figure how I can get the locals() of the exception stackframe Any advice? Thanks Agustin -- http://mail.python.org/mailman/listinfo/python-list
printing class __dict__
hi, i am a newbie. so bear wth me i wrote a program like this -- class H(object): def __init__( self): self.data =10 def e ( self ): pass def f ( self ): pass class H1(H): x2 = 11 def __init__(self): self.x = 10 class details(object): def data(self,className): print classname.__dict__ print classname.__name__ print classname.__bases__ bc = details() bc.data(H1) when i run it, i get error like this NameError: global name 'classname' is not defined can't i pass 'class' like an 'object'? any suggestions to access other classes details inside a class? -- http://mail.python.org/mailman/listinfo/python-list
Re: printing class __dict__
[EMAIL PROTECTED] wrote: hi, i am a newbie. so bear wth me i wrote a program like this -- class H(object): def __init__( self): self.data =10 def e ( self ): pass def f ( self ): pass class H1(H): x2 = 11 def __init__(self): self.x = 10 class details(object): def data(self,className): print classname.__dict__ print classname.__name__ print classname.__bases__ bc = details() bc.data(H1) when i run it, i get error like this NameError: global name 'classname' is not defined can't i pass 'class' like an 'object'? any suggestions to access other classes details inside a class? Python is case-sensitive. Now analyze your code. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: How do *you* use Python in non-GUI work?
On May 18, 5:20 pm, John Salerno [EMAIL PROTECTED] wrote: Hey all. Just thought I'd ask a general question for my own interest. Every time I think of something I might do in Python, it usually involves creating a GUI interface, so I was wondering what kind of work you all do with Python that does *not* involve any GUI work. This could be any little scripts you write for your own benefit, or what you do at work, if you feel like talking about that! :) Thanks. Most of my non-GUI stuff is login scripts and registry editing. I also have some scripts that can install various programs silently, such as Adobe Reader or Firefox. This is for work purposes as we have a specific set of applications that need to be installed on each machine. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: distutils directory problem
On May 18, 3:31 pm, Martin Manns [EMAIL PROTECTED] wrote: Hi, I have the following problem with the distutils package: (I have now spent hours reading and searching the manuals and tutorials, and I am still stuck.) I have a working directory ~/pyspread in which my libraries are situated and two icons directories ~/pyspread/icons and ~/pyspread/icons/actions Now I would like to create a setup.py file inside my ~/pyspread directory that installs my .py modules in .../site-packages/pyspread and the icons in appropriate sub-folders and adds pyspread.pth to .../site-packages so that .../site-packages/pyspread is in the PYTHONPATH. However, my setup.py puts everything (including .pyc files) into site-packages *and* into the sub-folders. What am I doing wrong? I am looking for a platform-independent solution. Currently, I am using python 2.5 on Linux. Here my setup.py #!/usr/bin/env python from distutils.core import setup setup(name='pyspread', version='0.0.7', description='A spreadsheet that accepts a pure python expression in each cell.', license='GPL v3 :: GNU General Public License', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: End Users/Desktop', ], author='Martin Manns', author_email='[EMAIL PROTECTED]', url='http://sourceforge.net/projects/pyspread/', packages=['pyspread'], package_dir={'pyspread': '.'}, scripts=['pyspread.py'], py_modules=['pyspread.mainapp', 'pyspread.pysgrid', 'pyspread.mygrid','pyspread.icontheme'], package_data={'pyspread': ['icons/*.png', 'icons/actions/*.png' ,\ 'test.pys', 'test.csv', 'test2.csv', \ 'README', 'COPYING']}, ) Thanks in advance Martin I highly recommend re-posting this to the distutils group. They have some excellent people over there that can probably tell you quite quickly what the issue is: http://mail.python.org/mailman/listinfo/distutils-sig Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: addendum Re: working with images (PIL ?)
Thanks, since posting I figured out how to interpret the histogram results, which seems to be the consensus in responses. I wrote a check image program and have been periodically calling it against a folder where I make a copy of our images used for production. My method right now is to check what we send for errors, but is not preventive. Also I determined whitespace is not the only issue, any color that dominates. I'm considering rewriting this code below to setup bins, so if combined neighboring colors exceeds the threshold then reject the image. I have examples where half the image appears black, but actually varies throughout. Since my image is RGB I'm looping through a 768 element list. Zach- import Image, os def check_image(file): try: im = Image.open(file) except: return Can't open file %s % file imData = im.histogram() i = 0 for ea in imData: if ea ((im.size[0] * im.size[1]) / 4): ## 25% of image size return bad image %s - %s element num is %s % (file, ea, str(i)) i = i + 1 return good image %s, image size is %s % (file, im.size) def main(dir): data = try: files = os.listdir(dir) for ea in files: data = data + str(check_image(os.path.join(dir,ea))) + \n except: return Can't get files in %s % dir return data print main(host\\path\\to\\image_folder\\) Ken Starks [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] As others have said, PIL has the 'histogram' method to do most of the work. However, as histogram works on each band separately, you have a bit of preliminary programming first to combine them. The ImageChops darker method is one easy-to-understand way (done twice), but there are lots of alternatives, I am sure. # import Image import ImageChops Im = Image.open(server\\vol\\temp\\image.jpg) R,G,B = Im.split() Result=ImageChops.darker(R,G) Result=ImageChops.darker(Result,B) WhiteArea=Result.histogram()[0] TotalArea=Im.size[0] * Im.size[1] PercentageWhite = (WhiteArea * 100.0)/TotalArea Poppy wrote: I've put together some code to demonstrate what my goal is though looping pixel by pixel it's rather slow. import Image def check_whitespace(): im = Image.open(server\\vol\\temp\\image.jpg) size = im.size i = 0 whitePixCount = 0 while i in range(size[1]): j = 0 while j in range(size[0]): p1 = im.getpixel((j,i)) if p1 == (255, 255, 255): whitePixCount = whitePixCount + 1 if whitePixCount = 492804: ## ((image dimensions 1404 x 1404) / 4) 25% return image no good j = j + 1 i = i + 1 print whitePixCount return image is good print check_whitespace() Poppy [EMAIL PROTECTED] wrote in message news:... I need to write a program to examine images (JPG) and determine how much area is whitespace. We need to throw a returned image out if too much of it is whitespace from the dataset we're working with. I've been examining the Python Image Library and can not determine if it offers the needed functionality. Does anyone have suggestions of other image libraries I should be looking at it, or if PIL can do what I need? -- http://mail.python.org/mailman/listinfo/python-list
Re: Disabling raw string to print newlines
On May 19, 4:01 pm, Paul McGuire [EMAIL PROTECTED] wrote: On May 19, 4:54 am, [EMAIL PROTECTED] wrote: Hello, *** import urllib2 import re import string import sys url = http://www.macgyver.com/; request = urllib2.Request(url) opener = urllib2.build_opener() html = opener.open(request).read() match = re.compile(PRE(.+)/PRE, re.DOTALL) out = match.findall(html) print out ** This worked like a charm! :) I used Python about a year ago and I have forgotten some of its properties. Thanks to both of you! -kuratkull I would like to print out string with formatting, but as I read, the string is made into a raw string when using re. How could I disable or bypass this? I googled for an hour and couldn't find a solution. Thank you in advance. Change your print statement to: print out[0] -- Paul -- http://mail.python.org/mailman/listinfo/python-list
ANN: Urwid 0.9.8.2 - Console UI Library
Announcing Urwid 0.9.8.2 Urwid home page: http://excess.org/urwid/ Tarball: http://excess.org/urwid/urwid-0.9.8.2.tar.gz RSS: http://excess.org/feeds/tag/urwid/ About this release: === This is a maintenance release that fixes a number of bugs that have been found in 0.9.8.1. New in this release: * Fixed incompatibilities with Python 2.3 * Fixed Pile cursor pref_col bug, WidgetWrap rows caching bug, Button mouse_event with no callback bug, Filler body bug triggered by the tutorial and a LineBox lline parameter typo. About Urwid === Urwid is a console UI library for Python. It features fluid interface resizing, UTF-8 support, multiple text layouts, simple attribute markup, powerful scrolling list boxes and flexible interface design. Urwid is released under the GNU LGPL. -- http://mail.python.org/mailman/listinfo/python-list
scope of optional arguments
If I call print walk([1,2,3], []) print walk([5,6,7]) I get [1, 2, 3] [4, 5, 6] but when I call print walk([1,2,3]) print walk([5,6,7]) I get [1, 2, 3] [1, 2, 3, 4, 5, 6] at stdout, where def walk(seq, result = []): for item in seq: result.append(item) return result Does that mean that the scope of optional arguments is global if they aren't used and local if they are (or am I missing something here)? Regards, CS -- http://mail.python.org/mailman/listinfo/python-list
Re: scope of optional arguments
http://www.ferg.org/projects/python_gotchas.html#contents_item_6 On Mon, May 19, 2008 at 10:30 AM, cseja [EMAIL PROTECTED] wrote: If I call print walk([1,2,3], []) print walk([5,6,7]) I get [1, 2, 3] [4, 5, 6] but when I call print walk([1,2,3]) print walk([5,6,7]) I get [1, 2, 3] [1, 2, 3, 4, 5, 6] at stdout, where def walk(seq, result = []): for item in seq: result.append(item) return result Does that mean that the scope of optional arguments is global if they aren't used and local if they are (or am I missing something here)? Regards, CS -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: scope of optional arguments
Whoops, I meant to call print walk([1,2,3], []) print walk([4,5,6]) and print walk([1,2,3]) print walk([4,5,6]) with def walk(seq, result = []): for item in seq: result.append(item) return result The question is still the same: Why do both calls give different results? Thank you very much for reading, I'm sorry for the inconvenience. -- http://mail.python.org/mailman/listinfo/python-list
Re: scope of optional arguments
Thank you very much for your fast and usefull response, Steven. Have a nice day. -- http://mail.python.org/mailman/listinfo/python-list
Re: is there a bug in urlunparse/urlunsplit
In article [EMAIL PROTECTED], Alex [EMAIL PROTECTED] wrote: Hi all. Is there a bug in the urlunparse/urlunsplit functions? Look at this fragment (I know is quite silly): urlunparse(urlparse('www.example.org','http')) --- 'http:///www.example.org' ^ There are too many slashes, isn't it? Is it a known bug or maybe I missed something... Hi Alex, For a few years now I've been using Fourthought's libraries for parsing URLs and they've performed beautifully. In the code comments, they state that urlparse() and friends exhibit some non-RFCish behavior, hence the inspiration for writing their own libraries. If I remember correctly, the file you want is uri.py and it is in 4Suite which you can download from here: http://www.fourthought.com/ HTH -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more -- http://mail.python.org/mailman/listinfo/python-list
Re: installing MySQLdb module
Hi Rafael, I googled around and people say you need the -dev package of mysql in order to have the C headers...where can you download this for mac os? PS I am running XAMPP (http://www.keitr.com/tutorials/xampp) if that changes anything Ok, here my solution to the problem (Mac OS X 10.4, Xampp and MySQLdb) 1) install Xcode from apple (for gcc, need free account for that, http://developer.apple.com/) 2) get Mac binary tar from MySQL (http://dev.mysql.com/downloads/mysql/ 5.0.html#macosx) 3) edit site.cfg (mysql_config = /Applications/xampp/xamppfiles/bin/ mysql_config) 4) copy include dir from MySQL package to /Applications/xampp/ xamppfiles/include/mysql I bet downloading the same version from MySQL as installed from Xampp could help. And yes, you only need the include folder from the MySQL binary package, do not install it. Peace, Zaphot -- http://mail.python.org/mailman/listinfo/python-list
Running commands on cisco routers using python
Is it possible to run specific commands on cisco router using Python? I have to run command show access-list on few hundred cisco routers and get the dump into a file. Please let me know if it is feasible and the best way to achieve this. Thanks, SPJ -- http://mail.python.org/mailman/listinfo/python-list
Re: TPCServer and xdrlib
On May 19, 10:28 am, Laszlo Nagy [EMAIL PROTECTED] wrote: I don't think that it is important. But if you are interested: - yes, the server will probably be I/O bound, not CPU bound - I'm have experience with thread programming, but not with twisted That part was just to show you that being multithreaded is not really a requirement. The server could be single-threaded, for example. Surely, if you are comfortable with writing a threaded server, there's no problem with that. No. Image binary data - base64encode - XML - gzip - looks very silly. It cannot be efficient. Do you have better ideas? BTW I do not care about the Okay, that would be silly. The questions above considered that you would be sending typical unserialized objects that would be serialized to XML, not pre-serialized binary data. use it. The server is different: it must be safe against external attacks. Maybe it was my bad English? Sorry for the misunderstanding. In general I That part was a joke. You didn't have to answer that. :-P I cannot predict acceptable speed requirements, but I can tell that there will be some clients downloading 100MB report files from the server, so I presume that I will need a progress bar. I think that I need to develop my own protocol for this, and probably the underlying Okay, so you need to wrap large binary files in some kind of message, without pre processing them. I think developing your own protocol using XDR is a safe bet. layer should use binary representation. Before I start re-inventing the wheel: If you are worried about not reinventing the wheel, there are a couple of solutions I can think of. None of them seem to fully support you security and session management requirements, so you should estimate the required project/development time for them. - You may create a standard web application for that (with Django ?). Binary transfers simply use HTTP and have trivial overhead. You have to implement security and session management (cookies ?) on top of that. - Subclass BaseHTTPServer to implement a stateful and secure protocol. Again, binary transfers have trivial overhead. - If the goal of the project is to provide versioned file support, you could use a dpkg/apt (or RPM?) based installation system (it uses HTTP and FTP for file transfers). Write trivial front-ends in the client and the server and choose a secure HTTP server. - Finally, if you want to create your own protocol, but don't want to use XDR, you could to a similar thing using MIME based messages (the first message part is a XML message that references the binary attachments). It is NOT the best way. Just to tell one example: big endian / little endian integers. Definitely I need some encoding. Huh ? XDR does exactly that. (But if you are right and this is the best way, why would you avoid?) I would avoid packing/unpacking objects by hand. -- http://mail.python.org/mailman/listinfo/python-list
Newbie: Keep TCP socket open
Hi Folks, I am newbie to Python, but have successfully created a simple client and server setup, I have one issue though. I am trying to test a box by sending many TCP conns (WHILE loop) but not closing them with a FIN/RST. However, no matter what i do, i cannot get the loop to stop sending FIN from the client. Any clues? Here is my current script #!/usr/bin/python import socket,sys from numpy import * num1=0 while (num1=10) : s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(10.0) s.connect((10.1.1.69, 50008)) # SMTP print s.recv(1024) + '\n', num1=num1+1 #s.close() sys.exit(1) -- http://mail.python.org/mailman/listinfo/python-list
Re: Running commands on cisco routers using python
On May 19, 10:18 am, SPJ [EMAIL PROTECTED] wrote: Is it possible to run specific commands on cisco router using Python? I have to run command show access-list on few hundred cisco routers and get the dump into a file. Please let me know if it is feasible and the best way to achieve this. Thanks, SPJ I think it depends on how you're connecting to the routers. Theoretically, you should be able to use Python's socket or ssh modules to connect to them, send commands and capture the output. Just experiment with one or two routers until you get it. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: Keep TCP socket open
On May 19, 10:25 am, Alan Wright [EMAIL PROTECTED] wrote: Hi Folks, I am newbie to Python, but have successfully created a simple client and server setup, I have one issue though. I am trying to test a box by sending many TCP conns (WHILE loop) but not closing them with a FIN/RST. However, no matter what i do, i cannot get the loop to stop sending FIN from the client. Any clues? Here is my current script #!/usr/bin/python import socket,sys from numpy import * num1=0 while (num1=10) : s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(10.0) s.connect((10.1.1.69, 50008)) # SMTP print s.recv(1024) + '\n', num1=num1+1 #s.close() sys.exit(1) socket.socket instances do an implicit close() on the socket when the object is destructed (in this case, it's destructed when it is garbage- collected). What's happening is that on each iteration, the variable s, which references the socket.socket instance, is assigned to a new socket.socket instance, therefore the instance of the previous iteration is no longer referenced by s, and since it's no longer referenced by anything, the instance is garbage-collected, automatically imposing an implicit close() on that instance. A simple solution could be to create a list and append the socket.socket instance of each iteration to that list, that way the instances would remain referenced in the list and not be garbage-collected; though you might be able to find a more elegant solution. Sebastian -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for programming algorithms
On May 19, 6:52 am, Bruno Desthuilliers bruno. [EMAIL PROTECTED] wrote: Henrique Dante de Almeida a écrit : On May 17, 7:32 pm, Vicent Giner [EMAIL PROTECTED] wrote: Hello. (snip) However, it is usually said that Python is not a compiled but interpreted programming language —I mean, it is not like C, in that sense. (snip) I guess that python is not a good language for that. (snip) My opinion: choose compiled or byte compiled languages. Slightly OT (ie : not talking about computation-heavy alorgithm being better implemented in C then wrapped in Python - this seems quite obvious) but just a couple facts: 1/ being interpreted or compiled (for whatever definition of these terms) is not a property of a language, but a property of an implementation of a language. 2/ actually, all known Python implementations compile to byte-code. Yes, I was actually referring to statically typed JIT-compiled languages. Sorry about that, blame the beers that entered my digestive system that night. :-P -- http://mail.python.org/mailman/listinfo/python-list
[no subject]
Hi there, I'm trying to install PyGreSQL for python 2.4. the installation seems to be done correctly, but when I try to import the pgdb module I got the message: import pgdb Traceback (most recent call last): File pyshell#2, line 1, in -toplevel- import pgdb File C:\Python24\Lib\site-packages\pgdb.py, line 69, in -toplevel- from _pg import * ImportError: DLL load failed: The specified module could not be found. I googled around and I found that the problem could be the libpq.dll file. Then I copied the libpq.dll to the windows directory as well as in the Python dll's directory but the problem is still there. Please, could someone help me to solve this problem? Thank you in advance! Ervin.-- http://mail.python.org/mailman/listinfo/python-list
Re: explain this function to me, lambda confusion
Paul McGuire [EMAIL PROTECTED] writes: [...] lambda is handy in defining parse actions in pyparsing. Parse actions are callbacks to be run when an expression within a larger grammar is matched. A common use for parse actions is to do some sort of text or type conversion. The simplest parse actions are called using the list of matched tokens. Here is a subexpression that will convert numeric strings found in a larger grammar to ints: integer = Word(0123456789).setParseAction(lambda tokens: int(tokens[0]) ) Could you use it as a decoratore instead? integer = Word(0123456789) @integer.setParseAction def parse_integer(tokens): return int(tokens[0]) I could make your grammar clearer, because you don't mix it with processing code... and no need for lambdas! -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for programming algorithms
On May 19, 7:03 am, Bruno Desthuilliers bruno. [EMAIL PROTECTED] wrote: Vicent Giner a écrit : Hello. I am new to Python. It seems a very interesting language to me. Its simplicity is very attractive. However, it is usually said that Python is not a compiled but interpreted programming language cf my answer to you and Henrique on this. I am working on my PhD Thesis, which is about Operations Research, heuristic algorithms, etc., and I am considering the possibility of programming all my algorithms in Python. The usual alternative is C, but I like Python more. Then use it. The main drawbacks I see to using Python are these: * As far as I understand, the fact that Python is not a compiled language makes it slower than C, when performing huge amounts of computations within an algorithm or program. In which way is this a problem here ? I thought your thesis was about algorithm, not about implementation optimisation ? And if it's the later, then even C might sometimes be too high level - you should drop to assembly language. * I don't know how likely it is to find libraries in Python related to my research field. I can't tell but you'd be surprised by the quantity of available Python libs. * I know Python is a serious and mature programming language, of course. But I do not know if it is seen as just funny in a research context. Is Python considered as a good programming language for implementing Operations Research algorithms, such as heuristics and other soft-computing algorithms? Don't know if this answers your question, but it seems that at least some authors consider it a good choice:http://www.oreilly.com/catalog/9780596529321/ All code examples in this books are in Python - very badly written Python, alas... Maybe this is not the right forum, but maybe you can give me some hints or tips... Hem... Obviously, most people here will have a little biased, you know ?-) I agree with what most people here said, that the language doesn't really matter, etc., but that simply does not apply to the specific case of optimization research. The little I know about optimization, even trivial problems may be hairy problems. Naïve implementations simply don't finish and the performance bottlenecks are not necessarily in the numeric computation algorithms (so numpy doesn't help much here). If the guy is doing research on that, it possible that he will work with thousands (or millions) of weird constraints. I'm pretty sure about that: when the algorithms take 4 hours to test a single execution, you value processor time. The situation would be simpler if there were good well-known toolkits for optimization in python (like numpy for matrix operations), but that's not the case. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for programming algorithms
Vicent Giner wrote: Hello. I am new to Python. It seems a very interesting language to me. Its simplicity is very attractive. However, it is usually said that Python is not a compiled but interpreted programming language —I mean, it is not like C, in that sense. ... I programmed several large optimization problems in python. Mostly I used the old numeric extension for the optimization parts eg vector calculations matrix inversions etc etc, but I think numpy is used now. Since most of the work was performed in the C extension we didn't really notice the 'slowness' of python's interpreter. -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: Dbase / foxpro files
Johny wrote: Thanks for your reply.Is it possible to delete a record by using the module? Thanks L -- http://mail.python.org/mailman/listinfo/python-list It is possible with mine. To clarify an earlier post, my module is for dBase III and VFP 6.0 files only (those were the only two I needed :). Hope this helps. -- Ethan -- http://mail.python.org/mailman/listinfo/python-list
Re: PyGreSQL installation
On Mon, 19 May 2008 18:00:30 +0200 [EMAIL PROTECTED] wrote: Hi there, I'm trying to install PyGreSQL for python 2.4. I assume that you got the installer from http://www.PyGreSQL.org/. If so, please join the PyGreSQL list (see above URL) and explain the problem there. It's my module but I don't create the Windows package. Others on that list can probably help you better or create a fixed installer if that is the problem. I googled around and I found that the problem could be the libpq.dll file. Then I copied the libpq.dll to the windows directory as well as in the Python dll's directory but the problem is still there. It's a guess but perhaps you need to properly install the PostgreSQL client rather than copying files piecemeal. -- D'Arcy J.M. Cain [EMAIL PROTECTED] | Democracy is three wolves http://www.druid.net/darcy/| and a sheep voting on +1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner. -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread killing - I know I know!
[EMAIL PROTECTED] wrote: On May 16, 11:40 am, Roger Heathcote [EMAIL PROTECTED] wrote:snip Despite many peoples insistence that allowing for the arbitrary killing of threads is a cardinal sin and although I have no particular threading problem to crack right now I remain interest in the taboo that is thread killing. The real world and it's data are messy and imperfect and I can snip In general, use processes when you can and threads only when you must. OS designers spent a lot of energy implementing protected memory, no sense throwing out a fair chunk of that hard work unless you actually need to. Fair point, but for sub processes that need to be in close contact with the original app, or very small functions that you'd like 100s or 1000s of it seems like a kludge having to spawn whole new processes build in socket communications and kill via explicit OS calls. I can't see that approach scaling particularly well but I guess there's no choice. Does anyone think it likely that the threading module (and threading in general) will be improved and augmented with features like timeouts and arbitrary threadicide in the next year or two? Seems there's little scope for tapping the power of the current generation of multiple cores with the current pythons, tho I appreciate breakneck speed has never been a design objective it looks like multicore is set to be the next generation PC architecture. Roger Heathcote - technicalbloke.com -- http://mail.python.org/mailman/listinfo/python-list
Re: addendum Re: working with images (PIL ?)
I would still be concerned that you are checking against the percentage of the 768 bins returned by the histogram method. Two pixels of widely different colour end up in the same bin, so long as just ONE of the Red, Green, or Blue components is equal. So, for example, colours (2, 27, 200) and (200, 27, 2) are both in the bin for G=27. But they are very different colours. There are actualy 256 * 256 * 256 colours, but I don't suppose you want that many bins! What you want is a much smaller number of bins, with pixels of 'close' colours (whatever that means) put into the same bin. What 'close' means for colours, is quite a difficult thing, and the consensus is that using the three RGB coordinates is not as good as certain other colour spaces. You could use the ImageOps.posterize method to reduce the number of colours in the image, but whether 'close' colours end up together, I don't know. You might try the PIL special interest group (SIG) 'image-sig' http://mail.python.org/mailman/listinfo/image-sig (If you want to know exactly how many unique colours an image actually has, load the image into the 'GIMP' assuming you have it, and go to : Menubar -- Filters -- Colours -- Colourcube analysis... ) Poppy wrote: Thanks, since posting I figured out how to interpret the histogram results, which seems to be the consensus in responses. I wrote a check image program and have been periodically calling it against a folder where I make a copy of our images used for production. My method right now is to check what we send for errors, but is not preventive. Also I determined whitespace is not the only issue, any color that dominates. I'm considering rewriting this code below to setup bins, so if combined neighboring colors exceeds the threshold then reject the image. I have examples where half the image appears black, but actually varies throughout. Since my image is RGB I'm looping through a 768 element list. Zach- import Image, os def check_image(file): try: im = Image.open(file) except: return Can't open file %s % file imData = im.histogram() i = 0 for ea in imData: if ea ((im.size[0] * im.size[1]) / 4): ## 25% of image size return bad image %s - %s element num is %s % (file, ea, str(i)) i = i + 1 return good image %s, image size is %s % (file, im.size) def main(dir): data = try: files = os.listdir(dir) for ea in files: data = data + str(check_image(os.path.join(dir,ea))) + \n except: return Can't get files in %s % dir return data print main(host\\path\\to\\image_folder\\) -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread killing - I know I know!
On Mon, May 19, 2008 at 11:36 AM, Roger Heathcote [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: On May 16, 11:40 am, Roger Heathcote [EMAIL PROTECTED] wrote:snip Despite many peoples insistence that allowing for the arbitrary killing of threads is a cardinal sin and although I have no particular threading problem to crack right now I remain interest in the taboo that is thread killing. The real world and it's data are messy and imperfect and I can snip In general, use processes when you can and threads only when you must. OS designers spent a lot of energy implementing protected memory, no sense throwing out a fair chunk of that hard work unless you actually need to. Fair point, but for sub processes that need to be in close contact with the original app, or very small functions that you'd like 100s or 1000s of it seems like a kludge having to spawn whole new processes build in socket communications and kill via explicit OS calls. I can't see that approach scaling particularly well but I guess there's no choice. It's not a kludge - the whole reason why killing a thread is undefined and a cardinal sin is because it's in your own address space and you can't guarantee anything about how it left things when you killed it. You simply can't have it both ways. If you want to be able to safely and sanely kill an uncooperative thread (*especially* third party code you don't control) you have to isolate it from your address space, and this means a process. This is a fundamental problem with the entire idea of shared-state concurrency. For the record, you can't use 1000s of threads either - if you really need 1000s of concurrent things running you need to re-think your concurrency model and possibly your choice of languages and environment. The messiness of the real world is *why* you should use processes, not a reason to avoid them. Does anyone think it likely that the threading module (and threading in general) will be improved and augmented with features like timeouts and arbitrary threadicide in the next year or two? Seems there's little scope for tapping the power of the current generation of multiple cores with the current pythons, tho I appreciate breakneck speed has never been a design objective it looks like multicore is set to be the next generation PC architecture. They absolutely should not be. Adding an API which can't work in the general case and is dangerous even when it can work does not do anyone any favors. Roger Heathcote - technicalbloke.com -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Using StringVars in List of Dictionaries as tkInter variables for Scale and Label widgets
I'm trying to build an unknown number of repeating gui elements dynamically so I need to store the variables in a list of dictionaries. I understand that Scale variable name needs to be a StringVar but I cannot figure out how to initialize the dictionary. I've tried the following code ps = PowerSupply() # Instantiate a Power Supply VM Object numOPs = ps.getOnum() # Find the number of outputs OPValues = [] # Global list to hold one dictionary per output for c in range(numOPs): OPValues.append({ }) ps.initOPValues(c, OPValues[c]) ps.initOPValues is defined as follows: def initOPValues(self, OPname, dname): OPDefaults = { 'Vval' : 0, 'Ival' : 0, 'Otemp' : 0 } dname = dict((d,StringVar()) for d in OPDefaults) for d in OPDefaults: dname[d].set(OPDefaults[d]) I get the following error: Traceback (most recent call last): File C:\Code\gui\tkinter.py, line 165, in module ps.initOPValues(c, OPValues[c]) File C:\Code\gui\tkinter.py, line 47, i initOPValues dname = dict((d,StringVar()) for d in OPDefaults) File C:\Code\gui\tkinter.py, line 47, in genexpr dname = dict((d,StringVar()) for d in OPDefaults) File C:\Python25\lib\lib-tk\Tkinter.py, line 254, in __init__ Variable.__init__(self, master, value, name) File C:\Python25\lib\lib-tk\Tkinter.py, line 185, in __init__ self._tk = master.tk AttributeError: 'NoneType' object has no attribute 'tk' Exception exceptions.AttributeError: StringVar instance has no attribute '_tk' in bound method StringVar.__del__ of Tkinter.StringVar instance at 0x00B7D468 ignored Any help is appreciated! Thanks, Kevin -- http://mail.python.org/mailman/listinfo/python-list
Re: python script to windows exe
On Mon, 19 May 2008 02:59:22 -0700 (PDT), sandeep [EMAIL PROTECTED] wrote: hi the py code that i have written is here.when i run this code i wont get any errors it just works fine for me.but when i created the exe i start getting an error in my 'getMailContent' function. The error description is TypeError:unsupported operand type(s) for :- 'instance' and 'int' Are you and py2exe using the same version of Python? (Make something in the exe that displays sys.version...) i dont know why i am start getting this error when i run it through the exe. import win32com,win32com.client import os,os.path import codecs import zipfile [EMAIL PROTECTED]:::Sandeep Kumar Sharma #outlook application refrence outlook_app=0 #outlook ids to access different folders look into msdn for more info. not a preffered way as i am hardcoding data here OlDefaultFolders={'olFolderCalendar':9,'olFolderConflicts': 19,'olFolderContacts':10,'olFolderDeletedItems':3,'olFolderDrafts': 16,'olFolderInbox':6,'olFolderJournal':11,'olFolderJunk': 23,'olFolderLocalFailures':21,'olFolderNotes':12,'olFolderOutbox': 4,'olFolderSentMail':5,'olFolderServerFailures': 22,'olFolderSyncIssues':20,'olFolderTasks': 13,'olPublicFoldersAllPublicFolders':18} #outlook types to save mailItem look into msdn for more info #although doesnot work for me :-( OlSaveAsType={'olTXT': 0,'olRTF':1,'olTemplate': 2,'olMSG': 3,'olDoc': 4,'olHTML':5,'olVCard': 6,'olVCal':7,'olICal': 8}; #refrence to content in inbox inbox_obj=0 #function which will initialise outlook and return its reference def getAppRef(): temp=win32com.client.Dispatch(OutLook.Application) return temp.GetNamespace(MAPI) #function to return the folders in the outlook def getOutLookFolders(a,b=OlDefaultFolders['olFolderInbox']): return a.GetDefaultFolder(b) #function to get email content def getMailContent(obj): txt_file=codecs.open('data.html',encoding='utf-8',mode='w') for kk in range(len(obj.Items),1,-1): #for kk in range(len(obj.Items-1),0,-1): #print 'hello' print 'writting file='+str(kk) mailItem=obj.Items[kk] writeData(mailItem,txt_file) #print mailItem.OlSaveAsType.olMSG #saveCopy(mailItem) #print sender=+mailItem.SenderName+' SenderEmailId='+str(mailItem.SenderEmailAddress)+' Time='+str(mailItem.ReceivedTime) #print 'Subject='+mailItem.Subject+' size='+str(mailItem.Size) txt_file.close() ''' file_zip=zipfile.ZipFile(txt_file,w,zipfile.ZIP_DEFLATED) file_zip.write('data.log') file_zip.close() ''' #function to create a directory #obviously not a best way :-( but i think can expected this sort of mistakes from beginners def createDir(): path=os.path.abspath(\email) if(os.path.exists(path)): print Directory already exists else: os.system(md +path) #function to save a copy of email def writeData(mailItem,file): data=p sender='h4SenderName/ h4'+checkStringType(mailItem.SenderName) time='brh4Time/ h4'+checkStringType(str(mailItem.ReceivedTime)) attachment='brh5Attachments Count/ h5'+str(len(mailItem.Attachments)) edata='h4Email Content/h4'+checkStringType(mailItem.Body)+/ phr/ dataToWrite=data+sender+time+attachment+edata getAttachmentInfo(mailItem.Attachments) file.write(getHTMLString(dataToWrite)) #checkStringType(dataToWrite) def getAttachmentInfo(atmts): for kk in range(1,len(atmts)): atmt=atmts[kk] #print File Name=+atmt.FileName+' DisplayName='+atmt.DisplayName+' PathName='+atmt.PathName+' ' abc=os.path.isdir(os.getcwd()+'\email') if(abc==True): print 'directory exists' else: os.mkdir(os.getcwd()+'\email') path=os.path.abspath(os.getcwd()+'\email') atmt.SaveAsFile(path+\\+atmt.DisplayName) # function to check whether the character encoding is ascii or smthing else def checkStringType(a): if isinstance(a,str): b='not a unicode string' else: a.encode('utf-8') #print 'unicode type' return a #function to save the coopy of an email #:-( but smhow it generate error whenever i make a call to it def saveCopy(mailItem): name=\\+mailItem.Subject+__+str(mailItem.ReceivedTime) print name #global outlook_app try: mailItem.SaveAs(path+name+.txt,OlSaveAsType['olTXT']) except BaseException: print BaseException def getHTMLString(b): a='htmlheadtitleYour Email Data log is here/title/ headbody'+b+'/body/html' return a #main entrance to the program def main(): global outlook_app,inbox_obj outlook_app=getAppRef() #print outlook_app.OlSaveAsType.olMSG print '==' print dir(outlook_app) print '==' inbox_obj=getOutLookFolders(outlook_app) print dir(inbox_obj) print (inbox_obj.Items) #saveCopy(inbox_obj.Items[1]) getMailContent(inbox_obj) main() my setup file has this code from
Python and Plone Boot Camps in Chapel Hill, NC
Triangle (NC) Zope and Python Users Group (TriZPUG) is proud to open registration for our fourth annual ultra-low cost Plone and Python training camps, BootCampArama 2008: http://trizpug.org/boot-camp/2008/ Registration is now open for: PyCamp: Python Boot Camp, August 4 - 8 Plone Boot Camp: Customizing Plone, July 28 - August 1 Advanced Plone Boot Camp: Plone 3 Techniques, August 4 - 8 All of these take place on the campus of the University of North Carolina at Chapel Hill in state of the art high tech classrooms, with free mass transit, low-cost accommodations with free wireless, and convenient dining options. Plone Boot Camp is taught by Joel Burton, twice chair of the Plone Foundation. Joel has logged more the 200 days at the head of Plone classrooms on four continents. See plonebootcamps.com for dozens of testimonials from Joel's students. PyCamp is taught by Chris Calloway, facilitator for TriZPUG and application analyst for the Southeast Coastal Ocean Observing System. Chris has developed PyCamp for over 1500 hours on behalf of Python user groups. Early bird registration runs through June 30. So register today! PyCamp is TriZPUG's Python Boot Camp, which takes a programmer familiar with basic programming concepts to the status of Python developer with one week of training. If you have previous scripting or programming experience and want to step into Python programming as quickly and painlessly as possible, this boot camp is for you. PyCamp is also the perfect follow-on to Plone Boot Camp: Customizing Plone the previous week. At Plone Boot Camp: Customizing Plone you will learn the essentials you need to build your Plone site and deploy it. This course is the most popular in the Plone world--for a good reason: it teaches you practical skills in a friendly, hands-on format. This bootcamp is aimed at: * people with HTML or web design experience * people with some or no Python experience * people with some or no Zope/Plone experience It covers using Plone, customizing, and deploying Plone sites. At Advanced Plone Boot Camp: Plone 3 Techniques you will learn to build a site using the best practices of Plone 3 as well as advance your skills in scripting and developing for Plone. The course covers the new technologies in Plone 3.0 and 3.1 intended for site integrators and developers: our new portlet infrastructure, viewlets, versioning, and a friendly introduction to Zope 3 component architecture. Now, updated for Plone 3.1! The course is intended for people who have experience with the basics of Plone site development and HTML/CSS. It will cover what you need to know to take advantage of these new technologies in Plone 3. For more information contact: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for programming algorithms
Thank you very much for all the answers I've got. As far as I have understood, Python can be a good alternative, or, at least, a reasonable choice. I intend to design new algorithms for a kind of Optimization problems, and then I have to implement them and show/prove that they are good enough, in terms of effectiveness (quality of the solution that the algorithm is able to find, for some given difficult problems), and not mainly in terms of efficiency (time to find the solution). I mean, in order to prove that my algorithms are good, I have to compare them with the results given by other algorithms, in terms of how much better is the solution given by my proposal, in front of the previous ones. Only comparatives in terms of number of iterations, and not time to find the solution, can be done (I think). And I also realize, from your posted answers, that the point is doing a good programming work, and that I will have to look very carefully at all those packages and resources you have mentioned, to do a good work at Python. Any other suggestion will be welcomed.:-) Thank you very much again! -- Vicent -- http://mail.python.org/mailman/listinfo/python-list
Re: How do *you* use Python in non-GUI work?
Hey all. Just thought I'd ask a general question for my own interest. Every time I think of something I might do in Python, it usually involves creating a GUI interface, so I was wondering what kind of work you all do with Python that does *not* involve any GUI work. This could be any little scripts you write for your own benefit, or what you do at work, if you feel like talking about that! :) web apps, command line utilities, and of course libraries. Wow, really? I would have never guessed that anyone is doing command line utilities and libraries as examples of projects that don't need a GUI. Just kidding :) Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for programming algorithms
On May 19, 6:11 pm, Henrique Dante de Almeida [EMAIL PROTECTED] wrote: On May 19, 7:03 am, Bruno Desthuilliers bruno. I'm pretty sure about that: when the algorithms take 4 hours to test a single execution, you value processor time. Yes, of course, but that should mean that I have to do it better, in the programming step (I would have to re-program or re-implement my algorithm). And I think the problem would be the same in any other language, wouldn't it? The situation would be simpler if there were good well-known toolkits for optimization in python (like numpy for matrix operations), but that's not the case. Are there such toolkits in other languages? I am not sure they exist in C, for example. By the way, is it possible (and easy) to call a C function from a Python program?? -- http://mail.python.org/mailman/listinfo/python-list
Re: Using StringVars in List of Dictionaries as tkInter variables for Scale and Label widgets
seanacais wrote: I'm trying to build an unknown number of repeating gui elements dynamically so I need to store the variables in a list of dictionaries. I understand that Scale variable name needs to be a StringVar but I cannot figure out how to initialize the dictionary. I've tried the following code ps = PowerSupply()# Instantiate a Power Supply VM Object numOPs = ps.getOnum() # Find the number of outputs OPValues = [] # Global list to hold one dictionary per output for c in range(numOPs): OPValues.append({ }) ps.initOPValues(c, OPValues[c]) ps.initOPValues is defined as follows: def initOPValues(self, OPname, dname): OPDefaults = { 'Vval' : 0, 'Ival' : 0, 'Otemp' : 0 } dname = dict((d,StringVar()) for d in OPDefaults) for d in OPDefaults: dname[d].set(OPDefaults[d]) I get the following error: Traceback (most recent call last): File C:\Code\gui\tkinter.py, line 165, in module ps.initOPValues(c, OPValues[c]) File C:\Code\gui\tkinter.py, line 47, i initOPValues dname = dict((d,StringVar()) for d in OPDefaults) File C:\Code\gui\tkinter.py, line 47, in genexpr dname = dict((d,StringVar()) for d in OPDefaults) File C:\Python25\lib\lib-tk\Tkinter.py, line 254, in __init__ Variable.__init__(self, master, value, name) File C:\Python25\lib\lib-tk\Tkinter.py, line 185, in __init__ self._tk = master.tk AttributeError: 'NoneType' object has no attribute 'tk' Exception exceptions.AttributeError: StringVar instance has no attribute '_tk' in bound method StringVar.__del__ of Tkinter.StringVar instance at 0x00B7D468 ignored Any help is appreciated! There's some magic going on behind the scene which means that you have to create a Tkinter.Tk instance before you can start churning out StringVars: import Tkinter as tk v = tk.StringVar() Traceback (most recent call last): File stdin, line 1, in module File /usr/lib/python2.5/lib-tk/Tkinter.py, line 257, in __init__ Variable.__init__(self, master, value, name) File /usr/lib/python2.5/lib-tk/Tkinter.py, line 188, in __init__ self._tk = master.tk AttributeError: 'NoneType' object has no attribute 'tk' root = tk.Tk() v = tk.StringVar() v.set(42) v.get() '42' Peter -- http://mail.python.org/mailman/listinfo/python-list
sre_parse.py - over-view or explanation needed
What does sre_parse.py (Secret Labs' Regular Expression Engine) do? I see this referred to in some errors when i call the source() function (e.g. source(findFile(scripts,thisonehere.py)) ) The error then refers to name ImportWarning not defined?? (--that might be a proprietary warning, as I am running another app on top of Python (not really relevant)). I am curious how the sre_parse.py module gets involved when neither the name or the file has any regular expression or special parse rules in it So I guess the first step is understanding sre_parse.py itself. Can someone help me on that? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: TPCServer and xdrlib
Laszlo Nagy wrote: It is possible to change the serialization used by Pyro http://pyro.sourceforge.net/manual/9-security.html#pickle to the the 'gnosis' XML Pickler. As I said earlier, I would not use XML. Just an example - I need to be able to transfer image files, word and excel documents. How silly it would be to base64encode a binary file, then put it into an XML. L Fair enough. In that case, here's 5 suggestions: - use simple file copying from a mounted network drive - use http (web server) - use ftp - use scp - use rsync Why wouldn't one of these work for you? Did I miss something in your original requirements? All of the above high level protocols are very efficient in concurrently transferring files from a server to multiple clients. --irmen -- http://mail.python.org/mailman/listinfo/python-list
Thread output with ncurses
Hey everyone, I currently have three independent applications that all 'do something' and output to the console when events are triggered. I'd like to combine these all into a single ncurses application. The idea would be that the application simply has three 'windows' or 'pads' and each thread would output to their respective one. What is the best way to go about this? Would I want to use a pad or window? Is this common functionality that is already implemented? (ie scrolling textbox that is easily written to like the console is). Any help or tips would be appreciated. Thanks! -Blaine -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie: Keep TCP socket open
Alan Wright wrote: while (num1=10) : s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(10.0) s.connect((10.1.1.69, 50008)) # SMTP print s.recv(1024) + '\n', num1=num1+1 #s.close() sys.exit(1) I think the following is happening: Reusing the 's' object for every new socket will make Python to garbage collect the previous ones. Garbage collecting a socket will likely close() it. Also after creating all sockets your program exits. I guess either Python or the operating system itself will go close all the sockets. Try putting every new socket you make into a big list instead, so that Python can't garbage collect it. And put your program to sleep at the end. import time allsockets=[] while (...): s=socket.socket(... allsockets.append(s) s.settimeout(... ... time.sleep(9) --irmen -- http://mail.python.org/mailman/listinfo/python-list
Re: How do *you* use Python in non-GUI work?
On Sun, May 18, 2008 at 6:20 PM, John Salerno [EMAIL PROTECTED] wrote: Hey all. Just thought I'd ask a general question for my own interest. Every time I think of something I might do in Python, it usually involves creating a GUI interface, so I was wondering what kind of work you all do with Python that does *not* involve any GUI work. This could be any little scripts you write for your own benefit, or what you do at work, if you feel like talking about that! :) Thanks. -- http://mail.python.org/mailman/listinfo/python-list I write a lot of job control and process monitoring scripts in Linux. Stuff that forks and execs processes, and then monitors procfs and sysfs to collect periodic data. I actually wouldn't mind doing a GUI for it, but pretty much all of the data display I need from it I can do by taking the data files and running them through gnuplot. (That, and I'm too lazy to figure out how to rewrite my telemetry plotter from Java to Python.) I guess I also write some data conversion programs, mostly the sort of thing where I have a bunch of data that I didn't think far enough in advance how I needed to be able to display it, so I just write something to convert it to where I need it. Incidentally, I used to do that all in Java too, until other people in my research group started making fun of me for it and also for not really knowing a scripting language. -- http://mail.python.org/mailman/listinfo/python-list
Re: ftplib returns EOFError
On Mon, 19 May 2008 13:27:23 +0100, Jon Bowlas wrote: Hi All, I've written a little method to connect to an ftpserver which works well, however when I send a file using this ftp connection oddly I _sometimes_ get returned an EOFError from ftplib.getline even though my file is actually transferred. Here's my script: def uploadViaFtp(self, file, filename): '''A method to upload a file via ftp''' ftpserverloc = self.getItunesUftpServer() ftpserverusername = self.getItunesUftpUser() ftpserverpassword = self.getItunesUftpPsswd() ftp = ftplib.FTP(ftpserverloc) ftp.login(ftpserverusername, ftpserverpassword) try: ftp.storbinary(STOR + filename, file, 1024) finally: file.close() ftp.quit() And here's the traceback: Traceback (innermost last): Module ZPublisher.Publish, line 114, in publish Module ZPublisher.mapply, line 88, in mapply Module ZPublisher.Publish, line 40, in call_object Module Products.FileSystemSite.FSPythonScript, line 108, in __call__ Module Shared.DC.Scripts.Bindings, line 311, in __call__ Module Shared.DC.Scripts.Bindings, line 348, in _bindAndExec Module Products.FileSystemSite.FSPythonScript, line 164, in _exec Module None, line 28, in upload_submit - FSPythonScript at /silva/service_views/UCLItunesUPodcast/edit/Asset/UCLItunesUTrack/upload_sub mit - Line 28 Module Products.UCLItunesUPodcast.UCLItunesUService, line 138, in uploadViaFtp Module ftplib, line 523, in quit Module ftplib, line 246, in voidcmd Module ftplib, line 221, in voidresp Module ftplib, line 207, in getresp Module ftplib, line 193, in getmultiline Module ftplib, line 183, in getline EOFError Any help in catching and ignoring this error would be greatly appreciated. Regards Jon ftp.quit() attempts to send a quit command and wait for the response before closing. Apparently, sometime the connection is already closed (don't know why) and you get the exception. I guess you could do something like this: try: ftp.quit() except EOFError: ftp.close() Ciao - FB -- http://mail.python.org/mailman/listinfo/python-list