Re: Finding closures through introspection
On 6/14/2010 9:33 PM, Steven D'Aprano wrote: On Mon, 14 Jun 2010 20:46:28 -0700, John Nagle wrote: So how can I detect a closure? I *think* you do it through the co_flags attribute of the code object. This is in Python 2.5: although this doesn't seem to be documented, at least not here: http://docs.python.org/reference/datamodel.html Got it. Check f.func_closure for a non-null value. For a closure, the value will be a Cell object. The value of func_closure in f.func_globals is None, but that's the wrong place to look, apparently. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: GUIs - A Modest Proposal
On 6/14/10 10:35 PM, rantingrick wrote: On Jun 14, 11:08 pm, Stephen Hansen me+list/pyt...@ixokai.io wrote: snip Does not perform to spec. Quote, Inside of A, there are four items in a vertical line. The bottom which takes up half of the total vertical space, and the top three share the rest. No problem, check this out... import Tkinter as tk app = tk.Tk() app.geometry('400x400+20+20') # Left tk.Label(app, text='C', bg='red', width=20).place(rely=0.0, relheight=0.1667, width=200) tk.Label(app, text='D', bg='blue', width=20).place(rely=0.1667, relheight=0.1667, width=200) tk.Label(app, text='E', bg='green', width=20).place(rely=0., relheight=0.1667, width=200) tk.Label(app, text='F', bg='white', width=20).place(rely=0.5, relheight=0.5, width=200) # Right tk.Label(app, text='G', bg='purple').place(x=200, rely=0.0, relheight=0.333, relwidth=1) tk.Label(app, text='H', bg='orange').place(x=200, rely=0., relheight=0.777, relwidth=1) app.mainloop() Very good. However, you're now doing a lot of complicated manual placements and numbers. Just noting this for the record. However *your* code does not perform to your own spec! You said this... Inside of B, G is one third the size of H. If you mean that G should be one-third the height of H then your code (and yes i have the new version that does not blow chunks!) does not follow this spec! Better re-check my friend. ;-) No, my code goes to spec-- though I concede the point that the spec may not have been stated clearly. Your code has the total height of B(the entire right column) being X; and G is one third of that total height, while H is 2/3'ds of it. That's close, but very specifically not what I was going for. I was going for B having a total height of X; and that H is 300% the size of G, as demonstrated in the following: http://ixokai.io/get/layout-results-comparison.jpg You should be able to see that your G is half the size of H, where mine is one third of its size. If you dispute this assertion, I can provide exact measurements to demonstrate, but it should be visually clear. But, that said: You're very close, close enough to satisfy the challenge. But that's an easy one. I now present you the following alterations to the existing spec: - A must be a set, fixed size of 100x20. - H must expand fully, but maintain its aspect ratio. Now, in addition, in my code I made it so I could add as many new items to the top half of the left-column, and not require any tweaking of other things. This way, it can elegantly be expanded. The F panel which must be the bottom 50% doesn't ever need to be modified-- I simply add more things to the top half and it adjusts accordingly. A few tiny modifications to the existing code is at: http://ixokai.io/get/layout-wx2.py_ And the image is: http://ixokai.io/get/layout-results-wx4.jpg -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: a +b ?
Steven D'Aprano st...@remove-this-cybersource.com.au wrote: Perhaps you need to spend some more time helping beginners then, and less time hanging around Lisp gurus *wink* I've never used map/reduce outside of Python, this is where I first encountered it. And I _have_ worked in organisations alongside new Python coders. That it's easy enough to express both map reduce in Python code helped a lot with explaining them. I'm certainly not saying that people should avoid higher-order functional code, but merely to remember that map and filter aren't introductory concepts, they're moderately advanced functions that many people find difficult. And I'm saying that I hope that most people who are professional developers are capable of learning such advanced functionality, which they will never do if there are no effective examples for them from which to learn. I'm not sure why Python's handling of functions is seen as any more complex than the way it treats everything as first- class objects. I fear that not encouraging people to explore this aspect does limit the language's power for them somewhat. From both Ben your posts I'm worried that I'm being seen as having contempt for (at least certain classes of) other developers, when it's really intended as the contrary. -- http://mail.python.org/mailman/listinfo/python-list
Re: lambdas
Thomas Jollans wrote: On 06/15/2010 12:06 AM, Craig Yoshioka wrote: I'm trying to write a class factory to create new classes dynamically at runtime from simple 'definition' files that happen to be written in python as well. I'm using a class factory since I couldn't find a way to use properties with dynamically generated instances, for example: I would prefer this, but it doesn't work: class Status(object): pass def makeStatus(object): def __init__(self,definitions): for key,function in definitions: setattr(self,key,property(function)) this works (and it's fine by me): def makeStatus(definitions): class Status(object): pass for key,function in definitions: setattr(Status,key,property(function)) return Status() but I would also like the functions to only be evaluated when necessary since some may be costly, so I want to do the following: def makeStatus(definitions): class Status(object): pass for key,function,data in definitions: setattr(Status,key,property(lambda x: function(data))) return Status() but all my properties now act as if they were invoked with the same data even though each one should have been a new lambda function with it's own associated data. It seems Python is 'optimizing'? all the lambdas to the same object even though that's clearly not what I want to do. Anyone have any suggestions as to: 1) why (I'm not 100% sure about this) I think that when Python encounters function(data) while executing any one of the lambdas, looks in the scope of the factory function, and uses the last value data had there - which has since changed. This old trick might help: (if it doesn't, my analysis was wrong) 2) what I should do setattr(Status, key, property(lambda x, d=data: function(d))) 3) a better way in which to implement this pattern how about this: class Status(object): def __init__(self, definitions): definitions must be a { key: function, ... } mapping self.functions = definitions self.cache = {} def __getattribute__(self, name): if name in self.cache: return self.cache[name] elif name in self.functions: self.cache[name] = self.functions[name]() return self.cache[name] else: return super(Status, self).__getattribute__(name) This doesn't use properties (why should it?) and proposes a different format for the definitions: a dict instead of a sequence of tuples. dict([(a,b), (c,d)]) == {a: b, c: d}, of course, so that's no problem. Have fun, Thomas An alternative implementation of the above idea: from functools import partial def get_alpha(data): return 2**data ... def get_beta(data): return data + 42 ... definitions = [(alpha, get_alpha, 10), (beta, get_beta, 20)] class Status(object): ... definitions = dict((k, partial(v, d)) for k, v, d in definitions) ... def __getattr__(self, name): ... if name not in self.definitions: ... raise AttributeError ... print calculating, name ... value = self.definitions[name]() ... setattr(self, name, value) ... return value ... st = Status() st.alpha calculating alpha 1024 st.alpha 1024 st.beta calculating beta 62 st.beta 62 st.gamma Traceback (most recent call last): File stdin, line 1, in module File stdin, line 5, in __getattr__ AttributeError del st.beta st.beta calculating beta 62 This has the advantage that there is no overhead for attributes whose value has already been calculated. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: a +b ?
alex23 wuwe...@gmail.com writes: Ben Finney ben+pyt...@benfinney.id.au wrote: alex23 wuwe...@gmail.com writes: (Although I have to say, I have little sympathy for Steven's hypothetical new programmer who isn't familiar with map and reduce. With ‘reduce’ gone in Python 3 [0], I can only interpret that as “I have little sympathy for programmers who start with Python 3”. Is that in line with what you meant? Yes, Ben, clearly I was being an asshole here […] No, it wasn't clear at all. That's why I asked, rather than making assumptions. Thanks for clarifying. -- \ “A thorough reading and understanding of the Bible is the | `\ surest path to atheism.” —Donald Morgan | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: a +b ?
On Mon, 14 Jun 2010 23:05:56 -0700, alex23 wrote: And I'm saying that I hope that most people who are professional developers are capable of learning such advanced functionality, which they will never do if there are no effective examples for them from which to learn. I'm not sure why Python's handling of functions is seen as any more complex than the way it treats everything as first- class objects. I fear that not encouraging people to explore this aspect does limit the language's power for them somewhat. In my experience, some functional tools are truly mind-blowing (at least they blow *my* mind) but there's nothing difficult about map and reduce. Some people don't like them, and even seem to fear reduce -- I don't get that myself, but there you go. However, the first step in understanding them is to understand that you can use functions as data, and -- again, this is my experience -- some newcomers to programming have great difficulty going from this idiom: code = condition(x) if code == 0: return functionA(x) if code == 1: return functionB(x) if code == 2: return functionC(x) to this first-class function idiom: dispatch_table = {0: functionA, 1: functionB, 2: functionC} code = condition(x) return dispatch[code](x) and from that I surmise that they probably would have problems with other functional forms, such as map, at least at first. Your mileage may vary. From both Ben your posts I'm worried that I'm being seen as having contempt for (at least certain classes of) other developers, when it's really intended as the contrary. No implication of contempt was meant. I don't think it's contemptuous to assume that people will all meet a certain minimum level of experience, knowledge and general programming skill. Unrealistic, perhaps, but not contemptuous *grin* -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: a +b ?
Ben Finney ben+pyt...@benfinney.id.au writes: No, it wasn't clear at all. That's why I asked, rather than making assumptions. Thanks for clarifying. It should go without saying, but unfortunately the tenor of this forum has been worsened (temporarily, I hope) by certain interminable threads of late. So, to be clear: Thanks for clarifying that you were not expressing the attitude I inferred. -- \ “I turned to speak to God/About the world's despair; But to | `\ make bad matters worse/I found God wasn't there.” —Robert Frost | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: GUIs - A Modest Proposal
On 6/14/10 9:08 PM, Stephen Hansen wrote: On 6/14/10 8:31 PM, rantingrick wrote: On Jun 14, 9:41 pm, Stephen Hansen me+list/pyt...@ixokai.io wrote: I wasn't aware of [row|column]configure, no: however, I am dubious of how it directly applies. Maybe you should become more aware of a subject before you start running your mouth about it, eh? You know what? You're an *beep*. For the record, this was inappropriate. A moment's frustration after a long day does not excuse belligerence, even if unnecessarily provoked. I apologize. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Mark built-in module as deprecated
On 2010-06-15 02:29, moerchendiser2k3 wrote: Hi, yes, that was my first idea when I just create an external module. I forgot something to say: In my case the initfoo() function is called on startup in my embedding environment, that means I call that on startup of my main app. ah. In that case, I don't think it's possible to do anything on import - AFAIK, if the module foo is already loaded/initialized, import foo is equivalent to foo = sys.modules['foo'] and doesn't invoke any module-specific code... You could issue a warning on each and every method call in your module, so that when it's used, the user gets warned. Then you could cache whether a warning has been issued already in a global static variable or in module state to be able to only warn once. Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: Capture the request/response log for local web server through python.
En Tue, 15 Jun 2010 00:41:08 -0300, shanti bhushan ershantibhus...@gmail.com escribió: Dear all, I have made local webserver up by the python script from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class MyHandler(BaseHTTPRequestHandler): def do_GET(self): try: if self.path.endswith(.html): f = open(curdir + sep + self.path) #self.path has / [...] def main(): try: server = HTTPServer(('', 80), MyHandler) print 'started httpserver...' server.serve_forever() [...] I have designed one html page also. when i access the HTML page ,i want to capture following things user_agents client-request ,server-response with the help of python script. please guide me to write such python script with which i can log all server /client request and response. HTTPServer already logs the request - using sys.stderr, but you may override log_message() if you want: http://docs.python.org/library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.log_message If you want to log the response, do that in the request handler, a good place would be at the end of your do_GET() method above. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Archiving emails in Gmail
Hi, I have a requirement that I want to log-in into a gmail account read all unread mails, mark them as read and then archive them. I am using libgmail (version 0.1.11) library to do so, using which I am able to log-in into a gmail account fetch all unread message and then read them one by one. Now my problem is that I am not able to mark the unread mail as read and archive it. Below is sample code that I am using. from libgmail import * ARCHIVE_ACTION='rc_^i' #the action string to archive a message UNREAD_MAILS = is:unread def ArchiveAll(): ga = GmailAccount(name='username', pw='password') print 'logging in...', ga.login() print 'successful' def _getAllUnreadMails(): return ga.getMessagesByQuery(UNREAD_MAILS, True) def _readMail(email): emailData = ga.getRawMessage(email) def _archiveAndMarkRead(email): ga._doThreadAction(ARCHIVE_ACTION, email) ga._doThreadAction(U_MARKREAD_ACTION, email) emails = _getAllUnreadMails() for email in emails: eData = _readMail(email) #Process email data _archiveAndMarkRead(email) print 'done' if __name__ == '__main__': ArchiveAll() after executing this code I am getting following error HTTP Error 500: Internal Server Error Traceback (most recent call last): File test_libgmail.py, line 30, in module ArchiveAll() File test_libgmail.py, line 26, in ArchiveAll [_archiveAndMarkRead(t) for t in sr[1]] File test_libgmail.py, line 21, in _archiveAndMarkRead ga._doThreadAction(ARCHIVE_ACTION, thread) File /home/3rdparty/libgmail/libgmail.py, line 669, in _doThreadAction items = self._parsePage(_buildURL(**params)) File /home/3rdparty/libgmail/libgmail.py, line 383, in _parsePage items = _parsePage(self._retrievePage(urlOrRequest)) File /home/3rdparty/libgmail/libgmail.py, line 99, in _parsePage lines = pageContent.splitlines() AttributeError: 'NoneType' object has no attribute 'splitlines' Can anyone help me in figuring out what's going wrong here? I guess google has deprecated this way of marking emails, correct me if I am wrong here. But if its true, is there any other way or library in Python to meet my requirements? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: a +b ?
Ben Finney ben+pyt...@benfinney.id.au wrote: No, it wasn't clear at all. That's why I asked, rather than making assumptions. Thanks for clarifying. No problem. Thank you for another pleasant exchange. -- http://mail.python.org/mailman/listinfo/python-list
Re: File descriptor to file object
En Mon, 14 Jun 2010 11:57:20 -0300, Nathan Huesken pyt...@lonely-star.org escribió: tempfile.mkstemp returns a file name and a file descriptor (as returned by os.open). Can I somehow convert this descriptor to a file object? py import os py help(os.fdopen) Help on built-in function fdopen in module nt: fdopen(...) fdopen(fd [, mode='r' [, bufsize]]) - file_object Return an open file object connected to a file descriptor. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Community (A Modest Proposal)
On Mon, 14 Jun 2010 16:20:29 -0400, Terry Reedy wrote about IDLE: We are at once lucky to have a built in editor It is certainly a boon to someone like me who now only programs in Python and had no experience, let alone commitment to any of the current alternative. I know that lots of people swear by IDEs, and back in Ancient Days I used to use the THINK Pascal IDE on a Macintosh so I'm not hostile to the idea. But in those days you could only run one app at a time, so you needed an IDE or you'd go insane. These days I have an xterm open with a couple of tabs in one window, an editor open in the other, and it all Just Works. The only nuisance is when I get a traceback, I have to manually copy the line number from the terminal window and paste it into the Go To Line dialog in my editor, instead of the editor magically scrolling to the right line automatically. But other than that, I don't see the advantage of an IDE. What am I missing? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Archiving emails in Gmail
* teja, on 15.06.2010 09:03: Hi, I have a requirement that I want to log-in into a gmail account read all unread mails, mark them as read and then archive them. I am using libgmail (version 0.1.11) library to do so, using which I am able to log-in into a gmail account fetch all unread message and then read them one by one. Now my problem is that I am not able to mark the unread mail as read and archive it. Below is sample code that I am using. from libgmail import * ARCHIVE_ACTION='rc_^i' #the action string to archive a message UNREAD_MAILS = is:unread def ArchiveAll(): ga = GmailAccount(name='username', pw='password') print 'logging in...', ga.login() print 'successful' def _getAllUnreadMails(): return ga.getMessagesByQuery(UNREAD_MAILS, True) def _readMail(email): emailData = ga.getRawMessage(email) def _archiveAndMarkRead(email): ga._doThreadAction(ARCHIVE_ACTION, email) ga._doThreadAction(U_MARKREAD_ACTION, email) emails = _getAllUnreadMails() for email in emails: eData = _readMail(email) #Process email data _archiveAndMarkRead(email) print 'done' if __name__ == '__main__': ArchiveAll() after executing this code I am getting following error HTTP Error 500: Internal Server Error Traceback (most recent call last): File test_libgmail.py, line 30, inmodule ArchiveAll() File test_libgmail.py, line 26, in ArchiveAll [_archiveAndMarkRead(t) for t in sr[1]] In the code you show above there is no line [_archiveAndMarkRead(t) for t in sr[1]] Instead you have _archiveAndMarkRead(email) I tentatively conclude from this that the error is in your real code, as opposed to the code you've shown. File test_libgmail.py, line 21, in _archiveAndMarkRead ga._doThreadAction(ARCHIVE_ACTION, thread) File /home/3rdparty/libgmail/libgmail.py, line 669, in _doThreadAction items = self._parsePage(_buildURL(**params)) File /home/3rdparty/libgmail/libgmail.py, line 383, in _parsePage items = _parsePage(self._retrievePage(urlOrRequest)) File /home/3rdparty/libgmail/libgmail.py, line 99, in _parsePage lines = pageContent.splitlines() AttributeError: 'NoneType' object has no attribute 'splitlines' Can anyone help me in figuring out what's going wrong here? You're passing a None value. It originates somewhere in your real code, which it appears that you have not shown. I guess google has deprecated this way of marking emails, correct me if I am wrong here. But if its true, is there any other way or library in Python to meet my requirements? You can access GMail via an ordinary e-mail client. What's that called, POP protocol? I think the protocol for sending is SMTP. Any library handling those two protocols can be used. Cheers hth., - Alf, who, unfortunately, wrt. to your real code, is not a telepath :-) -- blog at url: http://alfps.wordpress.com -- http://mail.python.org/mailman/listinfo/python-list
Re: GUIs - A Modest Proposal
On Jun 15, 1:41 am, Stephen Hansen me+list/pyt...@ixokai.io wrote: On 6/14/10 9:08 PM, Stephen Hansen wrote: You're an *beep*. For the record, this was inappropriate. A moment's frustration after a long day does not excuse belligerence, even if unnecessarily provoked. I apologize. No problem Stephen, as you'll find out over time i have a skin much thicker than your average grape, unlike some folks round here. Unfortunately though the code showdown will need to be postponed until tomorrow. However my good friend Mark will be glad to know I just grabbed my comfort blanket and teddy, had a lovely glass of warm milk and some biscuits, and now mummy is tucking me up safely in bed. Kiss mummy goodnight Mark... :- ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie subprocess.Popen performance issues/questions
Chris Seberino wrote: I tried to use subprocess.Popen to make my web app do a bunch of stuff in separate processes today. It appeared like only the first one finished and/or the rest of the forked processes crashed. First thing to do would be to show us a little code and to look for the exit codes of your subprocess calls. Of course sub processes may crash of your os is running out of resources ( num of preocess, num of file handles, memory. . . . ) Not knowing your code and your OS it might also be, that you try to acccess a shared system resource, which can only be use once, Hard to say with that little info. you could also try to add logging your subprocessesor to log their stdout / stderr. I only have around 300Mb. Is it possible that my subprocess.Popen code was swapping to disk so much that most of the Popen processes just crashed? Are there any tools to monitor how much memory I should upgrade to and/ or what else would cause a subprocess.Popen symphony have problems? Sincerely, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Community (A Modest Proposal)
On Tue, Jun 15, 2010 at 5:30 PM, Steven D'Aprano steve-remove-t...@cybersource.com.au wrote: But other than that, I don't see the advantage of an IDE. What am I missing? You're not missing anything my dear watson :) I myself use vim (as my editor) and 2-3 Terminals on virtual workspaces (in my DE). I guess the beauty with vim is you just read the line no. type it in and hit ^G IDEs are over glorified IHMO and yes I've had my fair share of them with things like Delphi, Visual Basic, Visual Studio, and others... --James -- -- -- Problems are solved by method -- http://mail.python.org/mailman/listinfo/python-list
Re: First program
En Sat, 12 Jun 2010 06:03:43 -0300, Phil H skilp...@gmail.co.za escribió: Trying my hand with Python but have had a small hiccup. Reading 'A byte of Python' and created helloworld.py as directed. #!/usr/bin/python # filename : helloworld.py print 'Hello World' At the terminal prompt cd to the file location and run from the prompt. p...@grumpy:~/projects/python$ python helloworld.py Hello World All fine. Then I tried the following as described in the tutorial and get the following error p...@grumpy:~/projects/python$ chmod a+x helloworld.py p...@grumpy:~/projects/python$ ./helloworld.py bash: ./helloworld.py: /usr/bin/python^M: bad interpreter: No such file or directory The permissions are: rwxr-xr-x. Looks like you created helloworld.py on Windows, or using Windows-oriented tools (perhaps a samba drive? ftp from a Windows disk?) Windows text files end each line with the \r\n sequence (CR LF, bytes 0x0D 0x0A, ^M^J). Unix (and Linux) uses only a \n (LF, 0x0A). The \r will be read as part of the previous line then. There are tools to convert back and forth those formats (dos2unix and unix2dos, or the crlf.py demo script in the Python source distribution). But to avoid problems, it's better to use the right tools for the OS you're working with (that is, don't use notepad to edit Linux files...) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: subprocess.Popen()/call() and appending file
On Jun 14, 7:11 pm, Kushal Kumaran kushal.kumaran+pyt...@gmail.com wrote: On Mon, Jun 14, 2010 at 7:01 PM,hiralhiralsmaill...@gmail.com wrote: Hi, Do we have any facility to append file from Popen()/call(); see below example... 1 import subprocess 2 f=open('log', 'w') 3 ...# writing some log-into into log file 4 p = subprocess.Popen(cmd, stdout=f, stderr=f) # (Q) 5 ...# do remaining stuff Q: At line# 4, the output of the 'cmd' will wipe-out everything in 'log' file. So to avoid this do we have any mechanism to append into the existing file from subprocess. Currently I am doing following... p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) o, e = p.communicate() print log, o print log, e Pleaese let me know if there is any better mechanism. It is not actually wiping out the old contents. You might be running into buffering issues. Explicitly flushing should help when switching between the high level IO functions provided by file objects and the low level IO that subprocess uses. Do a f.flush() before your subprocess.Popen call. -- regards, kushal- Hide quoted text - - Show quoted text - Thanx it works fine. -- http://mail.python.org/mailman/listinfo/python-list
Does MS Office need to be installed to use pywin32 for editing Excel docs?
I'm creating excel docs on the fly using XLWT. However, I need to include filters which I believe can only be done with pywin32. Does pywin32 use elements from Windows itself, or excel when dispatching? -- http://mail.python.org/mailman/listinfo/python-list
Re: Does MS Office need to be installed to use pywin32 for editing Excel docs?
On 15/06/2010 09:32, Astley Le Jasper wrote: Does pywin32 use elements from Windows itself, or excel when dispatching? Yes: it's simply exposing to the Python user the API provided by MS Office (or whatever other app) via the IDispatch COM mechanism. IOW, if you don't have Microsoft Excel installed, this won't work: import win32com.client win32com.client.Dispatch (Excel.Application) TJG -- http://mail.python.org/mailman/listinfo/python-list
Linking to a Python static library.
Hi, I am trying to figure out, what files to copy with my app so I am able to initialize the python runtime. Where can I find information about this? Thank you, Filip -- http://mail.python.org/mailman/listinfo/python-list
Re: Does MS Office need to be installed to use pywin32 for editing Excel docs?
On Jun 15, 10:44 am, Tim Golden m...@timgolden.me.uk wrote: On 15/06/2010 09:32, Astley Le Jasper wrote: Does pywin32 use elements from Windows itself, or excel when dispatching? Yes: it's simply exposing to the Python user the API provided by MS Office (or whatever other app) via the IDispatch COM mechanism. IOW, if you don't have Microsoft Excel installed, this won't work: import win32com.client win32com.client.Dispatch (Excel.Application) TJG Hi Tim, Thanks for that. ALJ -- http://mail.python.org/mailman/listinfo/python-list
Re: Archiving emails in Gmail
Ohh my bad... thanks a lot for replying Alf.. The error which I've pasted above, was thrown before I modified the code a bit.. Here's the error thrown on running the code I've pasted above.. there's not much of a difference in the error though. HTTP Error 500: Internal Server Error Traceback (most recent call last): File test_libgmail.py, line 40, in module ArchiveAll() File test_libgmail.py, line 35, in ArchiveAll _archiveAndMarkRead(email) File test_libgmail.py, line 28, in _archiveAndMarkRead ga._doThreadAction(ARCHIVE_ACTION, email) File /home/3rdparty/test/libgmail/libgmail.py, line 670, in _doThreadAction items = self._parsePage(_buildURL(**params)) File /home/3rdparty/test/libgmail/libgmail.py, line 384, in _parsePage items = _parsePage(self._retrievePage(urlOrRequest)) File /home/3rdparty/test/libgmail/libgmail.py, line 99, in _parsePage lines = pageContent.splitlines() AttributeError: 'NoneType' object has no attribute 'splitlines' I tried to debug the issue here, when self._retrievePage(urlOrRequest) is called (it is called internally in libgmail) a 500 internal server error is thrown. And hence further processing on the response can not be done. I also caught the url which throws 500: https://mail.google.com/mail/?ui=1search=allt=129374b41acebfcdview=upat=act=rc_^i Now I don't know why 500 is thrown and on which side the exact problem lies, i.e. the libgmail side or the gmail side. And there's a email library provided in Python (supports both POP and SMTP) but I dont know whether it allows us to archive mails or mark them as read for that matter. -- http://mail.python.org/mailman/listinfo/python-list
biopython
i am waiting for the reply as i am unable to proceed...;( -- madhuri :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Linking to a Python static library.
On 06/15/2010 10:20 AM, F van der Meeren wrote: Hi, I am trying to figure out, what files to copy with my app so I am able to initialize the python runtime. Where can I find information about this? You need to link with libpython. How you do this depends on the toolchain you're using. Which build tool/IDE are you using? GNU auto{conf,make}? CMake? waf? Something else? Check the documentation of the tools you're using on how to use libraries - I don't think Python behaves any differently to other libraries. For information on how to initialize the interpreter in a program linked with -lpython, check the Extending/Embedding section on docs.python.org If you run into any problems along the way, don't hesitate to ask! Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: Archiving emails in Gmail
On 06/15/2010 11:07 AM, teja wrote: And there's a email library provided in Python (supports both POP and SMTP) but I dont know whether it allows us to archive mails or mark them as read for that matter. POP (the protocol) only allows downloading messages, AFAIK. SMTP is for sending. A more powerful e-mail protocol is IMAP, which gmail also supports. I don't know about Python libraries, you'll probably find a reasonably full-featured one, but IMAP supports marking messages as read. As for archiving, I'm guessing that this'd be implemented by moving messages to an archive folder. Maybe you should connect to gmail with an email client (Thunderbird is nice) via IMAP and check 1. whether you can archive mails from there 2. how exactly gmail archiving maps to IMAP and then implement it using IMAP, having your script just do the same thing you did in Thunderbird, WLM, Sylpheed, Mail.app, or whatever you're using. Have fun, Thomas -- http://mail.python.org/mailman/listinfo/python-list
[ANN] Robot Framework 2.5
Hello, Robot Framework [1] is a generic open source test automation framework for acceptance testing and acceptance test driven development (ATDD). It has an easy-to-use tabular syntax for creating test cases and its testing capabilities can be extended by test libraries implemented either with Python or Java. It utilizes the keyword-driven testing approach and supports also data-driven testing and behavior-driven development (BDD). For executable example test cases see the Quick Start Guide [2] and the SeleniumLibrary demo [3]. Robot Framework 2.5 was released last Thursday. The biggest new features are continuing execution on failure, stopping execution gracefully, named arguments, full support for Jython 2.5, and test templates to ease data-driven testing. The new features, fixed bugs, and backwards incompatible changes are listed in the release notes [4], and release packages are available on the download page [5]. [1] http://robotframework.org [2] http://code.google.com/p/robotframework/wiki/QuickStartGuide [3] http://code.google.com/p/robotframework-seleniumlibrary/wiki/Demo [4] http://code.google.com/p/robotframework/wiki/ReleaseNotes25 [5] http://code.google.com/p/robotframework/downloads/list Cheers, .peke -- Agile Tester/Developer/Consultant :: http://eliga.fi Lead Developer of Robot Framework :: http://robotframework.org -- http://mail.python.org/mailman/listinfo/python-list
Re: First program
On Tue, 15 Jun 2010 04:53:52 -0300, Gabriel Genellina wrote: Looks like you created helloworld.py on Windows, or using Windows-oriented tools (perhaps a samba drive? ftp from a Windows disk?) Windows text files end each line with the \r\n sequence (CR LF, bytes 0x0D 0x0A, ^M^J). Unix (and Linux) uses only a \n (LF, 0x0A). The \r will be read as part of the previous line then. There are tools to convert back and forth those formats (dos2unix and unix2dos, or the crlf.py demo script in the Python source distribution). But to avoid problems, it's better to use the right tools for the OS you're working with (that is, don't use notepad to edit Linux files...) Thanks. See replies above. Used Gedit and ubuntu but saved in wrong format (there is a choice and I didn't know better). -- http://mail.python.org/mailman/listinfo/python-list
Re: Community (A Modest Proposal)
On Tue, 15 Jun 2010 17:45:43 +1000 James Mills prolo...@shortcircuit.net.au wrote: I myself use vim (as my editor) and 2-3 Terminals on virtual workspaces (in my DE). I guess the beauty with vim is you just read the line no. type it in and hit ^G You mean just G (Shift+g), right? ^G (Ctrl+G) prints the file name and cursor position. Incidentally, :linenumberReturn does the same as linenumberG. Sorry, that's seriously OT, but think about the havoc this could wreak if some uninformed layperson read this and took it to heart. ;) /W -- INVALID? DE! -- http://mail.python.org/mailman/listinfo/python-list
Re: Community (A Modest Proposal)
IDEs are seriously over-rated. Vim FTW. The only issue for beginners is they should know touch typing to fully utilize Vim and the initial curve is a bit high as compared to normal editors/IDEs. On Tue, Jun 15, 2010 at 4:16 PM, Andreas Waldenburger use...@geekmail.invalid wrote: On Tue, 15 Jun 2010 17:45:43 +1000 James Mills prolo...@shortcircuit.net.au wrote: I myself use vim (as my editor) and 2-3 Terminals on virtual workspaces (in my DE). I guess the beauty with vim is you just read the line no. type it in and hit ^G You mean just G (Shift+g), right? ^G (Ctrl+G) prints the file name and cursor position. Incidentally, :linenumberReturn does the same as linenumberG. Sorry, that's seriously OT, but think about the havoc this could wreak if some uninformed layperson read this and took it to heart. ;) /W -- INVALID? DE! -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: GUIs - A Modest Proposal
In article 80a7b823-6acb-4ac9-a273-525054265...@k25g2000prh.googlegroups.com, ant shi...@uklinux.net wrote: SNIP My concern is simple: I think that Python is doomed to remain a minor language unless we crack this problem. Capitalist fallacy: If I'm not a market leader, I'm a failure and my Mother will laugh at me. Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. alb...@spearc.xs4all.nl =n http://home.hccnet.nl/a.w.m.van.der.horst -- http://mail.python.org/mailman/listinfo/python-list
Re: a +b ?
Ben Finney ben+pyt...@benfinney.id.au wrote: It should go without saying, but unfortunately the tenor of this forum has been worsened (temporarily, I hope) by certain interminable threads of late. So, to be clear: Thanks for clarifying that you were not expressing the attitude I inferred. Ah, crap, I didn't see this until now. I _did_ take the wrong meaning from it and unfortunately replied accordingly :| So please take this as a sincere apology (laced with relief that I wasn't anything more than curt in the response). I hold some pretty strong views on epistemology and individuals' capacity for learning which haven't been meshing well with the modest proposals and crowdsourcing of project work which seems to be taking up more of this list all the time. So it's probably a good idea to take a break. A friend has been encouraging me to learn io, so now might be the time :) Sorry again, Ben. You're generally one of the more level-header posters to the list and I should have given you more credit (or better, just opted not to reply). Cheers, alex -- http://mail.python.org/mailman/listinfo/python-list
Re: The Python Web Authoring and Application Pages
Travis, Great job - thanks for sharing your research! Note: you may want to add cherrypy.org to your framework page. This is an excellent, light weight, template agnostic framework. Turbogears runs on top of CherryPy. Malcolm -- http://mail.python.org/mailman/listinfo/python-list
pythonize this!
goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) my solution: s = 0 for i in range(1, 2011): ... s += i**2 ... if not (i+1)%5: ... s -= 2*i**2 ... if not i%5: ... s -= 2*i**2 ... print s 536926141 bye -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
On 15 June 2010 21:49, superpollo ute...@esempio.net wrote: goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) Obligatory one-liner: sum((1, 1, 1, -1, -1)[(x-1) % 5] * x**2 for x in xrange(1, 2011)) 536926141 Cheers, Xav -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
superpollo wrote: ... s += i**2 ... if not (i+1)%5: ... s -= 2*i**2 ... if not i%5: ... s -= 2*i**2 if not (i % 5) in [1, 2]: s += i**2 else: s -= i**2 Untested code. Uli -- Sator Laser GmbH Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 -- http://mail.python.org/mailman/listinfo/python-list
Python Library Win7 -64 Bit
Dear All, Before I start, I'm aware of how much of a nightmare MSys and MINGW are in comparison to UNIX/Linux environments, I'm a casual Ubuntu user myself and I wouldn't go near Windows if I didn't have to. I'm trying to install the Python LibXML2 extensions onto my 64 bit Cython 2.6 setup under Windows 7. When I do a python setup.py build -c mingw32, everything starts off fine and the compilation begins. Distutils then returns complaining that most of the Python symbols (e.g. _imp_Py_NoneStruct and _imp_PyArg_ParseTuple) are undefined. This lead me to assume that the linker on my platform can't find a python library to link against. Sure enough, I looked through my build path and couldn't find libpython26.dll or libpython26.a anywhere. I managed to get hold of a libpython26 shared library file (I think I found it in my System32 folder) and copied it to C:\Python26\libs which is one of the directories on my gcc search path. However, I'm still getting the same rubbish about not all the python symbols being undefined. Has anyone had any prior experience with this sort of problem or can anyone point me in the right direction? The only solution I could come up with was to compile python itself from scratch which, even on a high end desktop, takes hours and hours and hours... (etc) on an Msys setup. Thanks, James Ravenscroft Funky Monkey Software james (at) funkymonkeysoftware (dot) com -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
superpollo, 15.06.2010 13:49: goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) my solution: s = 0 for i in range(1, 2011): ... s += i**2 ... if not (i+1)%5: ... s -= 2*i**2 ... if not i%5: ... s -= 2*i**2 Pretty ugly, if you ask me. What about this: s = 0 for i in range(1, 2011): if i%5 in (1,2,3): s += i**2 else: s -= i**2 Here's the obvious one-liner: s = sum(i**2 if i%5 in (1,2,3) else -i**2 for i in range(1, 2011)) Runs in ~600 usecs for me according to timeit - pretty fast. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: GUIs - A Modest Proposal
On 15/06/2010 08:39, rantingrick wrote: On Jun 15, 1:41 am, Stephen Hansenme+list/pyt...@ixokai.io wrote: On 6/14/10 9:08 PM, Stephen Hansen wrote: You're an *beep*. For the record, this was inappropriate. A moment's frustration after a long day does not excuse belligerence, even if unnecessarily provoked. I apologize. No problem Stephen, as you'll find out over time i have a skin much thicker than your average grape, unlike some folks round here. Unfortunately though the code showdown will need to be postponed until tomorrow. However my good friend Mark will be glad to know I just grabbed my comfort blanket and teddy, had a lovely glass of warm milk and some biscuits, and now mummy is tucking me up safely in bed. Kiss mummy goodnight Mark... :- ;-) With friends like you, who needs enemies? -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
superpollo ute...@esempio.net writes: goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) my solution: s = 0 for i in range(1, 2011): ... s += i**2 ... if not (i+1)%5: ... s -= 2*i**2 ... if not i%5: ... s -= 2*i**2 You compute i**2 too many times (7/5 times more than necessary) and twice too many modulos. I suggest: c = { 0:1, 1:1, 2:1, 3:-1, 4:-1 } #or, why not: c = lambda i : +1 if (i%5) 3 else -1 s = 0 for i in range(1,2011): s += c[(i-1)%5]*(i**2) print s Or, as a one liner using a list comprehension: print sum( ( c[(i-1)%5]*i**2 for i in xrange(1,2011) ) ) I don't know which one is the fastest (between dict+loop, dict+compr, lambda+loop and lambda+compr). -- Alain. -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
Ulrich Eckhardt ha scritto: superpollo wrote: ... s += i**2 ... if not (i+1)%5: ... s -= 2*i**2 ... if not i%5: ... s -= 2*i**2 if not (i % 5) in [1, 2]: s += i**2 else: s -= i**2 Untested code. does not work: s = 0 for i in range(1, 2011): ... if not (i % 5) in [1, 2]: ... s += i**2 ... else: ... s -= i**2 ... print s 546627205 but this does: s = 0 for i in range(1, 2011): ... if i % 5 in [1, 2, 3]: ... s += i**2 ... else: ... s -= i**2 ... print s 536926141 bye -- http://mail.python.org/mailman/listinfo/python-list
Re: a +b ?
alex23 wuwe...@gmail.com writes: Ben Finney ben+pyt...@benfinney.id.au wrote: Thanks for clarifying that you were not expressing the attitude I inferred. Ah, crap, I didn't see this until now. I _did_ take the wrong meaning from it and unfortunately replied accordingly :| So please take this as a sincere apology (laced with relief that I wasn't anything more than curt in the response). All's well. I'll raise a glass now for well-tempered discussion to resume in this forum soon. -- \“Our wines leave you nothing to hope for.” —restaurant menu, | `\ Switzerland | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: GUIs - A Modest Proposal
Stephen Hansen wrote: unless I've been long mistaken in pack not having a proportional option. A combination of fill/expand and anchor do most of everything else, though, that wx's flags and alignment options. It's a while since I used tkinter, but if I recall correctly, the grid manager does allow proportional resizing. And you really don't need pack, you can use grid to do anything that pack can do. Having said that, experience has made me very skeptical about the usefulness of proportional resizing. Most often, there is one main content area in a window that I want to give the user control over the size of, and the other stuff around it can just as well be fixed size. When that's not true, proportional sizing doesn't really cut it -- you really need some kind of splitter control to let the user adjust the allocation of space according to the needs of the moment. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
superpollo writes: goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) my solution: s = 0 for i in range(1, 2011): ... s += i**2 ... if not (i+1)%5: ... s -= 2*i**2 ... if not i%5: ... s -= 2*i**2 ... print s 536926141 bye Me two: s = 0 for k in range(1, 2010, 5): s += k**2 + (k + 1)**2 + (k + 2)**2 - (k + 3)**2 - (k + 4)**2 s = 0 for k in range(1, 2011): s += k**2 * (-1 if k % 5 in {4,0} else +1) -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
superpollo wrote: goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) from itertools import cycle, izip sum(sign*i*i for sign, i in izip(cycle([1]*3+[-1]*2), range(1, 2011))) 536926141 -- http://mail.python.org/mailman/listinfo/python-list
Different byte-code in same major version (2.6.x)?
Hi, I'm facing a curious problem: 2.6, 2.6.1 and 2.6.4 are generating different byte-code for the same source. I can not find the reason for. As you may know, I'm providing the 'decompyle' service as www.crazy-comnpilers.com. This service includes verification of the source against the original byte code. So I need to solve these kind of differences. This is the source: e.args += ('xxx',) While Python 2.6 (r26:66714, Oct 24 2008, 17:31:07) and Python 2.6.4 (r264:75706, Jan 8 2010, 18:50:31) both optimize the source and load a tuple constant, LOAD_NAME 'e' DUP_TOP LOAD_ATTR 'args' # load a tuple constant LOAD_CONST('xxx',) INPLACE_ADD ROT_TWO STORE_ATTR'args' Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin does *not* optimize: LOAD_NAME 'e' DUP_TOP LOAD_ATTR 'args' # load a string an build a tuple LOAD_CONST'xxx' BUILD_TUPLE_1 INPLACE_ADD ROT_TWO STORE_ATTR'args' I checked the source in SVN and did not find any change here. But why does this 2.6.1 generate different byte-code then? Is there anything special about the Darwin-Build? -- Regards Hartmut Goebel | Hartmut Goebel | h.goe...@crazy-compilers.com | | www.crazy-compilers.com | compilers which you thought are impossible | -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
Peter Otten ha scritto: superpollo wrote: goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) from itertools import cycle, izip sum(sign*i*i for sign, i in izip(cycle([1]*3+[-1]*2), range(1, 2011))) 536926141 don't understand it bit i like this a lot! -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
superpollo ha scritto: Peter Otten ha scritto: superpollo wrote: goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) from itertools import cycle, izip sum(sign*i*i for sign, i in izip(cycle([1]*3+[-1]*2), range(1, 2011))) 536926141 don't understand it bit i like this a lot! ^^^ *but* -- http://mail.python.org/mailman/listinfo/python-list
Re: GUIs - A Modest Proposal
On Jun 14, 9:00 pm, Stephen Hansen me+list/pyt...@ixokai.io wrote: On 6/14/10 1:00 PM, lkcl wrote: what we typically recommend is that _even_ though you're going to run the application desktop - as pure python - you still use JSONRPC [or XmlHTTPRequest if JSONRPC is overkill]. so, _even_ though it's a desktop application, you still run a local 127.0.0.1 web service (even python -m SimpleCGIServer.py will do the job!) rick's article is highly illustrative on all these points: http://www.ibm.com/developerworks/web/library/wa-aj-pyjamas/ Hmm. Depending on just how rich of a UI is possible, this is a slightly compelling idea. to be honest, if you don't put any effort in to use the appropriate lovely-prettiness panels you can end up with something truly 90s- esque. but with a little effort you can do round-edged lovely colour tabs: http://pyjs.org/examples/tabpanelwidget/output/Tabs.html Right now, I have to essentially maintain two separate code-bases: the desktop client and the web application. deep joy! In my scenario, both are actually lightweight (though not truly thin) clients to a master application server existing Elsewhere, that does the heavy lifting and manages all its users. Being able to take a code base and provide it to users as a traditional-seeming desktop application that works desktopy for them, with-- it sounds like-- two separate processes, one which is Python and is serving data, and more importantly accessing the MCP and getting instructions and doing its lightweight local lifting-- and another which is just a UI that communicates to that local server? basically, yes. splitting things more along the traditional MVC lines. the M being the web server with JSONRPC to do traditional Create-Update-Retrieve-Delete etc. and the VC bit being in pyjamas, talking JSONRPC to the server *even* on the desktop version! Then one would run basically the same code on a server to allow remote access on some internet-accessible server, that sounds like what you're implying is possible? yes, even on the desktoppy version (because it's the same app) This time the server is still there, but the client UI is converted into pure JS and shipped to the persons machine. yup. That sounds too good to be true. yup, it does. how can one person, a free software developer, have come up with something like The Holy Grail of software development, right? when all the money in the world, from ibm, adobe, microsoft, google, nokia and so on _hasn't_ managed it, in what... 20 years of computer science, right? i must be some sort of egomaniac, attention- seeker, snake-oil-seller or just an outright liar, right? those _are_ supposed to be rhetorical questions :) I sort of have to be reading too much into what you're saying. no, you got it. does what it says on the tin. the fly in the ointment is that the success of pyjamas desktop is critically dependent on its underlying DOM-bindings technology. ironically, the non-free and proprietary dependence on MSHTML works perfectly, whilst there are webkit developers *actively* destroying the webkit-glib/gobject port, and the mozilla foundation developers are trying desperately hard to break XPCOM (they've already side-lined python-xpcom as third party now) because they're so losing so badly to webkit that they are desperate to sacrifice everything to get speed, speed, speed. l. -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
Stefan Behnel, 15.06.2010 14:23: superpollo, 15.06.2010 13:49: goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) my solution: s = 0 for i in range(1, 2011): ... s += i**2 ... if not (i+1)%5: ... s -= 2*i**2 ... if not i%5: ... s -= 2*i**2 Pretty ugly, if you ask me. What about this: s = 0 for i in range(1, 2011): if i%5 in (1,2,3): s += i**2 else: s -= i**2 Here's the obvious one-liner: s = sum(i**2 if i%5 in (1,2,3) else -i**2 for i in range(1, 2011)) Runs in ~600 usecs for me according to timeit - pretty fast. Just for the record, this Cython code runs in ~15 usecs for me: def makesum(): return intsum(i**2 if i%5 in (1,2,3) else -i**2 for i in range(1, 2011)) using the latest Cython 0.13pre. The int cast is required to drop the sum() into efficient C code. Without it, the code runs in 55 usecs. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: GUIs - A Modest Proposal
lkcl ha scritto: ... That sounds too good to be true. yup, it does. how can one person, a free software developer, have come up with something like The Holy Grail of software development, right? when all the money in the world, from ibm, adobe, microsoft, google, nokia and so on _hasn't_ managed it, in what... 20 years of computer science, right? i must be some sort of egomaniac, attention- seeker, snake-oil-seller or just an outright liar, right? those _are_ supposed to be rhetorical questions :) I sort of have to be reading too much into what you're saying. no, you got it. does what it says on the tin. mind you, i am no python expert, but i really look forward to seeing pyjamas in the stdlib :-) anytime soon? bye -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
On 15 June 2010 22:55, superpollo ute...@esempio.net wrote: Peter Otten ha scritto: superpollo wrote: goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) from itertools import cycle, izip sum(sign*i*i for sign, i in izip(cycle([1]*3+[-1]*2), range(1, 2011))) 536926141 don't understand it bit i like this a lot! Peter's solution is really identical as mine, except he used a generator and I used a modulo operator. Cheers, Xav -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
On 06/15/2010 01:49 PM, superpollo wrote: my solution: [...] print s 536926141 Or, if you would like to use numpy: import numpy squares = numpy.arange(1, 2011, dtype=numpy.int)**2 signs = numpy.ones(len(squares), dtype=numpy.int) signs[3::5] = -1 signs[4::5] = -1 numpy.sum(signs*squares) 536926141 Cheers Andre -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
superpollo wrote: superpollo ha scritto: Peter Otten ha scritto: superpollo wrote: goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) from itertools import cycle, izip sum(sign*i*i for sign, i in izip(cycle([1]*3+[-1]*2), range(1, 2011))) 536926141 don't understand it bit i like this a lot! ^^^ *but* Works for women as well, we don't understand them, yet we love them ;) JM -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
sum(i*i*(-1)**((i % 5) / 4 + (i + 4) % 5 / 4) for i in range(1,2011)) 536926141 On Tue, Jun 15, 2010 at 6:25 PM, superpollo ute...@esempio.net wrote: superpollo ha scritto: Peter Otten ha scritto: superpollo wrote: goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) from itertools import cycle, izip sum(sign*i*i for sign, i in izip(cycle([1]*3+[-1]*2), range(1, 2011))) 536926141 don't understand it bit i like this a lot! ^^^ *but* -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
superpollo, 15.06.2010 14:55: Peter Otten ha scritto: superpollo wrote: goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) from itertools import cycle, izip sum(sign*i*i for sign, i in izip(cycle([1]*3+[-1]*2), range(1, 2011))) 536926141 don't understand it bit i like this a lot! Didn't you want to get it pythonized? If it's not understandable, it can't be pythonic. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Community (A Modest Proposal)
On 06/15/2010 01:30 AM, Steven D'Aprano wrote: I know that lots of people swear by IDEs, and back in Ancient Days I used to use the THINK Pascal IDE on a Macintosh so I'm not hostile to the idea. But in those days you could only run one app at a time, so you needed an IDE or you'd go insane. These days I have an xterm open with a couple of tabs in one window, an editor open in the other, and it all Just Works. The only nuisance is when I get a traceback, I have to manually copy the line number from the terminal window and paste it into the Go To Line dialog in my editor, instead of the editor magically scrolling to the right line automatically. But other than that, I don't see the advantage of an IDE. What am I missing? In some languages, due to the size and complexity of the libraries, an IDE is essential. Java is one of those languages. C++ development also highly benefits. Any compiled language also benefits from the project management and build management tools that an IDE provides. Project and build management and code completion are the killer features of IDEs. Vim has some code completion, but it's nowhere as easy to use or complete as in Visual Studio. With python I can usually get away with one interactive python session, a vim editor, my Python in a nutshell book, and the python.org docs. That's largely because python's standard libraries have help strings, and python lets you navigate the live object space. Also it helps that Python's libraries don't get hung up quite so much on patterns and LongDescriptiveNames. -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
Stefan Behnel ha scritto: superpollo, 15.06.2010 14:55: Peter Otten ha scritto: superpollo wrote: goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) from itertools import cycle, izip sum(sign*i*i for sign, i in izip(cycle([1]*3+[-1]*2), range(1, 2011))) 536926141 don't understand it bit i like this a lot! Didn't you want to get it pythonized? If it's not understandable, it can't be pythonic. maybe i must study itertools then ;-) thanks bye -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
Stefan Behnel wrote: superpollo, 15.06.2010 14:55: Peter Otten ha scritto: superpollo wrote: goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) from itertools import cycle, izip sum(sign*i*i for sign, i in izip(cycle([1]*3+[-1]*2), range(1, 2011))) 536926141 don't understand it bit i like this a lot! Didn't you want to get it pythonized? If it's not understandable, it can't be pythonic. I'm glad I didn't have to say that mayself ;) OP: You can work it out step by step: First build a list of signs: [1]*3+[-1]*2 [1, 1, 1, -1, -1] Then repeat them infinitely: c = cycle(xy) c.next() 'x' c.next() 'y' c.next() 'x' c.next() 'y' c.next() 'x' Combine with the bases using izip: signs = cycle([1]*3+[-1]*2) [sign*i for sign, i in izip(signs, range(10))] [0, 1, 2, -3, -4, 5, 6, 7, -8, -9] Finally calculate the sum: signs = cycle([1]*3+[-1]*2) sum(sign*i for sign, i in izip(signs, range(10))) -3 Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Community (A Modest Proposal)
On 2010-06-15, Steven D'Aprano steve-remove-t...@cybersource.com.au wrote: On Mon, 14 Jun 2010 16:20:29 -0400, Terry Reedy wrote about IDLE: We are at once lucky to have a built in editor It is certainly a boon to someone like me who now only programs in Python and had no experience, let alone commitment to any of the current alternative. I know that lots of people swear by IDEs, and back in Ancient Days I used to use the THINK Pascal IDE on a Macintosh so I'm not hostile to the idea. But in those days you could only run one app at a time, so you needed an IDE or you'd go insane. These days I have an xterm open with a couple of tabs in one window, an editor open in the other, and it all Just Works. The only nuisance is when I get a traceback, I have to manually copy the line number from the terminal window and paste it into the Go To Line dialog in my editor, instead of the editor magically scrolling to the right line automatically. But other than that, I don't see the advantage of an IDE. What am I missing? You got me. I tend to type the line number rather than cut/paste, but I too have tried IDEs and found them cumbersome. It's Emacs and a couple xterms for me. I do recommend an editor with syntax highlighting and indentation tools. -- Grant Edwards grant.b.edwardsYow! Why is everything made at of Lycra Spandex? gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Library Win7 -64 Bit
On 06/15/2010 02:03 PM, James Ravenscroft wrote: Dear All, Before I start, I'm aware of how much of a nightmare MSys and MINGW are in comparison to UNIX/Linux environments, I'm a casual Ubuntu user myself and I wouldn't go near Windows if I didn't have to. I'm trying to install the Python LibXML2 extensions onto my 64 bit Cython 2.6 setup under Windows 7. When I do a python setup.py build -c mingw32, everything starts off fine and the compilation begins. Distutils then returns complaining that most of the Python symbols (e.g. _imp_Py_NoneStruct and _imp_PyArg_ParseTuple) are undefined. This lead me to assume that the linker on my platform can't find a python library to link against. Sure enough, I looked through my build path and couldn't find libpython26.dll or libpython26.a anywhere. I managed to get hold of a libpython26 shared library file (I think I found it in my System32 folder) and copied it to C:\Python26\libs which is one of the directories on my gcc search path. However, I'm still getting the same rubbish about not all the python symbols being undefined. My guess would be that you're compiling for the wrong architecture. Does your mingw compiler produce 64-bit binaries? (the 32 in mingw32 would suggest otherwise) Debian GNU/Linux has mingw-w64 package, I'd expect there to be a native analogue on windows. Thomas Has anyone had any prior experience with this sort of problem or can anyone point me in the right direction? The only solution I could come up with was to compile python itself from scratch which, even on a high end desktop, takes hours and hours and hours... (etc) on an Msys setup. Thanks, James Ravenscroft Funky Monkey Software james (at) funkymonkeysoftware (dot) com -- http://mail.python.org/mailman/listinfo/python-list
Re: Archiving emails in Gmail
On 2010-06-15, teja tejasko...@gmail.com wrote: I have a requirement that I want to log-in into a gmail account read all unread mails, mark them as read and then archive them. I am using libgmail (version 0.1.11) library to do so, using which I am able to log-in into a gmail account fetch all unread message and then read them one by one. Now my problem is that I am not able to mark the unread mail as read and archive it. I don't know what libgmail is, but I use IMAP for stuff like that (with Gmail and other servers). Python's imaplib is a bit low-level (and IMAP sucks rather badly as a protocol), so you might want to take a look at imaplib2. http://docs.python.org/library/imaplib.html http://www.janeelix.com/piers/python/imaplib.html -- Grant Edwards grant.b.edwardsYow! Was my SOY LOAF left at out in th'RAIN? It tastes gmail.comREAL GOOD!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Different byte-code in same major version (2.6.x)?
On 06/15/2010 02:54 PM, Hartmut Goebel wrote: Hi, I'm facing a curious problem: 2.6, 2.6.1 and 2.6.4 are generating different byte-code for the same source. I can not find the reason for. As you may know, I'm providing the 'decompyle' service as www.crazy-comnpilers.com. This service includes verification of the source against the original byte code. So I need to solve these kind of differences. Do you know for certain that these builds were all compiled from the vanilla python.org source? If the builds were created by different distributors, patches might have been added, and these patches might affect the byte-code generated. This is the source: e.args += ('xxx',) While Python 2.6 (r26:66714, Oct 24 2008, 17:31:07) and Python 2.6.4 (r264:75706, Jan 8 2010, 18:50:31) both optimize the source and load a tuple constant, LOAD_NAME 'e' DUP_TOP LOAD_ATTR 'args' # load a tuple constant LOAD_CONST('xxx',) INPLACE_ADD ROT_TWO STORE_ATTR'args' Python 2.6.1 (r261:67515, Jul 7 2009, 23:51:51) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin does *not* optimize: LOAD_NAME 'e' DUP_TOP LOAD_ATTR 'args' # load a string an build a tuple LOAD_CONST'xxx' BUILD_TUPLE_1 INPLACE_ADD ROT_TWO STORE_ATTR'args' I checked the source in SVN and did not find any change here. But why does this 2.6.1 generate different byte-code then? Is there anything special about the Darwin-Build? -- http://mail.python.org/mailman/listinfo/python-list
Re: Archiving emails in Gmail
On 15/06/2010 15:10, Grant Edwards wrote: On 2010-06-15, tejatejasko...@gmail.com wrote: I have a requirement that I want to log-in into a gmail account read all unread mails, mark them as read and then archive them. I am using libgmail (version 0.1.11) library to do so, using which I am able to log-in into a gmail account fetch all unread message and then read them one by one. Now my problem is that I am not able to mark the unread mail as read and archive it. I don't know what libgmail is, but I use IMAP for stuff like that (with Gmail and other servers). Python's imaplib is a bit low-level (and IMAP sucks rather badly as a protocol), so you might want to take a look at imaplib2. http://docs.python.org/library/imaplib.html http://www.janeelix.com/piers/python/imaplib.html Or imapclient: http://imapclient.freshfoo.com/ TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: newbie subprocess.Popen performance issues/questions
On Jun 15, 2:44 am, News123 news1...@free.fr wrote: ChrisSeberinowrote: I tried to use subprocess.Popen to make my web app do a bunch of stuff in separate processes today. It appeared like only the first one finished and/or the rest of the forked processes crashed. First thing to do would be to show us a little code and to look for the exit codes of your subprocess calls. OK I've appended the 236 line Python script below that gets invoked with Popen asynchronously. In summary what it does is set up a web site with a hosting provider. That involves using modules (Mechanize and Selenium) that literally launch browsers and simulate mouse and keyboard actions to get the job done. Furthermore, Expect scripts are launched that copy code and SSH to remote accounts to do other work. Is any of that I just mentioned especially troublesome in a Popen process? # hosting company set up script import sys import os sys.path.append(os.path.dirname(__file__) + /../selenium) import selenium import mechanize import subprocess import smtplib import re HOSTMONSTER_URL = https://www.hostmonster.com; SELENIUM_PORT = SUCCESS_DOMAIN = Successfully assigned _DOMAIN_ as addon domain SUCCESS_DB = 'pAdded the databasenbsp;span class=status\w +_DB_/sp' TIMEOUT = 12 WP_DIR = os.path.dirname(__file__) + /wordpress # Get the inputs. user_name = sys.argv[1] cpanel_password = sys.argv[2] primary_domain= sys.argv[3] wp_admin_password = sys.argv[4] wp_admin_email= sys.argv[5] wp_db_password= sys.argv[6] wp_akismet_key= sys.argv[7] wp_adsense_id = sys.argv[8] title = sys.argv[9] description = sys.argv[10] keywords = sys.argv[11] domain= sys.argv[12] post_title= sys.argv[13] post_text = sys.argv[14] theme = sys.argv[15] auto_log = sys.argv[16] # Initialize the output variable. output = # Initialize the Mechanize browser. browser = mechanize.Browser() # Perform authentication for the Mechanize browser. browser.open(HOSTMONSTER_URL + /cgi-bin/cplogin) browser.select_form(l_login_form) browser[ldomain] = user_name browser[lpass] = cpanel_password response = browser.submit() browser.open(response.geturl()) browser.select_form(the_form) response = browser.submit() # Go to the databases page. browser.open(response.geturl()) link = browser.find_link(text_regex = ^MySQL.*Databases$) response = browser.follow_link(link) browser.open(response.geturl()) # Create the database and log a report. database = domain.replace(., ) browser.select_form(mainform) browser[db] = database response = browser.submit() success_db= SUCCESS_DB.replace(_DB_, database) if re.search(success_db, response.get_data()): output += domain + database creation: SUCCESS + \n else: output += domain + database creation: FAIL + \n open(auto_log, a).write(output.split(\n)[-2]) # Close the Mechanize browser. browser.close() # Initialize the Selenium browser. (Hostmonster) browser = selenium.selenium(localhost, SELENIUM_PORT, *chrome, HOSTMONSTER_URL) browser.start() # Perform authentication for the Selenium browser. (HostMonster) browser.open(/cgi/hosting/assign) browser.type(ldomain, user_name) browser.type(lpass, cpanel_password) browser.click(//inp...@value = 'LOGIN']) browser.wait_for_page_to_load(TIMEOUT) # Assign the domain and log a report. browser.type(domain, domain) browser.type(dir,domain) browser.type(sub,domain.replace(., -)) browser.click(//inp...@value = 'Add Domain']) browser.wait_for_page_to_load(TIMEOUT) success_domain = SUCCESS_DOMAIN.replace(_DOMAIN_, domain) if success_domain in browser.get_html_source(): output += domain + domain assignment: SUCCESS + \n else: output += domain + domain assignment: FAIL + \n open(auto_log, a).write(output.split(\n)[-2]) # Close the Selenium browser. (Hostmonster) browser.stop() # Initialize the WordPress instance and log a report. expect_output = subprocess.Popen([WP_DIR + /wp_rsync_expect, user_name, cpanel_password, primary_domain], stdout = subprocess.PIPE, stderr = subprocess.STDOUT).communicate()[0] expect_output += subprocess.Popen([WP_DIR + /wp_set_up_expect, user_name, cpanel_password, primary_domain, wp_db_password, domain, theme], stdout = subprocess.PIPE, stderr = subprocess.STDOUT).communicate()[0] if expect_output.strip().endswith(SUCCESS): output += domain +
Re: GUIs - A Modest Proposal
On Tue, 15 Jun 2010 05:57:13 -0700, lkcl wrote: to be honest, if you don't put any effort in to use the appropriate lovely-prettiness panels you can end up with something truly 90s- esque. but with a little effort you can do round-edged lovely colour tabs: http://pyjs.org/examples/tabpanelwidget/output/Tabs.html All I get is a plain page with no content. No images, no text, nothing. Shouldn't you at least include This site requires Javascript to work? You know, I like the idea of pyjamas, but I am so utterly sick and tired of javascript and flash running amok and web developers who try to take over my browser that I've turned them off. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Archiving emails in Gmail
On 2010-06-15, Tim Golden m...@timgolden.me.uk wrote: On 15/06/2010 15:10, Grant Edwards wrote: On 2010-06-15, tejatejasko...@gmail.com wrote: I have a requirement that I want to log-in into a gmail account read all unread mails, mark them as read and then archive them. I am using libgmail (version 0.1.11) library to do so, using which I am able to log-in into a gmail account fetch all unread message and then read them one by one. Now my problem is that I am not able to mark the unread mail as read and archive it. I don't know what libgmail is, but I use IMAP for stuff like that (with Gmail and other servers). Python's imaplib is a bit low-level (and IMAP sucks rather badly as a protocol), so you might want to take a look at imaplib2. http://docs.python.org/library/imaplib.html http://www.janeelix.com/piers/python/imaplib.html Or imapclient: http://imapclient.freshfoo.com/ That looks promising though it's still a bit incomplete (e.g. doesn't support 'idle' or 'examine' commands). But, for simple apps it looks like a good options. -- Grant Edwards grant.b.edwardsYow! What UNIVERSE is this, at please?? gmail.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Archiving emails in Gmail
On 15/06/2010 16:15, Grant Edwards wrote: On 2010-06-15, Tim Goldenm...@timgolden.me.uk wrote: On 15/06/2010 15:10, Grant Edwards wrote: On 2010-06-15, tejatejasko...@gmail.com wrote: I have a requirement that I want to log-in into a gmail account read all unread mails, mark them as read and then archive them. I am using libgmail (version 0.1.11) library to do so, using which I am able to log-in into a gmail account fetch all unread message and then read them one by one. Now my problem is that I am not able to mark the unread mail as read and archive it. I don't know what libgmail is, but I use IMAP for stuff like that (with Gmail and other servers). Python's imaplib is a bit low-level (and IMAP sucks rather badly as a protocol), so you might want to take a look at imaplib2. http://docs.python.org/library/imaplib.html http://www.janeelix.com/piers/python/imaplib.html Or imapclient: http://imapclient.freshfoo.com/ That looks promising though it's still a bit incomplete (e.g. doesn't support 'idle' or 'examine' commands). But, for simple apps it looks like a good options. I think that sums it up fairly well. I've used it for doing various things with my personal email (generating whitelists etc.). It is actively maintained by its owner Menno Smits and lately by Mark Hammond, but presumably only so far as their own requirements demand. TJG -- http://mail.python.org/mailman/listinfo/python-list
logging = logging.getLogger(__name__)
Newbie here. I may be missing something obvious, in which case, please feel free to berate and laugh at me. Here's a dubious line of code: logging = logging.getLogger(__name__) How can I refer to the original logging package logging after this statement is run? Specifically, I'm trying to add a log handler with logging.addHandler(x) and it is of course failing. Thanks, Brian -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there any module/utility like 'rsync' in python
hiral wrote: Hi, Is there any module/utility like 'rsync' in python. Thank you in advance. Not exactly what you asked for, but Mercurial provides a Python interface. You might find this URL a good starting point: http://mercurial.selenic.com/wiki/MercurialApi -- Jonathan -- http://mail.python.org/mailman/listinfo/python-list
Re: logging = logging.getLogger(__name__)
On 15/06/2010 16:35, genkuro wrote: Newbie here. I may be missing something obvious, in which case, please feel free to berate and laugh at me. Here's a dubious line of code: logging = logging.getLogger(__name__) How can I refer to the original logging package logging after this statement is run? Specifically, I'm trying to add a log handler with logging.addHandler(x) and it is of course failing. Thanks, Brian Change it to something like logger = logging.getLogger(__name__), then logger.addHandler(x). If you don't do this, your logging shadows the logging module so you won't get very far. HTH. Mark Lawrence -- http://mail.python.org/mailman/listinfo/python-list
Re: logging = logging.getLogger(__name__)
genkuro wrote: Newbie here. I may be missing something obvious, in which case, please feel free to berate and laugh at me. Here's a dubious line of code: logging = logging.getLogger(__name__) Dubious indeed. As a workaround you can import the module again, preferably under another name: import logging as real_logging_module You can think of import logging as a shortcut for logging = __import__(logging) and of import logging as x as a shortcut for x = __import__(logging) How can I refer to the original logging package logging after this statement is run? Specifically, I'm trying to add a log handler with logging.addHandler(x) and it is of course failing. Hmm, this shouldn't fail, as there is a Logger.addHandler() method whereas the logging module doesn't contain an addHandler() function: import logging logging.addHandler Traceback (most recent call last): File stdin, line 1, in module AttributeError: 'module' object has no attribute 'addHandler' logging.getLogger().addHandler bound method RootLogger.addHandler of logging.RootLogger instance at 0x7f06bdc71a28 Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there any module/utility like 'rsync' in python
Jonathan Fine j.f...@open.ac.uk writes: hiral wrote: Hi, Is there any module/utility like 'rsync' in python. Thank you in advance. Not exactly what you asked for, but Mercurial provides a Python interface. You might find this URL a good starting point: http://mercurial.selenic.com/wiki/MercurialApi Mercurial isn't really a substitute for rsync... whilst there's a little bit of overlap they're different things intended to address different problems. -- http://mail.python.org/mailman/listinfo/python-list
Re: logging = logging.getLogger(__name__)
Peter Otten __pete...@web.de writes: genkuro wrote: Newbie here. I may be missing something obvious, in which case, please feel free to berate and laugh at me. Here's a dubious line of code: logging = logging.getLogger(__name__) Dubious indeed. As a workaround you can import the module again, preferably under another name: It's better just to use another variable name - e.g. logger, Shirley? -- http://mail.python.org/mailman/listinfo/python-list
Re: logging = logging.getLogger(__name__)
On Jun 15, 8:49 am, Mark Lawrence breamore...@yahoo.co.uk wrote: On 15/06/2010 16:35, genkuro wrote: Newbie here. I may be missing something obvious, in which case, please feel free to berate and laugh at me. Here's a dubious line of code: logging = logging.getLogger(__name__) How can I refer to the original logging package logging after this statement is run? Specifically, I'm trying to add a log handler with logging.addHandler(x) and it is of course failing. Thanks, Brian Change it to something like logger = logging.getLogger(__name__), then logger.addHandler(x). If you don't do this, your logging shadows the logging module so you won't get very far. HTH. Mark Lawrence Hi Mark - I thought that would be the answer. I asked because I'm working with a framework where logging is similarly renamed in almost every file. The framework is under development so refactoring is an option. I'm coming to Python from Java. I'm still getting a feel for scoping limits. For the sake of curiosity, is there another way to refer to a package besides name? Thanks, Brian -- http://mail.python.org/mailman/listinfo/python-list
Re: logging = logging.getLogger(__name__)
genkuro wrote: Newbie here. I may be missing something obvious, in which case, please feel free to berate and laugh at me. Here's a dubious line of code: logging = logging.getLogger(__name__) How can I refer to the original logging package logging after this statement is run? Specifically, I'm trying to add a log handler with logging.addHandler(x) and it is of course failing. Thanks, Brian Welcome to the forum, and to Python. Excellent question. Simple answer is to change the left side to something like logger= And use that as your logger. However, if you already have lots of code (written by someone else, presumably), and don't want to change all the other references to that name, you could do something like (ugly): import logging as loggingmodule logging = loggingmodule.getLogger(... Then you can continue to use loggingmodule to refer to the module. The reason I don't encourage this is that whenever you look in the docs, you'll see a reference to something like logging.addHandler, and you'll have to remember to change it to loggingmodule.addHandler HTH, DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Community (A Modest Proposal)
On Tue, Jun 15, 2010 at 7:08 AM, Shashwat Anand anand.shash...@gmail.com wrote: IDEs are seriously over-rated. Vim FTW. The only issue for beginners is they should know touch typing to fully utilize Vim and the initial curve is a bit high as compared to normal editors/IDEs. Used to be vim-only. Then I got to know gedit's latex plugin better, and started doing literate code. Pretty much all gedit now. Still feels slightly dirty. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: logging = logging.getLogger(__name__)
genkuro wrote: On Jun 15, 8:49 am, Mark Lawrence breamore...@yahoo.co.uk wrote: On 15/06/2010 16:35, genkuro wrote: Newbie here. I may be missing something obvious, in which case, please feel free to berate and laugh at me. Here's a dubious line of code: logging = logging.getLogger(__name__) How can I refer to the original logging package logging after this statement is run? Specifically, I'm trying to add a log handler with logging.addHandler(x) and it is of course failing. Thanks, Brian Change it to something like logger = logging.getLogger(__name__), then logger.addHandler(x). If you don't do this, your logging shadows the logging module so you won't get very far. HTH. Mark Lawrence Hi Mark - I thought that would be the answer. I asked because I'm working with a framework where logging is similarly renamed in almost every file. The framework is under development so refactoring is an option. I'm coming to Python from Java. I'm still getting a feel for scoping limits. For the sake of curiosity, is there another way to refer to a package besides name? Thanks, Brian Yes, there is another way but you don't want to do that. As mentioned before, use a proper name (logger is a good candidate). import sys print sys.modules['logging'] module 'logging' from '/usr/lib/python2.5/logging/__init__.pyc' pylint usually tells you when you're shadowing some standard package, I would advise to use this tool (requires some tuning though). JM -- http://mail.python.org/mailman/listinfo/python-list
Re: logging = logging.getLogger(__name__)
On 15/06/2010 17:03, genkuro wrote: On Jun 15, 8:49 am, Mark Lawrencebreamore...@yahoo.co.uk wrote: On 15/06/2010 16:35, genkuro wrote: Newbie here. I may be missing something obvious, in which case, please feel free to berate and laugh at me. Here's a dubious line of code: logging = logging.getLogger(__name__) How can I refer to the original logging package logging after this statement is run? Specifically, I'm trying to add a log handler with logging.addHandler(x) and it is of course failing. Thanks, Brian Change it to something like logger = logging.getLogger(__name__), then logger.addHandler(x). If you don't do this, your logging shadows the logging module so you won't get very far. HTH. Mark Lawrence Hi Mark - I thought that would be the answer. I asked because I'm working with a framework where logging is similarly renamed in almost every file. The framework is under development so refactoring is an option. I'm coming to Python from Java. I'm still getting a feel for scoping limits. For the sake of curiosity, is there another way to refer to a package besides name? Thanks, Brian Peter Otten has already pointed out that you can use import logging as x, but I don't see the need for it in this instance. Paul Rudin has agreed with me, i.e. just use logger, so why not refactor your code now, I think that you'll appeciate it in the long term. Cheers. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: logging = logging.getLogger(__name__)
On 6/15/10 9:03 AM, genkuro wrote: I'm coming to Python from Java. I'm still getting a feel for scoping limits. For the sake of curiosity, is there another way to refer to a package besides name? The only way to refer to anything is by its name -- or, from a name and through subscript/dot notation if you've stored something in a container. But a package (and anything else) can have many names, and it really has no idea what they are. You can do import logging as logging_package which is just a shortcut for: import logging logging_package = logging del logging And such. That said: The frameworks I've seen that shadow the global 'logging' package with a specific logger do so somewhat on purpose (though I find the practice slightly dubious), so that naive code which previously just used the general root logger would work with the more specific one seamlessly. But such frameworks usually also have a setup/environment sort of file where this is not done, and that's where things like adding handlers belongs. Just as an aside. Renaming logging = ... to logger = ... is probably a better solution anyways :) -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
On Tue, Jun 15, 2010 at 6:21 AM, Alain Ketterlin al...@dpt-info.u-strasbg.fr wrote: You compute i**2 too many times (7/5 times more than necessary) and twice too many modulos. I suggest: c = { 0:1, 1:1, 2:1, 3:-1, 4:-1 } #or, why not: c = lambda i : +1 if (i%5) 3 else -1 s = 0 for i in range(1,2011): s += c[(i-1)%5]*(i**2) print s In fact, most of them are unnecessary: from itertools import izip, cycle def squares(start, stop): square = start * start step = start * 2 + 1 for root in xrange(start, stop): yield square square += step step += 2 print sum(sign * square for sign, square in izip(cycle([1,1,1,-1,-1]), squares(1, 2011))) Now, anybody know how to make that version a one-liner without making it go quadratic in run-time? Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: setprocname
Op 2010-06-14 22:00, John Nagle schreef: There's a way to do this in Windows. Look in Task Manager, with a browser running, and the description for each Firefox instance will show the page being displayed. Are you sure? I only see that on the Applications tab, which shows window titles; not on the Processes tab which shows the actual process names (on Windows XP). -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven -- http://mail.python.org/mailman/listinfo/python-list
Re: Will and Abe's Guide to Pyjamas
On 14-06-2010 17:53, lkcl wrote: oh look - there's a common theme, there: web technology equals useless :) this is getting sufficiently ridiculous, i thought it best to summarise the discussions of the past few days, from the perspective of four-year-olds: http://pyjs.org/will_and_abe_guide_to_pyjamas.html l. and how does this fit in ? http://pyxpcomext.mozdev.org/samples.html cheers, Stef -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
superpollo ute...@esempio.net writes: goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) print sum([-1,1,1,1,-1][i%5]*i**2 for i in xrange(1,2011)) -- http://mail.python.org/mailman/listinfo/python-list
Re: Different byte-code in same major version (2.6.x)?
Hartmut Goebel h.goe...@crazy-compilers.com writes: I'm facing a curious problem: 2.6, 2.6.1 and 2.6.4 are generating different byte-code for the same source. I can not find the reason for. Why should they generate the same bytecode? All that you should expect is that the same bytecode should be runnable on all three interpreters. It is ok if a newer version of the compiler does additional optimizations or that sort of thing, resulting in different bytecode. It's just like with any compiler. -- http://mail.python.org/mailman/listinfo/python-list
Re: pythonize this!
Paul Rubin ha scritto: superpollo ute...@esempio.net writes: goal (from e.c.m.): evaluate 1^2+2^2+3^2-4^2-5^2+6^2+7^2+8^2-9^2-10^2+...-2010^2, where each three consecutive + must be followed by two - (^ meaning ** in this context) print sum([-1,1,1,1,-1][i%5]*i**2 for i in xrange(1,2011)) beautiful. thx -- http://mail.python.org/mailman/listinfo/python-list
Possible to make subprocess.Popen jobs run serially rather than in parallel?
Possible to make subprocess.Popen jobs run serially rather than in parallel? In other words, if a computer is low on memory and doesn't mind waiting.can Popen be configured to submit to a queue and run jobs *ONE AT TIME*?? That might be useful and avoid crashes and disk swapping. cs -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Library Win7 -64 Bit
Has anyone had any prior experience with this sort of problem or can anyone point me in the right direction? My recommendation is to install the 32-bit version of Python, and use precompiled binaries of libxml. Failing that, install Visual Studio Express (or Visual Studio proper), and compile libxml with that. This recommendation assumes that you are looking for an approach with least effort. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Possible to make subprocess.Popen jobs run serially rather than in parallel?
On 6/15/10 11:52 AM, Chris Seberino wrote: Possible to make subprocess.Popen jobs run serially rather than in parallel? In other words, if a computer is low on memory and doesn't mind waiting.can Popen be configured to submit to a queue and run jobs *ONE AT TIME*?? That might be useful and avoid crashes and disk swapping. Just call process.wait() after you call process = subprocess.Popen(...) -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ signature.asc Description: OpenPGP digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: Python OpenSSL library
On 6/14/2010 11:58 AM, geremy condra wrote: On Mon, Jun 14, 2010 at 11:47 AM, Nobodynob...@nowhere.com wrote: On Mon, 14 Jun 2010 10:43:02 -0700, John Nagle wrote: The new SSL module in Python 2.6 There isn't an SSL module in Python 2.6. There is a module named ssl which pretends to implement SSL, but in fact doesn't. is convenient, but insecure. In which case, it isn't actually convenient, in any meaningful sense of the word. As one of my friends is fond of saying, it lets you talk encrypted to your attacker ;) That's a good way to put it. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Readability (html purifier) in Python
http://lab.arc90.com/experiments/readability/ Readability is a javascript bookmarklet that makes reading on the Web more enjoyable by removing the clutter around what you're reading. Does anyone know of something similar in Python? -- дамјан ((( http://damjan.softver.org.mk/ ))) Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. - Brian W. Kernighan -- http://mail.python.org/mailman/listinfo/python-list
Re: Readability (html purifier) in Python
Дамјан Георгиевски, 15.06.2010 17:44: http://lab.arc90.com/experiments/readability/ Readability is a javascript bookmarklet that makes reading on the Web more enjoyable by removing the clutter around what you're reading. Does anyone know of something similar in Python? Well, that sounds like a browser tool. Could you be a bit more specific about what kind of similar functionality you would expect from a similar Python tool? How would you tell it what you're reading, for example? Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Python OpenSSL library
On Mon, 14 Jun 2010 19:47:49 +0100 Nobody nob...@nowhere.com wrote: On Mon, 14 Jun 2010 10:43:02 -0700, John Nagle wrote: The new SSL module in Python 2.6 There isn't an SSL module in Python 2.6. There is a module named ssl which pretends to implement SSL, but in fact doesn't. What do you mean by doesn't? Can you point to an open bug report describing the issue? -- http://mail.python.org/mailman/listinfo/python-list
Introducing - Pyaudiogen
Hello list, Here's a little Python toy I've been hacking on, as I thought it might amuse some of you. [1] Python 3.1+ (not sure about 3.0) It's a package called 'audiogen' which includes bindings to libao for portable audio output and some functions/classes/... for generating audio. It grew from the idea that code like this would be neat: def sinewave(arguments go here): wavetable = # generate sinusoid waveform while True: yield wavetable or even something like this: def eric_idle(arguments do here): for note in (Do, Re, Mi): yield plucked_string(note) yield pause(beats=2) Generalised a bit to allow for stereo / multi-channel output, plus some decorators, and you get pyaudiogen. Some examples and all the code is on bitbucket [1]. For good measure, here's the sine wave function sketched above as real, working, code: @wave_gen(channels=1) # mono output def sinusoid(freq, amp, srate : 'rate'): from math import sin, pi wavelength = srate // freq wavetable = wave.from_float(amp*sin(2 * pi * x / wavelength) for x in range(int(wavelength))) while True: yield (wavetable,) Suggestions welcomed! -- Thomas [1] URL:http://bitbucket.org/jollybox/pyaudiogen -- http://mail.python.org/mailman/listinfo/python-list
Re: Python OpenSSL library
On Tue, Jun 15, 2010 at 1:27 PM, Antoine Pitrou solip...@pitrou.net wrote: On Mon, 14 Jun 2010 19:47:49 +0100 Nobody nob...@nowhere.com wrote: On Mon, 14 Jun 2010 10:43:02 -0700, John Nagle wrote: The new SSL module in Python 2.6 There isn't an SSL module in Python 2.6. There is a module named ssl which pretends to implement SSL, but in fact doesn't. What do you mean by doesn't? Can you point to an open bug report describing the issue? He's describing the lack of hostname checking, discussed here[0], here[1], and in my pycon lightning talk last year, wherever those are kept. My understanding is that it has led to vulnerabilities in code deployed by Red Hat and several other vendors; if you need to speak with them I can probably get the people involved in that effort to come forward privately. Both the lead for M2Crypto and the authors of zc.ssl have publicly stated that this needs to be fixed. Geremy Condra [0] http://mail.python.org/pipermail/python-list/2010-April/1242166.html [1] http://bugs.python.org/issue1589 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python OpenSSL library
Hello, He's describing the lack of hostname checking, discussed here[0], here[1], and in my pycon lightning talk last year, wherever those are kept. Ok, thank you. I have tried to put some effort into the py3k ssl docs, so that security issues get mentioned: http://docs.python.org/dev/py3k/library/ssl.html#security-considerations Any improvement or correction is welcome. Also, following issue1589 (certificate hostname checking), I think it would be useful at least to provide the necessary helper functions in order to check certificate conformity, even if they aren't called implicitly. I would encourage interested people to provide a patch for the py3k ssl module, and will gladly review it. Regards Antoine. -- http://mail.python.org/mailman/listinfo/python-list
Can code objects outlive the interpreter that created them?
Hi, I'm working on an application program that embeds Python using the C-API. Sometimes, I need to call functions written in pure Python from the C code, so I use Py_CompileString and PyEval_EvalCode. I would like to avoid compiling the same code over and over by storing the result of Py_CompileString in a static variable, however, the application does sometimes restart the Python interpreter. My question: is the PyCodeObject * returned from Py_CompileString still valid after Python is restarted? Andy Jost Sr. RD Engineer Silicon Engineering Group Synopsys, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python OpenSSL library
On Tue, Jun 15, 2010 at 1:57 PM, Antoine Pitrou solip...@pitrou.net wrote: Hello, He's describing the lack of hostname checking, discussed here[0], here[1], and in my pycon lightning talk last year, wherever those are kept. Ok, thank you. I have tried to put some effort into the py3k ssl docs, so that security issues get mentioned: http://docs.python.org/dev/py3k/library/ssl.html#security-considerations Any improvement or correction is welcome. Could similar notifications be added to urllib, etc? That's where people really get bitten badly by this. Also, following issue1589 (certificate hostname checking), I think it would be useful at least to provide the necessary helper functions in order to check certificate conformity, even if they aren't called implicitly. I would encourage interested people to provide a patch for the py3k ssl module, and will gladly review it. I'm not sure what this fixes if it doesn't get used in the higher-level modules, but I can ask if anybody is interested. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list