ANN: pywinauto 3.6 released
Hi, 0.3.6 release of pywinauto is now available. pywinauto is an open-source (LGPL) package for using Python as a GUI automation 'driver' for Windows NT based Operating Systems (NT/W2K/XP). SourceForge project page: http://sourceforge.net/projects/pywinauto Download from SourceForge http://sourceforge.net/project/showfiles.php?group_id=157379 Here is the list of changes from 0.3.5: 0.3.6 Scrolling and Treview Item Clicking added -- 28-July-2006 * Added parameter to ``_treeview_item.Rectangle()`` to have an option to get the Text rectangle of the item. And defaulted to this. * Added ``_treeview_item.Click()`` method to make it easy to click on tree view items. * Fixed a bug in ``TreeView.GetItem()`` that was expanding items when it shouldn't. * Added ``HwndWrapper.Scroll()`` method to allow scrolling. This is a very minimal implementation - and if the scrollbars are implemented as separate controls (rather then a property of a control - this will probably not work for you!). It works for Notepad and Paint - that is all I have tried so far. * Added a call to ``HwndWrapper.SetFocus()`` in ``_perform_click_input()`` so that calls to ``HwndWrapper.ClickInput()`` will make sure to click on the correct window. Thanks Mark Mark Mc Mahon Manchester, NH 03110, USA PA HREF=http://sourceforge.net/projects/pywinauto;pywinauto 0.3.6/A Simple Windows GUI automation with Python. (28-Jul-06) -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Skeletonz: The pythonic CMS system
Hi everyone I am very glad to announce a pythonic content management system (CMS) called Skeletonz. Say goodbye to tedius backend administration and say hello to insite dynamic editing of your site! The system is a CMS refreshment - - it represents a whole new way of editing! Say goodbye to bloatness also. Skeletonz is dynamic, very fast and dead simple to use. The system has been in development for around 9 months. Current version is 1.0 beta. Its alrady used on production websites. The features: * Administration is insite - this is done by Ajax and DOM hackery. * Simple and intuitive edit syntax. * Full blown plugin system. Currently there are around 14 plugins that can do a lot of useful things. * Simple admin section where you can add users, groups, alter permissions or create/restore backups. * Super perfomance. Around 600 req. pr. sec. can be served by Skeletonz internal Python webserver. Depends on the hardware of course. * Simple template system that's based on Cheetah. * Super clean Python code that follows the MVC pattern. Browse it here http://orangoo.com/skeletonz_dev/browser and see for yourself. * Plus a lot more... Some sites that use Skeletonz: * http://orangoo.com/labs/ * http://aspuru.chem.harvard.edu/ * http://birc.au.dk/ * http://www.chloecello.net/ The system is open-source and released under the GPL. Skeletonz is copyrighted by Bioinformatics Research Center, University of Aarhus. Check out the Skeletonz site for more information: http://orangoo.com/skeletonz/ For a demo, check out: http://orangoo.com/skeletonz_demo/ I hope you give Skeletonz a chance. Kind regards 4mir Salihefendic (http://amix.dk/ - [EMAIL PROTECTED]) -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Wing IDE 2.1.1 released
We're happy to announce the release of Wing IDE version 2.1.1, an advanced development environment for the Python programming language. This is a bugfix release, fixing several editor, subprocess, and startup bugs. The release can be downloaded from: http://wingware.com/downloads A complete list of changes is available here: http://wingware.com/pub/wingide/2.1.1/CHANGELOG.txt Wing IDE provides powerful debugging, editing, code intelligence, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Highlights of 2.1.x releases include: * Visual Studio, VI/Vim, and Brief key bindings * Subversion and Perforce support (+) * Redesigned and improved search tools * Named bookmarks (+) * Breakpoint manager (+) and call stack as list (+) These are available in Wing IDE Pro only This release is available for Windows (2000+), Linux, and Mac OS X (10.3+ with X11 installed) and can be compiled from sources on *BSD, Solaris, and other Posix operating systems. For more information see: Product Info: http://wingware.com/products Sales: http://wingware.com/store/purchase Sincerely, The Wingware Team -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: How do you implement this Python idiom in C++
Pierre Barbier de Reuille wrote: [EMAIL PROTECTED] wrote: Pierre Barbier de Reuille wrote: [...] I thank you for your response. The equivalent of your solution is posted hereunder: class cA(object): count=0 def __init__(self): self.__class__.count +=1 @classmethod def getcount(cls): return cls.count def __del__(self): self.__class__.count -=1 class cB(cA): count=0 def __init__(self): super(cB,self).__init__() for klass in self.__class__.__bases__: klass.count +=1 a=cA() ; b=cA(); c= cA() d=cB() ; e=cB(); f= cB() a.a=1;b.a=1;c.a=1;d.a=1;e.a=1;f.a=1 g=cA() g.a=1 print '#cA=',cA.getcount() # 7 print '#cB=',cB.getcount() # 3 del g print '#cA=',cA.getcount() # 6 print '#cB=',cB.getcount() # 3 There is nothing impossible in Python ;-) Alain Well, nothing is impossible, but it is now much much more complex ! As a proof of that, your version does not work completely :P (try deleting d for example). I add a working version, but you will also notice that I have to *explicitly* walk over all the classes of the hierarchy, testing for the one who have a count attribute, hoping that this attribute is indeed for counting the number of objects and not anything else ... so the solution is quite fragile and very slow. class cA(object): count=0 def __init__(self): self.__class__.count +=1 for klass in self.__class__.__bases__: if hasattr( klass, count ): klass.count += 1 @classmethod def getcount(cls): return cls.count def __del__(self): self.__class__.count -=1 for klass in self.__class__.__bases__: if hasattr( klass, count ): klass.count -= 1 class cB(cA): count=0 a=cA() ; b=cA(); c= cA() d=cB() ; e=cB(); f= cB() a.a=1;b.a=1;c.a=1;d.a=1;e.a=1;f.a=1 g=cA() g.a=1 print '#cA=',cA.getcount() # 7 print '#cB=',cB.getcount() # 3 del g del d print '#cA=',cA.getcount() # 5 print '#cB=',cB.getcount() # 2 Pierre Good point Pierre. But you'll have to admit that the class usage in Python is much simpler (just derive from the class) class cB(cA): count=0 contrarily to the C++ usage where you must remind the compiler of the Counted class in every derived class. In Python, you have to bite only once thru the sour apple Alain -- http://mail.python.org/mailman/listinfo/python-list
import a user created python file as module
Hi, I have the following directory structure in my project. Base: file1.py file2.py Directory1: file1-dir1.py I am able to import file1 into file2.py What I need to do is, import file1 in the file file1-dir1.py. I did not create the entire dir structure as package. Adding __init__.py file in both Base: as well as Directory1: is not helpful. I am unable to import file1 in the file1-dir1.py. It is not able to find the path of the file1.py. How and what should I do to import file1.py into file1-dir1.py ? Please give me some references to the tutorial topic which I can study as well. Thanks, Senthil -- http://mail.python.org/mailman/listinfo/python-list
Re: BCD List to HEX List
Philippe Martin [EMAIL PROTECTED] writes: Why are you avoiding naming the chip and its compiler? I must disagree on that one: There are many threads on this site where people just have fun talking algorithm. I'm not an algo. expert and I know there are many here. This is just like the very common situation here and on sci.crypt, where a person has a programming or algorithm question and gets asked what the application is, and when they answer, it turns out that what they need is not anything like what they thought they needed. on one device, the processor in an 8-bit arm and the X-compiler is made by epson on the other device, the processor is unknown to me and the environment is a subset of java made for smartcards called javacard. You mean ARM?? There is no such thing as an 8-bit ARM; they are 32-bit cpu's that (in some models) support a 16-bit instruction format. Javacard is an interpreter that runs in many 8-bit processors. The interpreter supports 32-bit arithmetic. -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested function scope problem (- variable definition branch)
Gerhard Fiedler [EMAIL PROTECTED] wrote: 8- | I'm not sure where you're trying to go. I think that most people (and even | Bruno, who argued this issue most strongly) call Python variables | variables every now and then, or maybe even usually. But it was helpful | for me to see the difference between Python variables and, say, C | variables. I think this has been a useful discussion in this respect. There | is a difference, and it is important (IMO). | | Whether Python variables are in fact variables probably depends mostly on | your definition of variable, and that's IMO a tough one -- a definition | of variable that includes all those language elements that various | languages call variables, and nothing else (that's the tough part). | Whether that definition exists, and whether it includes Python variables, | remains to be seen :) I am not one for formal definitions but I think something like this: if s is a python string containing hello world and I can write : s = s + some extra stuff then for me s is a variable - the fact that in the python implementation there are two things, namely the original hello world string and the new longer one is kind of irrelevant - if I try to print s I will get the new longer string, so from where I stand s is a variable - it has changed over time from having one value to another one... and that is about the simplest definition you can get - its a symbolic reference to something that can change over time - and in python it seems to me that every name is a variable, cos you can tie the name to very different things at different times: s = hello world print s hello world s = s + some more stuff print s hello world some more stuff s = [1,2,3,4,5,6,7,8,9,0] print s [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] def foo(): print banana s = foo s function foo at 0x011DDE30 s() banana s is surely a variable - there is nothing constant over time about it, and from this point of view its very mutable indeed - and what is more - in every case, after the assignment, unless you have stored a reference with a different name to them, the old values look from a programmer's point of view as if they have been overwritten - you can't use anything about s to get at them again... Now there's a thought - an optional slice notation that slices s over time, so that s{0} is the current s, and s{-1} the previous one, and so on, with the default being s[{0}] the {0} being optional This should be relatively easy to implement at the point of re binding the name by replacing the pointer (or whatever) to the object with a stack of them. I think you could only do it in python, but I may be wrong... Another world first for python? - (TIC) Look mommy! - I only use one variable name! - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: import a user created python file as module
On 30 Jul 2006 23:07:07 -0700, Phoe6 [EMAIL PROTECTED] wrote: Hi, I have the following directory structure in my project. Base: file1.py file2.py Directory1: file1-dir1.py I am able to import file1 into file2.py What I need to do is, import file1 in the file file1-dir1.py. I did not create the entire dir structure as package. Adding __init__.py file in both Base: as well as Directory1: is not helpful. I am unable to import file1 in the file1-dir1.py. It is not able to find the path of the file1.py. How and what should I do to import file1.py into file1-dir1.py ? Please give me some references to the tutorial topic which I can study as well. Modify the path where python searches for modules, for example in file1-dir1.py add: import sys sys.path.append(/path/to/Base) import file1 cheers, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: Html character entity conversion
John Machin wrote: Claudio Grondi wrote: [EMAIL PROTECTED] wrote: Claudio Grondi wrote: [EMAIL PROTECTED] wrote: Here is my script: from mechanize import * from BeautifulSoup import * import StringIO b = Browser() f = b.open(http://www.translate.ru/text.asp?lang=ru;) b.select_form(nr=0) b[source] = hello python html = b.submit().get_data() soup = BeautifulSoup(html) print soup.find(span, id = r_text).string OUTPUT: #1087;#1088;#1080;#1074;#1077;#1090; #1087;#1080;#1090;#1086;#1085; -- In russian it looks like: привет питон How can I translate this using standard Python libraries?? -- Pak Andrei, http://paxoblog.blogspot.com, icq://97449800 Translate to what and with what purpose? Assuming your intention is to get a Python Unicode string, what about: strHTML = '#1087;#1088;#1080;#1074;#1077;#1090; #1087;#1080;#1090;#1086;#1085;' strUnicodeHexCode = strHTML.replace('#','\u').replace(';','') strUnicode = eval(u'%s'%strUnicodeHexCode) ? I am sure, there is a more elegant and direct solution, but just wanted to provide here some quick response. Claudio Grondi Thank you, Claudio. Really interest solution, but it doesn't work... In [19]: strHTML = '#1087;#1088;#1080;#1074;#1077;#1090; #1087;#1080;#1090;#1086;#1085;' In [20]: strUnicodeHexCode = strHTML.replace('#','\u').replace(';','') In [21]: strUnicode = eval(u'%s'%strUnicodeHexCode) In [22]: print strUnicode --- exceptions.UnicodeEncodeErrorTraceback (most recent call last) C:\Documents and Settings\dron\ipython console C:\usr\lib\encodings\cp866.py in encode(self, input, errors) 16 def encode(self,input,errors='strict'): 17 --- 18 return codecs.charmap_encode(input,errors,encoding_map) 19 20 def decode(self,input,errors='strict'): UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-5: character maps to undefined In [23]: print strUnicode.encode(utf-8) сВЗсВИсВАсБ┤сБ╖сВР сВЗсВАсВРсВЖсВЕ -- it's not my string привет питон In [24]: strUnicode.encode(utf-8) Out[24]: '\xe1\x82\x87\xe1\x82\x88\xe1\x82\x80\xe1\x81\xb4\xe1\x81\xb7\xe1\x82\x90 \xe1\x82\x87\xe1\x82\x80\xe1\x82\x90\xe1\x82\x86\xe1\x82\ x85' -- and too many chars Have you considered, that the HTML page specifies charset=windows-1251 in its meta http-equiv=Content-Type content=text/html; charset=windows-1251 tag ? You are apparently on Linux or so, so I can't track this problem down having only a Windows box here, but inbetween I know that there is another problem with it: I have erronously assumed, that the numbers in #1087; are hexadecimal, but they are decimal, so it is necessary to do hex(int('1087')) on them to get at the right code to put into eval(). As you know now the idea I hope you will succeed as I did with: lstIntUnicodeDecimalCode = strHTML.replace('#','').split(';') lstIntUnicodeDecimalCode ['1087', '1088', '1080', '1074', '1077', '1090', ' 1087', '1080', '1090', '1086', '1085', ''] lstIntUnicodeDecimalCode = lstIntUnicodeDecimalCode[:-1] lstHexUnicode = [ hex(int(item)) for item in lstIntUnicodeDecimalCode] lstHexUnicode ['0x43f', '0x440', '0x438', '0x432', '0x435', '0x442', '0x43f', '0x438', '0x442', '0x43e', '0x43d'] eval( 'u%s'%''.join(lstHexUnicode).replace('0x','\u0' ) ) u'\u043f\u0440\u0438\u0432\u0435\u0442\u043f\u0438\u0442\u043e\u043d' strUnicode = eval( 'u%s'%''.join(lstHexUnicode).replace('0x','\u0' ) ) print strUnicode приветпитон Sorry for that mess not taking the space into consideration, but I think you can get the idea anyway. I hope he *doesn't* get that idea. # strHTML = '#1087;#1088;#1080;#1074;#1077;#1090;#1087;#1080;#1090;# 1086;#1085;' # strUnicode = [unichr(int(x)) for x in strHTML.replace('#','').split(';') if x] # strUnicode [u'\u043f', u'\u0440', u'\u0438', u'\u0432', u'\u0435', u'\u0442', u'\u043f', u' \u0438', u'\u0442', u'\u043e', u'\u043d'] # Knowing about the built-in function unichr() is a good thing, but ... there are still drawbacks, because (not tested!) e.g. : '100x hallo Python' translates to '100x #1087;#1088;#1080;#1074;#1077;#1090; #1055;#1080;#1090;#1086;#1085;' and can't be handled by improving the core idea by usage of unichr() instead of the eval() stuff because of the wrong approach with using .replace() and .split() which work only on the given example but not in general case. I am just too lazy to sit down and work on code extracting from the HTML the #; sequences to convert only them letting the other content of the string unchanged in order to arrive at a solution that works in general case (it should be not hard and I suppose the OP has it already :-) if he is at a Python skill level of playing around with the mechanize module). I am still convinced, that there must be a more elegant and direct solution, so the subject is still fully open for improvements towards the actual final goal. I
Re: import a user created python file as module
How and what should I do to import file1.py into file1-dir1.py ? Please give me some references to the tutorial topic which I can study as well. And some reference: http://docs.python.org/tut/node8.html Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: non-blocking PIPE read on Windows
Hi !If you don't want to use MS-specific things, you can use the normal pipes.See this code. If you want to use non-blocking version, you need to create a thread that handle the reads/writes. import os, sys, time, binascii, cPicklebpath,bname=os.path.split(sys.argv[0])def Log(Msg,IsMaster,First=False): fn=sys.argv[0]+'.'+['c','m'][int(IsMaster)]+'.log' mode='aw'[int(First)] f=open(fn,mode) f.write('\n%s:\n'%time.time()) f.write('%s\n'%Msg) f.flush() f.close()def ReadTextPacket(SourceStream): packet=SourceStream.read(6) psize=int(packet) packet=SourceStream.read (psize) return packetdef WriteTextPacket(DestStream,Packet): Packet=str(Packet) DestStream.write('%06d'%len(Packet)) DestStream.write(Packet) DestStream.flush()'''def ReadBinPacket(SourceStream): txtpacket=ReadTextPacket(SourceStream) pckpacket=binascii.unhexlify(txtpacket) obj=cPickle.loads(pckpacket) return objdef WriteBinPacket(DestStream,Obj): pckpacket=cPickle.dumps (Obj) txtpacket=binascii.hexlify(pckpacket) WriteTextPacket(DestStream,txtpacket)'''if 'C' in sys.argv: #Log('Client started',0,1) while 1: #Log('Waiting for packet',0,0) data=""> #Log('Packet received',0,0) #Log('The packet is: %s'%([data]),0,0) #Log('Print the result',0,0) WriteTextPacket(sys.stdout,Master wrote: %s%([data])) if data.strip()=='quit': #Log('Quit packet received',0,0) break #Log('Client finished',0,0)else: #Log('Master started',1,1) #Log('Start subprocess',1,0) import time st=time.time() child_stdin,child_stdout=os.popen2(r'c:\python24\python.exe %s C'%(bname)) for i in range(1000): #Log('Send packet',1,0) WriteTextPacket(child_stdin,['Alma'*100,i]) #Log('Waiting for packet',1,0) s=ReadTextPacket(child_stdout) #Log('Packet is: %s'%([s]),1,0) #Log('Print packet',1,0) #print Client's answer,[s] import time time.sleep(0.1) #Log('Send packet',1,0) WriteTextPacket(child_stdin,'quit') #Log('Waiting for packet',1,0) s=ReadTextPacket(child_stdout) #Log('Packet is: %s'%([s]),1,0) #Log('Print packet',1,0) #print Client's answer,[s] #Log('Master finished',1,0) print time.time()-stdd2006/7/28, Dennis Lee Bieber [EMAIL PROTECTED]:On 27 Jul 2006 22:26:25 -0700, placid [EMAIL PROTECTED] declaimed thefollowing in comp.lang.python: readline() blocks until the newline character is read, but when i use read(X) where X is a number of bytes then it doesnt block(expected functionality) but i dont know how many bytes the line will be and its not constant so i cant use this too. Any ideas of solving this problem?Use a thread that reads one character at a time; when it sees whatever signals end of line (it sounds like you're reading a progressbar implemented via croverwrite). Combine the characters into astring, return the string to the main program via a queue. If there is no such end of line character, but there IS anoticeable delay between writes, a more complex method might suffice-- in which one thread does the byte reads, setting a time value on each read; a related thread then does a sleep() loop, checking the last readtime against the pause length -- if close enough to the pause duration,combine and return...Alternatively, take a good old style terminal keyboard (a VT100 Tempest-rated model should be ideal), and use it to beat Bill Gates overthe head until he agrees to push a high-priority upgrade to the commandline I/O system... or makes files work with select() (so you can combine the time-out with the byte read)--WulfraedDennis Lee Bieber KD6MOG[EMAIL PROTECTED] [EMAIL PROTECTED]HTTP://wlfraed.home.netcom.com/(Bestiaria Support Staff: [EMAIL PROTECTED] )HTTP://www.bestiaria.com/--http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Small problem with print and comma
Dustan wrote: Dennis Lee Bieber wrote: for i in range(0,len(param)): print a[i], for it in param: print it, That's one way. However, if you need the position (this is for future reference; you don't need the position number here): for i in range(len(param)+1): print a[i], The last position was excluded because you forgot the '+1' part, creating an off-by-one bug. No, your code creates that bug. However, the above is not very pythonic - if param is a iterator and not a sequence-protocol-adherent object, it fails. The usual way to do it is for i, a in enumerate(param): print a, Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Need a compelling argument to use Django instead of Rails
Paul Boddie wrote: Ben Sizer wrote: Even C++ comes with OpenGL in the standard library. Which standard library? Sorry, it was a long day, and I used entirely the wrong term here. By that, I meant typically shipped with each compiler. I've never had to even install a development library to use OpenGL, whether under Win32 or Linux. It's just a typical part of the distribution. [Web-SIG standardisation] And I always thought that WSGI was solving the wrong problem. It certainly didn't go very far towards meeting the expressed goals of the Web-SIG. Oh well. http://mail.python.org/pipermail/web-sig/2004-August/000650.html There are some remarks just after that message about the SIG charter needing to change or having become irrelevant, but in fact the need for standard functionality is as relevant today as ever. At a slightly higher level, everyone would now prefer that you buy into their total full stack solution, perhaps with the exception of the Paste developers whose selection of packages either suggest a problem of internal framework proliferation or one of a lack of coherency in presenting a suitable solution to the casual inquirer. Yeah. On the server side I think there's been a sad lack of attention to the large middle ground that lies between simple CGI scripting and full stack solutions. In fact, I'd guess that the majority of web sites fall into that middle ground, just perhaps not the most interesting or financially lucrative ones. Examples might be things like the various PHP forums, or web-based non-real-time games. These applications are complex enough to deserve a decent implementation language such as Python, yet simple and small enough that most users won't want to set up dedicated hardware for the purpose. I think there's definitely scope in the standard library to go well beyond the current cgi module and the piecemeal offerings in other modules, without needing to provide another integrated web stack. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Re: Need a compelling argument to use Django instead of Rails
Sybren Stuvel wrote: Ben Sizer enlightened us with: PyGame was barely maintained for a year, and is based on SDL which was also barely maintained for a year, and which hasn't kept up with hardware advances at all. Still, ID Software and Epic both use SDL + OpenGL for their games. Why is it good for them but insufficient for you? Because id and Epic have many millions of dollars and better developers to throw at the problem than I do. :) To put it another way, they have lots of in-house middleware that is built on top of those technologies to make them more effective. SDL and OpenGL is the bottom of the stack for them. We mere mortals often prefer to start with something a little higher level. :) -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Newbie help - test for data type
Hi Listers, I have a requirement to test for a data type could someone tell me if this is possible in python? Basically I have a ZPT in Zope that users can select checkboxes in a form which pass arguments for a python function, however if there is only one checkbox selected it is passed as a string whereas more than one checkbox is passed as a list. Therefore if my function is required to perform an action based on each argument passed in the list the function works correctly but if it is passed as a string nothing happens. This is my function: selecteddeptcodes = context.REQUEST.DEPTCODE currentstatus = context.REQUEST.STATUS if currentstatus == 'pending': for dptcd in selecteddeptcodes: context.changetolive(DEPTCODE=dptcd) if currentstatus == 'old': for dptcd in selecteddeptcodes: context.changetopending(DEPTCODE=dptcd) return context.pub_dept_form(context, context.REQUEST, message='Updated Status') The argument in question is selecteddeptcodes. I tried to make my function conditional based on the length of the argument passed but if its just one checkbox value passed the length of the argument is 2 (which is the number of chars passed in the string) and if there are two checkboxes the length of the argument (which is the number of items in the list) is also 2. So that doesnt help. Any assistance would be appreciated. Jon -- http://mail.python.org/mailman/listinfo/python-list
Re: Need a compelling argument to use Django instead of Rails
Terry Reedy wrote: Ben Sizer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] PyGame was barely maintained for a year, and is based on SDL which was also barely maintained for a year, and which hasn't kept up with hardware advances at all. I believe there is a recent release of SDL, but which what advances I do not know. Pygame is being actively worked on by more than one person. The recent release of SDL was another minimal one, though there is an intention to make the important changes 'soon'. As for PyGame, it's good that development there has picked up again but I'd love to see it broaden its horizons beyond SDL. Maybe that is impractical, however. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Re: XML parsing and writing
c00i90wn wrote: Hey, I'm having a problem with the xml.dom.minidom package, I want to generate a simple xml for storing configuration variables, for that purpose I've written the following code, but before pasting it I'll tell you what my problem is. On first write of the xml everything goes as it should but on subsequent writes it starts to add more and more unneeded newlines to it making it hard to read and ugly. Maybe you should try to get your code a little cleaner first, that usually helps in finding these kinds of bugs. Try rewriting it with ElementTree or lxml, that usually helps you in getting your work done. http://effbot.org/zone/element-index.htm http://codespeak.net/lxml/ Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows vs. Linux
I am not a programming expert but I use python everyday on Windows XP: * python standard distribution (CPython) * iPython * cygwin for the command line interaction, add a unix/linux flavour to the blend EuGeNe -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie help - test for data type
Jonathan Bowlas wrote: Hi Listers, I have a requirement to test for a data type could someone tell me if this is possible in python? Basically I have a ZPT in Zope that users can select checkboxes in a form which pass arguments for a python function, however if there is only one checkbox selected it is passed as a string whereas more than one checkbox is passed as a list. Fantastic. If there are 0 checkboxes selected, does it return None? The built-in function isinstance() will help. if it is None: shouldbe = [] elif isinstance(it, str): shouldbe = [it] elif isinstance(it, list): shouldbe = it else: raise WTFError(repr(type(it)) Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie help - test for data type
Jonathan Bowlas wrote: Hi Listers, I have a requirement to test for a data type could someone tell me if this is possible in python? Basically I have a ZPT in Zope that users can select checkboxes in a form which pass arguments for a python function, however if there is only one checkbox selected it is passed as a string whereas more than one checkbox is passed as a list. Therefore if my function is required to perform an action based on each argument passed in the list the function works correctly but if it is passed as a string nothing happens. You need the isinstance() function. For example you can use isinstance(selecteddeptcodes, list) to test if your variable is a list. If you want to test the other way round use isinstance(selecteddeptcodes, str) if your variable is a string, isinstance(selecteddeptcodes, unicode) if it's a unicode string or isinstance(selecteddeptcodes, basestring) to test if it's a string or unicode string. Read more about this function and the types to test for in http://docs.python.org/lib/built-in-funcs.html. If you already have the code for a list argument I'd check if it's not a list and then turn it into a list: if not isintance(selecteddeptcodes, list): selecteddeptcodes = [selecteddeptcodes] Bye, Dennis -- http://mail.python.org/mailman/listinfo/python-list
Re: Has anyone used davlib by Greg Stein?
Has anyone worked with this? Is it any good? I'll take the palpable silence as a no then. :-) Thank's anyway! /Joel -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie help - test for data type
Thanks for everyones help, much appreciated, Ill check out the isinstance function. Jon -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Dennis Benzinger Sent: 31 July 2006 10:20 To: python-list@python.org Subject: Re: Newbie help - test for data type Jonathan Bowlas wrote: Hi Listers, I have a requirement to test for a data type could someone tell me if this is possible in python? Basically I have a ZPT in Zope that users can select checkboxes in a form which pass arguments for a python function, however if there is only one checkbox selected it is passed as a string whereas more than one checkbox is passed as a list. Therefore if my function is required to perform an action based on each argument passed in the list the function works correctly but if it is passed as a string nothing happens. You need the isinstance() function. For example you can use isinstance(selecteddeptcodes, list) to test if your variable is a list. If you want to test the other way round use isinstance(selecteddeptcodes, str) if your variable is a string, isinstance(selecteddeptcodes, unicode) if it's a unicode string or isinstance(selecteddeptcodes, basestring) to test if it's a string or unicode string. Read more about this function and the types to test for in http://docs.python.org/lib/built-in-funcs.html. If you already have the code for a list argument I'd check if it's not a list and then turn it into a list: if not isintance(selecteddeptcodes, list): selecteddeptcodes = [selecteddeptcodes] Bye, Dennis -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie help - test for data type
This is my function: selecteddeptcodes = context.REQUEST.DEPTCODE currentstatus = context.REQUEST.STATUS if currentstatus == 'pending': for dptcd in selecteddeptcodes: context.changetolive(DEPTCODE=dptcd) if currentstatus == 'old': for dptcd in selecteddeptcodes: context.changetopending(DEPTCODE=dptcd) return context.pub_dept_form(context, context.REQUEST, message='Updated Status') The argument in question is selecteddeptcodes. You can use isinstance or function like that: def list_from_string(s): ... try: ... s + '' ... return [s] ... except: ... return s and then: def f(selecteddeptcodes): ... if selecteddeptcodes is None: return ... selecteddeptcodes = list_from_string(selecteddeptcodes) ... for dptcd in selecteddeptcodes: print dptcd ... f(['aaa', 'bbb']) aaa bbb f(['aaa']) aaa f('aaa') aaa f(None) Regards, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: [OT]Newbie help - test for data type
Jonathan Bowlas wrote: Hi Listers, I have a requirement to test for a data type could someone tell me if this is possible in python? Basically I have a ZPT in Zope that users can select checkboxes in a form which pass arguments for a python function, however if there is only one checkbox selected it is passed as a string whereas more than one checkbox is passed as a list. You should have posted this on Zope's mailing-list. OT There's a mechanism in Zope to handle this case, cf section Passing Parameters to Scripts in: http://www.zope.org/Documentation/Books/ZopeBook/2_6Edition/DTML.stx/ScriptingZope.stx The mechanism is based on 'decorating' forms fields names with type annotation. In you case, this would look like: form name='xxx' action='yyy' method='POST' tal:repeat repeat=code deptcodes input type=checkbox name='selecteddeptcodes:list' value='' tal:attribute=value code / /tal:repeat !-- rest of the form here -- /form /OT HTH -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie help - test for data type
John Machin wrote: Jonathan Bowlas wrote: Hi Listers, I have a requirement to test for a data type could someone tell me if this is possible in python? Basically I have a ZPT in Zope that users can select checkboxes in a form which pass arguments for a python function, however if there is only one checkbox selected it is passed as a string whereas more than one checkbox is passed as a list. Fantastic. If there are 0 checkboxes selected, does it return None? If no checkbox is selected, then the control is not successful and it's name should not appear in the request. This is defined in the html spec (sections 17.2 and 17.13.2 of html 4.01 spec). -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie help - test for data type
Dennis Benzinger wrote: Jonathan Bowlas wrote: Hi Listers, I have a requirement to test for a data type could someone tell me if this is possible in python? Basically I have a ZPT in Zope that users can select checkboxes in a form which pass arguments for a python function, however if there is only one checkbox selected it is passed as a string whereas more than one checkbox is passed as a list. Therefore if my function is required to perform an action based on each argument passed in the list the function works correctly but if it is passed as a string nothing happens. You need the isinstance() function. Not in Zope. -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie help - test for data type
Rob Wolfe wrote: This is my function: selecteddeptcodes = context.REQUEST.DEPTCODE currentstatus = context.REQUEST.STATUS if currentstatus == 'pending': for dptcd in selecteddeptcodes: context.changetolive(DEPTCODE=dptcd) if currentstatus == 'old': for dptcd in selecteddeptcodes: context.changetopending(DEPTCODE=dptcd) return context.pub_dept_form(context, context.REQUEST, message='Updated Status') The argument in question is selecteddeptcodes. You can use isinstance or function like that: Zope has a better solution builtin. -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re:Newbie help - test for data type
Thanks Bruno, Ill use this. Much appreciated. Jon -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Bruno Desthuilliers Sent: 31 July 2006 10:37 To: python-list@python.org Subject: Re: [OT]Newbie help - test for data type Jonathan Bowlas wrote: Hi Listers, I have a requirement to test for a data type could someone tell me if this is possible in python? Basically I have a ZPT in Zope that users can select checkboxes in a form which pass arguments for a python function, however if there is only one checkbox selected it is passed as a string whereas more than one checkbox is passed as a list. You should have posted this on Zope's mailing-list. OT There's a mechanism in Zope to handle this case, cf section Passing Parameters to Scripts in: http://www.zope.org/Documentation/Books/ZopeBook/2_6Edition/DTML.stx/ScriptingZope.stx The mechanism is based on 'decorating' forms fields names with type annotation. In you case, this would look like: form name='xxx' action='' method='POST' tal:repeat repeat=code deptcodes input type=checkbox name='selecteddeptcodes:list' value='' tal:attribute=value code / /tal:repeat !-- rest of the form here -- /form /OT HTH -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: how to stop python
or if u want explicit exit of program then use: import sys sys.exit(1) or raise SystemExit, 'message' Dan wrote: bruce bedouglas at earthlink.net posted: perl has the concept of die. does python have anything similar. how can a python app be stopped? I see this sort of statement a lot in Perl: open(FH, myfile.txt) or die (Could not open file); I've no idea why you're asking for the Python equivalent to die, but if it's for this sort of case, you don't need it. Usually in Python you don't need to explicitly check for an error. The Python function will raise an exception instead of returning an error code. If you want to handle the error, enclose it in a try/except block. But if you just want the program to abort with an error message so that you don't get silent failure, it will happen automatically if you don't catch the exception. So the equivalent Python example looks something like this: fh = file(myfile.txt) If the file doesn't exist, and you don't catch the exception, you get something like this: $ ./foo.py Traceback (most recent call last): File ./foo.py, line 3, in ? fh = file(myfile.txt) IOError: [Errno 2] No such file or directory: 'myfile.txt' /Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: Fastest Way To Loop Through Every Pixel
Chaos wrote: nikie wrote: Chaos wrote: As my first attempt to loop through every pixel of an image, I used for thisY in range(0, thisHeight): for thisX in range(0, thisWidth): #Actions here for Pixel thisX, thisY But it takes 450-1000 milliseconds I want speeds less than 10 milliseconds Milliseconds don't mean much unless we knew how big your images are and what hardware you're using. Have you considered using NumPy? Assuming you can get the image into a numpy array efficiently, the actual algorithm boils down to something like this: grey = r*0.3 + g*0.59 + b*0.11 index = grey.argmin() x,y = index%step, index/step v = grey[x,y] where r,g,b and grey are numpy.ndarray objects; The arithmetic operators and the argmin-function are implemented in C, so you can expect decent performance. (the 4 lines above take about 80 ms for a 1000x1000 image on my PC) If that's not enough, you might want to use some specially optimized C library for this purpose. (I'd suggest Intel's IPP, but there are others). I really do not understand the code. Where did you get the varibales r, g, b and step and what does v produce? Sorry, I should have commented it better. The idea is that r,g,b are numpy-arrays containig the r, g, b-pixel-values in the image: import numpy, Image img = Image.open(Image1.jpg) r = numpy.array(img.getdata(0)) g = numpy.array(img.getdata(1)) b = numpy.array(img.getdata(2)) w,h = img.size The step is the length of one line of pixels, that is, the offset to a pixel (x,y) is x+y*step. (This is usually called step or stride in literature) step = w Now, I can use numpy's overridden arithmetic operators to do the per-pixel calculations (Note that numpy also overrides sin, cos, max, ..., but you'll have to use from numpy import * to get these overrides in your namespace): grey = r*0.3 + g*0.59 + b*0.11 The multiplication-operator is overridden, so that r*0.3 multiplies each value in the array r with 0.3 and returns the multiplied array, same for g*0.59, b*0.11. Adding the arrays adds them up value by value, and returns the sum array. This generally works quite well and intuitively if you perform only per-pixel operations. If you need a neighborhood, use slicing. The function argmin searches for the index of the minimum value in the array: index = grey.argmin() But since we want coordinates instead of indices, we'll have to transform these back using the step value: x,y = index % step, index / step Result: print x,y,r[index],g[index],b[index] Works for my image. Notes: - I'm _not_ sure if this is the fastest way to get an image into a numpy array. It's convenient, but if you need speed, digging into the numpy docs/newsgroup archive, and doing a few benchmarks for yourself would be a good idea - numpy does have 2d-Arrays, but I'm not that much of a numpy expert to tell you how to use that to get rid of the index/step-calculations. Again, numpy-docs/newsgroup might help - a general advice: using integer multiplications instead for floating-point may help with performance, too. - you said something about 10 ms, so I'm guessing your image doesn't come from a harddrive at all (because reading it alone will usually take longer than 10 ms). Numpy arrays have a C-Interface you might want to use to get data from a framegrabber/digital camera into a numpy array. -- http://mail.python.org/mailman/listinfo/python-list
Re: class variables
Colin J. Williams wrote: Andre Meyer wrote: Hi all I am trying to understand the magic of Python's class variables and tried the following code (see below). Just out of curiosity, I tried to define a property that provides access to a seemingly instancae variable which is in fact a class variable. class Foo(object): _v = 5 @apply def v(): def fget(self): return Foo._v # other solution [1] : # return self.__class__._v def fset(self, val): Foo._v = val # other solution [1] : # self.__class__._v = val return property(**locals()) [1] Depends on how you want this to work when subclassing Foo... Gives : f1 = Foo() f2 = Foo() f1.v 5 f2.v 5 f1.v = 42 f1.v 42 f2.v 42 Foo._v 42 All seems to work fine (case 4), but when a custom object is assigned, an instance variable is created instead of using theproerty (case 5). What goes wrong here? I'm afraid there are too much problems with indentation in the posted code to give any serious answer. (snip) -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
how to safely extract dict values
i have a dict with a particular key - the values for this key will be None, one valid scalar, or a list: {mykey, None} {mykey, foo} {mykey, [bar, baz]} let's ignore the None case - in the case of the one or many values, i want to suck the values into a list. here's one way to do this: if mydict.has_key(mykey): vals=[] _v = mydict[mykey] if isinstance(_v, types.ListType): vals.extend(_v) else: vals.append(_v) # now we can safely iterate through acts for val in vals: . my way is ugly. what's a better way? thanks, dz -- http://mail.python.org/mailman/listinfo/python-list
Re: Nested function scope problem
Antoon Pardon wrote: On 2006-07-29, Gerhard Fiedler [EMAIL PROTECTED] wrote: On 2006-07-29 13:47:37, Antoon Pardon wrote: I think the important thing to remember is that the assignment in Python is a alias maker and not a copy maker. In languages like C, Fortran, pascal, the assignment makes a copy from what is on the righthand and stores that in the variable on the lefthand. In languages like Lisp, Smalltalk and Python, the assignment essentially makes the lefthand an alias for the righthand. Yes, I think I got it now :) It seems that, in essence, Bruno is right in that Python doesn't really have variables. Everything that seems variable doesn't really change; what changes is that an element of what seems to change gets rebound. Aren't you looking too much at implementation details now? The difference between an alias assignment and a storage assigment is for instance totaly irrelevant for immutable objects/values like numbers. # Python a = 42 b = a del a # C int *a, *b; a = malloc(sizeof *a); *a = 42; b = a; free(a); I wouldn't say it's totally irrelevant. -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: how to safely extract dict values
David Zaret [EMAIL PROTECTED] writes: my way is ugly. what's a better way? Untested: for key in mydict: if isinstance(mydict[key], list): vals.extend(mydict[key]) else: vals.append(mydict[key]) -- http://mail.python.org/mailman/listinfo/python-list
Re: how to safely extract dict values
Paul Rubin wrote: David Zaret [EMAIL PROTECTED] writes: my way is ugly. what's a better way? Untested: for key in mydict: if isinstance(mydict[key], list): vals.extend(mydict[key]) else: vals.append(mydict[key]) Too much useless lookup IMHO... vals = [] for k, v in mydict.items(): if isinstance(v, list): vals.extend(v) else: vals.append(v) !-) But this is not that different from what the OP found so ugly... -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: how to safely extract dict values
On 7/31/06, David Zaret [EMAIL PROTECTED] wrote: i have a dict with a particular key - the values for this key will be None, one valid scalar, or a list: {mykey, None} {mykey, foo} {mykey, [bar, baz]} let's ignore the None case - in the case of the one or many values, i want to suck the values into a list. here's one way to do this: if mydict.has_key(mykey): vals=[] _v = mydict[mykey] if isinstance(_v, types.ListType): vals.extend(_v) else: vals.append(_v) # now we can safely iterate through acts for val in vals: . how about: vals = [] for val in mydict.values(): try: vals.extend(val) except: vals.append(val) cheers, amit. -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to safely extract dict values
David Zaret wrote: i have a dict with a particular key - the values for this key will be None, one valid scalar, or a list: {mykey, None} {mykey, foo} {mykey, [bar, baz]} let's ignore the None case - in the case of the one or many values, i want to suck the values into a list. here's one way to do this: if mydict.has_key(mykey): vals=[] _v = mydict[mykey] if isinstance(_v, types.ListType): vals.extend(_v) else: vals.append(_v) # now we can safely iterate through acts for val in vals: . my way is ugly. what's a better way? If you have control over the dict's creation and 'filling', you may want to handle the case there - eventually using a custom dict-like object that stores everything (but None) in lists. The implementation code for this object will not be less ugly than the one above, but at least ugliness will be hidden away !-) Else, you can shorten the code a bit (NB : ignoring the 'None' case...): v = d[k] v = ([v], v)[isinstance(v, list)] And this can be hidden away in a function: def get_as_list(d, k): v = d[k] return ([v], v)[isinstance(v, list)] vals = get_as_list(mydict, mykey) I don't like using isinstance() tests too much, but it depends on the context... HTH -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: how to safely extract dict values
Bruno Desthuilliers [EMAIL PROTECTED] writes: Too much useless lookup IMHO... Actually, you, me, and Amit all mis-read David's original exapmle. What he really wanted was (let's see if I get it right this time): if mykey in mydict: v = mydict[mykey] if not isinstance(v, list): v = [v] for val in v: ... -- http://mail.python.org/mailman/listinfo/python-list
Re: how to safely extract dict values
Amit Khemka wrote: On 7/31/06, David Zaret [EMAIL PROTECTED] wrote: i have a dict with a particular key - the values for this key will be None, one valid scalar, or a list: {mykey, None} {mykey, foo} {mykey, [bar, baz]} let's ignore the None case - in the case of the one or many values, i want to suck the values into a list. here's one way to do this: if mydict.has_key(mykey): vals=[] _v = mydict[mykey] if isinstance(_v, types.ListType): vals.extend(_v) else: vals.append(_v) # now we can safely iterate through acts for val in vals: . how about: vals = [] for val in mydict.values(): try: vals.extend(val) except: vals.append(val) l = [] l.extend((1, 2)) l [1, 2] l.extend('ab') l [1, 2, 'a', 'b'] -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows vs. Linux
Hi, [EMAIL PROTECTED] a écrit : Is Windows an okay enviornment in which to program under Python, or do you recommend that I run a dual-boot of Linux or maybe a VMWare install to program under Python? I'm used to practice windows linux and it makes sense to use python on both because the compatibility is excellent. Take care to use os.sep as the file path separator if you plan to stay compatible. My favorite os is linux, but on windows you have pythonwin which is an excellent python extension with a very good debugger. Also boa works fine on windows but have annoying bugs on linux. Furthermore, python comes with linux (nothing to install) and not with windows (needs python install if you deploy on users pcs). Regards, jm -- http://mail.python.org/mailman/listinfo/python-list
Re: How do you implement this Python idiom in C++
You are heading the wrong way... There are a number of ways to implement this but the easiest I can think of is to use RTTI. To get around with counting sub-objects you can rely on virtual inheritance, which only happens at the top of the inheritance tree. Here is a simple demo: #include iostream #include typeinfo #include map class count { public: typedef std::mapconst std::type_info*, unsigned int counts_t; static counts_t counts; const std::type_info* ti; static unsigned int get_count(const std::type_info c) {return counts[c];} count(const std::type_info c):ti(c){++counts[ti];} ~count(){--counts[ti];} }; count::counts_t count::counts; class c1: virtual private count { public: c1(): count(typeid(c1)){} }; class c2: public c1, virtual private count { public: c2(): count(typeid(c2)){} }; int main() { c1 t1[3]; c2 t2[5]; std::cout count::get_count(typeid(c1)) \n; count::get_count(typeid(c2)) \n; return 0; } -- http://mail.python.org/mailman/listinfo/python-list
Re: how to safely extract dict values
thanks for the many responses. i have zero control over the dict. in practice, i'm using turbogears which is automatically populating the result dict with zero-to-many choices from a generated list of HTML checkboxes. the user can select none, one, or many, and submit. cherrypy packs the **kwargs arg full of the selection, as i described in my op. using a try/exception case to switch between append and extend will not work. the scalar, coming back as a string, can certainly be iterated and i'll end up with a bunch of characters in my list. i like what's posted below - that's more compact - and at least closer to what i was looking for. thanks again, great newsgroup. dz Bruno Desthuilliers wrote: David Zaret wrote: i have a dict with a particular key - the values for this key will be None, one valid scalar, or a list: {mykey, None} {mykey, foo} {mykey, [bar, baz]} let's ignore the None case - in the case of the one or many values, i want to suck the values into a list. here's one way to do this: if mydict.has_key(mykey): vals=[] _v = mydict[mykey] if isinstance(_v, types.ListType): vals.extend(_v) else: vals.append(_v) # now we can safely iterate through acts for val in vals: . my way is ugly. what's a better way? If you have control over the dict's creation and 'filling', you may want to handle the case there - eventually using a custom dict-like object that stores everything (but None) in lists. The implementation code for this object will not be less ugly than the one above, but at least ugliness will be hidden away !-) Else, you can shorten the code a bit (NB : ignoring the 'None' case...): v = d[k] v = ([v], v)[isinstance(v, list)] And this can be hidden away in a function: def get_as_list(d, k): v = d[k] return ([v], v)[isinstance(v, list)] vals = get_as_list(mydict, mykey) I don't like using isinstance() tests too much, but it depends on the context... HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: how to safely extract dict values
Paul Rubin wrote: Bruno Desthuilliers [EMAIL PROTECTED] writes: Too much useless lookup IMHO... Actually, you, me, and Amit all mis-read David's original exapmle. Actually, I plea not guilty - cf my answer to the OP !-) -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: how to safely extract dict values
David Zaret wrote: thanks for the many responses. i have zero control over the dict. in practice, i'm using turbogears which is automatically populating the result dict with zero-to-many choices from a generated list of HTML checkboxes. the user can select none, one, or many, and submit. cherrypy packs the **kwargs arg full of the selection, as i described in my op. Are you sure you get mydict[mykey]==None if the user doesn't check any of the checkboxes ? According to html specs, the form's dataset shouldn't have the key at all in this case. using a try/exception case to switch between append and extend will not work. Nope. the scalar, coming back as a string, can certainly be iterated and i'll end up with a bunch of characters in my list. Yes. i like what's posted below Thanks - and BTW, please, don't top-post... -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows vs. Linux
[EMAIL PROTECTED] wrote: Is Windows an okay enviornment in which to program under Python, or do you recommend that I run a dual-boot of Linux or maybe a VMWare install to program under Python? Python is one of the best languages I've found for platform-independence - significantly better than Perl. Right now I'm coding Python that runs happily under Redhat, Windows /Cygwin and Windows native. It also integrates closely with command line tools like subversion, including piping their output into Python-based XML parsers. This really wouldn't be easy with Perl. Find yourself an editor that's pretty similar under both Unix and Windows. jEdit is a good place to start. You might also like to look at running Cygwin under Windows. It's a Unix-like command shell that provides nearly every command-line Unix tool you could want on a Windows box. Can be a little awkward at times, but it's a huge advantage over raw Windows. I'd never recommend dual-boot for anything! Hardware is cheap, time and trouble is expensive. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to safely extract dict values
oops ! my mistake :-D On 7/31/06, Bruno Desthuilliers [EMAIL PROTECTED] wrote: Amit Khemka wrote: how about: vals = [] for val in mydict.values(): try: vals.extend(val) except: vals.append(val) l = [] l.extend((1, 2)) l [1, 2] l.extend('ab') l [1, 2, 'a', 'b'] Oops, my mistake ... jumped in too quickly ! cheers, -- Amit Khemka -- onyomo.com Home Page: www.cse.iitd.ernet.in/~csd00377 Endless the world's turn, endless the sun's Spinning, Endless the quest; I turn again, back to my own beginning, And here, find rest. -- http://mail.python.org/mailman/listinfo/python-list
to automate an interactive shell
Hi all, I'm a newbie and would like to how python is efficient in automating an interative shell(I have a CLI executable which interatcs with the user). Any starters would be greatly appreciated. Thanks, Murugesh -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows vs. Linux
Andy Dingley a écrit : I'd never recommend dual-boot for anything! Don't agree man, it's good for testing... -- http://mail.python.org/mailman/listinfo/python-list
Re: non-blocking PIPE read on Windows
Hi !A new version with binary data handling. 103 seconds with 1000 data exchange.import os, sys, time, binascii, cPicklebpath,bname=os.path.split(sys.argv[0])def Log(Msg,IsMaster,First=False): fn=sys.argv[0]+'.'+['c','m'][int(IsMaster)]+'.log' mode='aw'[int(First)] f=open(fn,mode) f.write('\n%s:\n'%time.time()) f.write('%s\n'%Msg) f.flush() f.close()def ReadTextPacket(SourceStream): packet=SourceStream.read(6) psize=int(packet) packet=SourceStream.read(psize) return packetdef WriteTextPacket(DestStream,Packet): Packet=str(Packet) DestStream.write('%06d'%len(Packet)) DestStream.write(Packet) DestStream.flush() import base64def PackObj(Obj): pckpacket=cPickle.dumps(Obj) enstr=base64.encodestring(pckpacket) return enstrdef UnpackObj(Packet): pckpacket=base64.decodestring(Packet) obj=cPickle.loads(pckpacket) return obj#s=PackObj([1,None,'A']*10)#print s#print UnpackObj(s)#sys.exit()def ReadBinPacket(SourceStream): txtpacket=ReadTextPacket(SourceStream) obj=UnpackObj(txtpacket) return objdef WriteBinPacket(DestStream,Obj): txtpacket=PackObj(Obj) WriteTextPacket(DestStream,txtpacket) if 'C' in sys.argv: Log('Client started',0,1) try: while 1: #Log('Waiting for packet',0,0) data=""> #Log('Packet received',0,0) #Log('The packet is: %s'%([data]),0,0) #Log('Print the result',0,0) WriteBinPacket(sys.stdout,Master wrote: %s%([data])) if str(data).strip()=='quit': Log('Quit packet received',0,0) break except Exception,E: Log(str(E),0,0) Log('Client finished',0,0)else: Log('Master started',1,1) try: Log('Start subprocess',1,0) import time st=time.time() child_stdin,child_stdout=os.popen2(r'c:\python24\python.exe %s C'%(bname)) for i in range(1000): #Log('Send packet',1,0) WriteBinPacket(child_stdin,['Alma'*100,i]) #Log('Waiting for packet',1,0) s=ReadBinPacket(child_stdout) #Log('Packet is: %s'%([s]),1,0) #Log('Print packet',1,0) #print Client's answer,[s] import time time.sleep(0.1) #Log('Send packet',1,0) WriteBinPacket(child_stdin,'quit') #Log('Waiting for packet',1,0) s=ReadBinPacket(child_stdout) #Log('Packet is: %s'%([s]),1,0) #Log('Print packet',1,0) #print Client's answer,[s] Log('Master finished',1,0) except Exception,E: Log(str(E),1,0) print time.time()-stdd -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: pywinauto 3.6 released
I'll be out of the office until approximately August 20th. If you have any questions, please email [EMAIL PROTECTED] -- David Wahler -- http://mail.python.org/mailman/listinfo/python-list
Nuther problem with 'dive into Python'
Am going through Chapter 9 - HTTP Web Services in dive into Python. It uses the following: data = urllib.urlopen('http://diveintomark.org/xml/atom.xml').read() The page no longer exists, can anyone recommend an alternative page to use? Ben -- http://mail.python.org/mailman/listinfo/python-list
Another problem with 'Dive Into Python'
Am going through Chapter 9 - HTTP Web Services in dive into Python. It uses the following: data = urllib.urlopen('http://diveintomark.org/xml/atom.xml').read() The page no longer exists, can anyone recommend an alternative page to use? Ben -- http://mail.python.org/mailman/listinfo/python-list
gaierror: (8, 'hostname nor servname provided, or not known')
Hello, I asked this question about a week ago, but I did not provide a traceback. Here is the traceback: File /usr/local/lib/python2.4/xmlrpclib.py, line 1096, in __call__ return self.__send(self.__name, args) File /usr/local/lib/python2.4/xmlrpclib.py, line 1383, in __request verbose=self.__verbose File /usr/local/lib/python2.4/xmlrpclib.py, line 1129, in request self.send_content(h, request_body) File /usr/local/lib/python2.4/xmlrpclib.py, line 1243, in send_content connection.endheaders() File /usr/local/lib/python2.4/httplib.py, line 798, in endheaders self._send_output() File /usr/local/lib/python2.4/httplib.py, line 679, in _send_output self.send(msg) File /usr/local/lib/python2.4/httplib.py, line 646, in send self.connect() File /usr/local/lib/python2.4/httplib.py, line 1072, in connect sock.connect((self.host, self.port)) File string, line 1, in connect gaierror: (8, 'hostname nor servname provided, or not known') The program is connecting to the same host about 2 times per minute. After running for one or two hours, it raises this exception. Once it raised this exception, it keeps raising in. (My program is trying to connect but it cannot.) Then I restart my program and it works for anoter hour or two. I tried the same program on different machines and different operating system, but the error is always the same. Please help me identify the problem. Thanks, Laszlo -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows vs. Linux
Andy Dingley wrote: Python is one of the best languages I've found for platform-independence - significantly better than Perl. The reason I'm going with vmware is because I'm afraid that I will need to compile a C portiion of a Python module and that will not be a pretty picture under Windows... true or false? -- http://mail.python.org/mailman/listinfo/python-list
Re: BCD List to HEX List
Paul Rubin wrote: Philippe Martin [EMAIL PROTECTED] writes: Why are you avoiding naming the chip and its compiler? I must disagree on that one: There are many threads on this site where people just have fun talking algorithm. I'm not an algo. expert and I know there are many here. This is just like the very common situation here and on sci.crypt, where a person has a programming or algorithm question and gets asked what the application is, and when they answer, it turns out that what they need is not anything like what they thought they needed. on one device, the processor in an 8-bit arm and the X-compiler is made by epson on the other device, the processor is unknown to me and the environment is a subset of java made for smartcards called javacard. You mean ARM?? There is no such thing as an 8-bit ARM; they are 32-bit cpu's that (in some models) support a 16-bit instruction format. Javacard is an interpreter that runs in many 8-bit processors. The interpreter supports 32-bit arithmetic. I checked the processor and it is an EPSON 8 bit (SC88 I think). If you check the javacard specs, you'll see that not all VM support 32 bits. Regards, Philipped -- http://mail.python.org/mailman/listinfo/python-list
Re: BCD List to HEX List
John Machin wrote: Philippe Martin wrote: 3. How does the device manage to compute the 8-decimal-digit number that is your input?? What device manager ? think about it before being rude No device manager [noun] was mentioned. You may have inferred rudeness where astonishment was being implied. I'll try again: How does the [8-bit] device manage [verb, as in how is it able] to compute the [32-bit] 8-decimal-digit number that is [split up one decimal digit per array element thus becoming] your input?? I get keystrokes from the device keyboard and append to the array as needed. I actually need numbers much larger than 32 bits. Regards, Philippe -- http://mail.python.org/mailman/listinfo/python-list
Multiple Telnet sessions through one script
Hi I am new in python scripting. I want to open a Multiple telnet session through once script. In other way i can tell i want to open two linux consoles through one script. I wrote one script, but the issue is I am not able to open multiple consoles. The Scripts which i wrote is as follows: import pexpect session = pexpect.spawn(telnet localhost 2601\n) session.expect(Password: ) session.send(XYZ\n\n) session.expect(Router1 ) session1 = pexpect.spawn(telnet localhost 2604\n) session1.expect(Password: ) session1.send(ABCD\n\n) session1.expect(ospfd ) #session1.interact() session1.interact() output : ospf But in this case, i want in one console router one can open and on other console ospf should open. But this i want to do is through one script only. Regds Vik -- http://mail.python.org/mailman/listinfo/python-list
Re: Need a compelling argument to use Django instead of Rails
On 2006-07-29 01:07:12, Tim Roberts wrote: Vincent Delporte [EMAIL PROTECTED] wrote: BTW, what is the advantage of running a CherryPy/Django server instead of the regular way of code in pages? Improved performance because the Python interpreter is already up and running? Exactly. The Python interpreter can take a significant fraction of a second to start. For the typical short web request, the overhead can add up. Is this start-up overhead the same thing for PHP? Or is this handled differently there? Gerhard -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows vs. Linux
On Mon, Jul 31, 2006 at 04:30:50AM -0700, Andy Dingley wrote: [EMAIL PROTECTED] wrote: Is Windows an okay enviornment in which to program under Python, or do you recommend that I run a dual-boot of Linux or maybe a VMWare install to program under Python? Python is one of the best languages I've found for platform-independence - significantly better than Perl. Right now I'm coding Python that runs happily under Redhat, Windows /Cygwin and Windows native. It also integrates closely with command line tools like subversion, including piping their output into Python-based XML parsers. This really wouldn't be easy with Perl. No, it's easy with Perl too - but this is a Python list, so use Python :-) Find yourself an editor that's pretty similar under both Unix and Windows. jEdit is a good place to start. This is very good advice. I would recommend vim or emacs (mostly vim, but I don't wish to start a holy war) as the text-editing power tools of choice, but you should find something that suits your style. This list can probably provide some guidance there, too. You might also like to look at running Cygwin under Windows. It's a Unix-like command shell that provides nearly every command-line Unix tool you could want on a Windows box. Can be a little awkward at times, but it's a huge advantage over raw Windows. Ditto. -- yours, William woolgathering.cx -- http://mail.python.org/mailman/listinfo/python-list
Re: BCD List to HEX List
John Machin wrote: Philippe Martin wrote: Yes I had arm in mind (for some reason) while it is the Smc8831 (http://www.google.com/url?sa=Ustart=1q=http://www.epsondevice.com/www/PDFS/epdoc_ic.nsf/5388db40b5eee4f949256a9c001d589f/944b73008b0bad33492570a00015d6ba/%24FILE/S5U1C88000C_2Ev3.pdfe=9797) That appears to be volume 2 of the 2-volume set of manuals that come with the tools package. It says that vol 1 has details about the C compiler. This appears to be volume 1: http://www.epsondevice.com/www/PDFS/epdoc_ic.nsf/5388db40b5eee4f949256a9c001d589f/1410881ddee374f7492570a00015d65e/$FILE/C88000C_1Ev3.pdf Section 1.2.3 Data Types mentions unsigned and signed long (32-bit) data types. There are several references to long later, including declarations in sample C code, and details of how long (32-bit) function args are passed. There appears to be a fundamental disconnection here somewhere ... Just trust me John, I do not have access to 32 bit ints/longs. Regards, Philippe -- http://mail.python.org/mailman/listinfo/python-list
getting debug from urllib2
Have been experimenting with HTTP stuff in python 2.4 and am having a problem getting debug info. If I use utllib.utlopen I get debug but if I user utllib2 I do not. Below is the probram and the output I am getting. Any insight? Ben * Code * import urllib, urllib2, httplib url = 'http://www.mozillazine.org/atom.xml' httplib.HTTPConnection.debuglevel = 1 print urllib data = urllib.urlopen(url); print urllib2 request = urllib2.Request(url) opener = urllib2.build_opener() feeddata = opener.open(request).read() print End\n * Output * urllib connect: (www.mozillazine.org, 80) send: 'GET /atom.xml HTTP/1.0\r\nHost: www.mozillazine.org\r \nUser-agent: Python-urllib/1.16\r\n\r\n' reply: 'HTTP/1.0 200 OK\r\n' header: Date: Mon, 31 Jul 2006 13:43:11 GMT header: Server: Apache/2.0.55 (Gentoo) PHP/4.4.0-pl1-gentoo header: Last-Modified: Thu, 27 Jul 2006 18:05:52 GMT header: ETag: 20a1b4-6bcf-be12000 header: Accept-Ranges: bytes header: Content-Length: 27599 header: Content-Type: application/xml header: Age: 5 header: X-Cache: HIT from mz5.mz.osuosl.org header: X-Cache-Lookup: HIT from mz5.mz.osuosl.org:80 header: Connection: close urllib2 End -- http://mail.python.org/mailman/listinfo/python-list
Re: Need a compelling argument to use Django instead of Rails
Gerhard Fiedler wrote: On 2006-07-29 01:07:12, Tim Roberts wrote: Vincent Delporte [EMAIL PROTECTED] wrote: BTW, what is the advantage of running a CherryPy/Django server instead of the regular way of code in pages? Improved performance because the Python interpreter is already up and running? Exactly. The Python interpreter can take a significant fraction of a second to start. For the typical short web request, the overhead can add up. Is this start-up overhead the same thing for PHP? Or is this handled differently there? Typically you run PHP as a module in your webserver, so there should be no process startup overhead. mod_python provides the same sort of functionality for Python, but is not as popular or widely installed as the PHP Apache module. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Re: BCD List to HEX List
Philippe Martin [EMAIL PROTECTED] writes: I actually need numbers much larger than 32 bits. What is the max size hex number you need? What is the application if you don't mind my asking? -- http://mail.python.org/mailman/listinfo/python-list
Re: Fastest Way To Loop Through Every Pixel
Chaos [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Paul McGuire wrote: Paul McGuire [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Chaos [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] myCol = (0.3 * image.GetRed(thisX, thisY)) + (0.59 * image.GetGreen(thisX, thisY)) + (0.11 * image.GetBlue(thisX, thisY)) if myCol darkestCol: darkestCol = myCol possX = thisX possY = thisY Psyco may be of some help to you, especially if you extract out your myCol expression into its own function, something like: def darkness(img,x,y): return (0.3 * img.GetRed(x,y)) + (0.59 * img.GetGreen(x,y)) + (0.11 * img.GetBlue(x,y)) snip Even better than my other suggestions might be to write this function, and then wrap it in a memoizing decorator (http://wiki.python.org/moin/PythonDecoratorLibrary#head-11870a08b0fa59a8622 201abfac735ea47ffade5) - surely there must be some repeated colors in your image. -- Paul Its not only finding the darkest color, but also finding the X position and Y Position of the darkest color. Sorry, you are correct. To take advantage of memoizing, the darkness method would have to work with the r, g, and b values, not the x's and y's. -- Paul import psyco psyco.full() IMAGE_WIDTH = 200 IMAGE_HEIGHT = 200 imgColRange = range(IMAGE_WIDTH) imgRowRange = range(IMAGE_HEIGHT) @memoize# copy memoize from http://wiki.python.org/moin/PythonDecoratorLibrary, or similar def darkness(r,g,b): return 0.3*r + 0.59*g + 0.11*b def getDarkestPixel(image): getR = image.GetRed getG = image.GetGreen getB = image.GetBlue darkest = darkness( getR(0,0), getG(0,0), getB(0,0) ) # or with PIL, could do # darkest = darkness( *getpixel(0,0) ) dkX = 0 dkY = 0 for r in imgRowRange: for c in imgColRange: dk = darkness( getRed(r,c), getGrn(r,c), getBlu(r,c) ) if dk darkest: darkest = dk dkX = c dkY = r return dkX, dkY -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows vs. Linux
metaperl wrote: The reason I'm going with vmware is because I'm afraid that I will need to compile a C portiion of a Python module and that will not be a pretty picture under Windows... true or false? Provided you have the correct compilers installed it is no harder compiling C extensions under Windows than under Linux. The problem is getting the correct toolchain installed. You could try the instructions in section A of http://wiki.python.org/moin/PyrexOnWindows You only need to follow section B of that document if you want to use Pyrex, but if you are planning on writing C extensions I strongly recommend using Pyrex. Also, these days, you can use ctypes for many cases where you used to have to compile a C extension. -- http://mail.python.org/mailman/listinfo/python-list
Re: Fastest Way To Loop Through Every Pixel
Paul McGuire wrote: Chaos [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Paul McGuire wrote: Paul McGuire [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Chaos [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] myCol = (0.3 * image.GetRed(thisX, thisY)) + (0.59 * image.GetGreen(thisX, thisY)) + (0.11 * image.GetBlue(thisX, thisY)) if myCol darkestCol: darkestCol = myCol possX = thisX possY = thisY Psyco may be of some help to you, especially if you extract out your myCol expression into its own function, something like: def darkness(img,x,y): return (0.3 * img.GetRed(x,y)) + (0.59 * img.GetGreen(x,y)) + (0.11 * img.GetBlue(x,y)) snip Even better than my other suggestions might be to write this function, and then wrap it in a memoizing decorator (http://wiki.python.org/moin/PythonDecoratorLibrary#head-11870a08b0fa59a8622 201abfac735ea47ffade5) - surely there must be some repeated colors in your image. -- Paul Its not only finding the darkest color, but also finding the X position and Y Position of the darkest color. Sorry, you are correct. To take advantage of memoizing, the darkness method would have to work with the r, g, and b values, not the x's and y's. -- Paul import psyco psyco.full() IMAGE_WIDTH = 200 IMAGE_HEIGHT = 200 imgColRange = range(IMAGE_WIDTH) imgRowRange = range(IMAGE_HEIGHT) @memoize# copy memoize from http://wiki.python.org/moin/PythonDecoratorLibrary, or similar def darkness(r,g,b): return 0.3*r + 0.59*g + 0.11*b def getDarkestPixel(image): getR = image.GetRed getG = image.GetGreen getB = image.GetBlue darkest = darkness( getR(0,0), getG(0,0), getB(0,0) ) # or with PIL, could do # darkest = darkness( *getpixel(0,0) ) dkX = 0 dkY = 0 for r in imgRowRange: for c in imgColRange: dk = darkness( getRed(r,c), getGrn(r,c), getBlu(r,c) ) if dk darkest: darkest = dk dkX = c dkY = r return dkX, dkY From my experiences with Psyco/PIL, it's probably faster to move the image data into lists first (using list(Image.getdata) or list(image.getband)) and access the raw data in your loop(s). Don't use Image.getpixel in a tight loop, they result in Python-to-C-Calls which can't be optimized by Psyco. Even when you're not using Psyco, getpixel is probably slower (at least the PIL docs say so: Note that this method is rather slow; if you need to process larger parts of an image from Python, use the getdata method.) -- http://mail.python.org/mailman/listinfo/python-list
Re: BCD List to HEX List
Paul Rubin wrote: Philippe Martin [EMAIL PROTECTED] writes: I actually need numbers much larger than 32 bits. What is the max size hex number you need? What is the application if you don't mind my asking? Well I am under NDA so I cannot tell you what the application is - I need numbers (dec) with up to 24 digits. As I said, I went the other way - more data on the line (from dev 1 to dev 2) - but I feel there is no speed issue at this stage. Seems to work. Regards, Philippe PYTHON ** l2 = [1,2,3,4] l1 = [0,2,5,9] def sup (l1, l2): #assume same length for i in range(len(l1) ): if l1[i] l2[i]: return 1 if l1[i] l2[i]: return -1 return 0 def add (l1, l2): #assume same length r = [] idx = range (len(l1)) idx.reverse() carry = 0 for i in idx: if l1[i] + l2[i] 10: carry = 1 r.insert(0,(l1[i] + l2[i]) % 10) else: r.insert(0,l1[i] + l2[i] + carry) carry = 0 return r def sub (l1,l2): #assume same length - sub l1 from l2 r = [] idx = range (len(l1)) idx.reverse() carry = 0 for i in idx: print l1[i] + carry, l2[i] if ((l2[i]) - (l1[i]+carry) 0) : print 'CARRY' r.insert(0,(((10 + l2[i]) - (l1[i]+carry carry = 1 else: r.insert(0,(l2[i]) - (l1[i]+ carry)) carry = 0 return r print sub (l1,l2) * AND AM JUST TESTING IT IN JAVACARD ** // public byte CmpD(byte[] p_op1, byte[] p_op2, byte p_len) { byte l_count = (byte)0; for (; l_count p_len; l_count += 1) { short C = (short)(p_op1[l_count]); short D = (short)(p_op2[l_count]); if (C D) return 1; if (C D) return -1; } return 0; } // public static void SubD(byte[] p_op1, byte[] p_op2, byte[] p_dest, byte p_len) { byte l_count = (byte)0; byte l_carry = (byte)0; for (l_count = (byte)(p_len - (byte)1); l_count = (byte)0; l_count -= (byte)1) { if ((p_op2[l_count] - (byte)(p_op1[l_count]+l_carry) ) 0) { p_dest[l_count] = (byte)( ((byte)10 + p_op2[l_count]) - (byte)(p_op1[l_count] + l_carry)) ; l_carry = (byte)1; } else { p_dest[l_count] = (byte)( p_op2[l_count] - (byte)(p_op [l_count] + l_carry)) ; l_carry = -(byte)0; } } } // public static void AddD(byte[] p_op1, byte[] p_op2, byte[] p_dest, byte p_len) { byte l_count = (byte)0; byte l_carry = (byte)0; for (l_count = (byte)(p_len - (byte)1); l_count = (byte)0; l_count -= (byte)1) { if (p_op2[l_count] + (byte)(p_op1[l_count]) 10) { p_dest[l_count] = (byte)( ( p_op2[l_count] + p_op [l_count] )% 10) ; l_carry = (byte)1; } else { p_dest[l_count] = (byte)( p_op2[l_count] + p_op1[l_count] + l_carry) ; l_carry = -(byte)0; } } } -- http://mail.python.org/mailman/listinfo/python-list
Re: Fastest Way To Loop Through Every Pixel
Chaos wrote: I have tried PIL. Not only that, but the Image.eval function had no success either. I did some tests and I found out that Image.eval only called the function a certain number of times either 250, or 255. Unless I can find a working example for this function, its impossible to use. you might have better success by asking questions about the problem you're trying to solve, rather than about some artifact of your first attempt to solve it... the following PIL snippet locates the darkest pixel in an image in about 0.5 milliseconds for a 200x200 RGB image, on my machine: im = im.convert(L) # convert to grayscale lo, hi = im.getextrema() # find darkest pixel value lo = im.point(lambda x: x == lo) # highlight darkest pixel value x, y, _, _ = lo.getbbox() # locate uppermost/leftmost dark pixel /F -- http://mail.python.org/mailman/listinfo/python-list
Re: BCD List to HEX List
Philippe Martin [EMAIL PROTECTED] writes: Well I am under NDA so I cannot tell you what the application is - I need numbers (dec) with up to 24 digits. You actually need to represent numbers up to 10**24?? As I said, I went the other way - more data on the line (from dev 1 to dev 2) - but I feel there is no speed issue at this stage. What are your memory constraints? -- http://mail.python.org/mailman/listinfo/python-list
Re: BCD List to HEX List
Paul Rubin wrote: Philippe Martin [EMAIL PROTECTED] writes: Well I am under NDA so I cannot tell you what the application is - I need numbers (dec) with up to 24 digits. You actually need to represent numbers up to 10**24?? As I said, I went the other way - more data on the line (from dev 1 to dev 2) - but I feel there is no speed issue at this stage. What are your memory constraints? On device #1 no constraint for my purpose. On the smartcard, the tradeoff is between using EEPROM (plenty + slow + small life expectancy) for temp variables versus RAM (very little) ... but I do not think it is an issue eather in my case. Speed is what worries me most (crypto takes time). But so far so good. Regards, Philippe -- http://mail.python.org/mailman/listinfo/python-list
Re: BCD List to HEX List
Paul Rubin wrote: Philippe Martin [EMAIL PROTECTED] writes: Well I am under NDA so I cannot tell you what the application is - I need numbers (dec) with up to 24 digits. You actually need to represent numbers up to 10**24?? As I said, I went the other way - more data on the line (from dev 1 to dev 2) - but I feel there is no speed issue at this stage. What are your memory constraints? PS: in smart cards, you count RAM in hundreds of bytes and EEPROM in K-bytes. -- http://mail.python.org/mailman/listinfo/python-list
Re: BCD List to HEX List
Philippe Martin [EMAIL PROTECTED] writes: On device #1 no constraint for my purpose. On the smartcard, the tradeoff is between using EEPROM (plenty + slow + small life expectancy) for temp variables versus RAM (very little) ... but I do not think it is an issue eather in my case. Speed is what worries me most (crypto takes time). You should not have to do this decimal-hex conversion repeatedly in a crypto operation. Do you have a public-key accelerator (or MAC unit) on that cpu? Do you really care about speed? I had thought up a cute O(n**3) scheme that might have been ok for 8 digits but probably not for 24. -- http://mail.python.org/mailman/listinfo/python-list
poll() on OSX 10.3.9
Hello, I need to use the 'select' module in python, but get an error on the: Python 2.5b2 (r25b2:50512, Jul 31 2006, 15:01:51) [GCC 3.3 20030304 (Apple Computer, Inc. build 1640)] on darwin Type help, copyright, credits or license for more information. import select dir(select) ['__doc__', '__file__', '__name__', 'error', 'select'] this works fine on BSD4 Python 2.5b2 (r25b2:50512, Jul 31 2006, 12:43:17) [GCC 2.95.4 20020320 [FreeBSD]] on freebsd4 Type help, copyright, credits or license for more information. import itools from select import POLLIN import select dir(select) ['POLLERR', 'POLLHUP', 'POLLIN', 'POLLNVAL', 'POLLOUT', 'POLLPRI', 'POLLRDBAND', 'POLLRDNORM', 'POLLWRBAND', 'POLLWRNORM', '__doc__', '__file__', '__name__', 'error', 'poll', 'select'] is there anything specific to do to the python installation before compiling. i am using the itools library from http://www.ikaaro.org/itools which uses this python module thanks -- Norman Khine -- http://mail.python.org/mailman/listinfo/python-list
Re: BCD List to HEX List
Paul Rubin wrote: Philippe Martin [EMAIL PROTECTED] writes: On device #1 no constraint for my purpose. On the smartcard, the tradeoff is between using EEPROM (plenty + slow + small life expectancy) for temp variables versus RAM (very little) ... but I do not think it is an issue eather in my case. Speed is what worries me most (crypto takes time). You should not have to do this decimal-hex conversion repeatedly in a crypto operation. Do you have a public-key accelerator (or MAC unit) on that cpu? Do you really care about speed? I had thought up a cute O(n**3) scheme that might have been ok for 8 digits but probably not for 24. I did not explain myself correctly, the decimal operations are done in clear mode as they are made within the cards which by definition cannot be broken, requests and results that go to/from the devices are encrypted/signed with diversified keys ... but that another story ;-) Regards, Philippe -- http://mail.python.org/mailman/listinfo/python-list
trouble understanding super()
Here's some code from Python in a Nutshell. The comments are lines from a previous example that the calls to super replace in the new example: class A(object): def met(self): print 'A.met' class B(A): def met(self): print 'B.met' # A.met(self) super(B, self).met() class C(A): def met(self): print 'C.met' # A.met(self) super(C, self).met() class D(B, C): def met(self): print 'D.met' # B.met() # C.met() super(D, self).met() Then you call D().met() Now, I understand that the commented code would cause A.met to be called twice. But why does the second version (with super) not also do this? I guess my problem lies in not understanding exactly what the super function returns. super(D, self).met() seems like it would return something that has to do with both B and C, which each in turn return a superobject having to do with A, so why isn't A.met called twice still? Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple Telnet sessions through one script
Well, although you spawn seperate telnet processes there is still only one thread of control in your pythons script. If you need to do two things simultaneously you'll need to setup a parallel control mechanism. For example you could use python threads, each thread spawns a separate telnet and controls it accordingly. Similarly, you could fork off other python scripts that control each telnet session. Alright, so that's for controlling two telnets at once. I think you'll have another problem, and that's controlling each telnet session manually. To do this I think you'll need to setup an interface that provides the two consoles you are after. I'm not exactly sure the best way to do that. One thought I have is if you used one of the various GUI toolkits you could have your app open a window that is seperated into two consoles. Each thread could be bound to one of these consoles and you could switch between the two by clicking on one side versus the other. Although if you want to do it all in a shell, or have your program open multiple shells I'm not sure how to do that, you might check google. I suppose if you were doing things from a single shell and wanted to do thing similar to the GUI toolkit I described earlier, you could try something like ncurses. I guess I have one final idea, you could use a single shell, buffer output from each telnet session and have your main control loop give you the ability to switch back and forth between the two sessions. Anyhow, hope those ideas help you out a little. vmalhotra wrote: Hi I am new in python scripting. I want to open a Multiple telnet session through once script. In other way i can tell i want to open two linux consoles through one script. I wrote one script, but the issue is I am not able to open multiple consoles. The Scripts which i wrote is as follows: import pexpect session = pexpect.spawn(telnet localhost 2601\n) session.expect(Password: ) session.send(XYZ\n\n) session.expect(Router1 ) session1 = pexpect.spawn(telnet localhost 2604\n) session1.expect(Password: ) session1.send(ABCD\n\n) session1.expect(ospfd ) #session1.interact() session1.interact() output : ospf But in this case, i want in one console router one can open and on other console ospf should open. But this i want to do is through one script only. Regds Vik -- Carl J. Van Arsdall [EMAIL PROTECTED] Build and Release MontaVista Software -- http://mail.python.org/mailman/listinfo/python-list
FTP (ftplib) output capture
Hi Has anyone caputerd the output from the std ftp lib? It seems a bit annoying that everything is printed to stdout. It means incorporating this into any real program is a problem. It would have been much better if they used the std logging module and hooked up a console logger for the feault ftp application. Alas it isnt that way. Capturing stdout like this??? : import sys sys.stdout = open('bb', 'w) But I want to re-route it to the logging module not a file , so do I need to write a steam object? Thanks, -- http://mail.python.org/mailman/listinfo/python-list
Using Python for my web site
Hi, I am interested in re-writing my website in Python vs PHP but have a few questions. Here are my specs, please advise as to which configuration would be best: 1.Dell Poweredge Server, w/IIS, currently Windows but considering FreeBSD 2. Site consists of result pages for auctions and items for sale (100 per page) 3. MySQL (Dell Poweredge w/AMD) database server connected to my web server 4. Traffic, 30 million page loads/month I am trying to have the fastest page loads, averaging 100 items per result page. I have read about using Apache's mod_python so I could use PSP. Any help or tips are appreciated. -Adam -- http://mail.python.org/mailman/listinfo/python-list
Re: BCD List to HEX List
Philippe Martin wrote: Yes, I came here for the algorithm question, not the code result. To turn BCD x to binary integer y, set y to zero for each nibble n of x: y = (((y shifted left 2) + y) shifted left 1) + n Do you need instruction on extracting nibbles, and shifting and adding integers? A problem this small and simple does not call for a prototype. -- --Bryan -- http://mail.python.org/mailman/listinfo/python-list
Re: Mouse LED Control in Python
There is not enough information in that post to be able to reimpliment what he did in any language. You will have to try and get in touch with the author. -Chris On Sun, Jul 30, 2006 at 01:26:40PM -0700, [EMAIL PROTECTED] wrote: I found this link that describes the byte arrays to control the IM/Email Leds on my Logitech MX610 mouse: http://www.kdedevelopers.org/node/2029 The link to the tarball is dead so I can't look at that. Is there anyway to do what the link says in Python? If you follow the link above, it talks about 'sending the byte array to 0x10 (16)'. I'm not sure if that is possible in python. Can anyone help or point me in the right direction? I'd also be willing to have this be done in another language and just call different programs from a python program when I need something specific done (IM light on, for example). Text from the link if you can't be bothered to follow it: I've figured out the IM led now. As before, you send 6 bytes to report ID 0x10 (16), followed by the confirm message. The magic values are: unsigned char confirm[6] = { 0x01, 0x80, 0x52, 0x00, 0x00, 0x00 }; unsigned char email_off[6] = { 0x01, 0x80, 0x52, 0x06, 0x00, 0x00 }; unsigned char email_on[6] = { 0x01, 0x80, 0x52, 0x05, 0x00, 0x00 }; unsigned char email_pulse[6] = { 0x01, 0x80, 0x52, 0x04, 0x00, 0x00 }; unsigned char email_flash[6] = { 0x01, 0x80, 0x52, 0x03, 0x00, 0x00 }; unsigned char email_instanton[6] = { 0x01, 0x80, 0x52, 0x02, 0x00, 0x00 }; unsigned char email_instantoff[6] = { 0x01, 0x80, 0x52, 0x01, 0x00, 0x00 }; unsigned char im_off[6] = { 0x01, 0x80, 0x52, 0x00, 0x06, 0x00 }; unsigned char im_on[6] = { 0x01, 0x80, 0x52, 0x00, 0x05, 0x00 }; unsigned char im_pulse[6] = { 0x01, 0x80, 0x52, 0x00, 0x04, 0x00 }; unsigned char im_flash[6] = { 0x01, 0x80, 0x52, 0x00, 0x03, 0x00 }; unsigned char im_instantoff[6] = { 0x01, 0x80, 0x52, 0x00, 0x01, 0x00 }; unsigned char im_instanton[6] = { 0x01, 0x80, 0x52, 0x00, 0x02, 0x00 }; Thanks, Jeff -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Questions
Hi, I find Python very interesting and usefulas adeveloping matrix and other mathematical applications. Iwent through the tutorial to try tounderstandand work withvarious concepts. I have the following questions: Where could I find more information on the "self" classes. The use of the (self) is very abstract for me andI need more clarifications. Do youalreadyhave a built-in program or scheme for a linear regression that Icould try on datacoming from the Bloomberg system sources.Or could you give me a little indicationhowto buildit. I will do the rest. I found something onthe regression(test. (x)) on the existing module, but that wasn't appropriate. If you need an example ofthe formula for the mathematical regression, let me know. Many thanks in advance, Richard -- http://mail.python.org/mailman/listinfo/python-list
Re: Possible error in 'dive into Python' book, help!
In article [EMAIL PROTECTED], Ben Edwards (lists) [EMAIL PROTECTED] wrote: I have been going through Dive into Python which up to now has been excellent. I am now working through Chapter 9, XML Processing. I am 9 pages in (p182) in the 'Parsing XML section. The following code is supposed to return the whole XML document (I have put ti at the end of this email): from xml.dom import minidom xmldoc = minidom.parse('/home/ben/diveintopython-5.4/py/kgp/binary.xml') grammerNode = xmldoc.firstChild print grammerNode.toxml() But it only returns: !DOCTYPE grammar PUBLIC '-//diveintopython.org//DTD Kant Generator Pro v1.0//EN' 'kgp.dtd' The next line is then grammerNode.childNodes And it returns an empty tuples;( Kind of stuck here as I don't really want to continue. Has anyone any idea what is going on? OK, your xmldoc has two child nodes. The first is the !DOCTYPE ... you're getting above. Which of course doesn't have any children, so grammarNode.childNodes is naturally empty. The grammar element is the *second* child of the xmldoc, so of course isn't xmldoc.firstChild. Probably what you want is: grammarNode = xmldoc.documentElement Dive Into Python's assertion that A Document always has only one child node, the root element of the XML document looks a little off from where I'm standing: print xmldoc.toxml() ?xml version=1.0 ? !DOCTYPE grammar PUBLIC '-//diveintopython.org//DTD Kant Generator Pro v1.0//EN' 'kgp.dtd' grammar ref id=bit p0/p p1/p /ref ref id=byte pxref id=bit/xref id=bit/xref id=bit/xref id=bit/xref id=bit/xref id=bit/xref id=bit/xref id=bit//p /ref /grammar xmldoc.childNodes [xml.dom.minidom.DocumentType instance at 0x4053640c, DOM Element: grammar at 0x40536f0c] -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | Frankly I have no feelings towards penguins one way or the other \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for my web site
northband wrote: Hi, I am interested in re-writing my website in Python vs PHP but have a few questions. Here are my specs, please advise as to which configuration would be best: 1.Dell Poweredge Server, w/IIS, currently Windows but considering FreeBSD 2. Site consists of result pages for auctions and items for sale (100 per page) 3. MySQL (Dell Poweredge w/AMD) database server connected to my web server 4. Traffic, 30 million page loads/month I am trying to have the fastest page loads, averaging 100 items per result page. I have read about using Apache's mod_python so I could use PSP. Any help or tips are appreciated. -Adam you should try http://www.ikaaro.org/itools it is a python library and has all you need, although it is still in alpha state, it is running some heavy applications such as http://destinationsflybe.com as an example. for the mysql you can use the csv module. for now it has not been ported on window$, try gentoo or freebsd -- Norman Khine -- http://mail.python.org/mailman/listinfo/python-list
Re: getting debug from urllib2
On Mon, Jul 31, 2006 at 02:43:36PM +0100, Ben Edwards wrote: Have been experimenting with HTTP stuff in python 2.4 and am having a problem getting debug info. If I use utllib.utlopen I get debug but if I user utllib2 I do not. Below is the probram and the output I am getting. Any insight? urllib2 sets the debug level every time a connection is made. The HTTPHandler classes provide a way of setting this, but there is no convenient way of doing this when using the urlopen interface. -Chris Ben * Code * import urllib, urllib2, httplib url = 'http://www.mozillazine.org/atom.xml' httplib.HTTPConnection.debuglevel = 1 print urllib data = urllib.urlopen(url); print urllib2 request = urllib2.Request(url) opener = urllib2.build_opener() feeddata = opener.open(request).read() print End\n * Output * urllib connect: (www.mozillazine.org, 80) send: 'GET /atom.xml HTTP/1.0\r\nHost: www.mozillazine.org\r \nUser-agent: Python-urllib/1.16\r\n\r\n' reply: 'HTTP/1.0 200 OK\r\n' header: Date: Mon, 31 Jul 2006 13:43:11 GMT header: Server: Apache/2.0.55 (Gentoo) PHP/4.4.0-pl1-gentoo header: Last-Modified: Thu, 27 Jul 2006 18:05:52 GMT header: ETag: 20a1b4-6bcf-be12000 header: Accept-Ranges: bytes header: Content-Length: 27599 header: Content-Type: application/xml header: Age: 5 header: X-Cache: HIT from mz5.mz.osuosl.org header: X-Cache-Lookup: HIT from mz5.mz.osuosl.org:80 header: Connection: close urllib2 End -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble understanding super()
John Salerno wrote: Here's some code from Python in a Nutshell. The comments are lines from a previous example that the calls to super replace in the new example: class A(object): def met(self): print 'A.met' class B(A): def met(self): print 'B.met' # A.met(self) super(B, self).met() class C(A): def met(self): print 'C.met' # A.met(self) super(C, self).met() class D(B, C): def met(self): print 'D.met' # B.met() # C.met() super(D, self).met() Then you call D().met() Now, I understand that the commented code would cause A.met to be called twice. But why does the second version (with super) not also do this? I guess my problem lies in not understanding exactly what the super function returns. super(D, self).met() seems like it would return something that has to do with both B and C, which each in turn return a superobject having to do with A, so why isn't A.met called twice still? Thanks! Basically super(class_, self).method looks in self's mro (it's list of base classes) for class class_, and then starts searching *after* class class_ for the next class that implements the method. In this case the object's (instance of D) mro will be (D, B, C, A, object), so as super gets called in each class, it looks in that list (tuple, whatever) for the class following it (actually the next class following it that implements the method). Since no class appears in that list more than once, each class's implementation of the method will only be called once. HTH, ~Simon Also, if you haven't already, read: http://www.python.org/download/releases/2.2.3/descrintro/#cooperation -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for my web site
Thanks I will look into it. -Adam Norman Khine wrote: northband wrote: Hi, I am interested in re-writing my website in Python vs PHP but have a few questions. Here are my specs, please advise as to which configuration would be best: 1.Dell Poweredge Server, w/IIS, currently Windows but considering FreeBSD 2. Site consists of result pages for auctions and items for sale (100 per page) 3. MySQL (Dell Poweredge w/AMD) database server connected to my web server 4. Traffic, 30 million page loads/month I am trying to have the fastest page loads, averaging 100 items per result page. I have read about using Apache's mod_python so I could use PSP. Any help or tips are appreciated. -Adam you should try http://www.ikaaro.org/itools it is a python library and has all you need, although it is still in alpha state, it is running some heavy applications such as http://destinationsflybe.com as an example. for the mysql you can use the csv module. for now it has not been ported on window$, try gentoo or freebsd -- Norman Khine -- http://mail.python.org/mailman/listinfo/python-list
Re: FTP (ftplib) output capture
ChaosKCW wrote: Hi Has anyone caputerd the output from the std ftp lib? It seems a bit annoying that everything is printed to stdout. It means incorporating this into any real program is a problem. It would have been much better if they used the std logging module and hooked up a console logger for the feault ftp application. Alas it isnt that way. Capturing stdout like this??? : import sys sys.stdout = open('bb', 'w) But I want to re-route it to the logging module not a file , so do I need to write a steam object? Thanks, ftplib pre-dates the standard logging system by a bit. I think ftplib only prints stuff if you set its (the FTP class instances') debug level to greater than 0. If you really want to replace sys.stdout with something that passes the data to a logger, then something like the following (untested) class should do it: class FileLog: def __init__(self, log): self.log = log def write(self, data): self.log.debug(data) The best solution might be to subclass or rewrite FTP to really do what you want. I believe one of the goals of Python-3000 is better integration of the standard library with the new-ish standard logging system, so if you do a good job send it in. ;-) Peace, ~Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: Need a compelling argument to use Django instead of Rails
On 31 Jul 2006 07:05:27 -0700, Ben Sizer [EMAIL PROTECTED] wrote: Typically you run PHP as a module in your webserver, so there should be no process startup overhead. mod_python provides the same sort of functionality for Python, but is not as popular or widely installed as the PHP Apache module. So, if mod_python provides the same functionality, it's not the main reason why Python developers use application servers while PHP users still program with page codes in /htdocs. Why do PHP users stick to that old way of things? Because they mostly use shared hosts, with no way to install their application server? -- http://mail.python.org/mailman/listinfo/python-list
Re: BCD List to HEX List
[EMAIL PROTECTED] wrote: Philippe Martin wrote: Yes, I came here for the algorithm question, not the code result. To turn BCD x to binary integer y, set y to zero for each nibble n of x: y = (((y shifted left 2) + y) shifted left 1) + n Do you need instruction on extracting nibbles, and shifting and adding integers? A problem this small and simple does not call for a prototype. -- --Bryan 'cause you're smart -- http://mail.python.org/mailman/listinfo/python-list
Re: Need a compelling argument to use Django instead of Rails
Ben Sizer [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] As for PyGame, it's good that development there has picked up again but I'd love to see it broaden its horizons beyond SDL. Maybe that is impractical, however. By wrapping SDL and interfacing to Numeric, Pete Shinners picked a chunk that he could chew and maintain. The Pygame site has recently added a PyGame Cookbook or the equivalent so people can more easily share small chunks built on pygame and comment thereupon. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for my web site
northband wrote: Hi, I am interested in re-writing my website in Python vs PHP but have a few questions. Here are my specs, please advise as to which configuration would be best: 1.Dell Poweredge Server, w/IIS, currently Windows but considering FreeBSD I may be a bit biased, but I would not run a web server under Windows... 2. Site consists of result pages for auctions and items for sale (100 per page) 3. MySQL (Dell Poweredge w/AMD) database server connected to my web server Have you considered Postgresql instead ? 4. Traffic, 30 million page loads/month I am trying to have the fastest page loads, averaging 100 items per result page. I have read about using Apache's mod_python so I could use PSP. That's a possible solution. Any help or tips are appreciated. You may eventually be interested in Django (full stack MVC web framework, runs on mod_apache, supports both MySQL and Postgresql) http://www.djangoproject.com/ or Myghty (Python's extended port of Perl::Mason, runs on mod_apache, not tied to any RDBMS) + eventually SQLAlchemy (orm) http://www.myghty.org/ http://www.sqlalchemy.org/ Now I can't tell if either one or the other beats PSP when it comes to raw perfs... My 2 cents -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
running an app as user foo
hi. within python, what's the best way to automatically spawn an app as a given user/group. i'm testing an app, and i'm going to need to assign the app to a given user/group, as well as assign it certain access rights/modes (rwx) i then want to copy the test app to a given dir, and then spawn a process to run the app.. thanks -- http://mail.python.org/mailman/listinfo/python-list
Abstract the storage of an app
Hello, I'm trying to think of an OO way to abstract the storage of an application I am working on. The classes are (example): FamilyMember (base class) Family (container class) I've been thinking of using a FamilyDoc class to interface the Family container class to a storage location (particularly, in XML). I want to be able to use another backend for storing that data, ie SQL(ite). What would you suggest as a design pattern for something like this? -- http://mail.python.org/mailman/listinfo/python-list
Re: how to make python socket server work with the app.MainLoop() in wxpython?
I think you should use thread. I just write a similar program using thread. It works well You can try it, good luck! -- http://mail.python.org/mailman/listinfo/python-list
Problem with using unittest module
Hi, I have the following statement in my test : self.assertRaises(CDKeyException, ValidationObject.Validate, 1001,'NonExistantKey') and the test fails as if assertRaises was not catching the thrown exception: == ERROR: test (DBLookupValidationTests.DBLookupValidationTests) -- Traceback (most recent call last): File C:\Dev\jade.r12sp\src\RVPackages\CDKey\Server\DBLookupValidationTests.py, line 64, in test self.assertRaises(CDKeyException, ValidationObject.Validate, 1001,'NonExistantKey') File C:\tools\Python\lib\unittest.py, line 320, in failUnlessRaises callableObj(*args, **kwargs) File C:\Dev\jade.r12sp\src/Services/local/Home\Scripts/system\CDKey\DBLookupValidation.py, line 69, in Validate raise CDKeyException, self.logger.error(e) CDKeyException Any idea what is happening? Thanks, Olivier Langlois http://www.olivierlanglois.net -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble understanding super()
Simon Forman wrote: In this case the object's (instance of D) mro will be (D, B, C, A, object), so as super gets called in each class, it looks in that list (tuple, whatever) for the class following it (actually the next class following it that implements the method). Since no class appears in that list more than once, each class's implementation of the method will only be called once. But after super(D, self).met() is called, doesn't that then call both super(B, self).met() and super(C, self).met()? If so, how does that avoid calling A.met twice? Or is that not what's happening? Here's what I think gets called, in order, after running D().met(): print 'D.met' super(D, self).met() print 'B.met' super(B, self).met() print 'A.met' print 'C.met' super(C, self).met() print 'A.met' -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble understanding super()
John Salerno wrote: But after super(D, self).met() is called, doesn't that then call both super(B, self).met() and super(C, self).met()? If so, how does that avoid calling A.met twice? Or is that not what's happening? If you have an instance of a B then super(B,self).met() will call A.met(), but if self is actually an instance of a D, then super(B,self).met() actually calls C.met(). That is why super needs both the class and the instance: so it can jump sideways across the inheritance diamond instead of always passing calls to the base of the current class. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python for my web site
Thanks for the info. Reason why we are interested in PSP is because we think our developers would be able to quickly adapt to the migration, they are familiar with php and asp. I agree on the windows webserver, we are looking into using FreeBSD instead. What would postgre's advantage over MySQL be? I will look into Django. Thanks for your .2 -Adam Bruno Desthuilliers wrote: northband wrot Hi, I am interested in re-writing my website in Python vs PHP but have a few questions. Here are my specs, please advise as to which configuration would be best: 1.Dell Poweredge Server, w/IIS, currently Windows but considering FreeBSD I may be a bit biased, but I would not run a web server under Windows... 2. Site consists of result pages for auctions and items for sale (100 per page) 3. MySQL (Dell Poweredge w/AMD) database server connected to my web server Have you considered Postgresql instead ? 4. Traffic, 30 million page loads/month I am trying to have the fastest page loads, averaging 100 items per result page. I have read about using Apache's mod_python so I could use PSP. That's a possible solution. Any help or tips are appreciated. You may eventually be interested in Django (full stack MVC web framework, runs on mod_apache, supports both MySQL and Postgresql) http://www.djangoproject.com/ or Myghty (Python's extended port of Perl::Mason, runs on mod_apache, not tied to any RDBMS) + eventually SQLAlchemy (orm) http://www.myghty.org/ http://www.sqlalchemy.org/ Now I can't tell if either one or the other beats PSP when it comes to raw perfs... My 2 cents -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Re: Need a compelling argument to use Django instead of Rails
Vincent Delporte wrote: On 31 Jul 2006 07:05:27 -0700, Ben Sizer [EMAIL PROTECTED] wrote: Typically you run PHP as a module in your webserver, so there should be no process startup overhead. mod_python provides the same sort of functionality for Python, but is not as popular or widely installed as the PHP Apache module. So, if mod_python provides the same functionality, it's not the main reason why Python developers use application servers while PHP users still program with page codes in /htdocs. Why do PHP users stick to that old way of things? Because they mostly use shared hosts, with no way to install their application server? PHP has never been designed to allow writing such a thing as a web server (some may say that PHP has never been designed at all, but this is another troll^Mquestion). IIRC, it was initially meant to run as cgi, then rewrote as an apache module. And the fact is that while there's no startup overhead in PHP (at least when deployed as a module), you still have to rebuild the whole world (includes, app-specific conf etc) for each request. This is what long-running application servers try to solve. mod_python is at once lower-level and a bit more powerful than PHP. It really exposes most of Apache's API to Python - which BTW doesn't make it that well-suited for shared hosting... (most of the time, updating a mod_python based app requires restarting the server). -- bruno desthuilliers python -c print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')]) -- http://mail.python.org/mailman/listinfo/python-list
Python Docs Fix
A month ago, someone posted, under Python Docs Bugs, a complaint about the difficulty of finding the library ref sub-subsection on string methods. That's because it is section 2.3.6.1, and the table of contents only goes to 3 levels. I followed up the me-to's with an SF bug-report suggesting that the sub-sub-section somehow be lifted up a level so it would appear in the TOC. www.python.org/sf/1514540 This weekend, in response, Andrew Kuchling moved the entire section on builtin types to chapter status, which will lift everything in that section up a level and make them more visible. So thanks to Andrew for fixing this. And a note that the volunteer Python developers sometimes do respond to polite comments and suggestions, including those originating from c.l.p. And also a note that while eventual posting to the tracker is necessary, I think most items by non-experts are best discussed here first, as happened with this one. It certainly did not hurt that I reported that I was one of (at least) three agreeing with the OP. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list