From flt.johnson at gmail.com Sat Oct 1 00:50:42 2011 From: flt.johnson at gmail.com (Fletcher Johnson) Date: Fri, 30 Sep 2011 21:50:42 -0700 (PDT) Subject: overloading operators for a function object Message-ID: Is it possible to overload operators for a function? For instance I would like to do something roughly like... def func_maker(): def func(): pass def __eq__(other): if other == "check": return True return False func.__eq__ = __eq__ return func newfunc = func_maker() newfunc == "check" #true newfunc == "no" #false From clp2 at rebertia.com Sat Oct 1 01:00:33 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 30 Sep 2011 22:00:33 -0700 Subject: overloading operators for a function object In-Reply-To: References: Message-ID: On Fri, Sep 30, 2011 at 9:50 PM, Fletcher Johnson wrote: > Is it possible to overload operators for a function? > > For instance I would like to do something roughly like... > > def func_maker(): > ?def func(): pass > > ?def __eq__(other): > ? ?if other == "check": ?return True > ? ?return False > > ?func.__eq__ = __eq__ > ?return func > > newfunc = func_maker() > newfunc == "check" #true > newfunc == "no" #false You can write a callable [wrapper] object to get the same effect: class SpecialFunction(object): def __call__(self, actual, args, go, here): return whatever def __eq__(self, other): return other == "check" newfunc = SpecialFunction() newfunc == "check" # => True newfunc(1, 2, 3, 4) #=> whatever Cheers, Chris -- http://rebertia.com From wuwei23 at gmail.com Sat Oct 1 01:10:55 2011 From: wuwei23 at gmail.com (alex23) Date: Fri, 30 Sep 2011 22:10:55 -0700 (PDT) Subject: Suggested coding style References: <27620bc4-edd2-473e-809f-18f17b426b4f@db5g2000vbb.googlegroups.com> Message-ID: > > On Sep 29, 10:23?pm, rantingrick wrote: > > > What is so bad about breaking code in obscure places? > On Sep 29, 9:50?pm, alex23 wrote: > > Try coding in PHP across minor release versions and see how you feel > > about deprecating core functions on a whim. On Sep 30, 11:54?pm, rantingrick wrote: > I never said we should remove it now, i said we should deprecate it > now. Actually, *I* said deprecate, *you* said break. I don't see the word 'remove' anywhere in my comment. > Please Google deprecate. Please read what I wrote rather than what you want me to have said. > Well "alex" i can't see a mob approaching with pitchforks because we > deprecate a misplaced and rarely used functionality of the stdlib. No, but you don't see a lot of things. You're genuinely convinced that your viewpoint is superior and singularly correct. I don't think you're a reasonable arbiter of what functionality should be added or removed from the stdlib. > Well "alex", like yourself, i hold expertise in many fields BESIDES > programming. One of which being psychology. That only makes the claims that you regularly post about others even more offensive. From jason.swails at gmail.com Sat Oct 1 02:31:18 2011 From: jason.swails at gmail.com (Jason Swails) Date: Sat, 1 Oct 2011 02:31:18 -0400 Subject: executing arbitrary statements Message-ID: Hello everyone, I'm probably missing something pretty obvious, but I was wondering if there was a way of executing an arbitrary line of code somehow (such as a line of code based on user-input). There's the obvious use of "eval" that will evaluate a function call, but that doesn't allow all things. For instance: >>> import sys >>> eval(r"sys.stdout.write('Hello world!\n')") Hello world! >>> eval(r"print 'Hello world!'") Traceback (most recent call last): File "", line 1, in File "", line 1 print 'Hello world!' ^ SyntaxError: invalid syntax >>> Because write is a function eval works fine for it. But since print isn't (2.7), it throws a syntax error. Likewise, variable assignments aren't allowed either as they are also not functions and lack a return value: >>> eval("j = 1") Traceback (most recent call last): File "", line 1, in File "", line 1 j = 1 ^ SyntaxError: invalid syntax What I'm more or less looking to do is present a (limited) form of an interpreter inside the application I'm writing for the advanced user. I'm also interested to hear if this is a particularly bad idea for any reason, and if there are security issues involved with allowing users to execute their own code inside my program (keeping in mind that some people may "donate" their scripts to others that may run them as black boxes). Is it enough to disallow import statements, thereby not giving direct access to the sys and os modules? I know more or less what I want to do, but I'd also appreciate any experienced input/advice/suggestions. Thanks! Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sat Oct 1 03:06:43 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 1 Oct 2011 00:06:43 -0700 Subject: executing arbitrary statements In-Reply-To: References: Message-ID: On Fri, Sep 30, 2011 at 11:31 PM, Jason Swails wrote: > Hello everyone, > > I'm probably missing something pretty obvious, but I was wondering if there > was a way of executing an arbitrary line of code somehow (such as a line of > code based on user-input).? There's the obvious use of "eval" that will > evaluate a function call, but that doesn't allow all things. > Because write is a function eval works fine for it.? But since print isn't > (2.7), it throws a syntax error.? Likewise, variable assignments aren't > allowed either as they are also not functions and lack a return value: Use the `exec` statement, which is capable of executing statements (as opposed to just expressions): http://docs.python.org/reference/simple_stmts.html#the-exec-statement > What I'm more or less looking to do is present a (limited) form of an > interpreter inside the application I'm writing for the advanced user. > > I'm also interested to hear if this is a particularly bad idea for any > reason, It's potentially rather hacky and ad-hoc to effectively directly inject arbitrary statements at certain points in your code. Assuming you were to trust the user-provided code, callbacks/hooks or plugin modules are typically much cleaner ways to integrate custom code from the user. Depending on your particular use case, the `cmd` module might also be a workable alternative: http://docs.python.org/library/cmd.html > and if there are security issues involved with allowing users to > execute their own code inside my program (keeping in mind that some people > may "donate" their scripts to others that may run them as black boxes). It is *very much* a security issue! > Is > it enough to disallow import statements, thereby not giving direct access to > the sys and os modules? Not by a long shot! There are a bunch of known tricks that exploit introspection to circumvent such restrictions. Secure execution of untrusted Python code is a difficult problem. Some have accomplished it to a degree, but typically only by modifying the interpreter itself or imposing relatively onerous restrictions on the untrusted code. > I know more or less what I want to do, but I'd also > appreciate any experienced input/advice/suggestions. I additionally came across this in researching my reply: http://pypi.python.org/pypi/RestrictedPython/ Apparently the speed of execution leaves something to be desired, but the package /supposedly/ works well otherwise. Cheers, Chris -- http://rebertia.com From ladasky at my-deja.com Sat Oct 1 05:22:41 2011 From: ladasky at my-deja.com (John Ladasky) Date: Sat, 1 Oct 2011 02:22:41 -0700 (PDT) Subject: Simplest way to resize an image-like array References: <9b0b8951-bfc2-4047-8b4e-1ee0af20af27@q24g2000vby.googlegroups.com> Message-ID: On Sep 30, 1:51?pm, Jon Clements wrote: > Is something like > http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresize.html > any use? There we go! That's the kind of method I was seeking. I didn't think to look outside of scipy.interpolate. Thanks, Jon. From ladasky at my-deja.com Sat Oct 1 05:24:32 2011 From: ladasky at my-deja.com (John Ladasky) Date: Sat, 1 Oct 2011 02:24:32 -0700 (PDT) Subject: Simplest way to resize an image-like array References: Message-ID: On Sep 30, 11:54?pm, Dennis Lee Bieber wrote: > ? ? ? ? How difficult would it be to convert the "array" to a PIL image? I'm > fairly certain PIL has operations to rescale images. Yes, I considered this approach -- but I have a lot of arrays to resample, and I didn't want to further slow what is likely to be an already-slow process. From emekamicro at gmail.com Sat Oct 1 08:41:22 2011 From: emekamicro at gmail.com (Emeka) Date: Sat, 1 Oct 2011 13:41:22 +0100 Subject: TK + MVC Message-ID: Hello All, I need a basic example where MVC pattern is used with Python TK. Regards, Emeka -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From julian.bilcke at gmail.com Sat Oct 1 11:13:45 2011 From: julian.bilcke at gmail.com (julian bilcke) Date: Sat, 1 Oct 2011 17:13:45 +0200 Subject: How to inspect slot wrappers arguments in Python? Message-ID: Hi, I would like to get the list of parameters I need to initialize an AST node. I'm trying to use the `inspect` module, however it seems I can't use it on a built-in (native?) class, or else I misunderstood. I'm using Python 2.7 and tried with Python 3.2. This is working: >>> import inspect >>> class C: ... def __init__(a,b=4): ... self.sum = a + b ... >>> inspect.getargspec(C.__init__) ArgSpec(args=['a', 'b'], varargs=None, keywords=None, defaults=(4,)) This is not working: >>> import inspect >>> import ast >>> inspect.getargspec(ast.If.__init__) Traceback (most recent call last): File "", line 1, in File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 813, in getargspec raise TypeError('{!r} is not a Python function'.format(func)) TypeError: is not a Python function I am wondering if there is another way to get these parameters automatically? (ie. without compiling myself a dict) Regards, J. Bilcke -------------- next part -------------- An HTML attachment was scrubbed... URL: From prakashr85 at gmail.com Sat Oct 1 13:25:38 2011 From: prakashr85 at gmail.com (Prakash) Date: Sat, 1 Oct 2011 10:25:38 -0700 (PDT) Subject: Need A script to open a excel file and extract the data using autofilter Message-ID: <4f3ec474-dd9f-4585-8f3c-41323d79b8de@z19g2000vby.googlegroups.com> Need A script to open a excel file and extract the data using autofilter and write it in a new sheet or new file like I have to select all rows in which all the columns contain pass as status From prakashr85 at gmail.com Sat Oct 1 13:35:06 2011 From: prakashr85 at gmail.com (Prakash) Date: Sat, 1 Oct 2011 10:35:06 -0700 (PDT) Subject: Need A script to open a excel file and extract the data using autofilter References: <4f3ec474-dd9f-4585-8f3c-41323d79b8de@z19g2000vby.googlegroups.com> Message-ID: <74fc7fc6-8d5d-40fd-b152-0ce022a78a0c@m5g2000vbe.googlegroups.com> On Oct 1, 10:25?pm, Prakash wrote: > Need ?A script to open a excel file and extract the data using > autofilter and write it in a new sheet or new file like I have to > select all rows in which all the columns contain pass as status from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlApp.Workbooks.Open(r'C:\Users\Administrator\Desktop\test.xls') xlApp.Visible = 1 after opening the text.xls file i need to filter all the rows in which the status column is passed and copy the whole sheet to another sheet From tavares at fe.up.pt Sat Oct 1 14:46:11 2011 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Sat, 1 Oct 2011 11:46:11 -0700 (PDT) Subject: Symposium "Image Processing and Visualization in Solid Mechanics Processes" within ESMC2012 - Announce & Call for Papers Message-ID: <44b88062-566a-487c-851a-08213655f7bd@p11g2000yqe.googlegroups.com> Dear Colleague, Within the 8th EUROMECH Solid Mechanics Conference - ESMC2012 (www.esmc2012.tugraz.at), to be held in Graz University of Technology, Austria, July 9-13, 2012, we are organizing the Symposium ?Image Processing and Visualization in Solid Mechanics Processes?. Examples of topics that will be considered in the symposium ?Image Processing and Visualization in Solid Mechanics Processes? are: Image Analysis; Image Restoration, Compression, Segmentation and Description; Object Tracking, Matching, Recognition, and Reconstruction; Visual Inspection; 3D Vision; Medical Imaging; Data Processing, Modeling and Analysis; Scientific Visualization; Enhanced Visualization; Human Computer Interaction; Virtual Reality; Simulation and Animation; Software Development for Image Processing and Visualization; Grid Computing in Image Processing and Visualization; and Applications of Image Processing and Visualization. Due to your research activities in those fields, we would like to invite you to submit your work and participate in the Symposium ?Image Processing and Visualization in Solid Mechanics Processes?. For instructions and submission, please, access to the conference website at: www.esmc2012.tugraz.at Please note that, when submitting your work you should select the Symposium ?Image Processing and Visualization in Solid Mechanics Processes?. Important dates: - Abstract submission (two-page): November 30, 2011; - Notification of acceptance: February 28, 2011. Kind regards, Jo?o Manuel R. S. Tavares (University of Porto, Portugal, tavares at fe.up.pt) Renato Natal Jorge (University of Porto, Portugal, rnatal at fe.up.pt) (Symposium organizers) From cmpython at gmail.com Sat Oct 1 14:50:59 2011 From: cmpython at gmail.com (CM) Date: Sat, 1 Oct 2011 11:50:59 -0700 (PDT) Subject: options for plotting points on geographic map References: <28071425.854.1317315127547.JavaMail.geo-discussion-forums@prfb12> Message-ID: <5f2e4914-e90c-41c0-be47-830482f023c1@k6g2000yql.googlegroups.com> On Sep 29, 12:52?pm, Miki Tebeka wrote: > Probably the google maps routes will be faster (maybe using embedded webkit window). However it requires internet connection. > > See alsohttp://www.scipy.org/Cookbook/Matplotlib/Maps Thanks. But I just needed a small radius, not the whole globe, and I need towns/cities indicated. I think Google Maps is the way to go. From cmpython at gmail.com Sat Oct 1 14:52:16 2011 From: cmpython at gmail.com (CM) Date: Sat, 1 Oct 2011 11:52:16 -0700 (PDT) Subject: options for plotting points on geographic map References: Message-ID: <129a7899-2f93-4b54-847c-d946c6cdd498@c1g2000yql.googlegroups.com> > You could create the webpage and then render > it in your desktop app. I have seen plenty of apps like that. That's a good idea. I was able to get the basics of the pymaps approach going, so I may do just this. Thanks. From alex.kapps at web.de Sat Oct 1 17:35:34 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Sat, 01 Oct 2011 23:35:34 +0200 Subject: TK + MVC In-Reply-To: References: Message-ID: <4E8787A6.8000903@web.de> On 01.10.2011 14:41, Emeka wrote: > Hello All, > > I need a basic example where MVC pattern is used with Python TK. I'm still not 100% sure if I really understand the MVC pattern. Some say the view and the model must not interact directly, some say the view must not access the controller (but the controller controls the view). Some insist on a certain interface, others just talk about a certain data/control flow, etc. But I think a simple (and quick 'n' dirty) Tk MVC example can look like this: #!/usr/bin/python import Tkinter as tk class Model(object): def __init__(self): self._data = ["foo", "bar", "baz"] self.controllers = [] def data(self): return self._data def add(self, value): self._data.append(value) self.changed() def delete(self, index): del self._data[index] self.changed() def changed(self): for controller in self.controllers: controller.update() class Controller(object): def __init__(self, model): self.model = model self.views = [] def handle_insert(self, value): self.model.add(value) def handle_delete(self, index): self.model.delete(index) def get_data(self): return self.model.data() def update(self): for view in self.views: view.update() class View(object): def __init__(self, master, controller): self.controller = controller self.master = master self.list = tk.Listbox(self.master) self.list.pack(expand=1, fill="both") self.entry = tk.Entry(self.master) self.entry.pack(fill="x", expand=1) self.entry.bind("", self.enter_handler) self.list.bind("", self.delete_handler) self.update() def enter_handler(self, event): text = self.entry.get() self.controller.handle_insert(text) def delete_handler(self, event): for index in self.list.curselection(): self.controller.handle_delete(int(index)) def update(self): self.list.delete(0, "end") for entry in self.controller.get_data(): self.list.insert("end", entry) def main(): root = tk.Tk() model = Model() controller = Controller(model) view = View(root, controller) model.controllers.append(controller) controller.views.append(view) root.mainloop() if __name__ == '__main__': main() From monaghand.david at gmail.com Sat Oct 1 18:00:07 2011 From: monaghand.david at gmail.com (David Monaghan) Date: Sat, 01 Oct 2011 23:00:07 +0100 Subject: Need A script to open a excel file and extract the data using autofilter References: <4f3ec474-dd9f-4585-8f3c-41323d79b8de@z19g2000vby.googlegroups.com> <74fc7fc6-8d5d-40fd-b152-0ce022a78a0c@m5g2000vbe.googlegroups.com> Message-ID: On Sat, 1 Oct 2011 10:35:06 -0700 (PDT), Prakash wrote: >On Oct 1, 10:25?pm, Prakash wrote: >> Need ?A script to open a excel file and extract the data using >> autofilter and write it in a new sheet or new file like I have to >> select all rows in which all the columns contain pass as status > >from win32com.client import Dispatch >xlApp = Dispatch("Excel.Application") >xlApp.Workbooks.Open(r'C:\Users\Administrator\Desktop\test.xls') >xlApp.Visible = 1 > >after opening the text.xls file i need to filter all the rows in which >the status column is passed and copy the whole sheet to another sheet I don't do this often enough to have it to mind, so what I normally do is record a Macro, convert it to VBS and then convert that to Python. I'll leave the final step for you to complete yourself, but this will do what you ask up to the point of copying the selected lines: from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlWbook = xlApp.Workbooks.Open(r"C:\Users\Administrator\Desktop\test.xls") xlApp.Visible = 1 xlWorksheet = xlWbook.Worksheets(1) xlWorksheet.Columns("A:V").Select() xlApp.Selection.AutoFilter( 2, "pass") # column number, filter criteria xlApp.Selection.AutoFilter( 3, "pass") xlApp.Selection.AutoFilter( 4, "pass") xlApp.Selection.AutoFilter( 5, "pass") #etc, etc - up to column 22 in this case xlApp.Selection.Copy() DaveM From monaghand.david at gmail.com Sat Oct 1 19:38:01 2011 From: monaghand.david at gmail.com (David Monaghan) Date: Sun, 02 Oct 2011 00:38:01 +0100 Subject: Need A script to open a excel file and extract the data using autofilter References: <4f3ec474-dd9f-4585-8f3c-41323d79b8de@z19g2000vby.googlegroups.com> <74fc7fc6-8d5d-40fd-b152-0ce022a78a0c@m5g2000vbe.googlegroups.com> Message-ID: <0k8f8714tlh3s031cm48vh3iivm2ih7tbk@4ax.com> On Sat, 01 Oct 2011 23:00:07 +0100, David Monaghan wrote: >from win32com.client import Dispatch >xlApp = Dispatch("Excel.Application") >xlWbook = xlApp.Workbooks.Open(r"C:\Users\Administrator\Desktop\test.xls") >xlApp.Visible = 1 >xlWorksheet = xlWbook.Worksheets(1) >xlWorksheet.Columns("A:V").Select() >xlApp.Selection.AutoFilter( 2, "pass") # column number, filter criteria >xlApp.Selection.AutoFilter( 3, "pass") >xlApp.Selection.AutoFilter( 4, "pass") >xlApp.Selection.AutoFilter( 5, "pass") >#etc, etc - up to column 22 in this case >xlApp.Selection.Copy() Or rather: from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlWbook = xlApp.Workbooks.Open(r'C:\Users\Administrator\Desktop\test.xls') xlApp.Visible = 1 xlWorksheet = xlWbook.Worksheets(1) xlWorksheet.Columns("A:V").Select() for column in range(2,23): xlApp.Selection.AutoFilter(column, "pass") xlApp.Selection.Copy() From greg.ewing at canterbury.ac.nz Sat Oct 1 22:17:33 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 02 Oct 2011 15:17:33 +1300 Subject: Benefit and belief In-Reply-To: References: <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> Message-ID: <9epvttFc2lU1@mid.individual.net> Chris Angelico wrote: > But what if I'm a great windowing magnate, owning windows all over the world? Like Bill Gates, you mean? -- Greg From greg.ewing at canterbury.ac.nz Sat Oct 1 22:40:41 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 02 Oct 2011 15:40:41 +1300 Subject: TK + MVC In-Reply-To: References: Message-ID: <9eq19cFmb2U1@mid.individual.net> Alexander Kapps wrote: > But I think a simple (and quick 'n' dirty) Tk MVC example can look like > this: The Controller doesn't seem to add any value in that example. You might as well connect the Model and Views directly to each other. -- Greg From steve+comp.lang.python at pearwood.info Sat Oct 1 23:03:11 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 02 Oct 2011 14:03:11 +1100 Subject: [OT] Chaos Theory [was Re: Benefit and belief] References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> Message-ID: <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> By the way, who removed the OT label from the subject line? Please don't unless it actually comes back on topic. DevPlayer wrote: > I still assert that contradiction is caused by narrow perspective. There's no doubt that some *apparent* contradictions are caused by lack of correct information. But: N is an even number; N (the same N, for avoidance of doubt) is an odd number is still a contradiction, no matter how you look at it. [...] > If I am correct; not sure here; but I think that is part of the new > math Choas theory. (The notion that not all variables are known and > the results of well defined functions may result in completely > different actual outcomes) [Missing variables in such data sets and > functions, to me is basically a narrow(er) perspective of the all the > revelent factors for such computations.] Chaos theory goes back to Henri Poincar? in the 1880s, and possibly even older. 130 years is hardly "new". The principle of Chaos Theory is not that there are some unknown variables, but that even if you know all the variables, even the slightest error or uncertainty in their values may lead to radically different results in the future. As so often is the case, something which seemed controversial when first proposed is actually quite obvious. Sometimes errors cancel, and a small uncertainty doesn't make any difference in the final result; sometimes errors add, and a small uncertainty increases to a large uncertainty in the final result; and sometimes errors multiply, and a small uncertainty can add to a huge uncertainty. Opposition to this idea was not based on mathematics, logic or common sense, but on the idea that God and/or Nature would not be so cruel as to allow errors to multiply. Or in other words, "if this were true, it would be unfortunate, therefore it can't be true". The story of Mankind, really. -- Steven From greg.ewing at canterbury.ac.nz Sat Oct 1 23:24:42 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 02 Oct 2011 16:24:42 +1300 Subject: [OT] Chaos Theory [was Re: Benefit and belief] In-Reply-To: <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9eq3rtF7l0U1@mid.individual.net> Steven D'Aprano wrote: > By the way, who removed the OT label from the subject line? Probably nobody "removed" it, they just replied to some earlier message that didn't have it. Despite the term, a newsgroup thread is not a linear structure, it's a tree. Changing the subject line on one branch doesn't magically affect the other branches. -- Greg From ericsnowcurrently at gmail.com Sat Oct 1 23:41:57 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Sat, 1 Oct 2011 21:41:57 -0600 Subject: lower-case names for builtin types Message-ID: Anyone know the story behind the lower-case names for the non-exception built-in types (like list and type)? I am guessing that they were originally factory functions that, at some point, graduated to full types; and the names were kept lower-case for backward compatibility. However, if we were to consider making a change for Python 4, I am not sure how I feel about Int("5") over int("5"). Maybe it would be Integer("5"). Regardless, perhaps the type names are still lower-case for some other valid reason. If so, I would love to know what that is. Is there any merit to having lower-cased class names? -eric From steve+comp.lang.python at pearwood.info Sat Oct 1 23:52:44 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 02 Oct 2011 14:52:44 +1100 Subject: [OT] Chaos Theory [was Re: Benefit and belief] References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> <9eq3rtF7l0U1@mid.individual.net> Message-ID: <4e87e00d$0$29976$c3e8da3$5496439d@news.astraweb.com> Gregory Ewing wrote: > Steven D'Aprano wrote: >> By the way, who removed the OT label from the subject line? > > Probably nobody "removed" it, they just replied to some earlier > message that didn't have it. I started the "Benefit and belief" sub-thread, changing the subject line from "suggested coding style", and included a [OT] tag. So there was no earlier message of that subject without a tag to reply to. You know, I suspect this thread is a good example of chaos theory in action... for something that started off about coding styles, it has ended up in some fairly strange places... > Despite the term, a newsgroup thread is not a linear structure, > it's a tree. Changing the subject line on one branch doesn't > magically affect the other branches. I know that. I also know that it is irrelevant in this case. If your mail or news client has a threaded view, you can see for yourself who removed the tag. I was just being polite by not singling him out by name :) -- Steven From steve+comp.lang.python at pearwood.info Sun Oct 2 00:11:10 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 02 Oct 2011 15:11:10 +1100 Subject: lower-case names for builtin types References: Message-ID: <4e87e45f$0$29998$c3e8da3$5496439d@news.astraweb.com> Eric Snow wrote: > Anyone know the story behind the lower-case names for the > non-exception built-in types (like list and type)? I am guessing that > they were originally factory functions that, at some point, graduated > to full types; and the names were kept lower-case for backward > compatibility. Exactly. [steve at sylar ~]$ python1.5 Python 1.5.2 (#1, Apr 1 2009, 22:55:54) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> type(int) > However, if we were to consider making a change for Python 4, I am not > sure how I feel about Int("5") over int("5"). Maybe it would be > Integer("5"). > > Regardless, perhaps the type names are still lower-case for some other > valid reason. If so, I would love to know what that is. Is there any > merit to having lower-cased class names? Backwards compatibility and tradition. Many languages have functions to convert a value into a string, integer or float, which are usually written something like str(), int() and float(). It would seem strange to write them as Str(), Int() and Float() in Python just because they happen to be types. Maybe in Python 4000 there will be a push to rationalise the case of built-in types. -- Steven From ericsnowcurrently at gmail.com Sun Oct 2 00:41:47 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Sat, 1 Oct 2011 22:41:47 -0600 Subject: lower-case names for builtin types In-Reply-To: <4e87e45f$0$29998$c3e8da3$5496439d@news.astraweb.com> References: <4e87e45f$0$29998$c3e8da3$5496439d@news.astraweb.com> Message-ID: Thanks, Steven. On Sat, Oct 1, 2011 at 10:11 PM, Steven D'Aprano wrote: > Eric Snow wrote: > >> Anyone know the story behind the lower-case names for the >> non-exception built-in types (like list and type)? ?I am guessing that >> they were originally factory functions that, at some point, graduated >> to full types; and the names were kept lower-case for backward >> compatibility. > > Exactly. > > [steve at sylar ~]$ python1.5 > Python 1.5.2 (#1, Apr ?1 2009, 22:55:54) ?[GCC 4.1.2 20070925 (Red Hat > 4.1.2-27)] on linux2 > Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>>> type(int) > > > >> However, if we were to consider making a change for Python 4, I am not >> sure how I feel about Int("5") over int("5"). ?Maybe it would be >> Integer("5"). >> >> Regardless, perhaps the type names are still lower-case for some other >> valid reason. ?If so, I would love to know what that is. ?Is there any >> merit to having lower-cased class names? > > > Backwards compatibility and tradition. > > Many languages have functions to convert a value into a string, integer or > float, which are usually written something like str(), int() and float(). > It would seem strange to write them as Str(), Int() and Float() in Python > just because they happen to be types. > > Maybe in Python 4000 there will be a push to rationalise the case of > built-in types. > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > From bahamutzero8825 at gmail.com Sun Oct 2 01:12:05 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sun, 02 Oct 2011 00:12:05 -0500 Subject: Is there any way to access attributes from an imported module? Message-ID: <4E87F2A5.9000204@gmail.com> I'm not sure the subject's wording is the best, but I'll try to explain. I have a main script that imports several modules and I need to be able to call methods from a class instance inside that main script from a module. Currently, functions can be defined to access the methods, but such functions can only be called via commands sent to the main script (it's an IRC bot, and commands are sent via IRC). What I want to do is call those methods without sending commands (I want to send an IRC message from an except clause). I'm not too sure which bits are relevant, and it's probably a lot of code for a post, so I'll link: Main script (DelphiBot().load() is where commands are processed): https://github.com/sthrs/Beacon/blob/501ab1ffef83aa13613edb5985ad9a4570245a85/main.py The module I'm working on with examples of both functions that use commands and functions that don't: https://github.com/sthrs/Beacon/blob/501ab1ffef83aa13613edb5985ad9a4570245a85/modules/lastfm.py I have developer access to the repo, so modifying the main script is not an issue (I realize there is a very good possibility this will require changing the way the bot handles loading commands). A push in the right direction would be greatly appreciated, as I'm quite stumped. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 From steve+comp.lang.python at pearwood.info Sun Oct 2 02:55:13 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 02 Oct 2011 17:55:13 +1100 Subject: Is there any way to access attributes from an imported module? References: Message-ID: <4e880adc$0$29997$c3e8da3$5496439d@news.astraweb.com> Andrew Berg wrote: > I'm not sure the subject's wording is the best, but I'll try to explain. > I have a main script that imports several modules and I need to be able > to call methods from a class instance inside that main script from a > module. Currently, functions can be defined to access the methods, but > such functions can only be called via commands sent to the main script > (it's an IRC bot, and commands are sent via IRC). What I want to do is > call those methods without sending commands (I want to send an IRC > message from an except clause). Have I missed something? Why can't you just import the module and call the methods like you would for any other module and class? import module instance = module.Some_Class() result = instance.method(some, arguments, may, be, needed) -- Steven From raycores at gmail.com Sun Oct 2 03:26:23 2011 From: raycores at gmail.com (Lynn Oliver) Date: Sun, 2 Oct 2011 00:26:23 -0700 Subject: question on installing python 2.7.2 and tcl 8.5.10 on WinXP Message-ID: <0831907A-F8EB-4CC2-97A9-307671C8B3DA@gmail.com> Hello, I'm having problems building tcl/tk and python on Windows XP so that both are installed correctly. 1. ActivePython 2.7.2.5 works fine on my system but may be implicated in recent R6034 runtime errors from users. 2. Python.org 2.7.2 msi binaries install fine, but produce a "tcl wasn't installed correctly" runtime error from pyinstaller builds. 3. I built Python.org 2.7.2 sources using MSVC++ 2008 Express with a lot of manual work for the subprocess wrappers. The buildbot tools, which should more or less automate that process, did not work for me. 4. I can build tcl/tk 8.5.10 using MinGW/Msys. 5. When I built the tkinter component, I placed the build of tcl/tk where it was expected by the build scripts, and VC++ reported that the build was successful. However, if I start python.exe from the build directory, I can't import Tkinter (or tkinter). I feel like I must be missing some basic understanding of how and where things are installed; having completed the builds I still don't know how to install the resulting files into the correct directories. Any suggestions? Thanks for your help, Lynn -------------- next part -------------- An HTML attachment was scrubbed... URL: From bahamutzero8825 at gmail.com Sun Oct 2 04:01:20 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sun, 02 Oct 2011 03:01:20 -0500 Subject: Is there any way to access attributes from an imported module? In-Reply-To: <4e880adc$0$29997$c3e8da3$5496439d@news.astraweb.com> References: <4e880adc$0$29997$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E881A50.8060303@gmail.com> On 2011.10.02 01:55 AM, Steven D'Aprano wrote: > Have I missed something? Why can't you just import the module and call the > methods like you would for any other module and class? > > import module > instance = module.Some_Class() > result = instance.method(some, arguments, may, be, needed) I need to affect the instance created in the main script; creating a new instance would be pointless (and AFAICT would result in the interpreter hitting a recursion limit since the module is imported during creation of the instance). -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 From bahamutzero8825 at gmail.com Sun Oct 2 04:42:24 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sun, 02 Oct 2011 03:42:24 -0500 Subject: Is there any way to access attributes from an imported module? In-Reply-To: <4E880E87.5070507@islandtraining.com> References: <4E87F2A5.9000204@gmail.com> <4E880E87.5070507@islandtraining.com> Message-ID: <4E8823F0.8080102@gmail.com> On 2011.10.02 02:11 AM, Gary Herron wrote: > You may be able to do the simplest thing: If a module wants to call > something form the main module (or main script as you call it) just try > importing that main script and call whatever it is you want. This > results in a circular set of imports, but Python can often deal with > those without trouble. (Not always, so circular imports are best > avoided in general, but .. try it and see.) It doesn't work. I get an AttributeError any time I try to access the class instance from the sub-module. Even moving the load() call outside __init__() doesn't change this. > If there is code in the main script (module) that needs to be called > form elsewhere, take it out of the main module and put it in a separate > module. Then import that new module both in the main script, and the > various sub-modules. This is cleaner than the circular imports in the > previous solution. I need to affect a specific instance which imports the sub-modules. I worded the subject line wrong (and I've no clue how to word it now). This is quite hard to explain, and I don't think it's easy to understand without really examining the code (I don't even fully understand it). More ideas are certainly welcome, but I think I'll have to ask the developer (who has only been somewhat active lately). -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 From steve+comp.lang.python at pearwood.info Sun Oct 2 04:50:07 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 02 Oct 2011 19:50:07 +1100 Subject: Is there any way to access attributes from an imported module? References: <4e880adc$0$29997$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e8825c0$0$29992$c3e8da3$5496439d@news.astraweb.com> Andrew Berg wrote: > On 2011.10.02 01:55 AM, Steven D'Aprano wrote: >> Have I missed something? Why can't you just import the module and call >> the methods like you would for any other module and class? >> >> import module >> instance = module.Some_Class() >> result = instance.method(some, arguments, may, be, needed) > > I need to affect the instance created in the main script; Then call the methods on the instance created in the main script. I'm still failing to see your problem. -- Steven From tartley at tartley.com Sun Oct 2 05:10:16 2011 From: tartley at tartley.com (Jonathan Hartley) Date: Sun, 2 Oct 2011 02:10:16 -0700 (PDT) Subject: executing arbitrary statements In-Reply-To: References: Message-ID: <12122472.2101.1317546616537.JavaMail.geo-discussion-forums@yqma37> On Saturday, October 1, 2011 8:06:43 AM UTC+1, Chris Rebert wrote: > On Fri, Sep 30, 2011 at 11:31 PM, Jason Swails wrote: > > I'm probably missing something pretty obvious, but I was wondering if there > > was a way of executing an arbitrary line of code somehow (such as a line of > > code based on user-input).? There's the obvious use of "eval" that will > > evaluate a function call, but that doesn't allow all things. > > > Because write is a function eval works fine for it.? But since print isn't > > (2.7), it throws a syntax error.? Likewise, variable assignments aren't > > allowed either as they are also not functions and lack a return value: > > > Use the `exec` statement, which is capable of executing statements (as > opposed to just expressions): > http://docs.python.org/reference/simple_stmts.html#the-exec-statement > > > What I'm more or less looking to do is present a (limited) form of an > > interpreter inside the application I'm writing for the advanced user. > > > > I'm also interested to hear if this is a particularly bad idea for any > > reason, > > It's potentially rather hacky and ad-hoc to effectively directly > inject arbitrary statements at certain points in your code. > > Assuming you were to trust the user-provided code, callbacks/hooks or > plugin modules are typically much cleaner ways to integrate custom > code from the user. > > Depending on your particular use case, the `cmd` module might also be > a workable alternative: > http://docs.python.org/library/cmd.html > > > and if there are security issues involved with allowing users to > > execute their own code inside my program (keeping in mind that some people > > may "donate" their scripts to others that may run them as black boxes). > > It is *very much* a security issue! > > > Is > > it enough to disallow import statements, thereby not giving direct access to > > the sys and os modules? > > Not by a long shot! There are a bunch of known tricks that exploit > introspection to circumvent such restrictions. > Secure execution of untrusted Python code is a difficult problem. Some > have accomplished it to a degree, but typically only by modifying the > interpreter itself or imposing relatively onerous restrictions on the > untrusted code. > > > I know more or less what I want to do, but I'd also > > appreciate any experienced input/advice/suggestions. > > I additionally came across this in researching my reply: > http://pypi.python.org/pypi/RestrictedPython/ > Apparently the speed of execution leaves something to be desired, but > the package /supposedly/ works well otherwise. > > Cheers, > Chris > -- > http://rebertia.com I (and many others) entirely avoid using 'eval' in all my code for many years, based on the security concerns that Chris rightly highlights. It's worth noting though, that RaymondH's talks last year on some valid uses of 'eval' and 'exec' have opened my eyes to it somewhat. In summary, while it's dangerous to execute user-submitted code, there are no security risks associated with executing code generated by your own program. It takes a while to see how this might be useful, if (like me) you're not used to thinking about it. Raymond's premier example was his implementation of namedtuple: (see http://hg.python.org/cpython/file/default/Lib/collections/__init__.py) This defines a string, the contents of which is a class definition, with some string formatting markers in it. These are replaced with known values on invocation of the namedtuple factory function, which then exec's the class-definition string and returns the resulting new type. This results in an implementation that is both simpler and faster than trying to simply write a general-purpose class that does at runtime all the things that 'namedtuple' does. From tartley at tartley.com Sun Oct 2 05:10:16 2011 From: tartley at tartley.com (Jonathan Hartley) Date: Sun, 2 Oct 2011 02:10:16 -0700 (PDT) Subject: executing arbitrary statements In-Reply-To: References: Message-ID: <12122472.2101.1317546616537.JavaMail.geo-discussion-forums@yqma37> On Saturday, October 1, 2011 8:06:43 AM UTC+1, Chris Rebert wrote: > On Fri, Sep 30, 2011 at 11:31 PM, Jason Swails wrote: > > I'm probably missing something pretty obvious, but I was wondering if there > > was a way of executing an arbitrary line of code somehow (such as a line of > > code based on user-input).? There's the obvious use of "eval" that will > > evaluate a function call, but that doesn't allow all things. > > > Because write is a function eval works fine for it.? But since print isn't > > (2.7), it throws a syntax error.? Likewise, variable assignments aren't > > allowed either as they are also not functions and lack a return value: > > > Use the `exec` statement, which is capable of executing statements (as > opposed to just expressions): > http://docs.python.org/reference/simple_stmts.html#the-exec-statement > > > What I'm more or less looking to do is present a (limited) form of an > > interpreter inside the application I'm writing for the advanced user. > > > > I'm also interested to hear if this is a particularly bad idea for any > > reason, > > It's potentially rather hacky and ad-hoc to effectively directly > inject arbitrary statements at certain points in your code. > > Assuming you were to trust the user-provided code, callbacks/hooks or > plugin modules are typically much cleaner ways to integrate custom > code from the user. > > Depending on your particular use case, the `cmd` module might also be > a workable alternative: > http://docs.python.org/library/cmd.html > > > and if there are security issues involved with allowing users to > > execute their own code inside my program (keeping in mind that some people > > may "donate" their scripts to others that may run them as black boxes). > > It is *very much* a security issue! > > > Is > > it enough to disallow import statements, thereby not giving direct access to > > the sys and os modules? > > Not by a long shot! There are a bunch of known tricks that exploit > introspection to circumvent such restrictions. > Secure execution of untrusted Python code is a difficult problem. Some > have accomplished it to a degree, but typically only by modifying the > interpreter itself or imposing relatively onerous restrictions on the > untrusted code. > > > I know more or less what I want to do, but I'd also > > appreciate any experienced input/advice/suggestions. > > I additionally came across this in researching my reply: > http://pypi.python.org/pypi/RestrictedPython/ > Apparently the speed of execution leaves something to be desired, but > the package /supposedly/ works well otherwise. > > Cheers, > Chris > -- > http://rebertia.com I (and many others) entirely avoid using 'eval' in all my code for many years, based on the security concerns that Chris rightly highlights. It's worth noting though, that RaymondH's talks last year on some valid uses of 'eval' and 'exec' have opened my eyes to it somewhat. In summary, while it's dangerous to execute user-submitted code, there are no security risks associated with executing code generated by your own program. It takes a while to see how this might be useful, if (like me) you're not used to thinking about it. Raymond's premier example was his implementation of namedtuple: (see http://hg.python.org/cpython/file/default/Lib/collections/__init__.py) This defines a string, the contents of which is a class definition, with some string formatting markers in it. These are replaced with known values on invocation of the namedtuple factory function, which then exec's the class-definition string and returns the resulting new type. This results in an implementation that is both simpler and faster than trying to simply write a general-purpose class that does at runtime all the things that 'namedtuple' does. From steve+comp.lang.python at pearwood.info Sun Oct 2 10:11:04 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 03 Oct 2011 01:11:04 +1100 Subject: executing arbitrary statements References: Message-ID: <4e8870f9$0$29979$c3e8da3$5496439d@news.astraweb.com> Jonathan Hartley wrote: > I (and many others) entirely avoid using 'eval' in all my code for many > years, based on the security concerns that Chris rightly highlights. It's > worth noting though, that RaymondH's talks last year on some valid uses of > 'eval' and 'exec' have opened my eyes to it somewhat. In summary, while > it's dangerous to execute user-submitted code, there are no security risks > associated with executing code generated by your own program. That's not strictly true. If you look at the code for namedtuple, you will see that Raymond actually spends significant effort to sanitise the input to namedtuple. Right at the top of the class is this comment: # Parse and validate the field names. Validation serves two purposes, # generating informative error messages and preventing template injection attacks. So even something like namedtuple needs to take care of security risks. In a more general sense, "security" does not necessarily mean security against outsiders. Sometimes the threat you're defending from is an insider, or even yourself: for example, there are various utility programs designed to prevent you from emailing while drunk (I know people who should use them!), *many* security protocols designed to prevent a single rogue member of an organisation from doing harm (e.g. it takes at least two people to launch nuclear warheads), etc. This is why (for example) on Linux, the rm command defaults to interactive use when given as root. If you've ever typed rm -r * in the wrong directory (especially the root directory) you'll understand that sometimes the worst threat is yourself. -- Steven From rustompmody at gmail.com Sun Oct 2 11:03:07 2011 From: rustompmody at gmail.com (rusi) Date: Sun, 2 Oct 2011 08:03:07 -0700 (PDT) Subject: Chaos Theory [was Re: Benefit and belief] References: <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Oct 2, 8:03?am, Steven D'Aprano wrote: > By the way, who removed the OT label from the subject line? Please don't > unless it actually comes back on topic. > > DevPlayer wrote: > > I still assert that contradiction is caused by narrow perspective. > > There's no doubt that some *apparent* contradictions are caused by lack of > correct information. But: > > N is an even number; > N (the same N, for avoidance of doubt) is an odd number > > is still a contradiction, no matter how you look at it. DevPlayer is probably talking of 'synthetic/a posteriori' statements You're changing it to 'analytic/a priori' (like the OT subject line ) (see http://en.wikipedia.org/wiki/Analytic%E2%80%93synthetic_distinction#Kant ) From marko.loparic at gmail.com Sun Oct 2 13:36:30 2011 From: marko.loparic at gmail.com (markolopa) Date: Sun, 2 Oct 2011 10:36:30 -0700 (PDT) Subject: Replacing spreadsheets by Python and the browser Message-ID: <307ff168-fba6-4017-8ecb-a758b32c14b2@g23g2000vbz.googlegroups.com> Hello, Could you please recommend me a Python tool that could help me to get rid of the messy information and scripts I have in spreadsheets? Spreadsheets are great for having simple things done quickly. But as the needs grow their limitations can be quite frustrating. I would like to use the browser to edit information that for the moment I store in spreadsheets. I believe that the perfect tool for me would be that a combination a table editing tool and a tree navigation tool. I would like to navigate in a tree, expanding and collapsing nodes. The leaf nodes would then be tables with some editable columns. A good table editing tool (without the tree navigation) would already be very helpful. Examples of information I would store in such a tree/table system (which are now in spreasheets): - My dvd, avi collection: The tree would be the directory tree of the file system where I store my movies. For each directory containing the avis or the dvds there would be a table with one movie by row and several editable columns: the file name, the genre, the year, whether I have seen it or not, comments, etc. . The same thing for mp3. - My family budget. The tree would be the account tree, the rows in the table would be the deposits and withdrwals. This is actually my most important need. I don't find gnucash flexible enough for my needs. Beancount (http://furius.ca/beancount/) has a great html output, but I would like to use the browser also for input. I am very comfortable with Python, but I don't know much about web framewords and javascript interfaces. I am ready to learn anything that could help me to do the desired tasks quickly, without having to code a web application from scratch. Is javascript the way to go? In this case is there a Python lib can I use on the server side? Could a tool like django be helpful? Pyjamas? Both a single machine or a client-server architecture are fine for me. Thanks a lot in advance for all suggestion, Marko From rustompmody at gmail.com Sun Oct 2 13:48:35 2011 From: rustompmody at gmail.com (rusi) Date: Sun, 2 Oct 2011 10:48:35 -0700 (PDT) Subject: Replacing spreadsheets by Python and the browser References: <307ff168-fba6-4017-8ecb-a758b32c14b2@g23g2000vbz.googlegroups.com> Message-ID: <310597fc-3654-4eb1-a0a1-436554b421ae@q25g2000vbx.googlegroups.com> On Oct 2, 10:36?pm, markolopa wrote: > Hello, > > Could you please recommend me a Python tool that could help me to get > rid of the messy information and scripts I have in spreadsheets? > > Spreadsheets are great for having simple things done quickly. But as > the needs grow their limitations can be quite frustrating. I would > like to use the browser to edit information that for the moment I > store in spreadsheets. > > I believe that the perfect tool for me would be that a combination a > table editing tool and a tree navigation tool. I would like to > navigate in a tree, expanding and collapsing nodes. The leaf nodes > would then be tables with some editable columns. > > A good table editing tool (without the tree navigation) would already > be very helpful. > > Examples of information I would store in such a tree/table system > (which are now in spreasheets): > - My dvd, avi collection: The tree would be the directory tree of the > file system where I store my movies. For each directory containing the > avis or the dvds there would be a table with one movie by row and > several editable columns: the file name, the genre, the year, whether > I have seen it or not, comments, etc. > . The same thing for mp3. > - My family budget. The tree would be the account tree, the rows in > the table would be the deposits and withdrwals. This is actually my > most important need. I don't find gnucash flexible enough for my > needs. ?Beancount (http://furius.ca/beancount/) has a great html > output, but I would like to use the browser also for input. > > I am very comfortable with Python, but I don't know much about web > framewords and javascript interfaces. I am ready to learn anything > that could help me to do the desired tasks quickly, without having to > code a web application from scratch. Is javascript the way to go? In > this case is there a Python lib can I use on the server side? Could a > tool like django be helpful? Pyjamas? Both a single machine or a > client-server architecture are fine for me. > > Thanks a lot in advance for all suggestion, > Marko May not be what you are asking for but you may want to look at orgmode: http://orgmode.org/ From andrea.crotti.0 at gmail.com Sun Oct 2 13:51:25 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Sun, 02 Oct 2011 18:51:25 +0100 Subject: Replacing spreadsheets by Python and the browser In-Reply-To: <307ff168-fba6-4017-8ecb-a758b32c14b2@g23g2000vbz.googlegroups.com> References: <307ff168-fba6-4017-8ecb-a758b32c14b2@g23g2000vbz.googlegroups.com> Message-ID: <4E88A49D.2040704@gmail.com> On 10/02/2011 06:36 PM, markolopa wrote: > Hello, > > Could you please recommend me a Python tool that could help me to get > rid of the messy information and scripts I have in spreadsheets? > > Spreadsheets are great for having simple things done quickly. But as > the needs grow their limitations can be quite frustrating. I would > like to use the browser to edit information that for the moment I > store in spreadsheets. > > I believe that the perfect tool for me would be that a combination a > table editing tool and a tree navigation tool. I would like to > navigate in a tree, expanding and collapsing nodes. The leaf nodes > would then be tables with some editable columns. > > A good table editing tool (without the tree navigation) would already > be very helpful. > > Examples of information I would store in such a tree/table system > (which are now in spreasheets): > - My dvd, avi collection: The tree would be the directory tree of the > file system where I store my movies. For each directory containing the > avis or the dvds there would be a table with one movie by row and > several editable columns: the file name, the genre, the year, whether > I have seen it or not, comments, etc. > . The same thing for mp3. > - My family budget. The tree would be the account tree, the rows in > the table would be the deposits and withdrwals. This is actually my > most important need. I don't find gnucash flexible enough for my > needs. Beancount (http://furius.ca/beancount/) has a great html > output, but I would like to use the browser also for input. > > I am very comfortable with Python, but I don't know much about web > framewords and javascript interfaces. I am ready to learn anything > that could help me to do the desired tasks quickly, without having to > code a web application from scratch. Is javascript the way to go? In > this case is there a Python lib can I use on the server side? Could a > tool like django be helpful? Pyjamas? Both a single machine or a > client-server architecture are fine for me. > > Thanks a lot in advance for all suggestion, > Marko Well my answer is not really python-related, but one tool that really changed my life is orgmode http://orgmode.org/ It does almost everything you ask and a 1000 other things. If you want to go with a python project, in general you should probably need a lot of javascript to have something which is nice and easy to use, and yes something like django would work. From yasar11732 at gmail.com Sun Oct 2 14:22:56 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Sun, 2 Oct 2011 21:22:56 +0300 Subject: Adding new keywords to Python interpreter Message-ID: Hi people, Nowadays, I am trying to explore python source. I added a new keyword, essentially doing same thing as 'continue' keyword to the interpreter, mostly by following instructions in PEP 306. If anyone interested here is the video about how I did it: http://www.youtube.com/watch?v=Ww7BeIdUbUI notes in video are in Turkish, but you don't require the notes much, as they don't mention any crucial point. By the way, I am not saying this is the best, or even right way to do it. I am just sharing what I have done. Have a nice day :) -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From rantingrick at gmail.com Sun Oct 2 15:01:18 2011 From: rantingrick at gmail.com (rantingrick) Date: Sun, 2 Oct 2011 12:01:18 -0700 (PDT) Subject: Replacing spreadsheets by Python and the browser References: <307ff168-fba6-4017-8ecb-a758b32c14b2@g23g2000vbz.googlegroups.com> Message-ID: <8b7a28d7-d826-4e02-bb68-5cae6a0db6d1@i28g2000yqn.googlegroups.com> On Oct 2, 12:36?pm, markolopa wrote: > Examples of information I would store in such a tree/table system > (which are now in spreasheets): > - My dvd, avi collection: The tree would be the directory tree of the > file system where I store my movies. For each directory containing the > avis or the dvds there would be a table with one movie by row and > several editable columns: the file name, the genre, the year, whether > I have seen it or not, comments, etc. > . The same thing for mp3. > - My family budget. The tree would be the account tree, the rows in > the table would be the deposits and withdrwals. This is actually my > most important need. I don't find gnucash flexible enough for my > needs. ?Beancount (http://furius.ca/beancount/) has a great html > output, but I would like to use the browser also for input. Is there any reason why you could not use the advanced widgets in WxPython? You never said whether this MUST BE a web application. If GUI is okay then check out wxListCtrl and wxTreeCtrl. All you need to do is write a little control code and voila. http://www.wxpython.org/onlinedocs.php From python at bdurham.com Sun Oct 2 15:38:43 2011 From: python at bdurham.com (python at bdurham.com) Date: Sun, 02 Oct 2011 15:38:43 -0400 Subject: Replacing spreadsheets by Python and the browser In-Reply-To: References: <307ff168-fba6-4017-8ecb-a758b32c14b2@g23g2000vbz.googlegroups.com> Message-ID: <1317584323.23992.140258150165505@webmail.messagingengine.com> Check out ResolverOne http://www.resolversystems.com Malcolm From andrea.gavana at gmail.com Sun Oct 2 17:29:24 2011 From: andrea.gavana at gmail.com (Andrea Gavana) Date: Mon, 3 Oct 2011 00:29:24 +0300 Subject: Change import order with *.pth files Message-ID: Hi All, my apologies if this is a dumb question, but I couldn't find a solution - possibly because I am not sure how to state my problem in a short sentence. Let's say I am using a package called "blah", and this package is already installed on site-packages (and I need it to be there) with a name "blah-1.2-win". In the site-packages folder, there is a pth file called "blah.pth" which contains this line: blah-1.2-win To redirect Python to the correct folder when I type "import blah". Anyway, now I am developing another version of this package and it's called "blah-2.0-win", and it sits on my computer into a different folder (not on site-packages, on an entire different drive in reality). How can I tell Python *not* to use the version inside site-packages but to use the other one in my development folder (without touching the pth file in site-packages, of course)? I have tried fiddling with sys.path and to create a local (in my development folder) pth file, to no avail. I hope I have been able to explain my problem clearly... This is on Windows, Python 2.5 to 2.7. Thank you in advance for your suggestions. Andrea. "Imagination Is The Only Weapon In The War Against Reality." http://xoomer.alice.it/infinity77/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Sun Oct 2 17:43:44 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 02 Oct 2011 21:43:44 GMT Subject: [OT] Re: Chaos Theory [was Re: Benefit and belief] References: <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e88db0f$0$29981$c3e8da3$5496439d@news.astraweb.com> On Sun, 02 Oct 2011 08:03:07 -0700, rusi wrote: > On Oct 2, 8:03?am, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: >> By the way, who removed the OT label from the subject line? Please >> don't unless it actually comes back on topic. >> >> DevPlayer wrote: >> > I still assert that contradiction is caused by narrow perspective. >> >> There's no doubt that some *apparent* contradictions are caused by lack >> of correct information. But: >> >> N is an even number; >> N (the same N, for avoidance of doubt) is an odd number >> >> is still a contradiction, no matter how you look at it. > > DevPlayer is probably talking of 'synthetic/a posteriori' statements > You're changing it to 'analytic/a priori' (like the OT subject line > ) > (see > http://en.wikipedia.org/wiki/Analytic%E2%80%93synthetic_distinction#Kant > ) An interesting link. I knew the Objectivists were nuts, but I really didn't appreciate quite how nuts they were until I read Leonard Peikoff's criticism of Kant. Not that I necessary agree with Kant, but the Objectivist argument basically boils down to "We would like empirical knowledge to be 100% certain, but Kant demonstrates that it isn't. Therefore he must be wrong." Or to put it another way: "I reject your reality and substitute my own." But in any case, no, I am not merely talking about analytic/a priori statements. Here's a synthetic/a priori version: (a) The sum of odd numbers between 6 and 20 equals 91. (b) The sum of odd numbers between 6 and 20 equals 93. and here's a synthetic/a posteriori version: (c) During the 1936 Olympic Games, the leader of the host nation had a full beard. (d) During the 1936 Olympic Games, the leader of the host nation did not have a full beard. Unlike Kant, I don't think that analytic/a posteriori is contradictory. Here is an example: (e) Combustion is caused by a chemical reaction between an oxidant and some other reagent. (f) Combustion is caused by the release of phlogiston from materials. In all cases, we can be sure that the contradiction between the pair of statements are genuine contradictions and not mere apparent contradictions caused by "narrow perspective" or incomplete or erroneous knowledge. -- Steven From andrea.crotti.0 at gmail.com Sun Oct 2 17:57:23 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Sun, 02 Oct 2011 22:57:23 +0100 Subject: Change import order with *.pth files In-Reply-To: References: Message-ID: <4E88DE43.1040607@gmail.com> On 10/02/2011 10:29 PM, Andrea Gavana wrote: > Hi All, > > my apologies if this is a dumb question, but I couldn't find a > solution - possibly because I am not sure how to state my problem in > a short sentence. > > Let's say I am using a package called "blah", and this package is > already installed on site-packages (and I need it to be there) with a > name "blah-1.2-win". In the site-packages folder, there is a pth file > called "blah.pth" which contains this line: > > blah-1.2-win > > To redirect Python to the correct folder when I type "import blah". > Anyway, now I am developing another version of this package and it's > called "blah-2.0-win", and it sits on my computer into a different > folder (not on site-packages, on an entire different drive in > reality). How can I tell Python *not* to use the version inside > site-packages but to use the other one in my development folder > (without touching the pth file in site-packages, of course)? > > I have tried fiddling with sys.path and to create a local (in my > development folder) pth file, to no avail. I hope I have been able to > explain my problem clearly... This is on Windows, Python 2.5 to 2.7. > > Thank you in advance for your suggestions. > > Andrea. Well messing up with the pth file is not a very good idea in general, since it's thought to be manipulated by distutils, not by hand. The best way to solve your problem is to use virtualenv or something similar, check it out... From kw at codebykevin.com Sun Oct 2 18:02:05 2011 From: kw at codebykevin.com (Kevin Walzer) Date: Sun, 02 Oct 2011 18:02:05 -0400 Subject: getattr and method name Message-ID: I'm seeing a very odd error in an application I'm developing using Python 2.7.2, on Mac OS 10.7. This application uses a wrapper method to look up other method names via getattr and then call those methods. I have not previously had an issue with this name, but for some reason this functionality no longer works as expected. Here is the relevant code: #run command with root privileges def runCommand(self, cmd, *args): try: functionstring = args[2] callfunction = getattr(self, functionstring.split('.')[1]) self.passtext = self.tk.call('authorize::getAuthPassword') callfunction() except: try: print cmd functionstring = cmd.split()[2] callfunction = getattr(self, functionstring.split('.')[1]) self.passtext = self.tk.call('authorize::getAuthPassword') callfunction() except: raise I use this approach to call the method named in the "cmd" parameter because I also have to look up a password name that is returned by an underlying Tk package that I use in my application (that's the reason for the 'self.tk.call'). What is happening is when I use the "callfunction()" call, instead of the method name being called, a string like this is being invoked: > The "scanPackages" method (just to use it as an example) uses Popen to call an underlying system tool on the OS. However, when invoked via callfunction(), the 'bound method...' string is passed to the OS instead as a command! As a result, I get this output from the pipe: /bin/sh: bound: No such file or directory I am not sure what in my application is causing this kind of breakage, as earlier versions of the app ran fine with similar code on earlier versions on the OS. Is this the correct way to structure this kind of functionality, or am I better off structuring it some other way? --Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From steveo at syslang.net Sun Oct 2 18:12:03 2011 From: steveo at syslang.net (Steven W. Orr) Date: Sun, 02 Oct 2011 18:12:03 -0400 Subject: Advise on using logging.getLogger needed. Message-ID: <4E88E1B3.6080009@syslang.net> I hope I don't sound like I'm ranting :-( I have created a module (called xlogging) which sets up logging the way I want it. I found out that if I set up my logger without a name, then it gets applied to every logger that is referenced by every module that ever gets imported. The problem is that I must call xlogging.getLogger or logging.getLogger in all other modules using the name of the root logger, and I don't know what that name is. I want the name of the root logger to be the name of the running program, so in my setup, I say pname = sys.argv[0] try: rslash = pname.rindex('/') except ValueError: pass else: pname = pname[rslash + 1:] try: dot_py = pname.rindex('.py') except ValueError: pass else: pname = pname[0:dot_py] and then I say logger = logging.getLogger(pname) My problem is that I just want the modules that I write, to be able to get the named root logger and still be able to refer to possible sub-loggers. So, let's say I run program foo. At some point in my mail setup, I set the configuration for the foo logger. I'd like my xlogging module to supply a getLogger function such that if I don't supply any arguments, it will return the logger that would normally be returned by logging.getLogger(pname). Also, part of the reason I'm confused is because foo calls m1 and m2 and they want to say logger = xlogging.getLogger(MaybeWithAnArg?) at the top of their code. This means that the import statement for m1 and m2 are getting the calls to getLogger executed before I get the chance to set things up. I am running 2.6, so I don't have access to logging.getChild, but I'm not clear that I even want that. My modules are used by multiple programs. Does this mean that I should simply use __name__ all the time? (That seems inelegant, no?) If I'm making sense, is there a way to do this? -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From emekamicro at gmail.com Sun Oct 2 18:15:09 2011 From: emekamicro at gmail.com (Emeka) Date: Mon, 3 Oct 2011 00:15:09 +0200 Subject: TK + MVC In-Reply-To: <9eq19cFmb2U1@mid.individual.net> References: <9eq19cFmb2U1@mid.individual.net> Message-ID: Greg, Do you have an example where the Controller is connected? Regards, EMeka On Sun, Oct 2, 2011 at 4:40 AM, Gregory Ewing wrote: > Alexander Kapps wrote: > > But I think a simple (and quick 'n' dirty) Tk MVC example can look like >> this: >> > > The Controller doesn't seem to add any value in that example. > You might as well connect the Model and Views directly to > each other. > > -- > Greg > -- > http://mail.python.org/**mailman/listinfo/python-list > -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Oct 2 18:34:44 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 Oct 2011 15:34:44 -0700 Subject: getattr and method name In-Reply-To: References: Message-ID: On Sun, Oct 2, 2011 at 3:02 PM, Kevin Walzer wrote: > I'm seeing a very odd error in an application I'm developing using Python > 2.7.2, on Mac OS 10.7. > > This application uses a wrapper method to look up other method names via > getattr and then call those methods. I have not previously had an issue with > this name, but for some reason this functionality no longer works as > expected. > > Here is the relevant code: > > ? ?#run command with root privileges > ? ?def runCommand(self, cmd, *args): > ? ? ? ?try: > ? ? ? ? ? ?functionstring = args[2] > ? ? ? ? ? ?callfunction = getattr(self, functionstring.split('.')[1]) > ? ? ? ? ? ?self.passtext = self.tk.call('authorize::getAuthPassword') > ? ? ? ? ? ?callfunction() > ? ? ? ?except: > ? ? ? ? ? ?try: > ? ? ? ? ? ? ? ?print cmd > ? ? ? ? ? ? ? ?functionstring = cmd.split()[2] > ? ? ? ? ? ? ? ?callfunction = getattr(self, functionstring.split('.')[1]) > ? ? ? ? ? ? ? ?self.passtext = self.tk.call('authorize::getAuthPassword') > ? ? ? ? ? ? ? ?callfunction() > ? ? ? ? ? ?except: > ? ? ? ? ? ? ? ?raise > > I use this approach to call the method named in the "cmd" parameter because > I also have to look up a password name that is returned by an underlying Tk > package that I use in my application (that's the reason for the > 'self.tk.call'). What is happening is when I use the "callfunction()" call, > instead of the method name being called, a string like this is being > invoked: > > instance at 0x101b232d8>> Er, your terminology seems kinda funky. Do you mean to say that repr(callfunction) results in that string (which is normal and expected), or that the return value from callfunction() is that string (which would be rather bizarre)? I would presume the former. [One does not call/invoke a string; strings aren't callable.] > The "scanPackages" method (just to use it as an example) uses Popen to call > an underlying system tool on the OS. However, when invoked via > callfunction(), the 'bound method...' string is passed to the OS instead as > a command! As a result, I get this output from the pipe: > > /bin/sh: bound: No such file or directory Either you've elided some important part of the code from your fragment above, or the problem would seem to lie in scanPackages() [presumably its Popen() call is screwy]. Please post the code for scanPackages(), and (if applicable) the full code for runCommand(). Cheers, Chris -- http://rebertia.com From tjreedy at udel.edu Sun Oct 2 18:55:46 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 02 Oct 2011 18:55:46 -0400 Subject: getattr and method name In-Reply-To: References: Message-ID: On 10/2/2011 6:02 PM, Kevin Walzer wrote: > I'm seeing a very odd error in an application I'm developing using > Python 2.7.2, on Mac OS 10.7. > > This application uses a wrapper method to look up other method names via > getattr and then call those methods. I have not previously had an issue > with this name, but for some reason this functionality no longer works > as expected. > > Here is the relevant code: > > #run command with root privileges > def runCommand(self, cmd, *args): > try: > functionstring = args[2] > callfunction = getattr(self, functionstring.split('.')[1]) > self.passtext = self.tk.call('authorize::getAuthPassword') > callfunction() > except: > try: > print cmd > functionstring = cmd.split()[2] > callfunction = getattr(self, functionstring.split('.')[1]) > self.passtext = self.tk.call('authorize::getAuthPassword') > callfunction() > except: > raise > > I use this approach to call the method named in the "cmd" parameter > because I also have to look up a password name that is returned by an > underlying Tk package that I use in my application (that's the reason > for the 'self.tk.call'). What is happening is when I use the > "callfunction()" call, instead of the method name being called, a string > like this is being invoked: > > <__main__.phynchronicityApp instance at 0x101b232d8>> > > The "scanPackages" method (just to use it as an example) uses Popen to > call an underlying system tool on the OS. However, when invoked via > callfunction(), the 'bound method...' string is passed to the OS instead > as a command! As a result, I get this output from the pipe: > > /bin/sh: bound: No such file or directory > > I am not sure what in my application is causing this kind of breakage, > as earlier versions of the app ran fine with similar code on earlier > versions on the OS. Is this the correct way to structure this kind of > functionality, or am I better off structuring it some other way? I do not know of any 2.7 changes that would affect such code. Perhaps you changed something in the method being invoked (not shown) . You did not specify whether you have the problem in the first or second try block. I would start with printing the type and value of some to all of the variables. -- Terry Jan Reedy From alex.kapps at web.de Sun Oct 2 19:13:48 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Mon, 03 Oct 2011 01:13:48 +0200 Subject: TK + MVC In-Reply-To: <9eq19cFmb2U1@mid.individual.net> References: <9eq19cFmb2U1@mid.individual.net> Message-ID: <4E88F02C.10405@web.de> On 02.10.2011 04:40, Gregory Ewing wrote: > Alexander Kapps wrote: > >> But I think a simple (and quick 'n' dirty) Tk MVC example can look >> like this: > > The Controller doesn't seem to add any value in that example. > You might as well connect the Model and Views directly to > each other. > Sure, in that simple example the Controller is just there to show a complete MVC pattern with all three parts. There are often examples where the View is actually both, the View and the Controller. That's why I said that I'm not sure if I really understand the MVC pattern. There are so many different versions, sometimes strict and sometimes less strict, and I think what's the real problem with my example is, whether it is really correct to not connect the Model and the View directly, but to let the Controller "mediate" between both. From alex.kapps at web.de Sun Oct 2 19:14:35 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Mon, 03 Oct 2011 01:14:35 +0200 Subject: TK + MVC In-Reply-To: References: <9eq19cFmb2U1@mid.individual.net> Message-ID: <4E88F05B.3090801@web.de> On 03.10.2011 00:15, Emeka wrote: > Greg, > > Do you have an example where the Controller is connected? What do you mean? In my example, the Controller *is* connected (to both the View and the Model.) From steve+comp.lang.python at pearwood.info Sun Oct 2 19:21:32 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 02 Oct 2011 23:21:32 GMT Subject: getattr and method name References: Message-ID: <4e88f1fc$0$29981$c3e8da3$5496439d@news.astraweb.com> On Sun, 02 Oct 2011 18:02:05 -0400, Kevin Walzer wrote: > I'm seeing a very odd error in an application I'm developing using > Python 2.7.2, on Mac OS 10.7. > > This application uses a wrapper method to look up other method names via > getattr and then call those methods. I have not previously had an issue > with this name, but for some reason this functionality no longer works > as expected. > > Here is the relevant code: > > #run command with root privileges > def runCommand(self, cmd, *args): > try: > functionstring = args[2] > callfunction = getattr(self, functionstring.split('.')[1]) > self.passtext = self.tk.call('authorize::getAuthPassword') > callfunction() > except: Bare excepts should almost never be used. I'd say they certainly shouldn't be used like this: you can mask coding bugs, user KeyboardInterrupts, and other things which shouldn't be masked. It also obscures the intent of the code. As far as I can see, it appears that this method expects to be called like this: instance.runCommand(cmd, some, arbitrary, number, of, extra, args) In this case, the method tries to authenticate and then execute some command based on "number" (but ignoring all other arguments, including cmd); if ANY failure occurs at all, including too few arguments, missing dot in the argument, or failed authentication(?), then try again using "cmd" instead. I don't understand the intent of this code. > try: > print cmd > functionstring = cmd.split()[2] > callfunction = getattr(self, > functionstring.split('.')[1]) > self.passtext = self.tk.call( > 'authorize::getAuthPassword') > callfunction() > except: > raise This try block is completely unnecessary. What's the point of catching an exception only to immediately raise it again? > I use this approach to call the method named in the "cmd" parameter > because I also have to look up a password name that is returned by an > underlying Tk package that I use in my application (that's the reason > for the 'self.tk.call'). What's a password name? Generally passwords don't have names themselves. Do you mean a user or account name? > What is happening is when I use the > "callfunction()" call, instead of the method name being called, a string > like this is being invoked: > > <__main__.phynchronicityApp instance at 0x101b232d8>> Are you sure that's meant to be a string? It appears to be an actual bound method. What makes you think it is a string? Where is that output coming from? My *guess* is that this is the output of the "print cmd" line. If so, that tells you nothing about the type of cmd. It does however tell you that you need to look at what is calling the runCommand method. Why is it being called with a method as the command? What should it be called with? Given that you call cmd.split()[2], I would expect that cmd should be a string with at least three words. Taking a wild guess, perhaps you should call cmd to get a string which then gets split into pieces to get the name of the system tool you are expecting: > The "scanPackages" method (just to use it as an example) uses Popen to > call an underlying system tool on the OS. However, when invoked via > callfunction(), the 'bound method...' string is passed to the OS instead > as a command! As a result, I get this output from the pipe: > > /bin/sh: bound: No such file or directory Or possibly the error is in callfunction. What does it do? > I am not sure what in my application is causing this kind of breakage, > as earlier versions of the app ran fine with similar code on earlier > versions on the OS. Is this the correct way to structure this kind of > functionality, or am I better off structuring it some other way? Frankly, it looks like a mess. But I don't understand your intention well enough to make any recommendations. -- Steven From rhodri at wildebst.demon.co.uk Sun Oct 2 20:04:21 2011 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Mon, 03 Oct 2011 01:04:21 +0100 Subject: Is there any way to access attributes from an imported module? References: Message-ID: On Sun, 02 Oct 2011 06:12:05 +0100, Andrew Berg wrote: > I'm not sure the subject's wording is the best, but I'll try to explain. > I have a main script that imports several modules and I need to be able > to call methods from a class instance inside that main script from a > module. Do you mean that one of the imported modules wishes to use an instance created in the main script? If that's the case, you're going to have to pass the instance to the module somehow, since the module knows nothing of what if anything has imported it. -- Rhodri James *-* Wildebeest Herder to the Masses From kw at codebykevin.com Sun Oct 2 20:24:34 2011 From: kw at codebykevin.com (Kevin Walzer) Date: Sun, 02 Oct 2011 20:24:34 -0400 Subject: getattr and method name In-Reply-To: References: Message-ID: Turns out the error was a typo in the actual method being called...*faceinhands* Sorry for the noise. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From gherron at islandtraining.com Sun Oct 2 21:13:07 2011 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 02 Oct 2011 18:13:07 -0700 Subject: getattr and method name In-Reply-To: References: Message-ID: <4E890C23.8030904@islandtraining.com> On 10/02/2011 05:24 PM, Kevin Walzer wrote: > Turns out the error was a typo in the actual method being > called...*faceinhands* > > Sorry for the noise. > But this is a great example of why you should not use a naked except clause. As stated, your code will execute the except clause for *any* kind of an error, not just the exception you envisioned when you wrote it. If you had written the except clause to catch just the exceptions you were interested in, then the exception int a called function would have come through that code as in un-handled exception, instead of being caught and essentially ignored. Gary Herron From rustompmody at gmail.com Sun Oct 2 22:08:15 2011 From: rustompmody at gmail.com (rusi) Date: Sun, 2 Oct 2011 19:08:15 -0700 (PDT) Subject: Change import order with *.pth files References: Message-ID: <3b5dd4e2-8e47-4b11-b0f9-af91f942ec58@n15g2000vbn.googlegroups.com> On 10/02/2011 10:29 PM, Andrea Gavana wrote: > Hi All, > ? ? my apologies if this is a dumb question, but I couldn't find a > solution ?- possibly because I am not sure how to state my problem in > a short sentence. I think this (and such) are important questions and I too await answers. It seems that these questions are poorly dealt with in the python docs probably because the docs try hard to be generic wrt OS and this is an area where such 'genericity' confuses more than it helps. From roy at panix.com Sun Oct 2 22:12:40 2011 From: roy at panix.com (Roy Smith) Date: Sun, 02 Oct 2011 22:12:40 -0400 Subject: getattr and method name References: Message-ID: In article , Gary Herron wrote: > On 10/02/2011 05:24 PM, Kevin Walzer wrote: > > Turns out the error was a typo in the actual method being > > called...*faceinhands* > > > > Sorry for the noise. > > > > But this is a great example of why you should not use a naked except > clause. As stated, your code will execute the except clause for *any* > kind of an error, not just the exception you envisioned when you wrote > it. If you had written the except clause to catch just the exceptions > you were interested in, then the exception int a called function would > have come through that code as in un-handled exception, instead of being > caught and essentially ignored. And, along those same lines, a couple of bits of generic exception advice... 1) Create specific exceptions to describe specific problems. FooPackageSocketBindError sure beats IOError when it comes to trying to figure out what went wrong. 2) As much as possible, keep your try blocks short. In the original example, we've got: try: functionstring = args[2] callfunction = getattr(self, functionstring.split('.')[1]) self.passtext = self.tk.call('authorize::getAuthPassword') callfunction() If we caught an IndexError, we would not know if it came from the args[2], or the getattr(...)[1], or possibly even from something deep down within callfunction(). From bahamutzero8825 at gmail.com Sun Oct 2 22:21:41 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sun, 02 Oct 2011 21:21:41 -0500 Subject: Is there any way to access attributes from an imported module? In-Reply-To: <4E880E87.5070507@islandtraining.com> References: <4E87F2A5.9000204@gmail.com> <4E880E87.5070507@islandtraining.com> Message-ID: <4E891C35.6070003@gmail.com> I found a way to do it, albeit a very hackish one. Since the class instance already catches exceptions from the modules it imports, I can make a custom exception (in a common area for both it and the submodules to import) for it to catch and have it call its own methods there based on information stored in the exception. I'm eventually going to redesign it to be cleaner and more obvious, but for now, this is a nice quick-and-dirty solution. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 From phlip2005 at gmail.com Sun Oct 2 22:27:52 2011 From: phlip2005 at gmail.com (Phlip) Date: Sun, 2 Oct 2011 19:27:52 -0700 (PDT) Subject: timedelta is squicking me out Message-ID: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> has anyone invented a system like R*by's ActiveSupport's 5.years.ago, 42.minutes.since ? (Yes, I'm aware the notation will be different!) -- Phlip http://zeekland.zeroplayer.com/ From clp2 at rebertia.com Sun Oct 2 22:41:23 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 Oct 2011 19:41:23 -0700 Subject: timedelta is squicking me out In-Reply-To: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> Message-ID: On Sun, Oct 2, 2011 at 7:27 PM, Phlip wrote: > has anyone invented a system like R*by's ActiveSupport's 5.years.ago, > 42.minutes.since ? > > (Yes, I'm aware the notation will be different!) If something involves Python and nontrivial chronology, then mxDateTime is the go-to library. And indeed, it has a RelativeDateTime type: http://www.egenix.com/products/python/mxBase/mxDateTime/doc/#_Toc293683810 Cheers, Chris -- http://rebertia.com From steve+comp.lang.python at pearwood.info Mon Oct 3 00:37:43 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 03 Oct 2011 04:37:43 GMT Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> Message-ID: <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> On Fri, 30 Sep 2011 21:09:54 +0100, Nobody wrote: > On Thu, 29 Sep 2011 11:53:12 +0200, Alain Ketterlin wrote: > >>> I have a Python script which I would like to test without a tty >>> attached to the process. I could run it as a cron job, but is there an >>> easier way? [...] > I suspect that the OP just wants e.g.: > > script.py &>/dev/null <&- > > which will redirect stdout and stderr to /dev/null and close stdin. No, that's not what I wanted. I ended up just running the script as a cron job. It was a one-off (well, twice actually, since the first time demonstrated a bug in my code) test of some code that tries to determine the size of the current terminal. I wanted to ensure that it would do the right thing when run without a tty, such as from a cron job. Thanks to everyone who replied. -- Steven From greg.ewing at canterbury.ac.nz Mon Oct 3 00:59:14 2011 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Mon, 03 Oct 2011 17:59:14 +1300 Subject: TK + MVC In-Reply-To: References: <9eq19cFmb2U1@mid.individual.net> Message-ID: <4E894122.5060907@canterbury.ac.nz> Emeka wrote: > Greg, > > Do you have an example where the Controller is connected? No, in fact I've never really felt the need for anything called a Controller in the GUI stuff I've done. I just have Models and Views. Models hold the data, and Views display it and handle input. If you come across a case where a third object seems justified, then by all means use one. But don't feel obliged to include one just because it's part of some official pattern or other. -- Greg From hansmu at xs4all.nl Mon Oct 3 01:39:58 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Mon, 03 Oct 2011 07:39:58 +0200 Subject: Python without a tty In-Reply-To: <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e894aae$0$2450$e4fe514c@news2.news.xs4all.nl> On 3/10/11 06:37:43, Steven D'Aprano wrote: > On Fri, 30 Sep 2011 21:09:54 +0100, Nobody wrote: > >> On Thu, 29 Sep 2011 11:53:12 +0200, Alain Ketterlin wrote: >> >>>> I have a Python script which I would like to test without a tty >>>> attached to the process. I could run it as a cron job, but is there an >>>> easier way? > [...] >> I suspect that the OP just wants e.g.: >> >> script.py&>/dev/null<&- >> >> which will redirect stdout and stderr to /dev/null and close stdin. > > > No, that's not what I wanted. > > I ended up just running the script as a cron job. It was a one-off (well, > twice actually, since the first time demonstrated a bug in my code) test > of some code that tries to determine the size of the current terminal. I > wanted to ensure that it would do the right thing when run without a tty, > such as from a cron job. In that case, the "at" command would have been the answer. It is a bit like cron, but meant for one-off jobs. You might have received more useful answers if you'd mentioned you goals earlier. -- HansM From airween at gmail.com Mon Oct 3 02:10:57 2011 From: airween at gmail.com (=?utf-8?B?SGVnZWTDvHMs?= Ervin) Date: Mon, 3 Oct 2011 08:10:57 +0200 Subject: Python without a tty In-Reply-To: <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20111003061054.GA2530@arxnet.hu> hello, On Mon, Oct 03, 2011 at 04:37:43AM +0000, Steven D'Aprano wrote: > > I wanted to ensure that it would do the right thing when run without a tty, > such as from a cron job. If you fork() your process, then it will also loose the tty... import os import sys try: pid = os.fork() if pid > 0: sys.exit(0) except OSError, e: sys.exit(1) os.chdir("/") os.setsid() os.umask(0) a. From r32813 at freescale.com Mon Oct 3 02:45:25 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Mon, 3 Oct 2011 06:45:25 +0000 Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str In-Reply-To: References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> Message-ID: <02EA6D704E30CE499C5071776509A925F5BABD@039-SN1MPN1-003.039d.mgd.msft.net> Hello guys, I am migrating my application from python 1.5.2 to 2.7.1. I encountered an error when I run some commands (I put in debug statement however, not able to trace down to which line of code that cause it to generate a lot of messages in one second until my hard disk space is full. The error log I got in my log file is as below:- Oct 3 14:12:41 ('Encountered exception while processing from', (0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), , TypeError('exceptions must be old-style classes or derived from BaseException, not str',)) Does it mean in newer python I need to migrate all my Exception to non-string based exception type? That's should be a lot of changes. :p Regards, Wah Meng From hansmu at xs4all.nl Mon Oct 3 03:28:27 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Mon, 03 Oct 2011 09:28:27 +0200 Subject: Python without a tty In-Reply-To: References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e89641b$0$2536$e4fe514c@news2.news.xs4all.nl> On 3/10/11 08:10:57, Heged?s, Ervin wrote: > hello, > > On Mon, Oct 03, 2011 at 04:37:43AM +0000, Steven D'Aprano wrote: >> >> I wanted to ensure that it would do the right thing when run without a tty, >> such as from a cron job. > > If you fork() your process, then it will also loose the tty... Errhm, I suggest you check again. This cannot be true. > import os > import sys > > > try: > pid = os.fork() > if pid> 0: > sys.exit(0) > except OSError, e: > sys.exit(1) > > os.chdir("/") > os.setsid() > os.umask(0) It is os.setsid() that makes you lose the tty. Hope this helps, -- HansM From tartley at tartley.com Mon Oct 3 03:40:41 2011 From: tartley at tartley.com (Jonathan Hartley) Date: Mon, 3 Oct 2011 00:40:41 -0700 (PDT) Subject: executing arbitrary statements In-Reply-To: <4e8870f9$0$29979$c3e8da3$5496439d@news.astraweb.com> References: <4e8870f9$0$29979$c3e8da3$5496439d@news.astraweb.com> Message-ID: <11779918.2105.1317627641162.JavaMail.geo-discussion-forums@yqbr29> Fair points Steven. Thanks for further refining my initial refinement. :-) From steve+comp.lang.python at pearwood.info Mon Oct 3 03:44:00 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 03 Oct 2011 07:44:00 GMT Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> Message-ID: <4e8967c0$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 03 Oct 2011 06:45:25 +0000, Wong Wah Meng-R32813 wrote: > Does it mean in newer python I need to migrate all my Exception to > non-string based exception type? That's should be a lot of changes. :p Yes. Python 1.5 is very old. It's over 11 years old. You might find it easier to first migrate to Python 2.5, where string exceptions are still legal and only generate a warning, and then migrate to 2.7. Good luck! -- Steven From clp2 at rebertia.com Mon Oct 3 03:45:34 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 Oct 2011 00:45:34 -0700 Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str In-Reply-To: <02EA6D704E30CE499C5071776509A925F5BABD@039-SN1MPN1-003.039d.mgd.msft.net> References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> <02EA6D704E30CE499C5071776509A925F5BABD@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: On Sun, Oct 2, 2011 at 11:45 PM, Wong Wah Meng-R32813 wrote: > Hello guys, > > I am migrating my application from python 1.5.2 to 2.7.1. I encountered an error when I run some commands (I put in debug statement however, not able to trace down to which line of code that cause it to generate a lot of messages in one second until my hard disk space is full. The error log I got in my log file is as below:- > > Oct ?3 14:12:41 ?('Encountered exception while processing from', (0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), , TypeError('exceptions must be old-style classes or derived from BaseException, not str',)) > > Does it mean in newer python I need to migrate all my Exception to non-string based exception type? Correct. You can no longer do merely `raise "Some error message"`. You should instead raise an exception instance of the appropriate type; e.g. `raise ValueError("foo must be positive")`. It's advisable to read the NEWS / "What's New" documents for the intervening versions so you can learn what else has changed. > That's should be a lot of changes. :p To be fair, v1.5.2 is practically ancient at this point. It's over a decade old! And 2 *major* versions behind what's current. In a pinch, you could always write a script to mechanically change `raise "..."` to `raise StandardError("...")` [or some other fairly generic exception type]. Cheers, Chris From r32813 at freescale.com Mon Oct 3 03:51:52 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Mon, 3 Oct 2011 07:51:52 +0000 Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str In-Reply-To: References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> <02EA6D704E30CE499C5071776509A925F5BABD@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <02EA6D704E30CE499C5071776509A925F5BB2D@039-SN1MPN1-003.039d.mgd.msft.net> Noted. No choice then, I will convert all my raise statement to use the exception instance. Thanks! Regards, Wah Meng -----Original Message----- From: chris at rebertia.com [mailto:chris at rebertia.com] On Behalf Of Chris Rebert Sent: Monday, October 03, 2011 3:46 PM To: Wong Wah Meng-R32813 Cc: python-list at python.org Subject: Re: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str On Sun, Oct 2, 2011 at 11:45 PM, Wong Wah Meng-R32813 wrote: > Hello guys, > > I am migrating my application from python 1.5.2 to 2.7.1. I encountered an error when I run some commands (I put in debug statement however, not able to trace down to which line of code that cause it to generate a lot of messages in one second until my hard disk space is full. The error log I got in my log file is as below:- > > Oct ?3 14:12:41 ?('Encountered exception while processing from', (0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), , TypeError('exceptions must be old-style classes or derived from BaseException, not str',)) > > Does it mean in newer python I need to migrate all my Exception to non-string based exception type? Correct. You can no longer do merely `raise "Some error message"`. You should instead raise an exception instance of the appropriate type; e.g. `raise ValueError("foo must be positive")`. It's advisable to read the NEWS / "What's New" documents for the intervening versions so you can learn what else has changed. > That's should be a lot of changes. :p To be fair, v1.5.2 is practically ancient at this point. It's over a decade old! And 2 *major* versions behind what's current. In a pinch, you could always write a script to mechanically change `raise "..."` to `raise StandardError("...")` [or some other fairly generic exception type]. Cheers, Chris From airween at gmail.com Mon Oct 3 03:56:55 2011 From: airween at gmail.com (=?utf-8?B?SGVnZWTDvHMs?= Ervin) Date: Mon, 3 Oct 2011 09:56:55 +0200 Subject: Python without a tty In-Reply-To: <4e89641b$0$2536$e4fe514c@news2.news.xs4all.nl> References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> <4e89641b$0$2536$e4fe514c@news2.news.xs4all.nl> Message-ID: <20111003075653.GA4589@arxnet.hu> hello, On Mon, Oct 03, 2011 at 09:28:27AM +0200, Hans Mulder wrote: > On 3/10/11 08:10:57, Heged?s, Ervin wrote: > > > >If you fork() your process, then it will also loose the tty... > > Errhm, I suggest you check again. This cannot be true. > > >os.setsid() > > It is os.setsid() that makes you lose the tty. well, thank you, I confused Python fork() and glibc daemon() - as I know that detach the terminal - I'm really sorry. a. From r32813 at freescale.com Mon Oct 3 04:07:08 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Mon, 3 Oct 2011 08:07:08 +0000 Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str In-Reply-To: <4e8967c0$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> <4e8967c0$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <02EA6D704E30CE499C5071776509A925F5BB81@039-SN1MPN1-003.039d.mgd.msft.net> I see. Thanks for the tips. If I run out of time I shall consider only using 2.5. Regards, Wah Meng -----Original Message----- From: python-list-bounces+wahmeng=freescale.com at python.org [mailto:python-list-bounces+wahmeng=freescale.com at python.org] On Behalf Of Steven D'Aprano Sent: Monday, October 03, 2011 3:44 PM To: python-list at python.org Subject: Re: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str On Mon, 03 Oct 2011 06:45:25 +0000, Wong Wah Meng-R32813 wrote: > Does it mean in newer python I need to migrate all my Exception to > non-string based exception type? That's should be a lot of changes. :p Yes. Python 1.5 is very old. It's over 11 years old. You might find it easier to first migrate to Python 2.5, where string exceptions are still legal and only generate a warning, and then migrate to 2.7. Good luck! -- Steven -- http://mail.python.org/mailman/listinfo/python-list From adam at rybnik.pl Mon Oct 3 04:12:03 2011 From: adam at rybnik.pl (Adam Przybyla) Date: Mon, 3 Oct 2011 08:12:03 +0000 (UTC) Subject: Need A script to open a excel file and extract the data using autofilter References: <4f3ec474-dd9f-4585-8f3c-41323d79b8de@z19g2000vby.googlegroups.com> Message-ID: Prakash wrote: > Need A script to open a excel file and extract the data using > autofilter and write it in a new sheet or new file like I have to > select all rows in which all the columns contain pass as status ... try this: http://www.python-excel.org/ Regards Adam Przybyla From gagsl-py2 at yahoo.com.ar Mon Oct 3 04:14:20 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Oct 2011 05:14:20 -0300 Subject: Change import order with *.pth files References: Message-ID: En Sun, 02 Oct 2011 18:29:24 -0300, Andrea Gavana escribi?: > Let's say I am using a package called "blah", and this package is already > installed on site-packages (and I need it to be there) with a name > "blah-1.2-win". In the site-packages folder, there is a pth file called > "blah.pth" which contains this line: > > blah-1.2-win > > To redirect Python to the correct folder when I type "import blah". > Anyway, > now I am developing another version of this package and it's called > "blah-2.0-win", and it sits on my computer into a different folder (not > on > site-packages, on an entire different drive in reality). How can I tell > Python *not* to use the version inside site-packages but to use the other > one in my development folder (without touching the pth file in > site-packages, of course)? From Python 2.6 on, there is a per user site-packages directory, which is searched before the global one. See: http://docs.python.org/whatsnew/2.6.html#pep-370-per-user-site-packages-directory You could put your developing version on that directory. In Python 2.5 and earlier, if you have to PREPEND a directory to sys.path, you may set the PYTHONPATH environment variable, or edit the site.py standard module. This may be fine in your development environment, but I would never do that in production. -- Gabriel Genellina From greg.ewing at canterbury.ac.nz Mon Oct 3 04:51:19 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 03 Oct 2011 21:51:19 +1300 Subject: TK + MVC In-Reply-To: References: <9eq19cFmb2U1@mid.individual.net> Message-ID: <9etbcaF1mkU1@mid.individual.net> Alexander Kapps wrote: > Sure, in that simple example the Controller is just there to show a > complete MVC pattern with all three parts. There are often examples > where the View is actually both, the View and the Controller. I think what I'm really trying to say is that this example is *poor* at illustrating the supposed MVC pattern, because it gives no clue as to why one might want to use a Controller. > That's why I said that I'm not sure if I really understand the MVC > pattern. There are so many different versions, sometimes strict and > sometimes less strict, and I think what's the real problem with my > example is, whether it is really correct to not connect the Model and > the View directly, but to let the Controller "mediate" between both. I don't blame you for being confused. Different people seem to have different ideas about what the "C" in "MVC" means. As far as I can tell, in the original Smalltalk concept of MVC, the View handled output and the Controller handled input. In Apple's Cocoa tutorials, the Controller seems to be something that sits between the View and the Model with a somewhat ill-defined role. Then there are web frameworks that call themselves "MVC" with their own strange twists on what the terms mean. One possible role for a Controller-like object would be where the View is not a single widget, but some collection of widgets that cooperate to provide a user interface. In that case, the Controller could be something that creates and assembles the relevant widgets, and provides whatever glue code is needed to make them work together. I suspect that this is what Apple mean by a Controller in Cocoa. I've certainly created this kind of structure, but I tend not to use a separate object for it. Instead I create a subclass of Window (Toplevel in Tk terms), or some other container widget, to serve as both the coordinating object and a container for all the parts. I don't think of it as a Controller, but simply as a compound View that happens to be made up of several objects. So I don't think there's any single "correct" way to put a "C" into "MVC", or even necessarily a need to put one in at all. To my mind, the important things about the concept of model-view separation are: * The Model holds the data and provides a common interface for Views to access and change it. * Multiple Views, and different kinds of View, can be attached to a Model through its common interface. * There is some mechanism for a Model to broadcast an "I've changed" message to all its attached Views. Whether the Views attach to the Model directly or through some intermediate object is not really important. And when there is an intermediate object, whether you call it a Controller or regard it as simply another kind of View is just a matter of perspective. -- Greg From greg.ewing at canterbury.ac.nz Mon Oct 3 04:59:54 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 03 Oct 2011 21:59:54 +1300 Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str In-Reply-To: References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> Message-ID: <9etbscF5mgU1@mid.individual.net> Wong Wah Meng-R32813 wrote: > I am migrating my application from python 1.5.2 to 2.7.1. > Does it mean in newer python I need to migrate all my Exception to > non-string based exception type? That's should be a lot of changes. :p 'Fraid so. You are leaping quite a lot of versions at once, and string exceptions have been considered passe for a *long* time. They may already have been deprecated in 1.5, I'm not sure. Note that in Python 3 the condition is even stricter -- old style classes are gone, and exceptions must derive from BaseException or some other existing exception type. So you'd best do that now for the sake of easing migration to Python 3 in the future. -- Greg From greg.ewing at canterbury.ac.nz Mon Oct 3 05:04:26 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 03 Oct 2011 22:04:26 +1300 Subject: Python without a tty In-Reply-To: References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9etc4tF825U1@mid.individual.net> Heged?s wrote: > If you fork() your process, then it will also loose the tty... Um, no, fork() doesn't do that, as far as I know. > os.setsid() *This* is what's losing the tty. According to the Fine Man Page: DESCRIPTION The setsid function creates a new session. The calling process is the session leader of the new session, is the process group leader of a new process group and has no controlling terminal. ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- Greg From electronicswebthaya at gmail.com Mon Oct 3 06:08:17 2011 From: electronicswebthaya at gmail.com (deepika) Date: Mon, 3 Oct 2011 03:08:17 -0700 (PDT) Subject: http://www.electronicswebworld.com/ Message-ID: http://www.electronicswebworld.com/ online jobs for u http://www.tamilwebworld.com/ From chris at simplistix.co.uk Mon Oct 3 06:11:56 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 03 Oct 2011 11:11:56 +0100 Subject: packages, modules and double imports - oh my! Message-ID: <4E898A6C.4040909@simplistix.co.uk> Hi All, The attached package gives that smallest possible example of problems I'm hitting with some SQLAlchemy declarative classes. In short, I want to be able to do: python -m pack.module and have if the __name__=='__main__' block spit out the SQL to create the tables necessary for the modules in that class... So, using the attached package to demonstrate, the first problem I get is: cwithers at cwlin:~> python -m pack.module Traceback (most recent call last): File "/usr/lib64/python2.6/runpy.py", line 121, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib64/python2.6/runpy.py", line 34, in _run_code exec code in run_globals File "/home/cwithers/pack/module.py", line 3, in class MyClass(object): File "pack/__init__.py", line 7, in __init__ raise Exception('%r registered twice' % self.__name__) Exception: 'MyClass' registered twice Looks like I have a pack.module.MyClass and a __main__.MyClass, which feels like a bug to me... Ho hum, lets try something different: cwithers at cwlin:~> python pack/module.py Traceback (most recent call last): File "pack/module.py", line 1, in from pack import MyMeta ImportError: No module named pack Meh, okay, so only the path containing the script being run ends up on PYTHONPATH, okay, so: cwithers at cwlin:~> PYTHONPATH=. python pack/module.py Traceback (most recent call last): File "pack/module.py", line 3, in class MyClass(object): File "pack/__init__.py", line 7, in __init__ raise Exception('%r registered twice' % self.__name__) Exception: 'MyClass' registered twice ...back to square one :-( cwithers at cwlin:~> python -m pack /usr/bin/python: pack is a package and cannot be directly executed That's annoying, why isn't pack/__init__.py's __name__=='__main__' block executed? cwithers at cwlin:~> python pack /usr/bin/python: can't find '__main__.py' in 'pack' Wha? First I've ever heard of __main__.py... where's that documented? Anyway: cwithers at cwlin:~> python pack/__init__.py Traceback (most recent call last): File "pack/__init__.py", line 10, in from pack.module import MyClass ImportError: No module named pack.module Oh, right, we're back here..., so lets try: cwithers at cwlin:~> PYTHONPATH=. python pack/__init__.py {'MyClass': } {} wtf? why aren't these the same registry object?! Any help appreciated... Chris -------------- next part -------------- A non-text attachment was scrubbed... Name: pack.tgz Type: application/x-compressed-tar Size: 426 bytes Desc: not available URL: From clp2 at rebertia.com Mon Oct 3 06:22:32 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 Oct 2011 03:22:32 -0700 Subject: packages, modules and double imports - oh my! In-Reply-To: <4E898A6C.4040909@simplistix.co.uk> References: <4E898A6C.4040909@simplistix.co.uk> Message-ID: On Mon, Oct 3, 2011 at 3:11 AM, Chris Withers wrote: > Hi All, > > The attached package gives that smallest possible example of problems I'm > hitting with some SQLAlchemy declarative classes. > > In short, I want to be able to do: > > python -m pack.module and have if the __name__=='__main__' block spit out > the SQL to create the tables necessary for the modules in that class... > cwithers at cwlin:~> python -m pack > /usr/bin/python: pack is a package and cannot be directly executed > > That's annoying, why isn't pack/__init__.py's __name__=='__main__' block > executed? > > cwithers at cwlin:~> python pack > /usr/bin/python: can't find '__main__.py' in 'pack' > > Wha? First I've ever heard of __main__.py... where's that documented? http://docs.python.org/library/runpy.html : "The runpy module['s] main use is to implement the -m command line switch" "If the supplied module name refers to a package rather than a normal module, then that package is imported and the __main__ submodule within that package is then executed and the resulting module globals dictionary returned." (`runpy` having appeared in your first Traceback. Definitely seems like some explicit cross-references should be added to the docs.) Cheers, Chris From rajashree.thorat16 at gmail.com Mon Oct 3 08:00:25 2011 From: rajashree.thorat16 at gmail.com (Rajashree Thorat) Date: Mon, 3 Oct 2011 17:30:25 +0530 Subject: Problem regarding command line completion Message-ID: Hi All, Please can anyone help me in resolving following problem. import cmd class CmdLineApp(cmd.Cmd): def do_grep(self, line): print line option = ["--ignore-case", "--invert-match","--word-regexp","--line-regexp"] def complete_grep(self, text, line, begidx, endidx): return [i for i in CmdLineApp.option if i.startswith(text)] interpreter = CmdLineApp() interpreter.cmdloop() In above program I want to do command line completion (or tab completion). If the elements of option list starts with special character such as '-', '@', '#', '--' , then it is giving me output like (Cmd) grep grep (Cmd) grep ------ instead of (Cmd) grep -- --ignore-case --invert-match --word-regexp --line-regexp How I can handle this special characters? Thanks & Regards Rajshree Thorat -------------- next part -------------- An HTML attachment was scrubbed... URL: From awilliam at whitemice.org Mon Oct 3 08:02:19 2011 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Mon, 03 Oct 2011 08:02:19 -0400 Subject: parse xml In-Reply-To: References: Message-ID: <20111003080219.Horde.ms_VVJeICrNOiaRLGCllO1A@aleph.wmmi.net> Quoting ???? <1248283536 at qq.com>: > please click the > http://www.secinfo.com/d14qfp.q9j.htm > then ,click the following: > 44: XML IDEA: Condensed Consolidating Statements of Income XML > 5.11M (Details)--R158 > there is the citigroup's annual financial report --statements of > income,xml file. > how can i get a table of statements of income in python ? Read the document with etree, and either iterate over it or grab the required values with xpath. from lxml import etree doc = etree.parse(self.rfile) result = doc.xpath(self._xpath, namespaces=doc.getroot().nsmap) From rantingrick at gmail.com Mon Oct 3 08:25:19 2011 From: rantingrick at gmail.com (rantingrick) Date: Mon, 3 Oct 2011 05:25:19 -0700 (PDT) Subject: lower-case names for builtin types References: Message-ID: <29076d4a-7575-4989-a922-e824c5781ee6@z8g2000yqb.googlegroups.com> On Oct 1, 10:41?pm, Eric Snow wrote: > Anyone know the story behind the lower-case names for the > non-exception built-in types (like list and type)? ?I am guessing that > they were originally factory functions that, at some point, graduated > to full types; and the names were kept lower-case for backward > compatibility. Or it could be that they wanted to hoard all the good generic variable names! > However, if we were to consider making a change for Python 4, I am not > sure how I feel about Int("5") over int("5"). ?Maybe it would be > Integer("5"). Yes! Some folks get all huffy about this subject because they get SO attached to built in functions. What's so weird about calling a function that THEN calls a constructor as opposed to just calling the constructor directly? Seems like unnecessary overhead to me. From roy at panix.com Mon Oct 3 08:59:07 2011 From: roy at panix.com (Roy Smith) Date: Mon, 03 Oct 2011 08:59:07 -0400 Subject: timedelta is squicking me out References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> Message-ID: In article , Chris Rebert wrote: > If something involves Python and nontrivial chronology, then > mxDateTime is the go-to library. And indeed, it has a RelativeDateTime > type: > http://www.egenix.com/products/python/mxBase/mxDateTime/doc/#_Toc293683810 We've been using http://labix.org/python-dateutil, which is pretty good. I've never used mxDateTime, so I don't know how the two compare head-to-head. From redcat at streemit.net Mon Oct 3 09:51:52 2011 From: redcat at streemit.net (Redcat) Date: 3 Oct 2011 13:51:52 GMT Subject: To start a simple server References: <06b7fcdc-8615-4980-8d42-f212033ee5c8@dk6g2000vbb.googlegroups.com> Message-ID: <9etsvnF1kdU9@mid.individual.net> Are you running web.py on your computer, or is it running for example on a hosting company's computer? If it's not on your computer you have your port 8080 traffic blocked the hosting company's firewall. On Sun, 02 Oct 2011 20:59:40 -0700, sillyou su wrote: > i am learning webpy and I am following the tutorial ?http://webpy.org/ > docs/0.3/tutorial? . > > But when i installed mysql , i found problem. > > Here is the code: > #===============================================# import web > > urls=("/.","index") > > app=web.application(urls,globals()) > > class index: > def GET(self): > return 'hello world' > > if __name__=='__main__': > app.run() > #===============================================# > > And here is error information? > #===============================================# http://0.0.0.0:8080/ > > Traceback (most recent call last): > File "C:\Users\su\Desktop\code.py", line 18, in app.run() > File "C:\Python27\lib\site-packages\web\application.py", line 311, in > run > return wsgi.runwsgi(self.wsgifunc(*middleware)) File > "C:\Python27\lib\site-packages\web\wsgi.py", line 54, in runwsgi return > httpserver.runsimple(func, validip(listget(sys.argv, 1, ''))) File > "C:\Python27\lib\site-packages\web\httpserver.py", line 148, in > runsimple > server.start() > File "C:\Python27\lib\site-packages\web\wsgiserver\__init__.py", line > 1753, in start > raise socket.error(msg) > error: No socket could be created > #===============================================# > A service occupy port 8080. So i stop the service. > The program did run, but another problem came out. > #===============================================# > > the program is not running. In the browser? > ============================================ This webpage is not > available > The webpage at http://0.0.0.0:8080/ might be temporarily down or it may > have moved permanently to a new web address. Error 108 > (net::ERR_ADDRESS_INVALID): Unknown error. > > ============================================ > > now the program is running. In the browser? > ============================================ This webpage is not > available > The webpage at http://0.0.0.0:8080/ might be temporarily down or it may > have moved permanently to a new web address. Error 108 > (net::ERR_ADDRESS_INVALID): Unknown error. > ============================================ Nothing difference . > > I can't describe the problem very well in English. So I post all > information here . > > Thank you for any tips. From wilson.amit at gmail.com Mon Oct 3 11:03:18 2011 From: wilson.amit at gmail.com (amit) Date: Mon, 3 Oct 2011 08:03:18 -0700 (PDT) Subject: BaseHTTPServer ThreadMixIn not working Message-ID: Hi everyone, I am really stuck in a very simple problem and wanted to know if you could take some time to check it out - My code is simple. Using BaseHTTPServer and ThreadInMix I want to run a python script (Script1.py) for every request made simultaneously. My code-> from subprocess import PIPE, Popen from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler import time def simple_script(self): print 'simple_script' s = Popen('C:/Python27/python C:/Script1.py 5', shell=True, stdout=PIPE, stderr=PIPE) out, err = s.communicate() print out, err self.wfile.write(out) class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() self.wfile.write('{0}\n'.format(time.asctime())) simple_script(self) return class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): pass if __name__ == '__main__': server = ThreadedHTTPServer(('', 8080), Handler) print 'Starting server, use to stop' server.serve_forever() """ # C:/Script1.py import time, sys s = time.time() while True: if time.time() - s > int(sys.argv[1]): break else: time.sleep(1) print time.asctime() """ If I open multiple tabs/pages in Chrome/Firefox/IE and give URL: http://localhost:8080, the pages wait for previous page? This does not imply threading? Any help? Thanks From jeanmichel at sequans.com Mon Oct 3 11:12:44 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 03 Oct 2011 17:12:44 +0200 Subject: Advise on using logging.getLogger needed. In-Reply-To: <4E88E1B3.6080009@syslang.net> References: <4E88E1B3.6080009@syslang.net> Message-ID: <4E89D0EC.8020900@sequans.com> Steven W. Orr wrote: > I hope I don't sound like I'm ranting :-( > > I have created a module (called xlogging) which sets up logging the way I want > it. I found out that if I set up my logger without a name, then it gets > applied to every logger that is referenced by every module that ever gets > imported. > > The problem is that I must call xlogging.getLogger or logging.getLogger in all > other modules using the name of the root logger, and I don't know what that > name is. > > I want the name of the root logger to be the name of the running program, so > in my setup, I say > > pname = sys.argv[0] > try: > rslash = pname.rindex('/') > except ValueError: > pass > else: > pname = pname[rslash + 1:] > > try: > dot_py = pname.rindex('.py') > except ValueError: > pass > else: > pname = pname[0:dot_py] > > This is also written pname, _ = os.path.splitext(os.path.basename(sys.argv[0])) > and then I say > > logger = logging.getLogger(pname) > > My problem is that I just want the modules that I write, to be able to get the > named root logger and still be able to refer to possible sub-loggers. > > So, let's say I run program foo. At some point in my mail setup, I set the > configuration for the foo logger. I'd like my xlogging module to supply a > getLogger function such that if I don't supply any arguments, it will return > the logger that would normally be returned by logging.getLogger(pname). > > Also, part of the reason I'm confused is because foo calls m1 and m2 and they > want to say > > logger = xlogging.getLogger(MaybeWithAnArg?) > > at the top of their code. This means that the import statement for m1 and m2 > are getting the calls to getLogger executed before I get the chance to set > things up. > > I am running 2.6, so I don't have access to logging.getChild, but I'm not > clear that I even want that. > > My modules are used by multiple programs. Does this mean that I should simply > use __name__ all the time? (That seems inelegant, no?) > > If I'm making sense, is there a way to do this? > > > To be honest, I'm not sure I've understood exactly what you're trying to do, but I have the feeling you're just trying to the usual stuff with the wrong method. I would advise to drop your xlogging module, it just add some confusion. Maybe you'll be able to add it later on. * in libraries/modules, you never configure any logger. The configuration of the logger is let to the main program. -> only instanciate a logger, something like logger = logging.getLogger(__name__) Then use it, you don't care about what becomes of the logs, it's up to the program using the module to decide * From the main program, you can create a logger for your application, but you still configure the root logger, only the root logger will grab the log event from other modules. m1 module file: import logging _logger=logging.getLogger(__name__) def func(): _logger.debug('foo') myApp file: import m1 import logging _logger = logging.getLogger('MyApp') def run(): _logger.info('bar') m1.func() if __name__=='__main__': # here you configure the logs by configuring the *root* logger rootLogger = logging.getLogger() # no name => root logger rootLogger.handlers = [] # clean up the current configuration rootLogger.addHandler(logging.StreamHandler()) rootLogger.handlers[-1].setFormatter(logging.Formatter('%(name)s - %(levelname)s:%(message)s')) rootLogger.setLevel(level=logging.DEBUG) run() you should get something like MyApp - INFO:bar m1 - DEBUG:foo Hope it helps, JM From chris at simplistix.co.uk Mon Oct 3 11:25:53 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 03 Oct 2011 16:25:53 +0100 Subject: packages, modules and double imports - oh my! In-Reply-To: References: <4E898A6C.4040909@simplistix.co.uk> Message-ID: <4E89D401.3060407@simplistix.co.uk> On 03/10/2011 11:22, Chris Rebert wrote: > http://docs.python.org/library/runpy.html : > "The runpy module['s] main use is to implement the -m command line switch" > "If the supplied module name refers to a package rather than a normal > module, then that package is imported and the __main__ submodule > within that package is then executed and the resulting module globals > dictionary returned." Interesting, but doesn't help with the bizarre double-exec of module.py when it happens to be __main__... cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From rantingrick at gmail.com Mon Oct 3 11:54:04 2011 From: rantingrick at gmail.com (rantingrick) Date: Mon, 3 Oct 2011 08:54:04 -0700 (PDT) Subject: Chaos Theory [was Re: Benefit and belief] References: <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> <4e88db0f$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Oct 2, 4:43?pm, Steven D'Aprano wrote: > In all cases, we can be sure that the contradiction between the pair of > statements are genuine contradictions and not mere apparent > contradictions caused by "narrow perspective" or incomplete or erroneous > knowledge. Observer: Why is it that Clark Kent and Superman are never in the same place at the same time? ComicFanboy: Because Clark Kent IS Kal-El's secret identity duh! PuesdoWiseObserver: Wait a minute fanboy, they ARE in the same place at the same time since Clark Kent IS really Superman. Ha, i'm smart. TrueWiseObserver: Wrong pseudo. Superman will ALWAYS be superman even if he wears a dress and stilettos. Clark Kent is just an assumed identity of Superman. From SokolischSpeaks at moonbat.com Mon Oct 3 11:56:27 2011 From: SokolischSpeaks at moonbat.com (Gary Sokolisch) Date: Mon, 3 Oct 2011 11:56:27 -0400 Subject: Who Is Gary Sokolich? 1405 Message-ID: <107i3o920tscl$.xvt9vfbi86md.dlg@40tude.net> 1405 W Gary Sokolich 801 Kings Road Newport Beach, CA 92663-5715 (949) 650-5379 http://web.archive.org/web/20080821231423/http://www.tbpe.state.tx.us/da/da022808.htm TEXAS BOARD OF PROFESSIONAL ENGINEERS February 28, 2008 Board Meeting Disciplinary Actions W. Gary Sokolich , Newport Beach, California ? File B-29812 - It was alleged that Dr. Sokolich unlawfully offered or attempted to practice engineering in Texas (...) Dr. Sokolich chose to end the proceedings by signing a Consent Order that was accepted by the Board to cease and desist from representing himself as an ?Engineer? in Texas, from any and all representations that he can offer or perform engineering services and from the actual practice of engineering in Texas (...) Dr. Sokolich was also assessed a $1,360.00 administrative penalty. _______________ http://articles.latimes.com/1988-04-14/local/me-1922_1_ucla-researcher A former UCLA physiologist has agreed to provide copies of his research to the school to settle a lawsuit the university filed against him in 1985, lawyers in the case said. (...) The University of California Board of Regents filed a $620,000 lawsuit against Sokolich, accusing him of taking research on the hearing capabilities of animals in June, 1982. Sokolich was dismissed by UCLA (...). (...) From aivar.annamaa at gmail.com Mon Oct 3 12:21:56 2011 From: aivar.annamaa at gmail.com (Aivar Annamaa) Date: Mon, 3 Oct 2011 19:21:56 +0300 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) Message-ID: Hi! I'm looking for a trick or hidden feature to make Python 3 automatically call a "main" function but without programmers writing `if __name__ == "__main__": ...` I found rejected PEP 299, but i thought that maybe there's something new already. Here's why I want such a thing: I'm teaching introductory programming course with Python. I've seen that global variables attract beginners like honey attracts bees and this makes teaching function parameters harder. When students learn functions, they usually write their function definitions and function applications in the same scope -- in top-level of the module (don't know the correct term for it). This has the downside, that any variable introduced in top-level is automatically visible in function definitions and I have hard time convincing students not to use those variables in functions directly. I've been thinking that it might be better for teaching if all program code would be in functions. This would make "Hello World" a bit more difficult, but would help teaching the "real thing" ie. functions. best regards, Aivar -------------- next part -------------- An HTML attachment was scrubbed... URL: From alec.taylor6 at gmail.com Mon Oct 3 12:26:30 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 4 Oct 2011 03:26:30 +1100 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: Message-ID: Make something with http://metapython.org/ ? On Tue, Oct 4, 2011 at 3:21 AM, Aivar Annamaa wrote: > Hi! > > I'm looking for a trick or hidden feature to make Python 3 automatically > call a "main" function but without programmers writing `if __name__ == > "__main__": ...` > > I found rejected PEP 299, but i thought that maybe there's something new > already. > > Here's why I want such a thing: > I'm teaching introductory programming course with Python. I've seen that > global variables attract beginners like honey attracts bees and this makes > teaching function parameters harder. When students learn functions, they > usually write their function definitions and function applications in the > same scope -- in top-level of the module (don't know the correct term for > it). This has the downside, that any variable introduced in top-level is > automatically visible in function definitions and I have hard time > convincing students not to use those variables in functions directly. > > I've been thinking that it might be better for teaching if all program code > would be in functions. This would make "Hello World" a bit more difficult, > but would help teaching the "real thing" ie. functions. > > best regards, > Aivar > > -- > http://mail.python.org/mailman/listinfo/python-list > > From rosuav at gmail.com Mon Oct 3 12:27:41 2011 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Oct 2011 03:27:41 +1100 Subject: Chaos Theory [was Re: Benefit and belief] In-Reply-To: References: <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> <4e88db0f$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Oct 4, 2011 at 2:54 AM, rantingrick wrote: > Observer: Why is it that Clark Kent and Superman are never in the same > place at the same time? > ComicFanboy: Because Clark Kent IS Kal-El's secret identity duh! > PuesdoWiseObserver: Wait a minute fanboy, they ARE in the same place > at the same time since Clark Kent IS really Superman. Ha, i'm smart. > TrueWiseObserver: Wrong pseudo. Superman will ALWAYS be superman even > if he wears a dress and stilettos. Clark Kent is just an assumed > identity of Superman. ComicBookGeek: Actually, they have been seen together, on several occasions - thanks to stand-ins, dummies, or even super-speed and changing faster than the human eye can see. PhysicsExpert: Super-speed wouldn't work, the acceleration required to achieve it would burn up his surroundings! Your point? Chris Angelico PS. I did the arithmetic once on how much force Superman would have to exert on his surroundings in order to be seen in two places at once. It was like those calculations on Santa and the number of joules of energy the lead reindeer would be copping. From emekamicro at gmail.com Mon Oct 3 12:47:38 2011 From: emekamicro at gmail.com (Emeka) Date: Mon, 3 Oct 2011 17:47:38 +0100 Subject: TK + MVC In-Reply-To: <4E88F05B.3090801@web.de> References: <9eq19cFmb2U1@mid.individual.net> <4E88F05B.3090801@web.de> Message-ID: Alex, The question was not meant for you. I was responding to Greg's comment. Regards, Emeka On Mon, Oct 3, 2011 at 12:14 AM, Alexander Kapps wrote: > On 03.10.2011 00:15, Emeka wrote: > >> Greg, >> >> Do you have an example where the Controller is connected? >> > > What do you mean? In my example, the Controller *is* connected (to both the > View and the Model.) > -- > http://mail.python.org/**mailman/listinfo/python-list > -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From sillyousu at gmail.com Mon Oct 3 13:05:15 2011 From: sillyousu at gmail.com (sillyou su) Date: Mon, 3 Oct 2011 10:05:15 -0700 (PDT) Subject: To start a simple server References: <06b7fcdc-8615-4980-8d42-f212033ee5c8@dk6g2000vbb.googlegroups.com> <9etsvnF1kdU9@mid.individual.net> Message-ID: <4be53ff4-d534-4a4c-85ae-d1cc10813829@i33g2000yqm.googlegroups.com> I am running web.py on my computer From redcat at streemit.net Mon Oct 3 13:41:32 2011 From: redcat at streemit.net (Redcat) Date: 3 Oct 2011 17:41:32 GMT Subject: To start a simple server References: <06b7fcdc-8615-4980-8d42-f212033ee5c8@dk6g2000vbb.googlegroups.com> <9etsvnF1kdU9@mid.individual.net> <4be53ff4-d534-4a4c-85ae-d1cc10813829@i33g2000yqm.googlegroups.com> Message-ID: <9euaecF1kdU13@mid.individual.net> On Mon, 03 Oct 2011 10:05:15 -0700, sillyou su wrote: > I am running web.py on my computer Does "netstat -nat | grep 8080" show anything listening on port 8080? (I'm assuming here that you're running on a Linux box) From amelia at catfolks.net Mon Oct 3 14:15:16 2011 From: amelia at catfolks.net (Amelia T Cat) Date: 3 Oct 2011 18:15:16 GMT Subject: To start a simple server References: <06b7fcdc-8615-4980-8d42-f212033ee5c8@dk6g2000vbb.googlegroups.com> <9etsvnF1kdU9@mid.individual.net> Message-ID: <9eucdkF1kdU14@mid.individual.net> On Mon, 03 Oct 2011 10:09:59 -0700, sillyou su wrote: > ??? > > I should use 127.0.0.1 instance of 0.0.0.0 Theoretically either one should be fine. If you use 127.0.0.1 it will only expose the service to your local machine. If you use 0.0.0.0 ut will expose the service to other computers on the same network as the one running the service. From __peter__ at web.de Mon Oct 3 14:31:01 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 Oct 2011 20:31:01 +0200 Subject: Problem regarding command line completion References: Message-ID: Rajashree Thorat wrote: > Please can anyone help me in resolving following problem. > > import cmd > class CmdLineApp(cmd.Cmd): > > def do_grep(self, line): > print line > > option = ["--ignore-case", > "--invert-match","--word-regexp","--line-regexp"] > def complete_grep(self, text, line, begidx, endidx): > return [i for i in CmdLineApp.option if > i.startswith(text)] > > interpreter = CmdLineApp() > interpreter.cmdloop() > > In above program I want to do command line completion (or tab completion). > If the elements of option list starts with special character such as > '-', '@', '#', '--' , then it is giving me output like > > (Cmd) grep > grep > (Cmd) grep ------ > > instead of > > (Cmd) grep -- > --ignore-case --invert-match --word-regexp --line-regexp > > How I can handle this special characters? Try removing them from readline's set of delimiters with import readline delims = readline.get_completer_delims() my_delims = "".join(set(delims) - set("-@#")) readline.set_completer_delims(my_delims) From iurisilvio at gmail.com Mon Oct 3 14:39:12 2011 From: iurisilvio at gmail.com (Iuri) Date: Mon, 3 Oct 2011 15:39:12 -0300 Subject: To start a simple server In-Reply-To: <9eucdkF1kdU14@mid.individual.net> References: <06b7fcdc-8615-4980-8d42-f212033ee5c8@dk6g2000vbb.googlegroups.com> <9etsvnF1kdU9@mid.individual.net> <9eucdkF1kdU14@mid.individual.net> Message-ID: Something is running in your port 8080. Change the port and try again. On Mon, Oct 3, 2011 at 3:15 PM, Amelia T Cat wrote: > On Mon, 03 Oct 2011 10:09:59 -0700, sillyou su wrote: > > > ??? > > > > I should use 127.0.0.1 instance of 0.0.0.0 > > Theoretically either one should be fine. If you use 127.0.0.1 it will > only expose the service to your local machine. If you use 0.0.0.0 ut will > expose the service to other computers on the same network as the one > running the service. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Oct 3 14:54:26 2011 From: davea at ieee.org (Dave Angel) Date: Mon, 03 Oct 2011 14:54:26 -0400 Subject: packages, modules and double imports - oh my! In-Reply-To: <4E89D401.3060407@simplistix.co.uk> References: <4E898A6C.4040909@simplistix.co.uk> <4E89D401.3060407@simplistix.co.uk> Message-ID: <4E8A04E2.1000201@ieee.org> On 01/-10/-28163 02:59 PM, Chris Withers wrote: > On 03/10/2011 11:22, Chris Rebert wrote: >> http://docs.python.org/library/runpy.html : >> "The runpy module['s] main use is to implement the -m command line >> switch" >> "If the supplied module name refers to a package rather than a normal >> module, then that package is imported and the __main__ submodule >> within that package is then executed and the resulting module globals >> dictionary returned." > > Interesting, but doesn't help with the bizarre double-exec of > module.py when it happens to be __main__... > > cheers, > > Chris > Sounds to me like you have a circular dependency. It's never a good idea, and especially if you have a circular dependency on the script itself, it'll get loaded twice. Once it comes in as __main__, and the other time by its filename. So redesign the module to eliminate the circulars. If a.py imports b.py, then b.py should not import a.py, directly or indirectly. You are lucky you got an explicit error; We've seen other people get very obscure bugs when two instances of some module variables were in existence. DaveA From davea at ieee.org Mon Oct 3 15:14:13 2011 From: davea at ieee.org (Dave Angel) Date: Mon, 03 Oct 2011 15:14:13 -0400 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: Message-ID: <4E8A0985.2010007@ieee.org> On 01/-10/-28163 02:59 PM, Aivar Annamaa wrote: > Hi! > > I'm looking for a trick or hidden feature to make Python 3 automatically > call a "main" function but without programmers writing `if __name__ == > "__main__": ...` > > I found rejected PEP 299, but i thought that maybe there's something new > already. > > Here's why I want such a thing: > I'm teaching introductory programming course with Python. I've seen that > global variables attract beginners like honey attracts bees and this makes > teaching function parameters harder. When students learn functions, they > usually write their function definitions and function applications in the > same scope -- in top-level of the module (don't know the correct term for > it). This has the downside, that any variable introduced in top-level is > automatically visible in function definitions and I have hard time > convincing students not to use those variables in functions directly. > > I've been thinking that it might be better for teaching if all program code > would be in functions. This would make "Hello World" a bit more difficult, > but would help teaching the "real thing" ie. functions. > > best regards, > Aivar > It's not clear if you're asking for a new fork of the language, or just wanting to keep people from bad habits. Like it or not, there are plenty of globals already there, one of them being __name__ . All the built-ins are effectively global, and so is any function they define at top-level. Likewise any top-level class, and any symbols imported with import or with from/import. So I consider it impractical for the language to do something that self-discipline is required for. Is it explaining the if statement that's the problem? If so, you could have them do an unconditional main(sys.argv) at the bottom of their file, and not bother putting an if statement in front of it. Then when you get to user-written modules, you could introduce the if __name__ and explain its need. DaveA From ian.g.kelly at gmail.com Mon Oct 3 15:37:56 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 3 Oct 2011 13:37:56 -0600 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: <4E8A0985.2010007@ieee.org> References: <4E8A0985.2010007@ieee.org> Message-ID: On Mon, Oct 3, 2011 at 1:14 PM, Dave Angel wrote: > Is it explaining the if statement that's the problem? ?If so, you could have > them do an unconditional main(sys.argv) at the bottom of their file, and not > bother putting an if statement in front of it. ?Then when you get to > user-written modules, you could introduce the if __name__ and explain its > need. It's not a good idea to teach bad habits they'll just have to unlearn later on. Especially since they might not be paying attention when you talk about if __name__ and how to do it right. I would suggest giving them the whole if __name__ block as boilerplate and telling them they're not allowed to alter it. Then in a later class, explain its purpose. From galyle at gmail.com Mon Oct 3 15:55:37 2011 From: galyle at gmail.com (galyle) Date: Mon, 3 Oct 2011 12:55:37 -0700 (PDT) Subject: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus Message-ID: Hello, I'm trying to build a menu which provides suggestions to a user based on input to an entry. I have done something like this before using Tcl/Tk, so I expected that it would work without much difficulty with Tkinter. I was wrong. The problem I have is that, as soon as the menu is posted, it appears to take the keyboard focus until the user either selects an option or clicks an area outside of the menu. The behavior I would like is for keyboard input to go to the entry, and for the menu to update based on that input. I have tried different bindings (both to the entry and menu) and I have tried different focus/grab combinations (even force_focus and grab_set_global to the entry) when the menu is posted, but nothing seems to work. Are there any suggestions on how to get the behavior I'm seeking? The following code demonstrates the issue I'm having: import Tkinter class demo: def __init__(self, parent): self._entry = Tkinter.Entry(width = 60) self._suggestions = Tkinter.Menu(parent, tearoff = 0, takefocus = 0) self._entry.pack(padx = 20, pady = 20) self._entry.bind('', self._suggest_text, add = '+') def _suggest_text(self, event): curr = self._entry.get() + repr(event.char)[1] x = self._entry.winfo_rootx() y = self._entry.winfo_rooty() y += self._entry.winfo_height() try: self._suggestions.delete(0, 'end') self._suggestions.add_command(label = curr + '_1') self._suggestions.add_command(label = curr + '_2') self._suggestions.add_command(label = curr + '_3') self._suggestions.add_command(label = curr + '_4') self._suggestions.post(x, y) finally: self._suggestions.grab_release() if __name__ == '__main__': root = Tkinter.Tk() root.title('A Problem') demo(root) root.mainloop() From rantingrick at gmail.com Mon Oct 3 16:10:15 2011 From: rantingrick at gmail.com (rantingrick) Date: Mon, 3 Oct 2011 13:10:15 -0700 (PDT) Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: Message-ID: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> On Oct 3, 2:14?pm, Dave Angel wrote: > Like it or not, there are plenty of globals already there, one of them > being __name__ . ?All the built-ins are effectively global, and so > ? is any function they define at top-level. I keep wondering if that was another PyWart? I believe (and hindsight is 20-20) that all the built-in modules should have been protected by a top-level namespace. Something succicent, something like "py"... from py.archive import zipfile, tarfile from py.gui import Tkinter from py.markup import HTMLParser ...and voila, no more clashes with user defined modules! >?Likewise any top-level > class, and any symbols imported with import or with from/import. ?So I > consider it impractical for the language to do something that > self-discipline is required for. Also for scoping. py> count = 0 py> def foo(): ... global.count += 1 py> print count 1 Why? Well because many times i find myself wondering if this or that variable is local or global -- and when i say "global" i am speaking of module scope! The "global" cures the ill. From pulsarpietro at gmail.com Mon Oct 3 16:24:21 2011 From: pulsarpietro at gmail.com (pedr0) Date: Mon, 3 Oct 2011 13:24:21 -0700 (PDT) Subject: HTTP Persistent connection Message-ID: <25371269.3648.1317673461242.JavaMail.geo-discussion-forums@yqnv12> Hi at all, I have some problem with the httplib module, I would like have an HTTP persistent connection but when run this code : #first request http_connection = httplib.HTTPConnection(host) http_connection.request(method,url,headers=headers) response = http_connection.getresponse() #second request It works using two different socket, I can see that using wireshark, each request use two different source port. I am using Python 2.6.1, some can suggest me how solve problem ? Thanks in advance. \pedr0 From pulsarpietro at gmail.com Mon Oct 3 16:39:17 2011 From: pulsarpietro at gmail.com (pedr0) Date: Mon, 3 Oct 2011 13:39:17 -0700 (PDT) Subject: HTTP Persistent connection In-Reply-To: <25371269.3648.1317673461242.JavaMail.geo-discussion-forums@yqnv12> References: <25371269.3648.1317673461242.JavaMail.geo-discussion-forums@yqnv12> Message-ID: <27527508.4070.1317674357487.JavaMail.geo-discussion-forums@yqnk41> I forget to insert second request. host = "www.higuys.net" #first request http_connection = httplib.HTTPConnection(host) http_connection.request(method,url_first,headers=headers) response = http_connection.getresponse() #second request http_connection = httplib.HTTPConnection(host) http_connection.request(method,url_second,headers=headers) response = http_connection.getresponse() From rantingrick at gmail.com Mon Oct 3 16:40:01 2011 From: rantingrick at gmail.com (rantingrick) Date: Mon, 3 Oct 2011 13:40:01 -0700 (PDT) Subject: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus References: Message-ID: <9256d59e-efae-4bf0-8de9-56e5ac3c1ab2@j31g2000vbl.googlegroups.com> On Oct 3, 2:55?pm, galyle wrote: > Hello, I'm trying to build a menu which provides suggestions to a user > based on input to an entry. ?I have done something like this before > using Tcl/Tk, so I expected that it would work without much difficulty > with Tkinter. ?I was wrong. Why not just use the Tix.ComboBox instead? I believe it's editable. From gordon at panix.com Mon Oct 3 16:51:43 2011 From: gordon at panix.com (John Gordon) Date: Mon, 3 Oct 2011 20:51:43 +0000 (UTC) Subject: HTTP Persistent connection References: <25371269.3648.1317673461242.JavaMail.geo-discussion-forums@yqnv12> <27527508.4070.1317674357487.JavaMail.geo-discussion-forums@yqnk41> Message-ID: In <27527508.4070.1317674357487.JavaMail.geo-discussion-forums at yqnk41> pedr0 writes: > I forget to insert second request. > host = "www.higuys.net" > #first request > http_connection = httplib.HTTPConnection(host) > http_connection.request(method,url_first,headers=headers) > response = http_connection.getresponse() > #second request > http_connection = httplib.HTTPConnection(host) > http_connection.request(method,url_second,headers=headers) > response = http_connection.getresponse() I haven't used httplib much so maybe this is a dumb question, but if you want to reuse the same connection, why are you declaring two separate HTTPConnection objects? Wouldn't you want to reuse the same object? -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From rantingrick at gmail.com Mon Oct 3 16:55:44 2011 From: rantingrick at gmail.com (rantingrick) Date: Mon, 3 Oct 2011 13:55:44 -0700 (PDT) Subject: Chaos Theory [was Re: Benefit and belief] References: <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> <4e88db0f$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8b72b54c-c33a-454b-8b4f-f599a63ab111@j19g2000vbn.googlegroups.com> On Oct 3, 11:27?am, Chris Angelico wrote: > PhysicsExpert: Super-speed wouldn't work, the acceleration required to > achieve it would burn up his surroundings! For some definition of "super-speed" i suppose. Since we're bouncing around the "relatives" here we need to consider this one also -> Super Speed to a tortoise will be super-slow, say for example, compared to the air-speed velocity of an unladen swallow. > Your point? Reductio ad Absurdum From pulsarpietro at gmail.com Mon Oct 3 17:12:58 2011 From: pulsarpietro at gmail.com (pedr0) Date: Mon, 3 Oct 2011 14:12:58 -0700 (PDT) Subject: HTTP Persistent connection In-Reply-To: References: <25371269.3648.1317673461242.JavaMail.geo-discussion-forums@yqnv12> <27527508.4070.1317674357487.JavaMail.geo-discussion-forums@yqnk41> Message-ID: <906183.4513.1317676378727.JavaMail.geo-discussion-forums@yqgn17> Because I am a newbye!!! Thanks a lot for your answer! From ed at leafe.com Mon Oct 3 17:21:34 2011 From: ed at leafe.com (Ed Leafe) Date: Mon, 3 Oct 2011 16:21:34 -0500 Subject: Hello, and request for help with 'dynamic grids' In-Reply-To: <4E64CFAB.70804@fossworkflowguides.com> References: <4E645BA6.4070500@fossworkflowguides.com> <1315229031.32028.140258137504765@webmail.messagingengine.com> <4E64CFAB.70804@fossworkflowguides.com> Message-ID: <2EE49CA6-EB6F-4D51-90F3-3CB6317872D5@leafe.com> On Sep 5, 2011, at 8:33 AM, Simon Cropper wrote: > Dabo is a great product. Spoke extensively with Ed Leafe and Paul McNett. Unfortunately the framework is not 'dynamic'. If you have an fixed database and tables it can quite quickly create a basic data entry setup and menu. Looks great when it runs. The problem is creating the window and grid on the fly. Sorry, someone just pointed me to this message. Of course we can build a window and grid on the fly: the command is: form, grid = dabo.ui.browse() ...where is a data set, or any object with a getDataSet() method, such as a bizobj or a cursor. I demonstrated this at my session at PyCon 2007: http://www.youtube.com/watch?v=y8G8AefXDo8&t=3m6s If you don't want to do this in a separate window, you can call the grid's buildFromDataSet() method directly. This command has a ton of optional parameters to control just how you would like the grid to appear. -- Ed Leafe From greg.ewing at canterbury.ac.nz Mon Oct 3 17:50:25 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 04 Oct 2011 10:50:25 +1300 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: <4E8A0985.2010007@ieee.org> Message-ID: <9eup13F72aU1@mid.individual.net> Ian Kelly wrote: > I would suggest giving them the whole if __name__ block as boilerplate > and telling them they're not allowed to alter it. I would suggest not showing them "if __name__" at all; instead encourage them to do this: def main(): ... ... main() You only need "if __name__ == '__main__'" if you want a .py file that can be used as either a module or a main program. Most of the time you *don't* need that. I consider it advanced usage that beginners shouldn't be confused with. -- Greg From anikom15 at gmail.com Mon Oct 3 18:01:24 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Mon, 3 Oct 2011 15:01:24 -0700 Subject: overloading operators for a function object In-Reply-To: References: Message-ID: <20111003220124.GA20084@Smoke> On Fri, Sep 30, 2011 at 09:50:42PM -0700, Fletcher Johnson wrote: > Is it possible to overload operators for a function? > > For instance I would like to do something roughly like... > > def func_maker(): > def func(): pass > > def __eq__(other): > if other == "check": return True > return False > > func.__eq__ = __eq__ > return func > > newfunc = func_maker() > newfunc == "check" #true > newfunc == "no" #false I'm curious as to what you're going to use this for. From davea at ieee.org Mon Oct 3 18:22:35 2011 From: davea at ieee.org (Dave Angel) Date: Mon, 03 Oct 2011 18:22:35 -0400 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> Message-ID: <4E8A35AB.5020601@ieee.org> On 01/-10/-28163 02:59 PM, rantingrick wrote: > On Oct 3, 2:14 pm, Dave Angel wrote: > >> Like it or not, there are plenty of globals already there, one of them >> being __name__ . All the built-ins are effectively global, and so >> is any function they define at top-level. > I keep wondering if that was another PyWart? I believe (and hindsight > is 20-20) that all the built-in modules There's only one __builtins__ module, which is implicitly loaded, and contains tons of things which are effectively global, such as open, float, filter, sorted, etc. > should have been protected by > a top-level namespace. Something succicent, something like "py"... > > from py.archive import zipfile, tarfile > from py.gui import Tkinter > from py.markup import HTMLParser > > ...and voila, no more clashes with user defined modules! > Gee, you just described a package. So why not say that the stdlib should have been done as a package of modules ? I don't know if I agree or not, just trying to keep things level. >> Likewise any top-level >> class, and any symbols imported with import or with from/import. So I >> consider it impractical for the language to do something that >> self-discipline is required for. > Also for scoping. > > py> count = > py> def foo(): > ... global.count += > py> print count > 1 > > Why? Well because many times i find myself wondering if this or that > variable is local or global -- and when i say "global" i am speaking > of module scope! The "global" cures the ill. > DaveA From rhodri at wildebst.demon.co.uk Mon Oct 3 18:34:54 2011 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Mon, 03 Oct 2011 23:34:54 +0100 Subject: Is there any way to access attributes from an imported module? References: <4E87F2A5.9000204@gmail.com> <4E880E87.5070507@islandtraining.com> Message-ID: On Mon, 03 Oct 2011 03:21:41 +0100, Andrew Berg wrote: > I found a way to do it, albeit a very hackish one. Since the class > instance already catches exceptions from the modules it imports, I can > make a custom exception (in a common area for both it and the submodules > to import) for it to catch and have it call its own methods there based > on information stored in the exception. I'm eventually going to redesign > it to be cleaner and more obvious, but for now, this is a nice > quick-and-dirty solution. OK, I give up. I cannot construct a mental model of what's going on that doesn't grievously abuse at least one of the terms you are using. Could you post some illustrative code snippets, please? -- Rhodri James *-* Wildebeest Herder to the Masses From ian.g.kelly at gmail.com Mon Oct 3 18:41:08 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 3 Oct 2011 16:41:08 -0600 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> Message-ID: On Mon, Oct 3, 2011 at 2:10 PM, rantingrick wrote: > Also for scoping. > > py> count = 0 > py> def foo(): > ... ? ? global.count += 1 > py> print count > 1 > > Why? Well because many times i find myself wondering if this or that > variable is local or global -- and when i say "global" i am speaking > of module scope! The "global" cures the ill. def add_from_input(num_lines): total = global.sum(global.int(global.input()) for i in global.range(num_lines)) global.print("The total is", total) Yes, that's much better. From gelonida at gmail.com Mon Oct 3 18:51:48 2011 From: gelonida at gmail.com (Gelonida N) Date: Tue, 04 Oct 2011 00:51:48 +0200 Subject: Advise on using logging.getLogger needed. In-Reply-To: <4E88E1B3.6080009@syslang.net> References: <4E88E1B3.6080009@syslang.net> Message-ID: On 10/03/2011 12:12 AM, Steven W. Orr wrote: > I hope I don't sound like I'm ranting :-( > > I have created a module (called xlogging) which sets up logging the way I want > it. I found out that if I set up my logger without a name, then it gets > applied to every logger that is referenced by every module that ever gets > imported. > > The problem is that I must call xlogging.getLogger or logging.getLogger in all > other modules using the name of the root logger, and I don't know what that > name is. > . . . . > > My modules are used by multiple programs. Does this mean that I should simply > use __name__ all the time? (That seems inelegant, no?) > > If I'm making sense, is there a way to do this? > > My impression is, that you try to use logging in a rather unconventional way. What you should normally do: Only your main script should configure the logging. If you want to do logging already during the import phase, then make sure, that you configure logging importing any module, that wants to log during the import phase. All other modules should only have following lines import logging log = logging.getLogger('name') # normally unique name for each module if you have groups of modules, that belong together, then choose hierarchical names for example 'gui.mainwindow' 'gui.subwindow' or similiar So if xlogging.py is the module, that sets up logging the way you want, then you should import it ONLY in your main script. or perhaps in a 'if __name__ == '__main__' section for anything, that you might want to run stand alone you can configure obtain (and thus configure) the root logger with rootlogger = logging.getLogger() your module can also configure other loggers and configure them. gui_logger = logging.getlogger('gui') configuring this logger will affect the configuration of all loggers named 'gui' or 'gui.somethingelse' You might want to look at the python doc to see how you could configure logging via a config file http://docs.python.org/release/2.6/library/logging.html#configuring-logging or you can look at: http://antonym.org/2005/03/a-real-python-logging-example.html From galyle at gmail.com Mon Oct 3 19:24:11 2011 From: galyle at gmail.com (galyle) Date: Mon, 3 Oct 2011 16:24:11 -0700 (PDT) Subject: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus References: <9256d59e-efae-4bf0-8de9-56e5ac3c1ab2@j31g2000vbl.googlegroups.com> Message-ID: <7c5a214d-effb-41cc-aefb-ba301581e1ae@i23g2000yqm.googlegroups.com> On Oct 3, 2:40?pm, rantingrick wrote: > On Oct 3, 2:55?pm, galyle wrote: > > > Hello, I'm trying to build a menu which provides suggestions to a user > > based on input to an entry. ?I have done something like this before > > using Tcl/Tk, so I expected that it would work without much difficulty > > with Tkinter. ?I was wrong. > > Why not just use the Tix.ComboBox instead? I believe it's editable. Thanks for the suggestion. I tried using a Pmw.ComboBox, but I've run into essentially the same problem. If I bring up the selection list on a keypress, then the selection takes the focus and further input no longer goes to the entry of the ComboBox. However, if I set the focus to the entry after bringing up the selection list, I can at least continue inputting to the entry, even though the selection list menu gets placed behind the entry. This is not desirable behavior, but at least it is closer. Any idea how to bring the menu to the forefront without the entry losing focus? The following demo demonstrates the issue: import Tkinter import Pmw class demo: def __init__(self, parent): self._search_bar = Pmw.ComboBox(parent, label_text = 'Register Mnemonic', labelpos = 'w', entry_width = 60) self._search_bar.pack(padx = 20, pady = 20) self._search_bar._entryfield.component('entry').bind('', self._suggest_text, add = '+') def _suggest_text(self, event): curr = self._search_bar._entryfield.getvalue() + repr(event.char)[1] self._search_bar._list.setlist([curr + '_0', curr + '_1', curr + '_2']) self._search_bar._postList(event) self._search_bar._entryfield.component('entry').focus_set() print curr if __name__ == '__main__': root = Tkinter.Tk() root.title('A Problem') demo(root) root.mainloop() From rosuav at gmail.com Mon Oct 3 20:07:24 2011 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Oct 2011 11:07:24 +1100 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> Message-ID: On Tue, Oct 4, 2011 at 9:41 AM, Ian Kelly wrote: > def add_from_input(num_lines): > ? ?total = global.sum(global.int(global.input()) for i in > global.range(num_lines)) > ? ?global.print("The total is", total) That's pretty unfair to the globals. def add_from_input(param.num_lines): local.total = global.sum(global.int(global.input()) for tinyscope.i in global.range(param.num_lines)) global.print("The total is", local.total) FTFY. ChrisA From nobody at nowhere.com Mon Oct 3 20:08:10 2011 From: nobody at nowhere.com (Nobody) Date: Tue, 04 Oct 2011 01:08:10 +0100 Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> <9etc4tF825U1@mid.individual.net> Message-ID: On Mon, 03 Oct 2011 22:04:26 +1300, Gregory Ewing wrote: >> os.setsid() > > *This* is what's losing the tty. According to the Fine Man Page: > > DESCRIPTION > The setsid function creates a new session. The calling process is the > session leader of the new session, is the process group leader of a new > process group and has no controlling terminal. > ^^^^^^^^^^^^^^^^^^^^^^^^^^^ The above description is incomplete. This version has more detail: DESCRIPTION setsid() creates a new session if the calling process is not a process group leader. The calling process is the leader of the new session, the process group leader of the new process group, and has no control- ling tty. The process group ID and session ID of the calling process are set to the PID of the calling process. The calling process will be the only process in this new process group and in this new session. The key point is "... if the calling process is not a process group leader". The easiest way to achieve this condition is to fork(). This ensures that the child process won't be a process group leader unless it explicitly makes itself one with setpgid() or setpgrp(). A process launched from a shell typically /will/ be a process group leader unless it's part of a pipeline (the shell creates a new process group for each pipeline; one of the processes in that group will be its leader). setsid() will fail with EPERM if the calling process is a process group leader. From roy at panix.com Mon Oct 3 20:22:01 2011 From: roy at panix.com (Roy Smith) Date: Mon, 03 Oct 2011 20:22:01 -0400 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <4E8A0985.2010007@ieee.org> Message-ID: In article , Ian Kelly wrote: > It's not a good idea to teach bad habits they'll just have to unlearn > later on. Absolutely correct. People who teach teachers how to teach call this the Law of Primacy (http://en.wikipedia.org/wiki/Principles_of_learning#Primacy), and (despite a lot of the religious psychobabble that comes with the territory) it really is true. Much better to just say, "put this stuff at the end of your file and don't worry about it for now" then to teach people the wrong way to do things. At some point, you'll get up to talking about modules and/or the magic double-underscore namespace. Then you'll have the opportunity to double back and explain what it means. From rustompmody at gmail.com Mon Oct 3 23:00:55 2011 From: rustompmody at gmail.com (rusi) Date: Mon, 3 Oct 2011 20:00:55 -0700 (PDT) Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> <02EA6D704E30CE499C5071776509A925F5BABD@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: On Oct 3, 12:45?pm, Chris Rebert wrote: > On Sun, Oct 2, 2011 at 11:45 PM, Wong Wah Meng-R32813 > > wrote: > > Hello guys, > > > I am migrating my application from python 1.5.2 to 2.7.1. I encountered an error when I run some commands (I put in debug statement however, not able to trace down to which line of code that cause it to generate a lot of messages in one second until my hard disk space is full. The error log I got in my log file is as below:- > > > Oct ?3 14:12:41 ?('Encountered exception while processing from', (0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), , TypeError('exceptions must be old-style classes or derived from BaseException, not str',)) > > > Does it mean in newer python I need to migrate all my Exception to non-string based exception type? > > Correct. You can no longer do merely `raise "Some error message"`. You > should instead raise an exception instance of the appropriate type; > e.g. `raise ValueError("foo must be positive")`. > It's advisable to read the NEWS / "What's New" documents for the > intervening versions so you can learn what else has changed. > > > That's should be a lot of changes. :p > > To be fair, v1.5.2 is practically ancient at this point. It's over a > decade old! And 2 *major* versions behind what's current. > In a pinch, you could always write a script to mechanically change > `raise "..."` to `raise StandardError("...")` [or some other fairly > generic exception type]. > > Cheers, > Chris I wonder whether 2to3 could help directly or else have a hook to do this semi-automatically? NOTE: I am not advocating going straight to python 3, just using (parts of) the 2to3 'fixes' to aid migration. From sillyousu at gmail.com Mon Oct 3 23:42:14 2011 From: sillyousu at gmail.com (sillyou su) Date: Mon, 3 Oct 2011 20:42:14 -0700 (PDT) Subject: To start a simple server References: <06b7fcdc-8615-4980-8d42-f212033ee5c8@dk6g2000vbb.googlegroups.com> <9etsvnF1kdU9@mid.individual.net> <9eucdkF1kdU14@mid.individual.net> Message-ID: <7bceb2ea-676c-4dc7-9531-905ed1d14eb4@m5g2000vbe.googlegroups.com> On Oct 4, 2:15?am, Amelia T Cat wrote: > On Mon, 03 Oct 2011 10:09:59 -0700, sillyou su wrote: > > ??? > > > I should use 127.0.0.1 instance of ?0.0.0.0 > > Theoretically either one should be fine. If you use 127.0.0.1 it will > only expose the service to your local machine. If you use 0.0.0.0 ut will > expose the service to other computers on the same network as the one > running the service. Yes. Thank you. I run service on my computer. So I should use localhost to launch the service. From wuwei23 at gmail.com Tue Oct 4 00:27:12 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Oct 2011 21:27:12 -0700 (PDT) Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> Message-ID: <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> rantingrick wrote: > Why? Well because many times i find myself wondering if this or that > variable is local or global -- and when i say "global" i am speaking > of module scope! The "global" cures the ill. Given your stated propensity for huge code blocks not chunked into functions, I'm not surprised you lose track of what is global, what is nonlocal etc. This is another clear advantage of small functions: you can view it all at once. For the rest of us, a variable is global if its referenced but not defined in a specific scope. There's no need for such verbose hand-holding. I'd say the wart is in your design practice rather than the language itself. From wuwei23 at gmail.com Tue Oct 4 00:35:16 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Oct 2011 21:35:16 -0700 (PDT) Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: Message-ID: <74e9b784-7de4-4306-a747-bff85b1a1181@fx14g2000vbb.googlegroups.com> Sorry for hijacking Alec's response but I didn't see the OP. > Aivar Annamaa wrote: > > I'm looking for a trick or hidden feature to make Python 3 automatically > > call a "main" function but without programmers writing `if __name__ == > > "__main__": ...` One direct way is to call it from the command line: python -c "import mymodule; mymodule.main()" After your students have had to use that verbose form for a while, they'll be more than happy to add the boilerplate themselves to the end of their modules :) From wuwei23 at gmail.com Tue Oct 4 00:43:34 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Oct 2011 21:43:34 -0700 (PDT) Subject: Chaos Theory [was Re: Benefit and belief] References: <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> <4e88db0f$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <2675a628-e3a5-41a0-a9e2-2dc0803444de@t16g2000yqm.googlegroups.com> rantingrick wrote: > TrueWiseObserver: Wrong pseudo. Superman will ALWAYS be superman even > if he wears a dress and stilettos. Clark Kent is just an assumed > identity of Superman. Actually, he identifies with Clark Kent, Superman is the secret identity. You're thinking of Batman, for whom Bruce Wayne is the mask. From schesis at gmail.com Tue Oct 4 01:04:49 2011 From: schesis at gmail.com (Zero Piraeus) Date: Tue, 4 Oct 2011 01:04:49 -0400 Subject: Chaos Theory [was Re: Benefit and belief] In-Reply-To: <2675a628-e3a5-41a0-a9e2-2dc0803444de@t16g2000yqm.googlegroups.com> References: <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> <4e88db0f$0$29981$c3e8da3$5496439d@news.astraweb.com> <2675a628-e3a5-41a0-a9e2-2dc0803444de@t16g2000yqm.googlegroups.com> Message-ID: : On 4 October 2011 00:43, alex23 wrote: > rantingrick wrote: >> Clark Kent is just an assumed identity of Superman. > > Actually, he identifies with Clark Kent, Superman is the secret > identity. > > You're thinking of Batman, for whom Bruce Wayne is the mask. A dissenting view [and a Kill Bill spoiler, of sorts]: http://www.youtube.com/watch?v=PdWF7kd1tNo -[]z. From me+list/python at ixokai.io Tue Oct 4 02:24:27 2011 From: me+list/python at ixokai.io (Stephen Hansen) Date: Mon, 03 Oct 2011 23:24:27 -0700 Subject: Suggested coding style In-Reply-To: <27620bc4-edd2-473e-809f-18f17b426b4f@db5g2000vbb.googlegroups.com> References: <27620bc4-edd2-473e-809f-18f17b426b4f@db5g2000vbb.googlegroups.com> Message-ID: <4E8AA69B.303@ixokai.io> On 9/30/11 6:54 AM, rantingrick wrote: > a misplaced and rarely used functionality of the stdlib. Have you tried putting "\.zfill\(" and selecting Python in google.com/codesearch? It seems to have quite a few users, among only openly available code. Considering there is a much larger body of code that isn't openly available, its not hard to extrapolate from the search. (Then again, the Python Community is made up of only people on this list! Everyone knows that.) Sure, you can use format strings, but that is a significantly more complicated thing to do. It may not be /common/, but is not at all unusual for one to have in a string a number that they want to line up numerically with zeros. You may not have had to do it a lot. But, golly, you are not a representative sample of the world. Your code, your projects, the things you have done, are not a representative sample of all the Python code, projects, and things people have done with Python out there. The "zfill" may not be a super wonderful function, used by many in most places. But its there, its simple, its clear what it does. Removing it means that anyone who wants to do what it did, now have to learn a fairly complex mini-language, even if perhaps that is the only time they will /ever/ need to use said language. That's a burden which is just, frankly, silly. Its nice that the format mini-language is powerful. But its nice that there are also simple, clear, direct primitives people can use to accomplish simple, fairly common needs. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From wuwei23 at gmail.com Tue Oct 4 02:25:56 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Oct 2011 23:25:56 -0700 (PDT) Subject: Chaos Theory [was Re: Benefit and belief] References: <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> <4e88db0f$0$29981$c3e8da3$5496439d@news.astraweb.com> <2675a628-e3a5-41a0-a9e2-2dc0803444de@t16g2000yqm.googlegroups.com> Message-ID: <8433efdb-55ef-4e40-bbf6-4fc508bdc1b0@j1g2000yqj.googlegroups.com> Zero Piraeus wrote: > A dissenting view [and a Kill Bill spoiler, of sorts]: > > http://www.youtube.com/watch?v=PdWF7kd1tNo A fun diatribe, sure, but still an outsider view that is in direct conflict with how the characters are actually portrayed. From masood.524 at gmail.com Tue Oct 4 02:39:15 2011 From: masood.524 at gmail.com (masood shaik) Date: Mon, 3 Oct 2011 23:39:15 -0700 (PDT) Subject: how to call java methods in python Message-ID: Hi I am trying to import java method in python. But i am getting the following error. error: ImportError: No module named Calculator Calculator is the name of the class written in java. I am trying to access the methods of that class. Please help me. From wuwei23 at gmail.com Tue Oct 4 02:52:15 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Oct 2011 23:52:15 -0700 (PDT) Subject: how to call java methods in python References: Message-ID: On Oct 4, 4:39?pm, masood shaik wrote: > Please help me. Please help us help you. You've given us nothing but an error message. (Which seems to indicate that you're trying 'import Calculator'...) What are you using to call Java methods in Python? Can you provide a small example of code that demonstrates the problem? From lucaberto at libero.it Tue Oct 4 02:58:15 2011 From: lucaberto at libero.it (luca72) Date: Mon, 3 Oct 2011 23:58:15 -0700 (PDT) Subject: open html page for parsing Message-ID: Hello i have a simple question: up to now if i have to parse a page i do as follow: import urllib site = urllib.urlopen('http://www.blabla.ooo') list_a = site.readline() site.close() __and then i make my work__ Now i have the site that is open by an html file like this: insert the password; ;
this is in a file called example.html how can i open it with urllib From lucaberto at libero.it Tue Oct 4 03:00:45 2011 From: lucaberto at libero.it (luca72) Date: Tue, 4 Oct 2011 00:00:45 -0700 (PDT) Subject: urllib and parsing Message-ID: Hello i have a simple question: up to now if i have to parse a page i do as follow: import urllib site = urllib.urlopen('http://www.blabla.ooo') list_a = site.readline() site.close() __and then i make my work__ Now i have the site that is open by an html file like this: insert the password; ;
this is in a file called example.html how can i open it with urllib, please note i don't have to parse this file, but i have to parse the site where he point. From masood.524 at gmail.com Tue Oct 4 03:14:49 2011 From: masood.524 at gmail.com (masood shaik) Date: Tue, 4 Oct 2011 00:14:49 -0700 (PDT) Subject: how to call java methods in python References: Message-ID: <33a61c6f-508a-48f0-97dc-d51099199c30@z12g2000yqz.googlegroups.com> Hi I am trying out my hand on accessing java methods in python. here is my piece of code.. Calculator.java --------------- public class Calculator { public Calculator(){ } public double calculateTip(double cost, double tipPercentage){ return cost * tipPercentage; } public double calculateTax(double cost, double taxPercentage){ return cost * taxPercentage; } } javaInPython.py --------------- import Calculator class javaInPython(Calculator): def __init__(self): pass def calculateTotal(self, cost, tip, tax): return cost + self.calculateTip(tip,tax) + self.calculateTax(tax,tip) if __name__ == "__main__": calc = javaInPython() cost = 23.75 tip = .15 tax = .07 print "Starting Cost: ", cost print "Tip Percentage: ", tip print "Tax Percentage: ", tax Now i am trying to access the calculateTip() and its showing import error. It works fine when i am running it with jython but why its not happening in python. Please do help me. On Oct 4, 11:52?am, alex23 wrote: > On Oct 4, 4:39?pm, masood shaik wrote: > > > Please help me. > > Please help us help you. You've given us nothing but an error message. > (Which seems to indicate that you're trying 'import Calculator'...) > > What are you using to call Java methods in Python? > > Can you provide a small example of code that demonstrates the problem? From clp2 at rebertia.com Tue Oct 4 03:22:31 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 Oct 2011 00:22:31 -0700 Subject: open html page for parsing In-Reply-To: References: Message-ID: On Mon, Oct 3, 2011 at 11:58 PM, luca72 wrote: > Hello i have a simple question: > up to now if i have to parse a page i do as follow: > import urllib > site = urllib.urlopen('http://www.blabla.ooo') > list_a = site.readline() > site.close() > __and then i make my work__ > > Now i have the site that is open by an html file like this: > ? ? ? ? ? ? ? ? > insert the password > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?; > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?; > ? ? ? ? ? ? ? ? ? ? ? ? > ? ? ? ? ? ? ? ?
> > > > > > this is in a file called example.html > > how can i open it with urllib Assuming you meant "How do I submit the form in example.html and get the resulting response page?", use urllib.urlencode() to encode the form's key-value pairs, and then pass the encoded result as the `data` argument to urllib.urlopen(). Or use something like Selenium (http://seleniumhq.org/ ), mechanize (http://wwwsearch.sourceforge.net/mechanize/ ), or Scrapy (http://scrapy.org/ ) that emulates/drives a web browser and lets you fill out forms programatically. Cheers, Chris -- http://rebertia.com From r32813 at freescale.com Tue Oct 4 03:51:06 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Tue, 4 Oct 2011 07:51:06 +0000 Subject: Is exec() also not used in python 2.7.1 anymore? Message-ID: <02EA6D704E30CE499C5071776509A925F5C2ED@039-SN1MPN1-003.039d.mgd.msft.net> In migrating my application from python 1.5.2 to 2.7.1, one of my modules breaks when I import it. Here is the line where it breaks. Can I have a quick check if this built-in function still supported in python 2.7.1 and if so, what ought to be changed here? Thanks in advance for replying. exec('def %s(self, *args, **kw): pass'%methodStrName) SyntaxError: unqualified exec is not allowed in function '_exposeMethods' it contains a nested function with free variables Regards, Wah Meng -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Tue Oct 4 04:16:43 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 Oct 2011 01:16:43 -0700 Subject: how to call java methods in python In-Reply-To: <33a61c6f-508a-48f0-97dc-d51099199c30@z12g2000yqz.googlegroups.com> References: <33a61c6f-508a-48f0-97dc-d51099199c30@z12g2000yqz.googlegroups.com> Message-ID: On Tue, Oct 4, 2011 at 12:14 AM, masood shaik wrote: > Hi > ?I am trying out my hand on accessing java methods in python. here is > my piece of code.. > > Calculator.java > --------------- > public class Calculator { > > ? ?public Calculator(){ > > ? ?} > > ? ?public double calculateTip(double cost, double tipPercentage){ > ? ? ? ?return cost * tipPercentage; > ? ?} > > ? ?public double calculateTax(double cost, double taxPercentage){ > ? ? ? ?return cost * taxPercentage; > ? ?} > > } > > javaInPython.py > --------------- > import Calculator > > class javaInPython(Calculator): > ? ?def __init__(self): > ? ? ? ?pass > > ? ?def calculateTotal(self, cost, tip, tax): > ? ? ? ?return cost + self.calculateTip(tip,tax) + > self.calculateTax(tax,tip) > > if __name__ == "__main__": > ? ?calc = javaInPython() > ? ?cost = 23.75 > ? ?tip = .15 > ? ?tax = .07 > ? ?print "Starting Cost: ", cost > ? ?print "Tip Percentage: ", tip > ? ?print "Tax Percentage: ", tax > > Now i am trying to access the calculateTip() and its showing import > error. > It works fine when i am running it with jython but why its not > happening in python. That's because the integration functionality you're depending upon is *specific to Jython*. Unlike Jython, CPython does not include an automatic Java bridge. CPython doesn't feature Java integration; only Jython does. (N.B.: CPython is the reference implementation of Python, hosted at python.org.) Cheers, Chris From clp2 at rebertia.com Tue Oct 4 04:26:04 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 Oct 2011 01:26:04 -0700 Subject: Is exec() also not used in python 2.7.1 anymore? In-Reply-To: <02EA6D704E30CE499C5071776509A925F5C2ED@039-SN1MPN1-003.039d.mgd.msft.net> References: <02EA6D704E30CE499C5071776509A925F5C2ED@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: On Tue, Oct 4, 2011 at 12:51 AM, Wong Wah Meng-R32813 wrote: > In migrating my application from python 1.5.2 to 2.7.1, one of my modules > breaks when I import it. Here is the line where it breaks. Can I have a > quick check if this built-in function still supported in python 2.7.1 Er, `exec` is a primitive statement, not a built-in function (so, the parens around it are superfluous), but yes, it's still present in 2.7. (Ironically, exec was changed to a function in Python 3.0.) > and if > so, what ought to be changed here? Thanks in advance for replying. > > ? exec('def %s(self, *args, **kw): pass'%methodStrName) Defining a do-nothing, dynamically-named function seems kinda strange in the first place; why are you doing this? Cheers, Chris -- http://rebertia.com From __peter__ at web.de Tue Oct 4 04:40:05 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Oct 2011 10:40:05 +0200 Subject: Is exec() also not used in python 2.7.1 anymore? References: <02EA6D704E30CE499C5071776509A925F5C2ED@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: Wong Wah Meng-R32813 wrote: > In migrating my application from python 1.5.2 to 2.7.1, one of my modules > breaks when I import it. Here is the line where it breaks. Can I have a > quick check if this built-in function still supported in python 2.7.1 and > if so, what ought to be changed here? Thanks in advance for replying. > > exec('def %s(self, *args, **kw): pass'%methodStrName) > SyntaxError: unqualified exec is not allowed in function '_exposeMethods' > it contains a nested function with free variables I think the message is quite explicit about the problem. You have a nested function along the lines: >>> def f(): ... exec "" ... def g(): return x ... File "", line 2 SyntaxError: unqualified exec is not allowed in function 'f' it contains a nested function with free variables With the current scoping rules x in the inner function may refer either to a local variable in f() or a global variable -- and because of the exec statement the compiler cannot determine which. Depending on your usecase a workaround may be to declare the free variable as global: >>> def f(): ... exec "" ... def g(): ... global x ... return x ... return g ... >>> x = 42 >>> f()() 42 From aivar.annamaa at gmail.com Tue Oct 4 04:43:39 2011 From: aivar.annamaa at gmail.com (Aivar Annamaa) Date: Tue, 4 Oct 2011 11:43:39 +0300 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: Message-ID: Thanks for all the comments! It seems that the best way is still just to teach students self discipline. And hope that they (for now) believe some things (eg. dangers of global variables) without seeing. Aivar -------------- next part -------------- An HTML attachment was scrubbed... URL: From masood.524 at gmail.com Tue Oct 4 05:44:41 2011 From: masood.524 at gmail.com (masood shaik) Date: Tue, 4 Oct 2011 02:44:41 -0700 (PDT) Subject: how to call java methods in python References: <33a61c6f-508a-48f0-97dc-d51099199c30@z12g2000yqz.googlegroups.com> Message-ID: <735343b1-5c1e-4831-b794-b455675c2cd5@dk6g2000vbb.googlegroups.com> On Oct 4, 1:16?pm, Chris Rebert wrote: > On Tue, Oct 4, 2011 at 12:14 AM, masood shaik wrote: > > Hi > > ?I am trying out my hand on accessing java methods in python. here is > > my piece of code.. > > > Calculator.java > > --------------- > > public class Calculator { > > > ? ?public Calculator(){ > > > ? ?} > > > ? ?public double calculateTip(double cost, double tipPercentage){ > > ? ? ? ?return cost * tipPercentage; > > ? ?} > > > ? ?public double calculateTax(double cost, double taxPercentage){ > > ? ? ? ?return cost * taxPercentage; > > ? ?} > > > } > > > javaInPython.py > > --------------- > > import Calculator > > > class javaInPython(Calculator): > > ? ?def __init__(self): > > ? ? ? ?pass > > > ? ?def calculateTotal(self, cost, tip, tax): > > ? ? ? ?return cost + self.calculateTip(tip,tax) + > > self.calculateTax(tax,tip) > > > if __name__ == "__main__": > > ? ?calc = javaInPython() > > ? ?cost = 23.75 > > ? ?tip = .15 > > ? ?tax = .07 > > ? ?print "Starting Cost: ", cost > > ? ?print "Tip Percentage: ", tip > > ? ?print "Tax Percentage: ", tax > Please help me Regarding how to create java bridge as how to call a java function from python > > Now i am trying to access the calculateTip() and its showing import > > error. > > It works fine when i am running it with jython but why its not > > happening in python. > > That's because the integration functionality you're depending upon is > *specific to Jython*. Unlike Jython, CPython does not include an > automatic Java bridge. CPython doesn't feature Java integration; only > Jython does. > > (N.B.: CPython is the reference implementation of Python, hosted at python.org.) > > Cheers, > Chris From a24061 at ducksburg.com Tue Oct 4 05:56:57 2011 From: a24061 at ducksburg.com (Adam Funk) Date: Tue, 04 Oct 2011 10:56:57 +0100 Subject: recommend a graphics library for plotting by the pixel? Message-ID: <9s1rl8xt8t.ln2@news.ducksburg.com> I'd like to create a window with a "pause" button and a large plotting area, in which I'd like to draw a polygon, detect the pixel co?rdinates of a mouse click, and then start setting the colors of pixels by (x,y) co?rdinates. (This is just for my own amusement, to play with some formulas for generating fractals using random numbers.) There seems to be a large number of different python GUI libraries, and I wonder if someone can recommend the easiests one to learn for this purpose? (The only python graphics library I've used is PyGame, which I don't think is the way to go here.) -- In the 1970s, people began receiving utility bills for -?999,999,996.32 and it became harder to sustain the myth of the infallible electronic brain. (Stob 2001) From r32813 at freescale.com Tue Oct 4 06:32:41 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Tue, 4 Oct 2011 10:32:41 +0000 Subject: Is exec() also not used in python 2.7.1 anymore? In-Reply-To: References: <02EA6D704E30CE499C5071776509A925F5C2ED@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <02EA6D704E30CE499C5071776509A925F5C3AA@039-SN1MPN1-003.039d.mgd.msft.net> Haha... yeah I reviewed the code, it is supposed to exposed some remote methods locally (RMI proxy usage). However, I am not sure why what it does is merely a pass. I commented out this code and haven't seen any negative implication. I will look into this again if I am convinced the next error I see is due to I commented out this code. Thanks! Regards, Wah Meng -----Original Message----- From: chris at rebertia.com [mailto:chris at rebertia.com] On Behalf Of Chris Rebert Sent: Tuesday, October 04, 2011 4:26 PM To: Wong Wah Meng-R32813 Cc: python-list at python.org Subject: Re: Is exec() also not used in python 2.7.1 anymore? On Tue, Oct 4, 2011 at 12:51 AM, Wong Wah Meng-R32813 wrote: > In migrating my application from python 1.5.2 to 2.7.1, one of my modules > breaks when I import it. Here is the line where it breaks. Can I have a > quick check if this built-in function still supported in python 2.7.1 Er, `exec` is a primitive statement, not a built-in function (so, the parens around it are superfluous), but yes, it's still present in 2.7. (Ironically, exec was changed to a function in Python 3.0.) > and if > so, what ought to be changed here? Thanks in advance for replying. > > ? exec('def %s(self, *args, **kw): pass'%methodStrName) Defining a do-nothing, dynamically-named function seems kinda strange in the first place; why are you doing this? Cheers, Chris -- http://rebertia.com From gandalf at shopzeus.com Tue Oct 4 06:56:12 2011 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 04 Oct 2011 12:56:12 +0200 Subject: how to call java methods in python In-Reply-To: <735343b1-5c1e-4831-b794-b455675c2cd5@dk6g2000vbb.googlegroups.com> References: <33a61c6f-508a-48f0-97dc-d51099199c30@z12g2000yqz.googlegroups.com> <735343b1-5c1e-4831-b794-b455675c2cd5@dk6g2000vbb.googlegroups.com> Message-ID: <4E8AE64C.1050101@shopzeus.com> > Please help me > > Regarding how to create java bridge as how to call a java function > from python If you want to call a Java *method* from the C python implementation, then there are many possibilities. For example, you can write your Java program as a service. The Python program can talk to it through some kind of IPC mechanism. There are lots of ways to do communication between two running processes. Lower lever would be (just an example) to open a TCP/IP server socket on the Java side, and connect to it from the Python side. Then develop your own protocol for communication. Higher level would be (just another example) to use CORBA/ORB on the Java side, and do the same from the Python side. There are dozens of libraries that can help you communicate between processes. I suggest that you look after these libraries, and select one that suits your needs. If you want to call Java methods that run inside the same process with Python then I have bad news. This won't be possible. (Or it might be, but don't worth the work...) Best, Laszlo From svaliev at gmail.com Tue Oct 4 09:50:27 2011 From: svaliev at gmail.com (Valiev Sergey) Date: Tue, 4 Oct 2011 17:50:27 +0400 Subject: syntax enhancement Message-ID: Hi, you may found this idea stupid, but nevertheless... - `[]` - used for list comprehension, - `()` - used for generators, - `[start:stop]` / `[start:stop:step]` - used for slices. The idea is to use `(start:stop)` / `(start:stop:step)` as 'lazy evaluated' slices (like itertools.islice). What do you think about it? -- Best regards, Valiev Sergey *skype:* *svaliev* *jabber:* *svaliev at gmail.com* *phone:* +7 926 233-17-64 -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrea.crotti.0 at gmail.com Tue Oct 4 10:48:46 2011 From: andrea.crotti.0 at gmail.com (andrea.crotti.0 at gmail.com) Date: Tue, 04 Oct 2011 15:48:46 +0100 Subject: eggbasket Message-ID: <87aa9gdd81.fsf@precision.i-did-not-set--mail-host-address--so-tickle-me> I'm struggling trying to get a working local pypi server. Now eggbasket apparently also supports upload, which should be nice. So I: - created a virtualenv - installed all the necessary and trying to initializing the server I get: --8<---------------cut here---------------start------------->8--- eggbasket-server --init Traceback (most recent call last): File "/home/andrea/.local/bin/eggbasket-server", line 9, in load_entry_point('EggBasket==0.6.1b', 'console_scripts', 'eggbasket-server')() File "/home/andrea/.local/lib/python2.7/site-packages/EggBasket-0.6.1b-py2.7.egg/eggbasket/commands.py", line 145, in main init_database(args) File "/home/andrea/.local/lib/python2.7/site-packages/EggBasket-0.6.1b-py2.7.egg/eggbasket/commands.py", line 76, in init_database model = get_model() File "/usr/lib/python2.7/site-packages/TurboGears-1.5-py2.7.egg/turbogears/util.py", line 241, in get_model package = __import__(package_name, {}, {}, ["model"]) File "/home/andrea/.local/lib/python2.7/site-packages/EggBasket-0.6.1b-py2.7.egg/eggbasket/model.py", line 22, in from sqlalchemy.exceptions import InvalidRequestError ImportError: No module named exceptions --8<---------------cut here---------------end--------------->8--- But funny thing is that if try to understand to see what's going on, from within "model.py" import sqlalchemy.exceptions work perfectly, but importing something inside it gives this strange error, any idea of what it could be? How is it possible that the module exists and it's actually imported, and not found when I actually try to import something from it? From alec.taylor6 at gmail.com Tue Oct 4 10:53:25 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Wed, 5 Oct 2011 01:53:25 +1100 Subject: recommend a graphics library for plotting by the pixel? In-Reply-To: <9s1rl8xt8t.ln2@news.ducksburg.com> References: <9s1rl8xt8t.ln2@news.ducksburg.com> Message-ID: Sounds like a job for Processing... On Tue, Oct 4, 2011 at 8:56 PM, Adam Funk wrote: > I'd like to create a window with a "pause" button and a large plotting > area, in which I'd like to draw a polygon, detect the pixel > co?rdinates of a mouse click, and then start setting the colors of > pixels by (x,y) co?rdinates. ?(This is just for my own amusement, to > play with some formulas for generating fractals using random numbers.) > > There seems to be a large number of different python GUI libraries, > and I wonder if someone can recommend the easiests one to learn for > this purpose? ?(The only python graphics library I've used is PyGame, > which I don't think is the way to go here.) > > > -- > In the 1970s, people began receiving utility bills for > -?999,999,996.32 and it became harder to sustain the > myth of the infallible electronic brain. ?(Stob 2001) > -- > http://mail.python.org/mailman/listinfo/python-list > From woooee at gmail.com Tue Oct 4 11:41:06 2011 From: woooee at gmail.com (woooee) Date: Tue, 4 Oct 2011 08:41:06 -0700 (PDT) Subject: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus References: <9256d59e-efae-4bf0-8de9-56e5ac3c1ab2@j31g2000vbl.googlegroups.com> <7c5a214d-effb-41cc-aefb-ba301581e1ae@i23g2000yqm.googlegroups.com> Message-ID: <4a81ac45-4a55-4684-8588-7e9ec0f1d455@k15g2000yqd.googlegroups.com> Adding focus_set seems to work for me. What do want to do differently? import Tkinter class demo: def __init__(self, parent): self._entry = Tkinter.Entry(width = 60) self._suggestions = Tkinter.Menu(parent, tearoff = 0, takefocus = 0) self._entry.pack(padx = 20, pady = 20) self._entry.bind('', self._suggest_text, add = '+') self._entry.focus_set() def _suggest_text(self, event): curr = self._entry.get() + repr(event.char)[1] x = self._entry.winfo_rootx() y = self._entry.winfo_rooty() y += self._entry.winfo_height() try: self._suggestions.delete(0, 'end') self._suggestions.add_command(label = curr + '_1') self._suggestions.add_command(label = curr + '_2') self._suggestions.add_command(label = curr + '_3') self._suggestions.add_command(label = curr + '_4') self._suggestions.post(x, y) finally: self._suggestions.grab_release() if __name__ == '__main__': root = Tkinter.Tk() root.title('A Problem') demo(root) root.mainloop() From woooee at gmail.com Tue Oct 4 11:45:10 2011 From: woooee at gmail.com (woooee) Date: Tue, 4 Oct 2011 08:45:10 -0700 (PDT) Subject: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus References: Message-ID: Sorry, I did not understand the question correctly, and so have added another focus_set for the entry after the menu's creation. You can still enter after the menu comes up, even though you can't see where you are entering. import Tkinter class demo: def __init__(self, parent): self._entry = Tkinter.Entry(width = 60) self._suggestions = Tkinter.Menu(parent, tearoff = 0, takefocus = 0) self._entry.pack(padx = 20, pady = 20) self._entry.bind('', self._suggest_text, add = '+') self._entry.focus_set() def _suggest_text(self, event): curr = self._entry.get() + repr(event.char)[1] x = self._entry.winfo_rootx() y = self._entry.winfo_rooty() y += self._entry.winfo_height() try: self._suggestions.delete(0, 'end') self._suggestions.add_command(label = curr + '_1') self._suggestions.add_command(label = curr + '_2') self._suggestions.add_command(label = curr + '_3') self._suggestions.add_command(label = curr + '_4') self._suggestions.post(x, y) finally: self._suggestions.grab_release() self._entry.focus_set() if __name__ == '__main__': root = Tkinter.Tk() root.title('A Problem') demo(root) root.mainloop() From ian.g.kelly at gmail.com Tue Oct 4 11:49:58 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 4 Oct 2011 09:49:58 -0600 Subject: recommend a graphics library for plotting by the pixel? In-Reply-To: <9s1rl8xt8t.ln2@news.ducksburg.com> References: <9s1rl8xt8t.ln2@news.ducksburg.com> Message-ID: On Tue, Oct 4, 2011 at 3:56 AM, Adam Funk wrote: > I'd like to create a window with a "pause" button and a large plotting > area, in which I'd like to draw a polygon, detect the pixel > co?rdinates of a mouse click, and then start setting the colors of > pixels by (x,y) co?rdinates. ?(This is just for my own amusement, to > play with some formulas for generating fractals using random numbers.) > > There seems to be a large number of different python GUI libraries, > and I wonder if someone can recommend the easiests one to learn for > this purpose? ?(The only python graphics library I've used is PyGame, > which I don't think is the way to go here.) You could use wxPython. You'll need to create a custom control and have it paint itself by blitting from a wx.Bitmap, which you'll draw on by using a wx.MemoryDC and then refreshing the control. I would probably just use pygame myself. I guess you're avoiding it because of the requirement for a button, but there are GUI libraries available for it, or if all you need are a couple of buttons you could easily roll your own. Stay away from the Tkinter Canvas widget. It does vector graphics, and it will be inefficient if you try to use it as a raster. Cheers, Ian From ironfroggy at gmail.com Tue Oct 4 12:17:13 2011 From: ironfroggy at gmail.com (Calvin Spealman) Date: Tue, 4 Oct 2011 12:17:13 -0400 Subject: syntax enhancement In-Reply-To: References: Message-ID: On Tue, Oct 4, 2011 at 9:50 AM, Valiev Sergey wrote: > Hi, > you may found this idea stupid, but nevertheless... > - `[]` - used for list comprehension, > - `()` - used for generators, > - `[start:stop]` / `[start:stop:step]` - used for slices. > The idea is to use `(start:stop)` / `(start:stop:step)` as 'lazy evaluated' > slices (like itertools.islice). > What do you think about it? > It simply looks too much like a function call. > -- > Best regards, > Valiev Sergey > *skype:* *svaliev* > *jabber:* *svaliev at gmail.com* > *phone:* +7 926 233-17-64 > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy -------------- next part -------------- An HTML attachment was scrubbed... URL: From anikom15 at gmail.com Tue Oct 4 12:44:40 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Tue, 4 Oct 2011 09:44:40 -0700 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: <74e9b784-7de4-4306-a747-bff85b1a1181@fx14g2000vbb.googlegroups.com> References: <74e9b784-7de4-4306-a747-bff85b1a1181@fx14g2000vbb.googlegroups.com> Message-ID: <20111004164440.GA27367@Smoke> On Mon, Oct 03, 2011 at 09:35:16PM -0700, alex23 wrote: > Sorry for hijacking Alec's response but I didn't see the OP. > > > Aivar Annamaa wrote: > > > I'm looking for a trick or hidden feature to make Python 3 automatically > > > call a "main" function but without programmers writing `if __name__ == > > > "__main__": ...` > > One direct way is to call it from the command line: > > python -c "import mymodule; mymodule.main()" > > After your students have had to use that verbose form for a while, > they'll be more than happy to add the boilerplate themselves to the > end of their modules :) Boiler plate is silly. Let the students figure out stuff themselves. The students need to know why global variables in functions is unwieldly, not just not use them because it's cool. When I taught myself Python I quickly realized global variables were unwieldly and usually impractical after using them. From galyle at gmail.com Tue Oct 4 13:05:49 2011 From: galyle at gmail.com (galyle) Date: Tue, 4 Oct 2011 10:05:49 -0700 (PDT) Subject: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus References: Message-ID: <19357b0e-0c8f-4081-9ea5-56acc4f03731@d17g2000yqa.googlegroups.com> On Oct 4, 9:45?am, woooee wrote: > Sorry, I did not understand the question correctly, and so have added > another focus_set for the entry after the menu's creation. ?You can > still enter after the menu comes up, even though you can't see where > you are entering. > > import Tkinter > > class demo: > ? ? def __init__(self, parent): > ? ? ? ? self._entry = Tkinter.Entry(width = 60) > ? ? ? ? self._suggestions = Tkinter.Menu(parent, tearoff = 0, > takefocus = 0) > ? ? ? ? self._entry.pack(padx = 20, pady = 20) > ? ? ? ? self._entry.bind('', self._suggest_text, add = '+') > ? ? ? ? self._entry.focus_set() > > ? ? def _suggest_text(self, event): > ? ? ? ? curr = self._entry.get() + repr(event.char)[1] > ? ? ? ? x = self._entry.winfo_rootx() > ? ? ? ? y = self._entry.winfo_rooty() > ? ? ? ? y += self._entry.winfo_height() > ? ? ? ? try: > ? ? ? ? ? ? self._suggestions.delete(0, 'end') > ? ? ? ? ? ? self._suggestions.add_command(label = curr + '_1') > ? ? ? ? ? ? self._suggestions.add_command(label = curr + '_2') > ? ? ? ? ? ? self._suggestions.add_command(label = curr + '_3') > ? ? ? ? ? ? self._suggestions.add_command(label = curr + '_4') > ? ? ? ? ? ? self._suggestions.post(x, y) > ? ? ? ? finally: > ? ? ? ? ? ? self._suggestions.grab_release() > > ? ? ? ? self._entry.focus_set() > > if __name__ == '__main__': > ? ? root = Tkinter.Tk() > ? ? root.title('A Problem') > ? ? demo(root) > ? ? root.mainloop() Perhaps it is because I'm trying this on Windows, but the above code does not work for me. After the menu is posted, no further keyboard input gets directed to the entry until the menu is unposted. It looks like my best bet is to use the ComboBox suggested above. The ComboBox method is very close to working, but I've got a problem now where all focus on the app is directed to the ComboBox entry (I need to set it that way to redirect keyboard input from the popup menu), making it impossible to close the app without killing it. I've tried to return focus to the entry parent by binding the entry to and , but this has the effect of making the popup take the focus after every keystroke, which is not what I want. The (almost working) demo below should demonstrate the issue fairly well: import Tkinter import Pmw class demo: def __init__(self, parent): self._search_bar = Pmw.ComboBox(parent, label_text = 'Register Mnemonic', labelpos = 'w', entry_width = 60) self._search_bar.pack(padx = 20, pady = 20) self._search_bar._entryfield.component('entry').bind('', self._suggest_text, add = '+') def _suggest_text(self, event): curr = self._search_bar._entryfield.getvalue() curr += repr(event.char)[1] self._search_bar._list.setlist([curr + '_0', curr + '_1', curr + '_2']) self._search_bar._postList(event) self._search_bar._entryfield.component('entry').focus_set() self._search_bar._popup.lift() if __name__ == '__main__': root = Tkinter.Tk() root.title('A Problem') demo(root) root.mainloop() From chris at simplistix.co.uk Tue Oct 4 14:22:01 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 04 Oct 2011 19:22:01 +0100 Subject: TestFixtures 2.2.0 Released! Message-ID: <4E8B4EC9.5030108@simplistix.co.uk> Hi All, The TestFixtures releases keep coming, I hope someone other than me is finding these useful ;-) This release features a change to test_datetime and test_date so that they return instances of the real datetime.datetime and datetime.date classes by default. I'm hoping this will making using these mocks with other libraries such as SQLALchemy and the associated database backend libraries much easier However, if you need the old behaviour, it's still available via the new "strict" mode: http://packages.python.org/testfixtures/datetime.html#strict-dates-and-times The package is on PyPI and a full list of all the links to docs, issue trackers and the like can be found here: http://www.simplistix.co.uk/software/python/testfixtures Any questions, please do ask here or on the Simplistix open source mailing lists... cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From galyle at gmail.com Tue Oct 4 14:35:25 2011 From: galyle at gmail.com (galyle) Date: Tue, 4 Oct 2011 11:35:25 -0700 (PDT) Subject: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus References: <19357b0e-0c8f-4081-9ea5-56acc4f03731@d17g2000yqa.googlegroups.com> Message-ID: <1e2853df-25db-4e6f-9de6-9a0f915f8f3b@j10g2000vbb.googlegroups.com> On Oct 4, 11:05?am, galyle wrote: > On Oct 4, 9:45?am, woooee wrote: > > > > > > > > > > > Sorry, I did not understand the question correctly, and so have added > > another focus_set for the entry after the menu's creation. ?You can > > still enter after the menu comes up, even though you can't see where > > you are entering. > > > import Tkinter > > > class demo: > > ? ? def __init__(self, parent): > > ? ? ? ? self._entry = Tkinter.Entry(width = 60) > > ? ? ? ? self._suggestions = Tkinter.Menu(parent, tearoff = 0, > > takefocus = 0) > > ? ? ? ? self._entry.pack(padx = 20, pady = 20) > > ? ? ? ? self._entry.bind('', self._suggest_text, add = '+') > > ? ? ? ? self._entry.focus_set() > > > ? ? def _suggest_text(self, event): > > ? ? ? ? curr = self._entry.get() + repr(event.char)[1] > > ? ? ? ? x = self._entry.winfo_rootx() > > ? ? ? ? y = self._entry.winfo_rooty() > > ? ? ? ? y += self._entry.winfo_height() > > ? ? ? ? try: > > ? ? ? ? ? ? self._suggestions.delete(0, 'end') > > ? ? ? ? ? ? self._suggestions.add_command(label = curr + '_1') > > ? ? ? ? ? ? self._suggestions.add_command(label = curr + '_2') > > ? ? ? ? ? ? self._suggestions.add_command(label = curr + '_3') > > ? ? ? ? ? ? self._suggestions.add_command(label = curr + '_4') > > ? ? ? ? ? ? self._suggestions.post(x, y) > > ? ? ? ? finally: > > ? ? ? ? ? ? self._suggestions.grab_release() > > > ? ? ? ? self._entry.focus_set() > > > if __name__ == '__main__': > > ? ? root = Tkinter.Tk() > > ? ? root.title('A Problem') > > ? ? demo(root) > > ? ? root.mainloop() > > Perhaps it is because I'm trying this on Windows, but the above code > does not work for me. ?After the menu is posted, no further keyboard > input gets directed to the entry until the menu is unposted. > > It looks like my best bet is to use the ComboBox suggested above. ?The > ComboBox method is very close to working, but I've got a problem now > where all focus on the app is directed to the ComboBox entry (I need > to set it that way to redirect keyboard input from the popup menu), > making it impossible to close the app without killing it. ?I've tried > to return focus to the entry parent by binding the entry to > and , but this has the effect of making the popup take the > focus after every keystroke, which is not what I want. > > The (almost working) demo below should demonstrate the issue fairly > well: > > import Tkinter > import Pmw > > class demo: > ? ? def __init__(self, parent): > ? ? ? ? self._search_bar = Pmw.ComboBox(parent, > ? ? ? ? ? ? label_text = 'Register Mnemonic', > ? ? ? ? ? ? labelpos = 'w', entry_width = 60) > ? ? ? ? self._search_bar.pack(padx = 20, pady = 20) > ? ? ? ? self._search_bar._entryfield.component('entry').bind('', > ? ? ? ? ? ? self._suggest_text, add = '+') > > ? ? def _suggest_text(self, event): > ? ? ? ? curr = self._search_bar._entryfield.getvalue() > ? ? ? ? curr += repr(event.char)[1] > ? ? ? ? self._search_bar._list.setlist([curr + '_0', curr + '_1', > ? ? ? ? ? ? curr + '_2']) > ? ? ? ? self._search_bar._postList(event) > ? ? ? ? self._search_bar._entryfield.component('entry').focus_set() > ? ? ? ? self._search_bar._popup.lift() > > if __name__ == '__main__': > ? ? root = Tkinter.Tk() > ? ? root.title('A Problem') > ? ? demo(root) > ? ? root.mainloop() Well, it required quite a bit of digging, but I finally have what I want. For those who are curious, the following demo should provide some help: import Tkinter import Pmw class demo: def __init__(self, parent): self._parent = parent self._search_bar = Pmw.ComboBox(parent, label_text = 'Register Mnemonic', labelpos = 'w', entry_width = 60) self._search_bar.pack(padx = 20, pady = 20) self._search_bar._entryfield.component('entry').bind('', self._suggest_text, add = '+') self._search_bar._entryfield.component('entry').bind('', self._remove_list, add = '+') self._search_bar._entryfield.component('entry').bind('', self._remove_list, add = '+') self._search_bar._entryfield.component('entry').bind('', self._remove_list, add = '+') self._search_bar._popup.bind('', self._remove_list, add = '+') def _suggest_text(self, event): x = self._search_bar._entryfield.winfo_rootx() y = self._search_bar._entryfield.winfo_rooty() + \ self._search_bar._entryfield.winfo_height() w = self._search_bar._entryfield.winfo_width() + \ self._search_bar._arrowBtn.winfo_width() curr = self._search_bar._entryfield.getvalue() curr += repr(event.char)[1] self._search_bar._list.setlist([curr + '_0', curr + '_1', curr + '_2']) self._search_bar._list.configure(hull_width=w) Pmw.setgeometryanddeiconify(self._search_bar._popup, '+%d+%d' % (x, y)) self._search_bar._popup.lift() def _remove_list(self, event): self._search_bar._popup.withdraw() if __name__ == '__main__': root = Tkinter.Tk() root.title('A Problem') demo(root) root.mainloop() From chris at simplistix.co.uk Tue Oct 4 14:42:06 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 04 Oct 2011 19:42:06 +0100 Subject: Need A script to open a excel file and extract the data using autofilter In-Reply-To: References: <4f3ec474-dd9f-4585-8f3c-41323d79b8de@z19g2000vby.googlegroups.com> <74fc7fc6-8d5d-40fd-b152-0ce022a78a0c@m5g2000vbe.googlegroups.com> Message-ID: <4E8B537E.9020704@simplistix.co.uk> On 01/10/2011 23:00, David Monaghan wrote: >> after opening the text.xls file i need to filter all the rows in which >> the status column is passed and copy the whole sheet to another sheet > > I don't do this often enough to have it to mind, so what I normally do is > record a Macro, convert it to VBS and then convert that to Python. Ouch! Slow, error prone and Windows only ;-) Please consider using xlrd and described on http://www.python-excel.org cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From derek at simkowiak.net Tue Oct 4 15:18:50 2011 From: derek at simkowiak.net (Derek Simkowiak) Date: Tue, 04 Oct 2011 12:18:50 -0700 Subject: recommend a graphics library for plotting by the pixel? In-Reply-To: References: <9s1rl8xt8t.ln2@news.ducksburg.com> Message-ID: <4E8B5C1A.9030909@simkowiak.net> If this is strictly for 2D pixel graphics, I recommend using PyGame (aka SDL). Why do you not think it's the way to go? It was built for this type of thing. You may also want to use PIL (Python Imaging Library) for various image manipulation tasks, but PIL doesn't handle mouse clicks and screen blitting the way PyGame does. --Derek Simkowiak http://derek.simkowiak.net On 10/04/2011 07:53 AM, Alec Taylor wrote: > Sounds like a job for Processing... > > On Tue, Oct 4, 2011 at 8:56 PM, Adam Funk wrote: >> I'd like to create a window with a "pause" button and a large plotting >> area, in which I'd like to draw a polygon, detect the pixel >> co?rdinates of a mouse click, and then start setting the colors of >> pixels by (x,y) co?rdinates. (This is just for my own amusement, to >> play with some formulas for generating fractals using random numbers.) >> >> There seems to be a large number of different python GUI libraries, >> and I wonder if someone can recommend the easiests one to learn for >> this purpose? (The only python graphics library I've used is PyGame, >> which I don't think is the way to go here.) >> >> >> -- >> In the 1970s, people began receiving utility bills for >> -?999,999,996.32 and it became harder to sustain the >> myth of the infallible electronic brain. (Stob 2001) >> -- >> http://mail.python.org/mailman/listinfo/python-list >> From miki.tebeka at gmail.com Tue Oct 4 15:34:32 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Tue, 4 Oct 2011 12:34:32 -0700 (PDT) Subject: eggbasket In-Reply-To: References: Message-ID: <3874595.317.1317756872917.JavaMail.geo-discussion-forums@prma7> > How is it possible that the module exists and it's actually imported, > and not found when I actually try to import something from it? Do you have a local file/directory that is called sqlalchemy? From miki.tebeka at gmail.com Tue Oct 4 15:34:32 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Tue, 4 Oct 2011 12:34:32 -0700 (PDT) Subject: eggbasket In-Reply-To: References: Message-ID: <3874595.317.1317756872917.JavaMail.geo-discussion-forums@prma7> > How is it possible that the module exists and it's actually imported, > and not found when I actually try to import something from it? Do you have a local file/directory that is called sqlalchemy? From pulsarpietro at gmail.com Tue Oct 4 16:08:41 2011 From: pulsarpietro at gmail.com (pedr0) Date: Tue, 4 Oct 2011 13:08:41 -0700 (PDT) Subject: HTTP ResponseNotReady Message-ID: <7336281.656.1317758921108.JavaMail.geo-discussion-forums@yqjh13> Hi at all, I don't understand why, in this piece of code, i catch the raise ResponseNotReady(self.__state) http.client.ResponseNotReady: Request-sent EVERY time I run this piece of code: #connection http_connection = http.client.HTTPConnection('www.xxx.net',80,timeout=60) #first request http_connection.request("POST", "/",params,headers=headers_) r1 = http_connection.getresponse() #second request http_connection.request("GET", "/","",headers=headers_) r2 = http_connection.getresponse() Someone can help me ? From pulsarpietro at gmail.com Tue Oct 4 16:29:30 2011 From: pulsarpietro at gmail.com (pedr0) Date: Tue, 4 Oct 2011 13:29:30 -0700 (PDT) Subject: HTTP ResponseNotReady In-Reply-To: <7336281.656.1317758921108.JavaMail.geo-discussion-forums@yqjh13> References: <7336281.656.1317758921108.JavaMail.geo-discussion-forums@yqjh13> Message-ID: <575322.1824.1317760170966.JavaMail.geo-discussion-forums@yqar15> Hi solved this problem, I have to add: #connection http_connection = http.client.HTTPConnection('www.xxx.net',80,timeout=60) #first request http_connection.request("POST", "/",params,headers=headers_) r1 = http_connection.getresponse() r1.read() // THIS ONE #second request http_connection.request("GET", "/","",headers=headers_) r2 = http_connection.getresponse() Someone know if this is a bug ? Thanks From python at mrabarnett.plus.com Tue Oct 4 16:53:48 2011 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Oct 2011 21:53:48 +0100 Subject: HTTP ResponseNotReady In-Reply-To: <575322.1824.1317760170966.JavaMail.geo-discussion-forums@yqar15> References: <7336281.656.1317758921108.JavaMail.geo-discussion-forums@yqjh13> <575322.1824.1317760170966.JavaMail.geo-discussion-forums@yqar15> Message-ID: <4E8B725C.2050501@mrabarnett.plus.com> On 04/10/2011 21:29, pedr0 wrote: > Hi solved this problem, I have to add: > > > > #connection > http_connection = http.client.HTTPConnection('www.xxx.net',80,timeout=60) > #first request > http_connection.request("POST", "/",params,headers=headers_) > r1 = http_connection.getresponse() > r1.read() // THIS ONE > #second request > http_connection.request("GET", "/","",headers=headers_) > r2 = http_connection.getresponse() > > > Someone know if this is a bug ? > It's not a bug. The documentation for "getresponse" says: """HTTPConnection.getresponse() Should be called after a request is sent to get the response from the server. Returns an HTTPResponse instance. Note Note that you must have read the whole response before you can send a new request to the server. """ The note is highlighted. From pulsarpietro at gmail.com Tue Oct 4 17:00:27 2011 From: pulsarpietro at gmail.com (pedr0) Date: Tue, 4 Oct 2011 14:00:27 -0700 (PDT) Subject: HTTP ResponseNotReady In-Reply-To: References: <7336281.656.1317758921108.JavaMail.geo-discussion-forums@yqjh13> <575322.1824.1317760170966.JavaMail.geo-discussion-forums@yqar15> Message-ID: <11222070.2131.1317762027904.JavaMail.geo-discussion-forums@yqlb4> Mumble mumble... I described bad my question I think, yes I read that, but maybe is not a correct way of working. The http request I did retrieve (every time) an empty response, when I print the read() result call the result is the same of the sample you are talking about. http://docs.python.org/py3k/library/http.client.html?highlight=http.client#http.client (2th sample) Then I have to call the read() function only for change the state of my request, for this reasons I asked for a bug open in the http.client module. From pulsarpietro at gmail.com Tue Oct 4 17:00:27 2011 From: pulsarpietro at gmail.com (pedr0) Date: Tue, 4 Oct 2011 14:00:27 -0700 (PDT) Subject: HTTP ResponseNotReady In-Reply-To: References: <7336281.656.1317758921108.JavaMail.geo-discussion-forums@yqjh13> <575322.1824.1317760170966.JavaMail.geo-discussion-forums@yqar15> Message-ID: <11222070.2131.1317762027904.JavaMail.geo-discussion-forums@yqlb4> Mumble mumble... I described bad my question I think, yes I read that, but maybe is not a correct way of working. The http request I did retrieve (every time) an empty response, when I print the read() result call the result is the same of the sample you are talking about. http://docs.python.org/py3k/library/http.client.html?highlight=http.client#http.client (2th sample) Then I have to call the read() function only for change the state of my request, for this reasons I asked for a bug open in the http.client module. From andrea.crotti.0 at gmail.com Tue Oct 4 17:08:30 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Tue, 04 Oct 2011 22:08:30 +0100 Subject: eggbasket In-Reply-To: <3874595.317.1317756872917.JavaMail.geo-discussion-forums@prma7> References: <3874595.317.1317756872917.JavaMail.geo-discussion-forums@prma7> Message-ID: <4E8B75CE.1070700@gmail.com> On 10/04/2011 08:34 PM, Miki Tebeka wrote: > Do you have a local file/directory that is called sqlalchemy? Funny thing, I have the same problem with another machine, with sqlalchemy installed system-wide instead of locally. Strange issue, maybe a problem with python 2.7/Linux? From monaghand.david at gmail.com Tue Oct 4 17:12:54 2011 From: monaghand.david at gmail.com (David Monaghan) Date: Tue, 04 Oct 2011 22:12:54 +0100 Subject: Need A script to open a excel file and extract the data using autofilter References: <4f3ec474-dd9f-4585-8f3c-41323d79b8de@z19g2000vby.googlegroups.com> <74fc7fc6-8d5d-40fd-b152-0ce022a78a0c@m5g2000vbe.googlegroups.com> Message-ID: On Tue, 04 Oct 2011 19:42:06 +0100, Chris Withers wrote: >On 01/10/2011 23:00, David Monaghan wrote: >>> after opening the text.xls file i need to filter all the rows in which >>> the status column is passed and copy the whole sheet to another sheet >> >> I don't do this often enough to have it to mind, so what I normally do is >> record a Macro, convert it to VBS and then convert that to Python. > >Ouch! Slow, error prone and Windows only ;-) > >Please consider using xlrd and described on http://www.python-excel.org All true! The reason I usually do it like that is I normally only need to do very simple things and I usually stop at the VBS stage. And I wasn't aware of xlrd - I'll give it a look. DaveM From ben+python at benfinney.id.au Tue Oct 4 17:45:55 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 05 Oct 2011 08:45:55 +1100 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <74e9b784-7de4-4306-a747-bff85b1a1181@fx14g2000vbb.googlegroups.com> Message-ID: <871uus1ld8.fsf@benfinney.id.au> Westley Mart?nez writes: > Boiler plate is silly. Let the students figure out stuff themselves. That argues directly against the Primacy effect mentioned earlier , which is demonstrated by much scientific evidence. What scientific evidence do you have to argue against it? > The students need to know why global variables in functions is > unwieldly, not just not use them because it's cool. If you say so. But why not show them the traps after *first* teaching them the recommended way to do it? > When I taught myself Python I quickly realized global variables were > unwieldly and usually impractical after using them. That's no argument at all against how to teach Python in a teacher-student relationship. -- \ ?If you have the facts on your side, pound the facts. If you | `\ have the law on your side, pound the law. If you have neither | _o__) on your side, pound the table.? ?anonymous | Ben Finney From bthate at gmail.com Tue Oct 4 19:16:09 2011 From: bthate at gmail.com (Bart Thate) Date: Tue, 4 Oct 2011 16:16:09 -0700 (PDT) Subject: GOZERBOT 0.99.0 RELEASED Message-ID: <4caa84b1-27aa-402d-9fec-042562a433dd@x16g2000yql.googlegroups.com> Hello world and everybody ! i'm pleased to announce the release of GOZERBOT 0.99.0, the first in a series of releases that are supposed to lead to a proper 1.0 release for GOZERBOT. The intention is to get a 1.0 version of GOZERBOT available for users that still use this bot, got almost 2000 download of 0.9.2 so its worth to support all those users with a release they can build on. I dont have the intention to develop GOZERBOT any further beyond that, that's what JSONBOT is all about, so keep in mind these are pure maintenance releases. 2 major changes crept into this release, namely: * no more seperate gozerplugs package, its all wrapped into 1 thing. The gozerplugs package has find its way under the gplugs directory in the main distro so no more seperate installing of plugins. * SQLAlchemy is now optional, so GOZERBOT can run on older versions of debian etc. Since this leads to less dependancies GOZERBOT is easier to install. note: there is not going to be a seperate "all" distro as those dependancies are already included. SQLAlchemy is made optional by providing plugins that use direct queries on the database, this is the default. You can change operations back to SA by setting db_driver = "alchemy" in gozerdata/ mainconfig. The intention is to release a new version of GOZERBOT every week or so, until its stable for a long period of time. When its time i'll cut of the 1.0 release ;] urls: * download tar - http://code.google.com/p/gozerbot/downloads/list * mercurial clone - "hg clone https://gozerbot.googlecode.com/hg mybot" * please report bugs at http://code.google.com/p/gozerbot/issues/entry especially if you are already running a GOZERBOT and run into problems. * path to the futire - http://jsonbot.org read the provided README for instructions on how to get the bot running. About GOZERBOT: GOZERBOT is a channel bot supporting conversations in irc channels and jabber conference rooms. It is mainly used to send notifications (RSS, nagios, etc.) and to have custom commands made for the channel. More then just a channel bot GOZERBOT aims to provide a platform for the user to program his own bot and make it into something thats usefull. This is done with a plugin structure that makes it easy to program your own plugins. GOZERBOT comes with some batteries included. From ameyer2 at yahoo.com Tue Oct 4 21:07:10 2011 From: ameyer2 at yahoo.com (Alan Meyer) Date: Tue, 04 Oct 2011 21:07:10 -0400 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: Message-ID: <4E8BADBE.2090300@yahoo.com> On 10/3/2011 12:26 PM, Alec Taylor wrote: ... > On Tue, Oct 4, 2011 at 3:21 AM, Aivar Annamaa wrote: ... >> I'm looking for a trick or hidden feature to make Python 3 automatically >> call a "main" function but without programmers writing `if __name__ == >> "__main__": ...` ... >> Here's why I want such a thing: >> I'm teaching introductory programming course with Python. I've seen that >> global variables attract beginners like honey attracts bees and this makes >> teaching function parameters harder. ... Teaching good programming practice is hard. Many programmers, not just students, take the attitude, "My code works. Who cares what it looks like?" Getting them to understand that code has to be readable, understandable, and maintainable can be very hard. I wonder if some teaching exercises would help, for example: 1. Find a program, perhaps submitted by a student in a previous class or perhaps something you write yourself, that's full of global variables. Assign the students to rewrite the program so that it has no globals at all, and to write up a comparison of the pros and cons of the global and no-global approaches. 2. Find or write a program with lots of globals. Introduce some subtle bugs into the program that have to do with global references. Assign the students to a) find and fix the bugs and b) explain how the code could have been written to prevent bugs like this from creeping in. 3. Find or write a program with a number of globals. For each global, ask the students to write an analysis comparing its usefulness and/or dangerousness. Are some of the globals worse than others? Why? 4. Find or write a program with some globals. Make up a change request from a user that will run into problems because of the globals. Assign the students to implement the change request. There are probably lots of other similar exercises one could make up. The idea is not to force students to do the right thing, but to get them to understand the differences between the better ways and the worse ways to write code. Incidentally, all of these exercises involve maintaining or re-writing existing code written by other people. Students don't usually do much of that, but when they get a real job, they find that maintenance is most of what they actually do, especially as junior programmers. Having to work in the real world of maintaining other people's code gives a student a better appreciation of the value of clean, modular, readable, documented code. Alan From ameyer2 at yahoo.com Tue Oct 4 21:09:15 2011 From: ameyer2 at yahoo.com (Alan Meyer) Date: Tue, 04 Oct 2011 21:09:15 -0400 Subject: Need A script to open a excel file and extract the data using autofilter In-Reply-To: References: <4f3ec474-dd9f-4585-8f3c-41323d79b8de@z19g2000vby.googlegroups.com> <74fc7fc6-8d5d-40fd-b152-0ce022a78a0c@m5g2000vbe.googlegroups.com> Message-ID: <4E8BAE3B.3090807@yahoo.com> On 10/4/2011 5:12 PM, David Monaghan wrote: > On Tue, 04 Oct 2011 19:42:06 +0100, Chris Withers > wrote: > >> On 01/10/2011 23:00, David Monaghan wrote: >>>> after opening the text.xls file i need to filter all the rows in which >>>> the status column is passed and copy the whole sheet to another sheet >>> >>> I don't do this often enough to have it to mind, so what I normally do is >>> record a Macro, convert it to VBS and then convert that to Python. >> >> Ouch! Slow, error prone and Windows only ;-) >> >> Please consider using xlrd and described on http://www.python-excel.org > > All true! The reason I usually do it like that is I normally only need to do > very simple things and I usually stop at the VBS stage. And I wasn't aware > of xlrd - I'll give it a look. > > DaveM I've used xlrd. It's pretty nice. Alan From ameyer2 at yahoo.com Tue Oct 4 21:22:42 2011 From: ameyer2 at yahoo.com (Alan Meyer) Date: Tue, 04 Oct 2011 21:22:42 -0400 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: <4E8BADBE.2090300@yahoo.com> References: <4E8BADBE.2090300@yahoo.com> Message-ID: <4E8BB162.5080100@yahoo.com> On 10/4/2011 9:07 PM, Alan Meyer wrote: > ... and to write up a comparison of the pros and cons of the global and > no-global approaches. ... Of course you'll need to be fair in evaluating the students comparisons. Some bright students are likely to come up with good reasons for using globals in some situations, and they might even be right. Or if they're not completely right, they might nevertheless be partly right. They should get high marks for that. You could even make up an exercise where the students are assigned to write a program that uses a global that could NOT be better implemented without globals. Then ask one or two of the authors of the better programs to defend their programs in front of the class. It's always a mistake to read student papers with preconceived, set in concrete ideas about what's right and what's wrong. Many years ago when I was teaching (philosophy, not computer science), in every class I taught there was always at least one student who taught me something I didn't know, or taught me that something I thought I knew was wrong. Alan From steve+comp.lang.python at pearwood.info Tue Oct 4 21:27:27 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 05 Oct 2011 01:27:27 GMT Subject: how to call java methods in python References: <33a61c6f-508a-48f0-97dc-d51099199c30@z12g2000yqz.googlegroups.com> Message-ID: <4e8bb27e$0$29978$c3e8da3$5496439d@news.astraweb.com> On Tue, 04 Oct 2011 00:14:49 -0700, masood shaik wrote: > Hi > I am trying out my hand on accessing java methods in python. here is > my piece of code.. [...] > Now i am trying to access the calculateTip() and its showing import > error. > It works fine when i am running it with jython but why its not happening > in python. Jython *is* Python. It is a Python implementation built on the Java virtual machine. Integrating Java with Python is a major reason for using Jython. http://www.jython.org/ You can't just import a Java library into the C implementation of Python, any more than you can just import a Python library into Java. You need an interface between them. Jython includes one such interface. The C reference implementation of Python does not. To integrate Java libraries with CPython is harder, but not impossible. I have never tried any of these, but you could try JPype, Py4J, or JCC: http://jpype.sourceforge.net/ http://py4j.sourceforge.net/index.html http://pypi.python.org/pypi/JCC/2.1 -- Steven From steve+comp.lang.python at pearwood.info Tue Oct 4 21:28:26 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 05 Oct 2011 01:28:26 GMT Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <4E8BADBE.2090300@yahoo.com> Message-ID: <4e8bb2b9$0$29978$c3e8da3$5496439d@news.astraweb.com> On Tue, 04 Oct 2011 21:07:10 -0400, Alan Meyer wrote: > Incidentally, all of these exercises involve maintaining or re-writing > existing code written by other people. Students don't usually do much > of that, but when they get a real job, they find that maintenance is > most of what they actually do, especially as junior programmers. Having > to work in the real world of maintaining other people's code gives a > student a better appreciation of the value of clean, modular, readable, > documented code. Well said that man!!! -- Steven From tjreedy at udel.edu Tue Oct 4 21:45:14 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 Oct 2011 21:45:14 -0400 Subject: syntax enhancement In-Reply-To: References: Message-ID: On 10/4/2011 9:50 AM, Valiev Sergey wrote: > - `[]` - used for list comprehension, > - `()` - used for generators, > - `[start:stop]` / `[start:stop:step]` - used for slices. > The idea is to use `(start:stop)` / `(start:stop:step)` as 'lazy > evaluated' slices (like itertools.islice). > What do you think about it? a(b) is already used for function calls. Making a(b:c) be something unreleated does not seem like a good idea to me. At present, a[b:c] == a[slice(b,c)]. However, a(slice(b,c)) is already a function call and could not equal a(b:c). -- Terry Jan Reedy From steve+comp.lang.python at pearwood.info Tue Oct 4 22:06:14 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 05 Oct 2011 02:06:14 GMT Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> Message-ID: <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 03 Oct 2011 21:27:12 -0700, alex23 wrote: > rantingrick wrote: >> Why? Well because many times i find myself wondering if this or that >> variable is local or global -- and when i say "global" i am speaking of >> module scope! The "global" cures the ill. > > Given your stated propensity for huge code blocks not chunked into > functions, I'm not surprised you lose track of what is global, what is > nonlocal etc. This is another clear advantage of small functions: you > can view it all at once. For the rest of us, a variable is global if its > referenced but not defined in a specific scope. There's no need for such > verbose hand-holding. > > I'd say the wart is in your design practice rather than the language > itself. Furthermore, rick's suggestion that all globals should be referenced using an explicit global namespace would become extraordinarily horrible in practice. Let's take a simple example from the shutil module: # From Python 2.5 shutil.py def copystat(src, dst): """Copy all stat info (mode bits, atime and mtime) from src to dst""" st = os.stat(src) mode = stat.S_IMODE(st.st_mode) if hasattr(os, 'utime'): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, 'chmod'): os.chmod(dst, mode) Under Rick's proposal, that would be written: def copystat(src, dst): """Copy all stat info (mode bits, atime and mtime) from src to dst""" st = global.os.stat(src) mode = global.stat.S_IMODE(st.st_mode) if global.hasattr(os, 'utime'): global.os.utime(dst, (st.st_atime, st.st_mtime)) if global.hasattr(os, 'chmod'): global.os.chmod(dst, mode) Imported modules are variables like any other, and as they usually exist in the global scope, so they will all need to be explicitly referenced as global. This will get tiresome very quickly, and is a cure far worse than the disease, and alone is enough to disqualify this suggestion from serious consideration. Furthermore, "globals" in Python also includes the built-ins, so every reference to built-ins like len, sum, list, int, abs, etc. will also need an explicit reference, e.g. global.len, global.sum. (The alternative would be a significantly different name-lookup strategy: instead of names being "local" vs "global or builtin", they would be "local or builtin" vs "global". This will break monkey-patching.) -- Steven From ameyer2 at yahoo.com Tue Oct 4 22:23:49 2011 From: ameyer2 at yahoo.com (Alan Meyer) Date: Tue, 04 Oct 2011 22:23:49 -0400 Subject: how to call java methods in python In-Reply-To: References: Message-ID: <4E8BBFB5.1030304@yahoo.com> On 10/4/2011 2:39 AM, masood shaik wrote: > Hi > > I am trying to import java method in python. But i am getting the > following error. > > > error: ImportError: No module named Calculator > > > Calculator is the name of the class written in java. I am trying to > access the methods of that class. > > Please help me. Masood, What you are trying to do requires a lot of understanding of advanced computer programming. I suggest you read Laszlo's response, and the links suggested by Steven. If you find those responses too hard to understand, or if you don't understand the difference between Jython and CPython, or if you don't know what CPython is, then you are "in over your head" as we say in the U.S. You are trying to do something that is too hard for you. If that is so, and if this is for a school project, I suggest you talk to the teacher about getting an easier project. Good luck. Alan From wuwei23 at gmail.com Tue Oct 4 23:20:34 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 Oct 2011 20:20:34 -0700 (PDT) Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Imported modules are variables like any other, and as they usually exist > in the global scope, so they will all need to be explicitly referenced as > global. This will get tiresome very quickly, and is a cure far worse than > the disease, and alone is enough to disqualify this suggestion from > serious consideration. But on the gripping hand, it is a clear triumph of "Explicit is better than implicit." ;) From wuwei23 at gmail.com Tue Oct 4 23:24:41 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 Oct 2011 20:24:41 -0700 (PDT) Subject: recommend a graphics library for plotting by the pixel? References: <9s1rl8xt8t.ln2@news.ducksburg.com> Message-ID: <6a4f8ef3-81d1-4e91-8cd8-8014a021a2aa@18g2000yqz.googlegroups.com> On Oct 5, 12:53?am, Alec Taylor wrote: > Sounds like a job for Processing... Don't you mean PyProcessing? :) http://code.google.com/p/pyprocessing/ From steve+comp.lang.python at pearwood.info Wed Oct 5 01:37:52 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 05 Oct 2011 05:37:52 GMT Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e8bed30$0$29978$c3e8da3$5496439d@news.astraweb.com> On Tue, 04 Oct 2011 20:20:34 -0700, alex23 wrote: > Steven D'Aprano wrote: >> Imported modules are variables like any other, and as they usually >> exist in the global scope, so they will all need to be explicitly >> referenced as global. This will get tiresome very quickly, and is a >> cure far worse than the disease, and alone is enough to disqualify this >> suggestion from serious consideration. > > But on the gripping hand, it is a clear triumph of "Explicit is better > than implicit." ;) I see your wink, but explicitness is not a binary state. You can have too much explicitness. Which would you rather? import math x = math.sin(1.2345) or: import the module called 'math' into the current namespace and bind that module to the name 'math' in the current namespace bind the name 'x' in the current namespace to the return result of calling the attribute named 'sin' in the object currently bound to the name 'math' in the current namespace using the float literal 1.2345 as the argument I'm thinking that the second version might get a bit annoying after a little while, no matter what the Zen says. Besides, based on the Zen, should we also write this? local.x = global.math.sin(1.2345) -- Steven From gagsl-py2 at yahoo.com.ar Wed Oct 5 02:08:20 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 Oct 2011 03:08:20 -0300 Subject: BaseHTTPServer ThreadMixIn not working References: Message-ID: En Mon, 03 Oct 2011 12:03:18 -0300, amit escribi?: > I am really stuck in a very simple problem and wanted to know if you > could take some time to check it out - > > My code is simple. Using BaseHTTPServer and ThreadInMix I want to run > a python script (Script1.py) for every request made simultaneously. > [...] > > If I open multiple tabs/pages in Chrome/Firefox/IE and give URL: > http://localhost:8080, the pages wait for previous page? This does not > imply threading? Any help? Thanks Your code is fine, and Python behaves correctly. The browser is queuing all similar requests when it sees they all refer to the same URI. Had the first response contained an Expires: header in the future, there would be no need to ask again for the same object; the ETag: and Last-Modified: headers may play a role too. So, only after the first response is completely read, Chrome/Firefox/IE sees it is invalid and knows she cannot re-use the received body and has to issue the second request and waits again and ... Try with different URLs for each request: http://localhost:8080/a http://localhost:8080/b http://localhost:8080/c and you'll see they all are processed in parallel. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Wed Oct 5 02:27:08 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 Oct 2011 03:27:08 -0300 Subject: Is exec() also not used in python 2.7.1 anymore? References: <02EA6D704E30CE499C5071776509A925F5C2ED@039-SN1MPN1-003.039d.mgd.msft.net> <02EA6D704E30CE499C5071776509A925F5C3AA@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: En Tue, 04 Oct 2011 07:32:41 -0300, Wong Wah Meng-R32813 escribi?: > Haha... yeah I reviewed the code, it is supposed to exposed some remote > methods locally (RMI proxy usage). However, I am not sure why what it > does is merely a pass. > > I commented out this code and haven't seen any negative implication. I > will look into this again if I am convinced the next error I see is due > to I commented out this code. >> exec('def %s(self, *args, **kw): pass'%methodStrName) In case you convince yourself that defining this dynamic but empty function is really needed, you can avoid exec this way: def some_function(...) ... # instead of exec('def ...' % methodStrName) def empty_function(self, *args, **kw): pass empty_function.func_name = methodStrName ... # presumably methodStrName is referred somehow in # the remaining code block, or perhaps locals(); # modify accordingly -- Gabriel Genellina From greg.ewing at canterbury.ac.nz Wed Oct 5 02:43:57 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 05 Oct 2011 19:43:57 +1300 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9f2clfF437U1@mid.individual.net> alex23 wrote: > But on the gripping hand, it is a clear triumph of "Explicit is better > than implicit." ;) I think we may have found the long-lost 20th principle of the Zen: "If it results in eye-bleedingly horrible code, it might be a bad idea." -- Greg From rosuav at gmail.com Wed Oct 5 03:01:39 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Oct 2011 18:01:39 +1100 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: <4E8BB162.5080100@yahoo.com> References: <4E8BADBE.2090300@yahoo.com> <4E8BB162.5080100@yahoo.com> Message-ID: On Wed, Oct 5, 2011 at 12:22 PM, Alan Meyer wrote: > Of course you'll need to be fair in evaluating the students comparisons. > ?Some bright students are likely to come up with good reasons for using > globals in some situations, and they might even be right. ?Or if they're not > completely right, they might nevertheless be partly right. ?They should get > high marks for that. > Definitely. There's always a right time to do the wrong thing, just as much as there's a wrong time to do the right thing. Even the much-maligned goto has its place. ChrisA From r32813 at freescale.com Wed Oct 5 03:43:57 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Wed, 5 Oct 2011 07:43:57 +0000 Subject: ImportError: No module named _sha256 Message-ID: <02EA6D704E30CE499C5071776509A925F5C810@039-SN1MPN1-003.039d.mgd.msft.net> Hello there, In migrating my application from python 1.5.2 to 2.7.1, I encountered an issue modules which utilizes _sha256 cannot be loaded. This includes hashlib, random and tempfile. I think this should be related to the build of my python 64-bit on HP11.31 using HP-UX compiler. I have tried including the header files of openSSL and library of openSSL during the build however the binary generated still unable to load those modules. Can anyone advise? $ python Python 2.7.1 (r271:86832, Sep 30 2011, 17:07:25) [C] on hp-ux11 Type "help", "copyright", "credits" or "license" for more information. >>> import hashlib Traceback (most recent call last): File "", line 1, in File "/home/r32813/genesis/GEN_DEV_271/Enablers/Python/lib/python2.7/hashlib.py", line 136, in globals()[__func_name] = __get_hash(__func_name) File "/home/r32813/genesis/GEN_DEV_271/Enablers/Python/lib/python2.7/hashlib.py", line 74, in __get_builtin_constructor import _sha256 ImportError: No module named _sha256 >>> Regards, Wah Meng -------------- next part -------------- An HTML attachment was scrubbed... URL: From 5960761 at gmail.com Wed Oct 5 05:02:44 2011 From: 5960761 at gmail.com (Daniel) Date: Wed, 05 Oct 2011 12:02:44 +0300 Subject: issue with pexpect Message-ID: <1317805364.3169.5.camel@laptop.bulsat.com> Hello, For about week i am experiencing a problem with pexpect that's why i hope you can help me :). Following is my code which tries to remove some files from the root dir and the code works on linux debian and freebsd but with no success on linux fedora .. any idea why this happen only in fedora ? #!/usr/bin/env python from __future__ import print_function import sys import pexpect import time spa=pexpect.spawn('su root') spa.expect('.*') print(spa.after) spa.sendline('abc') spa.expect('.*') print(spa.after) spa.sendline('rm -rf /root/py/pe*') spa.expect('.*') print(spa.after) spa.close() this is the output in Fedora linux it looks that the script can't authenticate as root python]$ ./sk64.py Password: rm -rf /root/py/pe* i appreciate any help thanks in advance From ben+python at benfinney.id.au Wed Oct 5 07:44:34 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 05 Oct 2011 22:44:34 +1100 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> <4e8bed30$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87wrcjzmql.fsf@benfinney.id.au> Steven D'Aprano writes: > import the module called 'math' into the current namespace and bind > that module to the name 'math' in the current namespace > > bind the name 'x' in the current namespace to the return result of > calling the attribute named 'sin' in the object currently bound to the > name 'math' in the current namespace using the float literal 1.2345 as > the argument This mocking is hurtful to people who identify too strongly with COBOL. I wonder whether that means it's intentionally hurtful. -- \ ?The long-term solution to mountains of waste is not more | `\ landfill sites but fewer shopping centres.? ?Clive Hamilton, | _o__) _Affluenza_, 2005 | Ben Finney From r32813 at freescale.com Wed Oct 5 07:56:08 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Wed, 5 Oct 2011 11:56:08 +0000 Subject: socket.getsockname is returning junk!! Message-ID: <02EA6D704E30CE499C5071776509A925F5C8F8@039-SN1MPN1-003.039d.mgd.msft.net> Hello guys, I am migrating my application from python 1.5.2 to 2.7.1. One of the existing code breaks. The getsockname method from socket object somehow returns me with some number which I deem as junk, rather than the listening port as I would have expected in the older python. Has anyone seen the same thing or is it due to my python is built with some corrupted library or something? $ python Python 2.7.1 (r271:86832, Oct 5 2011, 18:34:15) [C] on hp-ux11 Type "help", "copyright", "credits" or "license" for more information. >>> import socket >>> sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) >>> sock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 ) >>> sock.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1 ) >>> sock.setsockopt( socket.IPPROTO_TCP, 1, 1 ) >>> server_address=('zmy02hp3', 11111) >>> sock.bind(server_address) >>> sock.getsockname() (0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') In python 1.5.2 >>> server_address=('zmy02aix04', 11111) >>> sock.bind(server_address) >>> sock.getsockname() ('10.228.51.41', 11111) >>> Regards, Wah Meng -------------- next part -------------- An HTML attachment was scrubbed... URL: From 5960761 at gmail.com Wed Oct 5 08:32:05 2011 From: 5960761 at gmail.com (Daniel) Date: Wed, 05 Oct 2011 15:32:05 +0300 Subject: issue with pexpect Message-ID: <1317817925.2908.2.camel@laptop.bulsat.com> Hello, For about week i am experiencing a problem with pexpect that's why i hope you can help me :). Following is my code which tries to remove some files from the root dir and the code works on linux debian and freebsd but with no success on linux fedora .. any idea why this happen only in fedora ? #!/usr/bin/env python from __future__ import print_function import sys import pexpect import time spa=pexpect.spawn('su root') spa.expect('.*') print(spa.after) spa.sendline('abc') spa.expect('.*') print(spa.after) spa.sendline('rm -rf /root/py/pe*') spa.expect('.*') print(spa.after) spa.close() this is the output in Fedora linux it looks that the script can't authenticate as root python]$ ./sk64.py Password: rm -rf /root/py/pe* i appreciate any help thanks in advance From roy at panix.com Wed Oct 5 08:57:04 2011 From: roy at panix.com (Roy Smith) Date: Wed, 05 Oct 2011 08:57:04 -0400 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <4E8BADBE.2090300@yahoo.com> <4E8BB162.5080100@yahoo.com> Message-ID: In article , Chris Angelico wrote: > Definitely. There's always a right time to do the wrong thing, just as > much as there's a wrong time to do the right thing. Even the > much-maligned goto has its place. Not in python, it doesn't :-) But, yes, I agree that in languages that support it, it can be useful. When I was writing C++ for a living, I must have written a goto at least once every couple of years. From rosuav at gmail.com Wed Oct 5 09:10:26 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Oct 2011 00:10:26 +1100 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: <4E8BADBE.2090300@yahoo.com> <4E8BB162.5080100@yahoo.com> Message-ID: On Wed, Oct 5, 2011 at 11:57 PM, Roy Smith wrote: > In article , > ?Chris Angelico wrote: > >> Definitely. There's always a right time to do the wrong thing, just as >> much as there's a wrong time to do the right thing. Even the >> much-maligned goto has its place. > > Not in python, it doesn't :-) The absence from the language doesn't prove that. All it means is that, on those rare occasions when a goto would have been correct, the programmer had to make do with something else :-) How often do you see a loop structure that exists solely so someone can 'break' out of it? Or, worse, raising an exception? I haven't seen it in Python, but frequently in C or C++ code where the programmer had a fixation on avoiding gotos. ChrisA From mzaccariotto at h-umus.it Wed Oct 5 09:26:52 2011 From: mzaccariotto at h-umus.it (Mauro Zaccariotto) Date: Wed, 5 Oct 2011 06:26:52 -0700 (PDT) Subject: httplib2 download forbidden Message-ID: <43d464bd-460d-416b-a61e-d2cb385169aa@q13g2000vby.googlegroups.com> Hi! does anyone know what's happening here http://code.google.com/p/httplib2/ ? I get this: "403. That?s an error. Your client does not have permission to get URL /p/httplib2/ from this server. That?s all we know." It seems like the httplib2 googlecode project is preventing from accessing the project web page and downloading httplib2 library package. I'm in extreme need of using httplib2! thanks From a24061 at ducksburg.com Wed Oct 5 09:29:38 2011 From: a24061 at ducksburg.com (Adam Funk) Date: Wed, 05 Oct 2011 14:29:38 +0100 Subject: recommend a graphics library for plotting by the pixel? References: <9s1rl8xt8t.ln2@news.ducksburg.com> Message-ID: <2n2ul8xi9s.ln2@news.ducksburg.com> On 2011-10-04, Derek Simkowiak wrote: > If this is strictly for 2D pixel graphics, I recommend using PyGame > (aka SDL). Why do you not think it's the way to go? It was built for > this type of thing. I only know PyGame because we did an exercise in recreating the old breakout game and messing around with it at a local Python group. I was under the mistaken impression from that exercise that you have to maintain a set of all the objects on the screen and redraw them all every time through the loop that ends with pygame.display.flip() --- *but* I now see that the loop starts with these: clock.tick(tick_rate) screen.fill((0,0,0)) # comes from screen = pygame.display.set_mode((screen_width,screen_height)) # before the loop and that I was then deleting hit bricks, calculating the new positions of the balls, and then redrawing everything that was left on the secondary screen because things were moving around and disappearing. I guess if I don't clear the screen at the beginning of the loop but just blit pixels onto it, when I call display.flip(), it will add the new blittings to what was already there? If that's true, this will be much easier than I thought. The only buttons I have in mind are "pause", "step", "go", and "quit", and I can just as easily do those with keypresses. From faucheuses at gmail.com Wed Oct 5 09:33:51 2011 From: faucheuses at gmail.com (faucheuse) Date: Wed, 5 Oct 2011 06:33:51 -0700 (PDT) Subject: A tuple in order to pass returned values ? Message-ID: <9dfbc534-25a1-403f-b382-9d6ce011789b@z8g2000yqb.googlegroups.com> Hi, (new to python and first message here \o/) I was wondering something : when you do : return value1, value2, value3 It returns a tuple. So if I want to pass these value to a function, the function have to look like : def function(self,(value1, value2, value3)) #self because i'm working with classes I tried it, and it works perfectly, but I was wondering if it's a good choice to do so, if there is a problem by coding like that. So my question is : Is there a problem doig so ? From faucheuses at gmail.com Wed Oct 5 09:37:05 2011 From: faucheuses at gmail.com (faucheuse) Date: Wed, 5 Oct 2011 06:37:05 -0700 (PDT) Subject: A tuple in order to pass returned values ? Message-ID: Hi, (new to python and first message here \o/) I was wondering something : when you do : return value1, value2, value3 It returns a tuple. So if I want to pass these value to a function, the function have to look like : def function(self,(value1, value2, value3)) #self because i'm working with classes I tried it, and it works perfectly, but I was wondering if it's a good choice to do so, if there is a problem by coding like that. So my question is : Is there a problem doig so ? From 5960761 at gmail.com Wed Oct 5 09:46:24 2011 From: 5960761 at gmail.com (Daniel) Date: Wed, 05 Oct 2011 16:46:24 +0300 Subject: issue with pexpect In-Reply-To: References: <1317805364.3169.5.camel@laptop.bulsat.com> Message-ID: <1317822384.2908.8.camel@laptop.bulsat.com> there is no such implementation in fedora you can su as a root .. i can su from regular user to root with no problems the problem come when i use the pexpect module On Wed, 2011-10-05 at 14:47 +0200, Nizamov Shawkat wrote: > 2011/10/5 Daniel <5960761 at gmail.com>: > > Hello, > > For about week i am experiencing a problem with pexpect that's why i > > hope you can help me :). > > Following is my code which tries to remove some files from the root dir > > and the code works on linux debian and freebsd but with no success on > > linux fedora .. any idea why this happen only in fedora ? > > > > #!/usr/bin/env python > > from __future__ import print_function > > import sys > > import pexpect > > import time > > > > spa=pexpect.spawn('su root') > > spa.expect('.*') > > print(spa.after) > > spa.sendline('abc') > > spa.expect('.*') > > print(spa.after) > > spa.sendline('rm -rf /root/py/pe*') > > spa.expect('.*') > > print(spa.after) > > spa.close() > > > > > > this is the output in Fedora linux it looks that the script can't > > authenticate as root > > > > Hi! > > The problem may be that root user is disabled. This was introduced in > Ubuntu long ago and I believe that later this was also accepted in > Fedora. That means that you simply can not "su" to root, no matter > what password you supply. This is the way how your OS operates and is > not connected in any way to python or pexpect. Therefore, either use > sudo (generally recommended) or enable root user (insecure!). > > Hope it helps, > S.Nizamov From andrea.crotti.0 at gmail.com Wed Oct 5 10:11:12 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Wed, 05 Oct 2011 15:11:12 +0100 Subject: eggbasket In-Reply-To: <4E8B75CE.1070700@gmail.com> References: <3874595.317.1317756872917.JavaMail.geo-discussion-forums@prma7> <4E8B75CE.1070700@gmail.com> Message-ID: <4E8C6580.5020809@gmail.com> Well it was easy, apparently sqlalchemy.exceptions doesn't exist but sqlalchemy.exc does, and that's the correct one, maybe a version problem... I get another problem right after File "/home/andrea/PSI_refactor/test_local_pypi/lib/python2.7/site-packages/EggBasket-0.6.1b-py2.7.egg/eggbasket/commands.py", line 82, in init_database model.User.query().filter_by(user_name=u'admin').one() TypeError: 'Query' object is not callable so I might try chishop or anything else... Actually do I really need to have a local pypi server to be able to use easy_install? If I have a whole directory full of directory eggs isn't there any way to use that? From ulrich.eckhardt at dominalaser.com Wed Oct 5 10:31:03 2011 From: ulrich.eckhardt at dominalaser.com (Ulrich Eckhardt) Date: Wed, 05 Oct 2011 16:31:03 +0200 Subject: A tuple in order to pass returned values ? In-Reply-To: <9dfbc534-25a1-403f-b382-9d6ce011789b@z8g2000yqb.googlegroups.com> References: <9dfbc534-25a1-403f-b382-9d6ce011789b@z8g2000yqb.googlegroups.com> Message-ID: <7a6ul8-djv.ln1@satorlaser.homedns.org> Am 05.10.2011 15:33, schrieb faucheuse: > I was wondering something : > when you do : return value1, value2, value3 > It returns a tuple. Right. > So if I want to pass these value to a function, the function have to > look like : > def function(self,(value1, value2, value3)) [...] No, you don't have to, but you can: # example functions def fni(): return 1, 2 def fno(v1, v2): pass # store result in a tuple and unpack tuple for function call t = fni() fno(*fni) # store results in individual values v1, v2 = fni() fno(v1, v2) Note that the first variant can be written in a single line, too. A completely different alternative is passing a tuple to the function as a single parameter. You can then access the elements using normal tuple indexing. That said, I don't see a problem with your syntax, except that it's a bit unusual. Welcome to Python! Uli From rvince99 at gmail.com Wed Oct 5 10:34:19 2011 From: rvince99 at gmail.com (RVince) Date: Wed, 5 Oct 2011 07:34:19 -0700 (PDT) Subject: Writing file out to another machine Message-ID: <0d795922-d946-480d-8f41-95656e56fa86@g23g2000vbz.googlegroups.com> I have a project whereby I need it to write out a file to a different server (that the originating server has write access to). So, say I need to write out from myserver1, where my app is running, onto, say S:/IT/tmp how can I specify/do this? Thanks, RVince From ddandd at gmail.com Wed Oct 5 10:53:56 2011 From: ddandd at gmail.com (Daniel Dorani) Date: Wed, 5 Oct 2011 07:53:56 -0700 (PDT) Subject: A tuple in order to pass returned values ? In-Reply-To: <9dfbc534-25a1-403f-b382-9d6ce011789b@z8g2000yqb.googlegroups.com> References: <9dfbc534-25a1-403f-b382-9d6ce011789b@z8g2000yqb.googlegroups.com> Message-ID: <14537227.998.1317826436383.JavaMail.geo-discussion-forums@yqnk41> this feature has been removed in python3 in accordance to the PEP 3113 (http://www.python.org/dev/peps/pep-3113/), you should consider using the * operator http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists . From 5960761 at gmail.com Wed Oct 5 11:05:50 2011 From: 5960761 at gmail.com (Daniel) Date: Wed, 05 Oct 2011 18:05:50 +0300 Subject: issue with pexpect In-Reply-To: References: <1317805364.3169.5.camel@laptop.bulsat.com> Message-ID: <1317827150.2908.13.camel@laptop.bulsat.com> Okey i figure it out how to do the job in fedora i added slight delay before sending each command either by the delaybeforesend attribute or by the time module ;) cheers On Wed, 2011-10-05 at 14:47 +0200, Nizamov Shawkat wrote: > 2011/10/5 Daniel <5960761 at gmail.com>: > > Hello, > > For about week i am experiencing a problem with pexpect that's why i > > hope you can help me :). > > Following is my code which tries to remove some files from the root dir > > and the code works on linux debian and freebsd but with no success on > > linux fedora .. any idea why this happen only in fedora ? > > > > #!/usr/bin/env python > > from __future__ import print_function > > import sys > > import pexpect > > import time > > > > spa=pexpect.spawn('su root') > > spa.expect('.*') > > print(spa.after) > > spa.sendline('abc') > > spa.expect('.*') > > print(spa.after) > > spa.sendline('rm -rf /root/py/pe*') > > spa.expect('.*') > > print(spa.after) > > spa.close() > > > > > > this is the output in Fedora linux it looks that the script can't > > authenticate as root > > > > Hi! > > The problem may be that root user is disabled. This was introduced in > Ubuntu long ago and I believe that later this was also accepted in > Fedora. That means that you simply can not "su" to root, no matter > what password you supply. This is the way how your OS operates and is > not connected in any way to python or pexpect. Therefore, either use > sudo (generally recommended) or enable root user (insecure!). > > Hope it helps, > S.Nizamov From faucheuses at gmail.com Wed Oct 5 11:18:07 2011 From: faucheuses at gmail.com (faucheuse) Date: Wed, 5 Oct 2011 08:18:07 -0700 (PDT) Subject: A tuple in order to pass returned values ? References: <9dfbc534-25a1-403f-b382-9d6ce011789b@z8g2000yqb.googlegroups.com> <14537227.998.1317826436383.JavaMail.geo-discussion-forums@yqnk41> Message-ID: Thanks for the answer. From davea at ieee.org Wed Oct 5 11:19:21 2011 From: davea at ieee.org (Dave Angel) Date: Wed, 05 Oct 2011 11:19:21 -0400 Subject: A tuple in order to pass returned values ? In-Reply-To: <9dfbc534-25a1-403f-b382-9d6ce011789b@z8g2000yqb.googlegroups.com> References: <9dfbc534-25a1-403f-b382-9d6ce011789b@z8g2000yqb.googlegroups.com> Message-ID: <4E8C7579.7060207@ieee.org> On 01/-10/-28163 02:59 PM, faucheuse wrote: > Hi, (new to python and first message here \o/) > > I was wondering something : > when you do : return value1, value2, value3 > It returns a tuple. > > So if I want to pass these value to a function, the function have to > look like : > def function(self,(value1, value2, value3)) #self because i'm working > with classes > > I tried it, and it works perfectly, but I was wondering if it's a good > choice to do so, if there is a problem by coding like that. > > So my question is : Is there a problem doig so ? > In the abstract, no. There's no relationship between the two, except they happen to use the same name in their respective local namespaces. In practice, I wouldn't do it. If the three values really comprise one "thing" then it makes sense for a function to expect a single thing, and that thing needs a name. So I'd define the function as def function(self, mything): interesting, useful, related = mything ... work on them But it's certainly possible that the writer of the first function really had three independent things to return, and if the second method is expecting those same three independent things, he should define the method as: def function(self, this, that, theother): Python does have magic syntax to make this sort of thing easier to work with, using * and **. But I seldom use them unless forced to by meta-concerns, such as passing unknown arguments through one method to a method of a superclass. DaveA From gordon at panix.com Wed Oct 5 11:41:44 2011 From: gordon at panix.com (John Gordon) Date: Wed, 5 Oct 2011 15:41:44 +0000 (UTC) Subject: Writing file out to another machine References: <0d795922-d946-480d-8f41-95656e56fa86@g23g2000vbz.googlegroups.com> Message-ID: In <0d795922-d946-480d-8f41-95656e56fa86 at g23g2000vbz.googlegroups.com> RVince writes: > I have a project whereby I need it to write out a file to a different > server (that the originating server has write access to). So, say I > need to write out from myserver1, where my app is running, onto, say > S:/IT/tmp how can I specify/do this? Thanks, RVince scp file host:/some/location -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From anikom15 at gmail.com Wed Oct 5 12:37:06 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 5 Oct 2011 09:37:06 -0700 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20111005163705.GA29662@Smoke> On Tue, Oct 04, 2011 at 08:20:34PM -0700, alex23 wrote: > Steven D'Aprano wrote: > > Imported modules are variables like any other, and as they usually exist > > in the global scope, so they will all need to be explicitly referenced as > > global. This will get tiresome very quickly, and is a cure far worse than > > the disease, and alone is enough to disqualify this suggestion from > > serious consideration. > > But on the gripping hand, it is a clear triumph of "Explicit is better > than implicit." ;) > Simple is better than complex. Readability counts. From anikom15 at gmail.com Wed Oct 5 12:39:34 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 5 Oct 2011 09:39:34 -0700 Subject: recommend a graphics library for plotting by the pixel? In-Reply-To: <2n2ul8xi9s.ln2@news.ducksburg.com> References: <9s1rl8xt8t.ln2@news.ducksburg.com> <2n2ul8xi9s.ln2@news.ducksburg.com> Message-ID: <20111005163934.GB29662@Smoke> On Wed, Oct 05, 2011 at 02:29:38PM +0100, Adam Funk wrote: > On 2011-10-04, Derek Simkowiak wrote: > > > If this is strictly for 2D pixel graphics, I recommend using PyGame > > (aka SDL). Why do you not think it's the way to go? It was built for > > this type of thing. > > I only know PyGame because we did an exercise in recreating the old > breakout game and messing around with it at a local Python group. > > I was under the mistaken impression from that exercise that you have > to maintain a set of all the objects on the screen and redraw them all > every time through the loop that ends with pygame.display.flip() --- > *but* I now see that the loop starts with these: > > clock.tick(tick_rate) > screen.fill((0,0,0)) > # comes from screen = pygame.display.set_mode((screen_width,screen_height)) > # before the loop > > and that I was then deleting hit bricks, calculating the new positions > of the balls, and then redrawing everything that was left on the > secondary screen because things were moving around and disappearing. > > I guess if I don't clear the screen at the beginning of the loop but > just blit pixels onto it, when I call display.flip(), it will add the > new blittings to what was already there? If that's true, this will be > much easier than I thought. > > The only buttons I have in mind are "pause", "step", "go", and "quit", > and I can just as easily do those with keypresses. Yep. Blitting is replacing the old colors with new colors. It doesn't replace colors unless you tell it to. From s.maggiolo at gmail.com Wed Oct 5 12:55:53 2011 From: s.maggiolo at gmail.com (Stefano Maggiolo) Date: Wed, 5 Oct 2011 18:55:53 +0200 Subject: Convenient filtering in for cycles Message-ID: Dear all, I would like to know if there is a (more) convenient way of doing this structure: ===(1)=== for x in l: if P(x): do_stuff(x) ====== Let's say that my dream syntax would be ===(2)=== for x in l if P(x): do_stuff(x) ====== as if it was the second part of a list comprehension. But sadly it is not in the language. Obvious alternatives are ===(3)=== for x in (x for x in l if P(x)): do_stuff(x) ====== ===(4)=== for x in l: if not P(x): continue do_stuff(x) ====== ===(5)=== [do_stuff(x) for x in l if P(x)] ====== As I see it, every syntax-valid solution has its drawbacks: (1) adds an indentation level; (3) adds an unnatural repetition of variable names and "for"; (4) has the "masked goto" continue (even if it is quite easy to understand what happens); (5) is good but not usable when do_stuff is what it usually is, that is a list of instructions. Is there some better and valid construction I missed? If not, is there a reason why (2) is not in the language? Pardon my boldness, but I am asking this because there are two invalid construct that I keep writing when I don't pay attention: one is (2), and the other is list comprehensions as in ===(6)=== for x in (x in l if P(x)): do_stuff(x) ====== which accidentally would be a better solution than (1), (3), (4), (5), though not as good as (2). Thank you for your attention, Stefano Maggiolo From ian.g.kelly at gmail.com Wed Oct 5 13:24:51 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 5 Oct 2011 11:24:51 -0600 Subject: Convenient filtering in for cycles In-Reply-To: References: Message-ID: On Wed, Oct 5, 2011 at 10:55 AM, Stefano Maggiolo wrote: > Dear all, > > I would like to know if there is a (more) convenient way of doing this > structure: > > ===(1)=== > for x in l: > ? ?if P(x): > ? ? ? ?do_stuff(x) > ====== > > Let's say that my dream syntax would be > > ===(2)=== > for x in l if P(x): > ? ?do_stuff(x) > ====== for x in filter(P, l): do_stuff(x) This works nicely if P is a function but can be a bit unwieldy if you want to use an arbitrary expression, since you would need to put it in a lambda. > Is there some better and valid construction I missed? If not, is there > a reason why (2) is not in the language? I guess because, as you helpfully enumerated, there are already plenty of options for iterating with a condition. Syntax isn't added without a strong reason, and avoiding an extra line or an extra indentation level isn't enough. Cheers, Ian From ian.g.kelly at gmail.com Wed Oct 5 13:39:57 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 5 Oct 2011 11:39:57 -0600 Subject: Convenient filtering in for cycles In-Reply-To: References: Message-ID: On Wed, Oct 5, 2011 at 11:24 AM, Ian Kelly wrote: >> Is there some better and valid construction I missed? If not, is there >> a reason why (2) is not in the language? > > I guess because, as you helpfully enumerated, there are already plenty > of options for iterating with a condition. ?Syntax isn't added without > a strong reason, and avoiding an extra line or an extra indentation > level isn't enough. Also, see these older threads: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ef807313aa47efc/4f4269a7b566cb87 http://groups.google.com/group/python-ideas/browse_thread/thread/87eee156ac2c3a24/61621e7779b5b255 http://groups.google.com/group/python-ideas/browse_thread/thread/e2d076fe35ece873/862674672b4de683 Cheers, Ian From s.maggiolo at gmail.com Wed Oct 5 14:05:00 2011 From: s.maggiolo at gmail.com (Stefano Maggiolo) Date: Wed, 5 Oct 2011 20:05:00 +0200 Subject: Convenient filtering in for cycles In-Reply-To: References: Message-ID: Dear Ian, thank you for you kind response. I was pretty confident the issue had already been discussed, but I was unable to look it up. I suppose your "filter" syntax is the best given the options (I always forget about map and filter...) and definitely I see that the work needed to add such a feature is hardly worth the convenience. Still, I think it is sad that generators/list comprehensions and for cycles do not share the same syntax. Unfortunately, this example from one of your links convinces that anyway it is too late: (x for x in (l1 if c else l2)) # valid (x for x in l1 if c else l2) # SyntaxError for x in l1 if c else l2 # valid Cheers, Stefano From python.list at tim.thechases.com Wed Oct 5 14:31:41 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 05 Oct 2011 13:31:41 -0500 Subject: syntax enhancement In-Reply-To: References: Message-ID: <4E8CA28D.8060104@tim.thechases.com> On 10/04/11 20:45, Terry Reedy wrote: > On 10/4/2011 9:50 AM, Valiev Sergey wrote: > >> - `[]` - used for list comprehension, >> - `()` - used for generators, >> - `[start:stop]` / `[start:stop:step]` - used for slices. >> The idea is to use `(start:stop)` / `(start:stop:step)` as 'lazy >> evaluated' slices (like itertools.islice). >> What do you think about it? > > a(b) is already used for function calls. Making a(b:c) be something > unreleated does not seem like a good idea to me. At present, a[b:c] == > a[slice(b,c)]. However, a(slice(b,c)) is already a function call and > could not equal a(b:c). I'm very -1 on the initial proposal with parens, but I wouldn't object to generators growing a method (__getitem__?) to do slices via itertools, something like gen = (a for a in iterator if test(a)) for thing in gen[4::2]: do_something(thing) acting something like gen = (a for a in iterator if test(a)) for thing in itertools.islice(gen, start=4, step=2): do_something(thing) -tkc From tjreedy at udel.edu Wed Oct 5 16:09:14 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 05 Oct 2011 16:09:14 -0400 Subject: syntax enhancement In-Reply-To: <4E8CA28D.8060104@tim.thechases.com> References: <4E8CA28D.8060104@tim.thechases.com> Message-ID: On 10/5/2011 2:31 PM, Tim Chase wrote: > On 10/04/11 20:45, Terry Reedy wrote: >> On 10/4/2011 9:50 AM, Valiev Sergey wrote: >> >>> - `[]` - used for list comprehension, >>> - `()` - used for generators, >>> - `[start:stop]` / `[start:stop:step]` - used for slices. >>> The idea is to use `(start:stop)` / `(start:stop:step)` as 'lazy >>> evaluated' slices (like itertools.islice). >>> What do you think about it? >> >> a(b) is already used for function calls. Making a(b:c) be something >> unreleated does not seem like a good idea to me. At present, a[b:c] == >> a[slice(b,c)]. However, a(slice(b,c)) is already a function call and >> could not equal a(b:c). > > I'm very -1 on the initial proposal with parens, but I wouldn't object > to generators growing a method (__getitem__?) to do slices via > itertools, something like > > gen = (a for a in iterator if test(a)) > for thing in gen[4::2]: > do_something(thing) > > acting something like > > gen = (a for a in iterator if test(a)) > for thing in itertools.islice(gen, start=4, step=2): 'end' arg is required > do_something(thing) islice(gen,4,None,2) is 11 more characters than gen[4::2] If you start with 'from itertools import islice as sl', then each use is 7 more chars. In the normal case with an 'end' arg, the difference would be 4 chars less: sl(gen,4,100,2) # 3 extra chars to type ;=) gen[4:100:2] This would complicate the language and make generators more different from other iterators without adding new functionality -- Terry Jan Reedy From tjreedy at udel.edu Wed Oct 5 16:11:18 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 05 Oct 2011 16:11:18 -0400 Subject: Writing file out to another machine In-Reply-To: <0d795922-d946-480d-8f41-95656e56fa86@g23g2000vbz.googlegroups.com> References: <0d795922-d946-480d-8f41-95656e56fa86@g23g2000vbz.googlegroups.com> Message-ID: On 10/5/2011 10:34 AM, RVince wrote: > I have a project whereby I need it to write out a file to a different > server (that the originating server has write access to). So, say I > need to write out from myserver1, where my app is running, onto, say > S:/IT/tmp how can I specify/do this? Thanks, RVince open('S:/IT/tmp','w') ?? -- Terry Jan Reedy From gordon at panix.com Wed Oct 5 17:22:37 2011 From: gordon at panix.com (John Gordon) Date: Wed, 5 Oct 2011 21:22:37 +0000 (UTC) Subject: Writing file out to another machine References: <0d795922-d946-480d-8f41-95656e56fa86@g23g2000vbz.googlegroups.com> Message-ID: In Terry Reedy writes: > On 10/5/2011 10:34 AM, RVince wrote: > > I have a project whereby I need it to write out a file to a different > > server (that the originating server has write access to). So, say I > > need to write out from myserver1, where my app is running, onto, say > > S:/IT/tmp how can I specify/do this? Thanks, RVince > open('S:/IT/tmp','w') ?? I assume he intended "S:" to indicate a remote server. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From anikom15 at gmail.com Wed Oct 5 17:28:22 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 5 Oct 2011 14:28:22 -0700 Subject: syntax enhancement In-Reply-To: <4E8CA28D.8060104@tim.thechases.com> References: <4E8CA28D.8060104@tim.thechases.com> Message-ID: <20111005212822.GA30294@Smoke> On Wed, Oct 05, 2011 at 01:31:41PM -0500, Tim Chase wrote: > On 10/04/11 20:45, Terry Reedy wrote: > >On 10/4/2011 9:50 AM, Valiev Sergey wrote: > > > >>- `[]` - used for list comprehension, > >>- `()` - used for generators, > >>- `[start:stop]` / `[start:stop:step]` - used for slices. > >>The idea is to use `(start:stop)` / `(start:stop:step)` as 'lazy > >>evaluated' slices (like itertools.islice). > >>What do you think about it? > > > >a(b) is already used for function calls. Making a(b:c) be something > >unreleated does not seem like a good idea to me. At present, a[b:c] == > >a[slice(b,c)]. However, a(slice(b,c)) is already a function call and > >could not equal a(b:c). > > I'm very -1 on the initial proposal with parens, but I wouldn't > object to generators growing a method (__getitem__?) to do slices > via itertools, something like > > gen = (a for a in iterator if test(a)) > for thing in gen[4::2]: > do_something(thing) > > acting something like > > gen = (a for a in iterator if test(a)) > for thing in itertools.islice(gen, start=4, step=2): > do_something(thing) > > -tkc > > > > Wait, how would this work fundamentally? A list can be sliced because all the values are there. A generator does not have all its value at once (it generates each value as requested). I don't like change so I look at these kinds of suggestions with lots of scrutiny and biased criticism. From rosuav at gmail.com Wed Oct 5 17:31:28 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Oct 2011 08:31:28 +1100 Subject: Writing file out to another machine In-Reply-To: References: <0d795922-d946-480d-8f41-95656e56fa86@g23g2000vbz.googlegroups.com> Message-ID: On Thu, Oct 6, 2011 at 8:22 AM, John Gordon wrote: > I assume he intended "S:" to indicate a remote server. > The most obvious understanding of it is a drive letter (ie Windows box). But if not, more clarification is needed. ChrisA From ian.g.kelly at gmail.com Wed Oct 5 17:46:15 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 5 Oct 2011 15:46:15 -0600 Subject: syntax enhancement In-Reply-To: <20111005212822.GA30294@Smoke> References: <4E8CA28D.8060104@tim.thechases.com> <20111005212822.GA30294@Smoke> Message-ID: On Wed, Oct 5, 2011 at 3:28 PM, Westley Mart?nez wrote: > Wait, how would this work fundamentally? ?A list can be sliced because > all the values are there. ?A generator does not have all its value at > once (it generates each value as requested). ?I don't like change so I > look at these kinds of suggestions with lots of scrutiny and biased > criticism. Like islice, it would return an iterator that lazily pulls values from the generator as they are requested, discarding unneeded values as necessary. From gregor.hochschild at googlemail.com Wed Oct 5 19:35:59 2011 From: gregor.hochschild at googlemail.com (Greg) Date: Wed, 5 Oct 2011 16:35:59 -0700 (PDT) Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file Message-ID: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> Hi, I am having some encoding problems when I first parse stuff from a non-english website using BeautifulSoup and then write the results to a txt file. I have the text both as a normal (text) and as a unicode string (utext): print repr(text) 'Branie zak\xc2\xb3adnik\xc3\xb3w' print repr(utext) u'Branie zak\xb3adnik\xf3w' print text or print utext (fileSoup.prettify() also shows 'wrong' symbols): Branie zak?adnik?w Now I am trying to save this to a file but I never get the encoding right. Here is what I tried (+ lot's of different things with encode, decode...): outFile=open(filePath,"w") outFile.write(text) outFile.close() outFile=codecs.open( filePath, "w", "UTF8" ) outFile.write(utext) outFile.close() Thanks!! From tjreedy at udel.edu Wed Oct 5 21:36:34 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 05 Oct 2011 21:36:34 -0400 Subject: Writing file out to another machine In-Reply-To: References: <0d795922-d946-480d-8f41-95656e56fa86@g23g2000vbz.googlegroups.com> Message-ID: On 10/5/2011 5:31 PM, Chris Angelico wrote: > On Thu, Oct 6, 2011 at 8:22 AM, John Gordon wrote: >> I assume he intended "S:" to indicate a remote server. >> > > The most obvious understanding of it is a drive letter (ie Windows > box). More exactly, a remote server filesystem 'mounted' (not sure of the Windows' term) as a local drive. I am pretty sure I have read of this being done. > But if not, more clarification is needed. Definitely. -- Terry Jan Reedy From steve+comp.lang.python at pearwood.info Wed Oct 5 21:55:51 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 06 Oct 2011 01:55:51 GMT Subject: syntax enhancement References: Message-ID: <4e8d0aa7$0$29978$c3e8da3$5496439d@news.astraweb.com> On Wed, 05 Oct 2011 13:31:41 -0500, Tim Chase wrote: > I'm very -1 on the initial proposal with parens, but I wouldn't object > to generators growing a method (__getitem__?) to do slices via > itertools, something like > > gen = (a for a in iterator if test(a)) > for thing in gen[4::2]: > do_something(thing) > > acting something like > > gen = (a for a in iterator if test(a)) > for thing in itertools.islice(gen, start=4, step=2): > do_something(thing) The problem is that adding slicing to iterators is that it requires ALL iterators to support slicing, whether appropriate or not, and regardless of the implementation. Just use islice. Not everything needs to be a built-in. -- Steven From steve+comp.lang.python at pearwood.info Wed Oct 5 22:08:46 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 06 Oct 2011 02:08:46 GMT Subject: Convenient filtering in for cycles References: Message-ID: <4e8d0dae$0$29978$c3e8da3$5496439d@news.astraweb.com> On Wed, 05 Oct 2011 18:55:53 +0200, Stefano Maggiolo wrote: > Dear all, > > I would like to know if there is a (more) convenient way of doing this > structure: > > ===(1)=== > for x in l: > if P(x): > do_stuff(x) > ====== That seems pretty convenient to me. It's simple, obvious and readable. > Let's say that my dream syntax would be > > ===(2)=== > for x in l if P(x): > do_stuff(x) > ====== That is exactly the same as #1 above, except it takes one extra line (trivial) and one extra indent level (almost always trivial). So what's the problem with #1? If you have so many indent levels that one more level causes you grief, then consider that Nature's way of telling you that you have too much code in one chunk and that you should refactor some of it into functions. > as if it was the second part of a list comprehension. But sadly it is > not in the language. Obvious alternatives are > > ===(3)=== > for x in (x for x in l if P(x)): > do_stuff(x) > ====== A hard to read mess. Best avoided. > ===(4)=== > for x in l: > if not P(x): > continue > do_stuff(x) > ====== Saves an indent level, otherwise virtually identical to #1. > ===(5)=== > [do_stuff(x) for x in l if P(x)] > ====== Only appropriate if you care about the return results of do_stuff. If you are using a list comprehension solely for the side-effects, don't. > As I see it, every syntax-valid solution has its drawbacks: (1) adds an > indentation level; This shouldn't be a drawback. This should be an advantage. It's an extra indentation level because it represents a block of code. > (3) adds an unnatural repetition of variable names and "for"; (4) has > the "masked goto" continue (even if it is quite easy to understand what > happens); While it is true that "goto is harmful", it is possible to take the hatred of goto to ridiculous levels. Calling a function is a "masked goto". For-loops and while loops are "masked gotos". That doesn't make them bad things. There is nothing inherently wrong with continue and break for flow control, although of course you can write bad code with any construct. > (5) is good but not usable when do_stuff is what it usually is, that is > a list of instructions. > > Is there some better and valid construction I missed? If not, is there a > reason why (2) is not in the language? Because it complicates the language for very little benefit. That makes the language harder to learn and read and the compiler harder to maintain. Unless there is a concrete gain from the feature, why bother? -- Steven From wuwei23 at gmail.com Wed Oct 5 23:34:35 2011 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Oct 2011 20:34:35 -0700 (PDT) Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> <4e8bed30$0$29978$c3e8da3$5496439d@news.astraweb.com> <87wrcjzmql.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > This mocking is hurtful to people who identify too strongly with COBOL. > I wonder whether that means it's intentionally hurtful. Far, _far_ less hurtful than COBOL itself... From wuwei23 at gmail.com Wed Oct 5 23:36:25 2011 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Oct 2011 20:36:25 -0700 (PDT) Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <4E8BADBE.2090300@yahoo.com> <4E8BB162.5080100@yahoo.com> Message-ID: On Oct 5, 11:10?pm, Chris Angelico wrote: > The absence from the language doesn't prove that. All it means is > that, on those rare occasions when a goto would have been correct, the > programmer had to make do with something else :-) Like the goto module? :) http://entrian.com/goto/ From steve+comp.lang.python at pearwood.info Wed Oct 5 23:40:14 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 06 Oct 2011 03:40:14 GMT Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> Message-ID: <4e8d231e$0$29978$c3e8da3$5496439d@news.astraweb.com> On Wed, 05 Oct 2011 16:35:59 -0700, Greg wrote: > Hi, I am having some encoding problems when I first parse stuff from a > non-english website using BeautifulSoup and then write the results to a > txt file. If you haven't already read this, you should do so: http://www.joelonsoftware.com/articles/Unicode.html > I have the text both as a normal (text) and as a unicode string (utext): > print repr(text) > 'Branie zak\xc2\xb3adnik\xc3\xb3w' This is pretty much meaningless, because we don't know how you got the text and what it actually is. You're showing us a bunch of bytes, with no clue as to whether they are the right bytes or not. Considering that your Unicode text is also incorrect, I would say it is *not* right and your description of the problem is 100% backwards: the problem is not *writing* the text, but *reading* the bytes and decoding it. You should do something like this: (1) Inspect the web page to find out what encoding is actually used. (2) If the web page doesn't know what encoding it uses, or if it uses bits and pieces of different encodings, then the source is broken and you shouldn't expect much better results. You could try guessing, but you should expect mojibake in your results. http://en.wikipedia.org/wiki/Mojibake (3) Decode the web page into Unicode text, using the correct encoding. (4) Do all your processing in Unicode, not bytes. (5) Encode the text into bytes using UTF-8 encoding. (6) Write the bytes to a file. [...] > Now I am trying to save this to a file but I never get the encoding > right. Here is what I tried (+ lot's of different things with encode, > decode...): > outFile=codecs.open( filePath, "w", "UTF8" ) > outFile.write(utext) > outFile.close() That's the correct approach, but it won't help you if utext contains the wrong characters in the first place. The critical step is taking the bytes in the web page and turning them into text. How are you generating utext? -- Steven From wuwei23 at gmail.com Wed Oct 5 23:42:18 2011 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Oct 2011 20:42:18 -0700 (PDT) Subject: Convenient filtering in for cycles References: Message-ID: On Oct 6, 2:55?am, Stefano Maggiolo wrote: > I would like to know if there is a (more) convenient way of doing this > structure: > > ===(1)=== > for x in l: > ? ? if P(x): > ? ? ? ? do_stuff(x) > ====== map(do_stuff, filter(P, l)) From cs at zip.com.au Wed Oct 5 23:44:33 2011 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 6 Oct 2011 14:44:33 +1100 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> Message-ID: <20111006034433.GA23530@cskk.homeip.net> On 03Oct2011 13:10, rantingrick wrote: | Also for scoping. | | py> count = 0 | py> def foo(): | ... global.count += 1 | py> print count | 1 | | Why? Well because many times i find myself wondering if this or that | variable is local or global -- and when i say "global" i am speaking | of module scope! The "global" cures the ill. I must admit I rarely have this concern. My own module globals are almost entirely CONSTANT type names. (Excluding function and class names.) What's the common ambifuity case for you? -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Generally, these things are dreadful, but I saw a clip the other night on tv of someone who had built a scorpion costume for their spaniel, complete with legs and a stinger. It was quite impressive. Made me want to run out and buy a dog and a some foam rubber. - David Farley From alec.taylor6 at gmail.com Thu Oct 6 00:02:50 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Thu, 6 Oct 2011 15:02:50 +1100 Subject: recommend a graphics library for plotting by the pixel? In-Reply-To: <6a4f8ef3-81d1-4e91-8cd8-8014a021a2aa@18g2000yqz.googlegroups.com> References: <9s1rl8xt8t.ln2@news.ducksburg.com> <6a4f8ef3-81d1-4e91-8cd8-8014a021a2aa@18g2000yqz.googlegroups.com> Message-ID: Hehe, sure, why not? :P On Wed, Oct 5, 2011 at 2:24 PM, alex23 wrote: > On Oct 5, 12:53?am, Alec Taylor wrote: >> Sounds like a job for Processing... > > Don't you mean PyProcessing? :) > > http://code.google.com/p/pyprocessing/ > -- > http://mail.python.org/mailman/listinfo/python-list > From anikom15 at gmail.com Thu Oct 6 00:26:49 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 5 Oct 2011 21:26:49 -0700 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: <20111006034433.GA23530@cskk.homeip.net> References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <20111006034433.GA23530@cskk.homeip.net> Message-ID: <20111006042648.GA31575@Smoke> On Thu, Oct 06, 2011 at 02:44:33PM +1100, Cameron Simpson wrote: > On 03Oct2011 13:10, rantingrick wrote: > | Also for scoping. > | > | py> count = 0 > | py> def foo(): > | ... global.count += 1 > | py> print count > | 1 > | > | Why? Well because many times i find myself wondering if this or that > | variable is local or global -- and when i say "global" i am speaking > | of module scope! The "global" cures the ill. > > I must admit I rarely have this concern. My own module globals are > almost entirely CONSTANT type names. (Excluding function and class > names.) > > What's the common ambifuity case for you? I never have this concern either. Python's functions and classes are powerful enough to avoid globals entirely. In C I have a few sometimes and in Fortran and the like they're everywhere. Global variables are POWERFUL and USEFUL but there's a certain paradigm that goes with them, and Python works better with an object-oriented w/ functional elements approach. From gregor.hochschild at googlemail.com Thu Oct 6 00:39:17 2011 From: gregor.hochschild at googlemail.com (Greg) Date: Wed, 5 Oct 2011 21:39:17 -0700 (PDT) Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> <4e8d231e$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4aeb76e9-511f-4a46-94c7-bf2ab84877df@z12g2000yqz.googlegroups.com> Brilliant! It worked. Thanks! Here is the final code for those who are struggling with similar problems: ## open and decode file # In this case, the encoding comes from the charset argument in a meta tag # e.g. fileObj = open(filePath,"r").read() fileContent = fileObj.decode("iso-8859-2") fileSoup = BeautifulSoup(fileContent) ## Do some BeautifulSoup magic and preserve unicode, presume result is saved in 'text' ## ## write extracted text to file f = open(outFilePath, 'w') f.write(text.encode('utf-8')) f.close() On Oct 5, 11:40?pm, Steven D'Aprano wrote: > On Wed, 05 Oct 2011 16:35:59 -0700, Greg wrote: > > Hi, I am having some encoding problems when I first parse stuff from a > > non-english website using BeautifulSoup and then write the results to a > > txt file. > > If you haven't already read this, you should do so: > > http://www.joelonsoftware.com/articles/Unicode.html > > > I have the text both as a normal (text) and as a unicode string (utext): > > print repr(text) > > 'Branie zak\xc2\xb3adnik\xc3\xb3w' > > This is pretty much meaningless, because we don't know how you got the > text and what it actually is. You're showing us a bunch of bytes, with no > clue as to whether they are the right bytes or not. Considering that your > Unicode text is also incorrect, I would say it is *not* right and your > description of the problem is 100% backwards: the problem is not > *writing* the text, but *reading* the bytes and decoding it. > > You should do something like this: > > (1) Inspect the web page to find out what encoding is actually used. > > (2) If the web page doesn't know what encoding it uses, or if it uses > bits and pieces of different encodings, then the source is broken and you > shouldn't expect much better results. You could try guessing, but you > should expect mojibake in your results. > > http://en.wikipedia.org/wiki/Mojibake > > (3) Decode the web page into Unicode text, using the correct encoding. > > (4) Do all your processing in Unicode, not bytes. > > (5) Encode the text into bytes using UTF-8 encoding. > > (6) Write the bytes to a file. > > [...] > > > Now I am trying to save this to a file but I never get the encoding > > right. Here is what I tried (+ lot's of different things with encode, > > decode...): > > outFile=codecs.open( filePath, "w", "UTF8" ) > > outFile.write(utext) > > outFile.close() > > That's the correct approach, but it won't help you if utext contains the > wrong characters in the first place. The critical step is taking the > bytes in the web page and turning them into text. > > How are you generating utext? > > -- > Steven From rosuav at gmail.com Thu Oct 6 00:58:24 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Oct 2011 15:58:24 +1100 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: <4E8BADBE.2090300@yahoo.com> <4E8BB162.5080100@yahoo.com> Message-ID: On Thu, Oct 6, 2011 at 2:36 PM, alex23 wrote: > On Oct 5, 11:10?pm, Chris Angelico wrote: >> The absence from the language doesn't prove that. All it means is >> that, on those rare occasions when a goto would have been correct, the >> programmer had to make do with something else :-) > > Like the goto module? :) > > http://entrian.com/goto/ Yes. That module is extremely valuable and needs to be brought into the main trunk. Rick, can this go on your Python 4000 list? ChrisA From rosuav at gmail.com Thu Oct 6 01:00:31 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Oct 2011 16:00:31 +1100 Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file In-Reply-To: <4aeb76e9-511f-4a46-94c7-bf2ab84877df@z12g2000yqz.googlegroups.com> References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> <4e8d231e$0$29978$c3e8da3$5496439d@news.astraweb.com> <4aeb76e9-511f-4a46-94c7-bf2ab84877df@z12g2000yqz.googlegroups.com> Message-ID: On Thu, Oct 6, 2011 at 3:39 PM, Greg wrote: > Brilliant! It worked. Thanks! > > Here is the final code for those who are struggling with similar > problems: > > ## open and decode file > # In this case, the encoding comes from the charset argument in a meta > tag > # e.g. > fileContent = fileObj.decode("iso-8859-2") > f.write(text.encode('utf-8')) In other words, when you decode correctly into Unicode and encode correctly onto the disk, it works! This is why encodings are so important :) ChrisA From sajuptpm at gmail.com Thu Oct 6 01:01:56 2011 From: sajuptpm at gmail.com (sajuptpm) Date: Wed, 5 Oct 2011 22:01:56 -0700 (PDT) Subject: selenium pyvirtualdisplay script on remote server Message-ID: <9e56fd9f-87ab-4164-af26-83f3efce5d84@b6g2000vbz.googlegroups.com> Hi Friends, Here the isuue is i can't find the "li" element. that is because that element is out of display, so i adjust scroll bar or do focus around that area to get that element via find_element_by_id("loc_opt") I already tested with scroll bar and focus and its working fine in my laptop. But when i run this script on Remote Server, it can't find that element.?????? Note: Here i am using pyvirtualdisplay, Xvfb and Xephyr, because server don't have Xserver. Its also working fine with pyvirtualdisplay in my laptop. but the issue is in Remote Server. Has anyone faced this problem before ? Please suggest a solution. class Search: def __init__(self): """ """ self.display = Display(visible=0, size=(800, 600)) self.display.start() self.url ='http://www.google.com' self.search_url = None self.driver = webdriver().Firefox() def search(self, search_query, search_location=None): """ """ if search_query: self.search_url = "%s/search?q=%s" %(self.url, search_query) print "\nURL : ", self.search_url self.driver.get(self.search_url) self.submit_search() #self.driver.execute_script("window.scrollBy(0,200)") self.driver.execute_script("document.getElementById('tbpi').focus();") more_search_tools_link = self.driver.find_element_by_id("tbpi") more_search_tools_link.click() self.driver.execute_script("window.scrollBy(0,200)") loc_li = self.driver.find_element_by_id("loc_opt") From hansmeetschool at gmail.com Thu Oct 6 01:45:42 2011 From: hansmeetschool at gmail.com (Hansmeet Singh) Date: Wed, 5 Oct 2011 22:45:42 -0700 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: <4E8BADBE.2090300@yahoo.com> <4E8BB162.5080100@yahoo.com> Message-ID: REMEMBER STEVE On Wed, Oct 5, 2011 at 9:58 PM, Chris Angelico wrote: > On Thu, Oct 6, 2011 at 2:36 PM, alex23 wrote: > > On Oct 5, 11:10 pm, Chris Angelico wrote: > >> The absence from the language doesn't prove that. All it means is > >> that, on those rare occasions when a goto would have been correct, the > >> programmer had to make do with something else :-) > > > > Like the goto module? :) > > > > http://entrian.com/goto/ > > Yes. That module is extremely valuable and needs to be brought into > the main trunk. Rick, can this go on your Python 4000 list? > > ChrisA > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Thu Oct 6 03:05:01 2011 From: timr at probo.com (Tim Roberts) Date: Thu, 06 Oct 2011 00:05:01 -0700 Subject: urllib and parsing References: Message-ID: luca72 wrote: > >Hello i have a simple question: >up to now if i have to parse a page i do as follow: >... >Now i have the site that is open by an html file like this: >... >how can i open it with urllib, please note i don't have to parse this >file, but i have to parse the site where he point. Well, you can use htmllib to parse the HTML, look for the "form" tag, and extract the "action" verb. Or, if you really just want this one site, you can use urllib2 to provide POST parameters: import urllib import urllib2 url = 'http://lalal.hhdik/' values = {'password' : 'password', 'Entra' : 'Entra' } data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read() -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From timr at probo.com Thu Oct 6 03:05:42 2011 From: timr at probo.com (Tim Roberts) Date: Thu, 06 Oct 2011 00:05:42 -0700 Subject: httplib2 download forbidden References: <43d464bd-460d-416b-a61e-d2cb385169aa@q13g2000vby.googlegroups.com> Message-ID: Mauro Zaccariotto wrote: > >Hi! does anyone know what's happening here http://code.google.com/p/httplib2/ >? I get this: >"403. That?s an error. >Your client does not have permission to get URL /p/httplib2/ from this >server. That?s all we know." It's working for me. Do you have some kind of proxy in the way? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ladasky at my-deja.com Thu Oct 6 04:00:09 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 6 Oct 2011 01:00:09 -0700 (PDT) Subject: Simplest way to resize an image-like array References: <9b0b8951-bfc2-4047-8b4e-1ee0af20af27@q24g2000vby.googlegroups.com> Message-ID: On Oct 1, 2:22?am, John Ladasky wrote: > On Sep 30, 1:51?pm, Jon Clements wrote: > > > Is something like > >http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresi... > > any use? > > There we go! ?That's the kind of method I was seeking. ?I didn't think > to look outside of scipy.interpolate. ?Thanks, Jon. Oh, grumble, scipy.misc.imresize bumps the array down to an 8-bit integer array. I need to do some arithmetic with the arrays, and it needs to be more precise than 8 bits. So I may have to rewrite the function to yield a 16-bit integer at least. From mzaccariotto at h-umus.it Thu Oct 6 04:36:19 2011 From: mzaccariotto at h-umus.it (Mauro Zaccariotto) Date: Thu, 6 Oct 2011 01:36:19 -0700 (PDT) Subject: httplib2 download forbidden References: <43d464bd-460d-416b-a61e-d2cb385169aa@q13g2000vby.googlegroups.com> Message-ID: <2e19f37e-de88-483c-8bad-660ccfcf2ec0@k15g2000yqd.googlegroups.com> On 6 Ott, 09:05, Tim Roberts wrote: > Mauro Zaccariotto wrote: > > >Hi! does anyone know what's happening herehttp://code.google.com/p/httplib2/ > >? I get this: > >"403. That s an error. > >Your client does not have permission to get URL /p/httplib2/ from this > >server. That s all we know." > > It's working for me. ?Do you have some kind of proxy in the way? > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. No, but today it's working again. O__o thank you anyway From ulrich.eckhardt at dominalaser.com Thu Oct 6 05:29:21 2011 From: ulrich.eckhardt at dominalaser.com (Ulrich Eckhardt) Date: Thu, 06 Oct 2011 11:29:21 +0200 Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file In-Reply-To: <4e8d231e$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> <4e8d231e$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 06.10.2011 05:40, schrieb Steven D'Aprano: > (4) Do all your processing in Unicode, not bytes. > > (5) Encode the text into bytes using UTF-8 encoding. > > (6) Write the bytes to a file. Just wondering, why do you split the latter two parts? I would have used codecs.open() to open the file and define the encoding in a single step. Is there a downside to this approach? Otherwise, I can only confirm that your overall approach is the easiest way to get correct results. Uli From shanghaizheng2010 at gmail.com Thu Oct 6 07:31:21 2011 From: shanghaizheng2010 at gmail.com (fashion fans) Date: Thu, 6 Oct 2011 04:31:21 -0700 (PDT) Subject: The hyper fused upper part of Nike Air Max displays the humanity Message-ID: <2c1890e6-56fe-4882-9fc6-e9d12925823e@z8g2000yqb.googlegroups.com> The hyper fused upper part of Nike Air Max displays the humanity of the designer because of its lightweight, breathability and a feeling of plusher fitness. The mesh inner collar, and the soft springy cushion http://www.outlet-nike-air-max.com/inside can protect the feet against most possible injures. Besides the rubber materials around the translucent perimeter displays a particular appearance of the shoes, which is a love of most women, especially those who pursuit to be in fashion. Meanwhile the rubber material is a guaranty of the durability and traction, which is fully the practice. With the {2}{/2}dynamic colors of Women?s Nike Air Max 2011, you will soon experience the vitality of sports when you are dressed in such a pair of classic nice cheap Nike running shoes, because it can not only create a healthy condition for feet, but also can restore the original active in the shortest time. What?s more, the Nike Air Max 2011 will not cause any exacerbation if you once were injured in feet. http://www.outlet-nike-air-max.com/ From rosuav at gmail.com Thu Oct 6 07:34:12 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Oct 2011 22:34:12 +1100 Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file In-Reply-To: References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> <4e8d231e$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Oct 6, 2011 at 8:29 PM, Ulrich Eckhardt wrote: > Just wondering, why do you split the latter two parts? I would have used > codecs.open() to open the file and define the encoding in a single step. Is > there a downside to this approach? > Those two steps still happen, even if you achieve them in a single function call. What Steven described is language- and library- independent. ChrisA From davea at ieee.org Thu Oct 6 09:14:21 2011 From: davea at ieee.org (Dave Angel) Date: Thu, 06 Oct 2011 09:14:21 -0400 Subject: Writing file out to another machine In-Reply-To: References: <0d795922-d946-480d-8f41-95656e56fa86@g23g2000vbz.googlegroups.com> Message-ID: <4E8DA9AD.1090108@ieee.org> On 01/-10/-28163 02:59 PM, Dennis Lee Bieber wrote: > On Wed, 05 Oct 2011 21:36:34 -0400, Terry Reedy > declaimed the following in gmane.comp.python.general: > >> On 10/5/2011 5:31 PM, Chris Angelico wrote: >>> On Thu, Oct 6, 2011 at 8:22 AM, John Gordon wrote: >>>> I assume he intended "S:" to indicate a remote server. >>>> >>> The most obvious understanding of it is a drive letter (ie Windows >>> box). >> More exactly, a remote server filesystem 'mounted' (not sure of the >> Windows' term) as a local drive. I am pretty sure I have read of this >> being done. >> > "My Computer" > > "Map Network Drive" > > So I suspect you could refer to it as a "mapped" filesystem. Or you could refer to it as a 'net use' drive, since that's the commandline way to mount it on Windoze. DaveA From dreyemi at gmail.com Thu Oct 6 09:34:28 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Thu, 6 Oct 2011 14:34:28 +0100 Subject: Implementing Python-OAuth2 Message-ID: Hello friends, I'm working on a pretty large application that I will like to use oauth2 on as an authentication and authorization mechanism. I understand fairly the technology and I have written my own implementation before I stumbled on python-oauth2. I need advise on leveraging python-oauth2 api for creating consumer key, creating consumer secret, access token and token secret. Regards -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From ed at leafe.com Thu Oct 6 10:31:34 2011 From: ed at leafe.com (Ed Leafe) Date: Thu, 6 Oct 2011 09:31:34 -0500 Subject: Dabo 0.9.4 Released! Message-ID: Yes, it's been over a year, but today we're finally releasing Dabo 0.9.4! What can I say? While we've been actively developing Dabo all along, and committing improvements and fixes regularly, we don't seem to get around to doing releases as often as we should. Since Dabo has a Web Update feature that lets developers receive regular updates between releases, most people are fairly current, but creating a new release will help newcomers to Dabo get up to speed quicker. The changes won't be too big for most current users of the framework, but compared to the 0.9.3 release, lots has been fixed and improved! Full release notes are at: http://svn.dabodev.com/dabo/tags/dabo-0.9.4/ChangeLog ...but here are just a few of the major changes since 0.9.3: - better handling of edge cases in bizobj relations - addition of support in bizobjs for many-to-many relationships - improved efficiency in detecting changed records - added the dDatePicker control - added the option of vertical text for grid headers - integrated a code editor into the command window You can grab the latest version, as always, from http://dabodev.com/download -- Ed Leafe From nt_mahmood at yahoo.com Thu Oct 6 11:27:51 2011 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Thu, 6 Oct 2011 08:27:51 -0700 (PDT) Subject: passing multiple string to a command line option Message-ID: <1317914871.44539.YahooMailNeo@web111719.mail.gq1.yahoo.com> Dear developers, Suppose I have this list in command line options: ... -b b1,b2,b3 Here is what I wrote: parser = optparse.OptionParser() # Benchmark options parser.add_option("-b", "--benchmark", default="", help="The benchmark to be loaded.") process = [] benchmarks = options.benchmark.split(',') for bench_name in benchmarks: ??? process.append(bench_name) ??? At this stage, I want to bind each process to something: np = 2 for i in xrange(np): ??? ... ??? system.cpu[i].workload = process[i] however I get this error: ? File "configs/example/cmp.py", line 81, in ??? system.cpu[i].workload = process[i] ? File "/home/mahmood/gem5/src/python/m5/SimObject.py", line 627, in __setattr__ ??? value = param.convert(value) ? File "/home/mahmood/gem5/src/python/m5/params.py", line 236, in convert ??? tmp_list = [ ParamDesc.convert(self, value) ] ? File "/home/mahmood/gem5/src/python/m5/params.py", line 159, in convert ??? return self.ptype(value) TypeError: __init__() takes exactly 1 argument (2 given) Error setting param TmpClass.workload to bzip2_chicken params.py is part of the simulator and I didn't wrote that. My question is what is the simplest way to fix that? Or is there any better idea than what I did in order to parse such command line option? ?thanks // Naderan *Mahmood; From jeanmichel at sequans.com Thu Oct 6 11:28:20 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 06 Oct 2011 17:28:20 +0200 Subject: A tuple in order to pass returned values ? In-Reply-To: References: Message-ID: <4E8DC914.6020906@sequans.com> faucheuse wrote: > Hi, (new to python and first message here \o/) > > I was wondering something : > when you do : return value1, value2, value3 > It returns a tuple. > > So if I want to pass these value to a function, the function have to > look like : > def function(self,(value1, value2, value3)) #self because i'm working > with classes > > I tried it, and it works perfectly, but I was wondering if it's a good > choice to do so, if there is a problem by coding like that. > > So my question is : Is there a problem doig so ? > There is no problem with that but ppl will usually write something like: def function(self, a3Tuple): v1, v2 ,v3 = a3Tuple In a general manner, ppl will tend to use the minimum arguments required. However, do not pack values into tuple if they are not related. A better thing to do would be to use objects instead of tuples, tuples can serve as lazy structures for small application/script, they can become harmful in more complexe applications, especialy when used in public interfaces. JM From alain.leufroy at logilab.fr Thu Oct 6 11:34:08 2011 From: alain.leufroy at logilab.fr (Alain Leufroy) Date: Thu, 6 Oct 2011 17:34:08 +0200 (CEST) Subject: ANN: hgview 1.4.0 - Mercurial log navigator Message-ID: Announcing HgView 1.4.0 ======================= HgView home page: http://www.logilab.org/project/hgview Tarball: http://ftp.logilab.org/pub/hgview/hgview-1.4.0.tar.gz Hg repository: http://www.logilab.org/src/hgview About this release ================== Text mode inside make it into hgview 1.4.0! This release introduces a *new text based* user interface thanks to the urwid library (http://excess.org/urwid ) This interface includes the following features: * display the revision graph (with working directory as a node, and basic support for the mq), * display the files affected by a selected changeset (with basic support for the bfiles), * display diffs (with syntax highlighting thanks to pygments), * automatically refresh the displayed revision graph when the repository is being modified, * easy key-based navigation in revisions' history of a repo (same as the GUI), * a command system for special actions (see help) To use it type : ``hgview --interface curses`` (or configure it permanently in your config file) There are also some bugfixes. About HgView ============ hgview is a simple tool aiming at visually navigate in a Mercurial (hg) repository history. It is written in Python with quick and efficient key-based navigation in mind, trying to be fast enough for big repositories. --$ python-projects mailing list http://lists.logilab.org/mailman/listinfo/python-projects From jgaynor at ncsa.illinois.edu Thu Oct 6 12:15:52 2011 From: jgaynor at ncsa.illinois.edu (Jeff Gaynor) Date: Thu, 06 Oct 2011 11:15:52 -0500 Subject: Implementing Python-OAuth2 In-Reply-To: References: Message-ID: <4E8DD438.20207@ncsa.illinois.edu> On 10/06/2011 08:34 AM, Kayode Odeyemi wrote: > Hello friends, > > I'm working on a pretty large application that I will like to use > oauth2 on as an authentication and authorization mechanism. > > I understand fairly the technology and I have written my own > implementation before I stumbled on python-oauth2. > > I need advise on leveraging python-oauth2 api for creating consumer > key, creating consumer secret, access token and token secret. > This works well, but be advised that the original python oauth library had some serious issues, so was redone as python-oauth2. What is confusing is that it refers to OAuth version 1.0a, not the upcoming OAuth version 2.0, so make sure you read the right spec before using it, since they are very different indeed. There are *no* usable OAuth version 2..0 implementation in any language (usually Java comes first) that I know of, so you will get to role your own, which is hard. There are a few beta-level versions E.g. Twitter) but these are special cased to the author's needs. The spec itself is not quite ready either and since it has changed quite substantially in the last year, I suspect that everyone is waiting to see it settle to a steady state. Jeff From tjreedy at udel.edu Thu Oct 6 13:18:10 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 06 Oct 2011 13:18:10 -0400 Subject: passing multiple string to a command line option In-Reply-To: <1317914871.44539.YahooMailNeo@web111719.mail.gq1.yahoo.com> References: <1317914871.44539.YahooMailNeo@web111719.mail.gq1.yahoo.com> Message-ID: On 10/6/2011 11:27 AM, Mahmood Naderan wrote: > Dear developers, > Suppose I have this list in command line options: > ... -b b1,b2,b3 > > Here is what I wrote: > parser = optparse.OptionParser() If you are starting a new project, consider using argparse, which has superceded optparse. > # Benchmark options > parser.add_option("-b", "--benchmark", default="", help="The benchmark to be loaded.") > process = [] > benchmarks = options.benchmark.split(',') > for bench_name in benchmarks: > process.append(bench_name) > > At this stage, I want to bind each process to something: > np = 2 > for i in xrange(np): > ... > system.cpu[i].workload = process[i] > > however I get this error: > > File "configs/example/cmp.py", line 81, in > system.cpu[i].workload = process[i] > File "/home/mahmood/gem5/src/python/m5/SimObject.py", line 627, in __setattr__ > value = param.convert(value) > File "/home/mahmood/gem5/src/python/m5/params.py", line 236, in convert > tmp_list = [ ParamDesc.convert(self, value) ] > File "/home/mahmood/gem5/src/python/m5/params.py", line 159, in convert > return self.ptype(value) > TypeError: __init__() takes exactly 1 argument (2 given) > Error setting param TmpClass.workload to bzip2_chicken > > params.py is part of the simulator and I didn't wrote that. > > My question is what is the simplest way to fix that? > Or is there any better idea than what I did in order to parse such command line option? > > thanks > > // Naderan *Mahmood; -- Terry Jan Reedy From ndbecker2 at gmail.com Thu Oct 6 13:18:19 2011 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 06 Oct 2011 13:18:19 -0400 Subject: Dabo 0.9.4 Released! References: Message-ID: Ed Leafe wrote: > Yes, it's been over a year, but today we're finally releasing Dabo 0.9.4! > > What can I say? While we've been actively developing Dabo all along, and > committing improvements and fixes regularly, we don't seem to get around to > doing releases as often as we should. Since Dabo has a Web Update feature that > lets developers receive regular updates between releases, most people are > fairly current, but creating a new release will help newcomers to Dabo get up > to speed quicker. > > The changes won't be too big for most current users of the framework, but > compared to the 0.9.3 release, lots has been fixed and improved! Full release > notes are at: http://svn.dabodev.com/dabo/tags/dabo-0.9.4/ChangeLog > > ...but here are just a few of the major changes since 0.9.3: > > - better handling of edge cases in bizobj relations > - addition of support in bizobjs for many-to-many relationships > - improved efficiency in detecting changed records > - added the dDatePicker control > - added the option of vertical text for grid headers > - integrated a code editor into the command window > > You can grab the latest version, as always, from http://dabodev.com/download > > > > -- Ed Leafe What is it? From miki.tebeka at gmail.com Thu Oct 6 13:24:12 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 6 Oct 2011 10:24:12 -0700 (PDT) Subject: L.A. user group? Message-ID: <9383115.2083.1317921852552.JavaMail.geo-discussion-forums@prma7> Greetings, Is there an L.A. Python user group out there? Thanks, -- Miki From wxjmfauth at gmail.com Thu Oct 6 13:41:57 2011 From: wxjmfauth at gmail.com (jmfauth) Date: Thu, 6 Oct 2011 10:41:57 -0700 (PDT) Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> <4e8d231e$0$29978$c3e8da3$5496439d@news.astraweb.com> <4aeb76e9-511f-4a46-94c7-bf2ab84877df@z12g2000yqz.googlegroups.com> Message-ID: <2f816797-7ecc-4c97-8488-8e8f1ffc5b65@t16g2000yqm.googlegroups.com> On 6 oct, 06:39, Greg wrote: > Brilliant! It worked. Thanks! > > Here is the final code for those who are struggling with similar > problems: > > ## open and decode file > # In this case, the encoding comes from the charset argument in a meta > tag > # e.g. > fileObj = open(filePath,"r").read() > fileContent = fileObj.decode("iso-8859-2") > fileSoup = BeautifulSoup(fileContent) > > ## Do some BeautifulSoup magic and preserve unicode, presume result is > saved in 'text' ## > > ## write extracted text to file > f = open(outFilePath, 'w') > f.write(text.encode('utf-8')) > f.close() > or (Python2/Python3) >>> import io >>> with io.open('abc.txt', 'r', encoding='iso-8859-2') as f: ... r = f.read() ... >>> repr(r) u'a\nb\nc\n' >>> with io.open('def.txt', 'w', encoding='utf-8-sig') as f: ... t = f.write(r) ... >>> f.closed True jmf From fzadrozny at appcelerator.com Thu Oct 6 14:03:54 2011 From: fzadrozny at appcelerator.com (Fabio Zadrozny) Date: Thu, 6 Oct 2011 15:03:54 -0300 Subject: PyDev 2.2.3 Released Message-ID: Hi All, PyDev 2.2.3 has been released Details on PyDev: http://pydev.org Details on its development: http://pydev.blogspot.com Release Highlights: ------------------------------- * Performance improvements * Major: Fixed critical issue when dealing with zip files. * Added option to create method whenever a field would be created in quick fixes (and vice-versa), to properly deal with functional programming styles. * Fixed issue where PyDev was changing the image from another plugin in the Project Explorer (i.e.: removing error decorations from JSP). * Fixed issue: if the django models was opened in PyDev, the 'objects' object was not found in the code analysis. * Test runner no longer leaves exception visible. * Fixed issue on Py3: Relative imports are only relative if they have a leading dot (otherwise it always goes to the absolute). * Default is now set to create project with the projects itself as the source folder. * Handling deletion of .class files. * Fixed issue where loading class InterpreterInfo in AdditionalSystemInterpreterInfo.getPersistingFolder ended up raising a BundleStatusException in the initialization. * Fixed some code formatting issues What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python, Jython and IronPython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer Appcelerator http://appcelerator.com/ Aptana http://aptana.com/ PyDev - Python Development Environment for Eclipse http://pydev.org http://pydev.blogspot.com From brian.curtin at gmail.com Thu Oct 6 14:24:34 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Thu, 6 Oct 2011 13:24:34 -0500 Subject: L.A. user group? In-Reply-To: <9383115.2083.1317921852552.JavaMail.geo-discussion-forums@prma7> References: <9383115.2083.1317921852552.JavaMail.geo-discussion-forums@prma7> Message-ID: On Thu, Oct 6, 2011 at 12:24, Miki Tebeka wrote: > Greetings, > > Is there an L.A. Python user group out there? http://socal-piggies.org might work for you. They recently had a meeting in Santa Monica, and I believe many of the members are LA based. From miki.tebeka at gmail.com Thu Oct 6 14:25:08 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 6 Oct 2011 11:25:08 -0700 (PDT) Subject: passing multiple string to a command line option In-Reply-To: References: Message-ID: <22850959.1256.1317925508336.JavaMail.geo-discussion-forums@prcs9> As far as I see, the problem is not in the command line but in system.cpu[i].workload = process[i] call tree. Without seeing the code of SimObject and params I can't tell much more. From miki.tebeka at gmail.com Thu Oct 6 14:25:08 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 6 Oct 2011 11:25:08 -0700 (PDT) Subject: passing multiple string to a command line option In-Reply-To: References: Message-ID: <22850959.1256.1317925508336.JavaMail.geo-discussion-forums@prcs9> As far as I see, the problem is not in the command line but in system.cpu[i].workload = process[i] call tree. Without seeing the code of SimObject and params I can't tell much more. From thudfoo at gmail.com Thu Oct 6 15:22:06 2011 From: thudfoo at gmail.com (xDog Walker) Date: Thu, 6 Oct 2011 12:22:06 -0700 Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file In-Reply-To: <2f816797-7ecc-4c97-8488-8e8f1ffc5b65@t16g2000yqm.googlegroups.com> References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> <4aeb76e9-511f-4a46-94c7-bf2ab84877df@z12g2000yqz.googlegroups.com> <2f816797-7ecc-4c97-8488-8e8f1ffc5b65@t16g2000yqm.googlegroups.com> Message-ID: <201110061222.07161.thudfoo@gmail.com> On Thursday 2011 October 06 10:41, jmfauth wrote: > or ?(Python2/Python3) > > >>> import io > >>> with io.open('abc.txt', 'r', encoding='iso-8859-2') as f: > > ... ? ? r = f.read() > ... > > >>> repr(r) > > u'a\nb\nc\n' > > >>> with io.open('def.txt', 'w', encoding='utf-8-sig') as f: > > ... ? ? t = f.write(r) > ... > > >>> f.closed > > True > > jmf What is this io of which you speak? -- I have seen the future and I am not in it. From gordon at panix.com Thu Oct 6 15:29:51 2011 From: gordon at panix.com (John Gordon) Date: Thu, 6 Oct 2011 19:29:51 +0000 (UTC) Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> <4aeb76e9-511f-4a46-94c7-bf2ab84877df@z12g2000yqz.googlegroups.com> <2f816797-7ecc-4c97-8488-8e8f1ffc5b65@t16g2000yqm.googlegroups.com> Message-ID: In xDog Walker writes: > What is this io of which you speak? It was introduced in Python 2.6. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From nt_mahmood at yahoo.com Thu Oct 6 15:51:58 2011 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Thu, 6 Oct 2011 12:51:58 -0700 (PDT) Subject: passing multiple string to a command line option In-Reply-To: <22850959.1256.1317925508336.JavaMail.geo-discussion-forums@prcs9> References: <22850959.1256.1317925508336.JavaMail.geo-discussion-forums@prcs9> Message-ID: <1317930718.65743.YahooMailNeo@web111724.mail.gq1.yahoo.com> >Without seeing the code of SimObject and params I can't tell much more. >? ? File "/home/mahmood/gem5/src/python/m5/params.py", line 159, in convert >? ? ? return self.ptype(value) following is part of params.py and I marked line 159. I didn't wrote this code so changing this may cause problem with other files. If there is an alternative for doing such thing "passing multiple strings to command line option", it is? much better. ?# Regular parameter description. class ParamDesc(object): ??? file_ext = 'ptype' ??? def __init__(self, ptype_str, ptype, *args, **kwargs): ??????? self.ptype_str = ptype_str ??????? # remember ptype only if it is provided ??????? if ptype != None: ??????????? self.ptype = ptype ??????? if args: ??????????? if len(args) == 1: ??????????????? self.desc = args[0] ??????????? elif len(args) == 2: ??????????????? self.default = args[0] ??????????????? self.desc = args[1] ??????????? else: ??????????????? raise TypeError, 'too many arguments' ??????? if kwargs.has_key('desc'): ??????????? assert(not hasattr(self, 'desc')) ??????????? self.desc = kwargs['desc'] ??????????? del kwargs['desc'] ??????? if kwargs.has_key('default'): ??????????? assert(not hasattr(self, 'default')) ??????????? self.default = kwargs['default'] ??????????? del kwargs['default'] ??????? if kwargs: ??????????? raise TypeError, 'extra unknown kwargs %s' % kwargs ??????? if not hasattr(self, 'desc'): ??????????? raise TypeError, 'desc attribute missing' ??? def __getattr__(self, attr): ??????? if attr == 'ptype': ??????????? ptype = SimObject.allClasses[self.ptype_str] ??????????? assert isSimObjectClass(ptype) ??????????? self.ptype = ptype ??????????? return ptype ??????? raise AttributeError, "'%s' object has no attribute '%s'" % \ ????????????? (type(self).__name__, attr) ??? def convert(self, value): ??????? if isinstance(value, proxy.BaseProxy): ??????????? value.set_param_desc(self) ??????????? return value ??????? if not hasattr(self, 'ptype') and isNullPointer(value): ??????????? # deferred evaluation of SimObject; continue to defer if ??????????? # we're just assigning a null pointer ??????????? return value ??????? if isinstance(value, self.ptype): ??????????? return value ??????? if isNullPointer(value) and isSimObjectClass(self.ptype): ??????????? return value ??????? return self.ptype(value)???????????? # LINE 159 ??? def cxx_predecls(self, code): ??????? self.ptype.cxx_predecls(code) ??? def swig_predecls(self, code): ??????? self.ptype.swig_predecls(code) ??? def cxx_decl(self, code): ??????? code('${{self.ptype.cxx_type}} ${{self.name}};') // Naderan *Mahmood; ----- Original Message ----- From: Miki Tebeka To: comp.lang.python at googlegroups.com Cc: python mailing list ; Mahmood Naderan Sent: Thursday, October 6, 2011 9:55 PM Subject: Re: passing multiple string to a command line option As far as I see, the problem is not in the command line but in? ? system.cpu[i].workload = process[i] call tree. Without seeing the code of SimObject and params I can't tell much more. From Joshua.R.English at gmail.com Thu Oct 6 21:14:26 2011 From: Joshua.R.English at gmail.com (Josh English) Date: Thu, 6 Oct 2011 18:14:26 -0700 (PDT) Subject: Deleting files on a shared server Message-ID: <24959174.190.1317950066875.JavaMail.geo-discussion-forums@prho12> This is a follow-up to some questions I posted a month or two ago. I have two programs running on various Windows XP boxes, sharing several resource files on a Windows 2003 server. It's a mapped drive on the workstations to a shared folder. I am using a locking utility that works by creating ".lock" files in the shared folder and deleting those files when the program is done with them. To delete the files, I am using os.unlink. One lock file refuses to disappear, even though I have code at both application startup and shutdown (on the OnInit and OnExit methods to the wxPython Application object) that hunts down .lock files and deletes them. Is there a better command than os.unlink to delete a file on Windows 2003 server? Josh From steve+comp.lang.python at pearwood.info Thu Oct 6 22:02:26 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 07 Oct 2011 13:02:26 +1100 Subject: A tuple in order to pass returned values ? References: Message-ID: <4e8e5db3$0$29967$c3e8da3$5496439d@news.astraweb.com> Jean-Michel Pichavant wrote: > In a general manner, ppl will tend to use the minimum arguments > required. However, do not pack values into tuple if they are not related. How would you return multiple values if not in a tuple? Tuples are *the* mechanism for returning multiple values in Python. If you're doing something else, you're wasting your time. > A better thing to do would be to use objects instead of tuples, tuples > can serve as lazy structures for small application/script, they can > become harmful in more complexe applications, especialy when used in > public interfaces. First off, tuples *are* objects, like everything else in Python. If you are creating custom classes *just* to hold state, instead of using a tuple, you are wasting time. Instead of this: class Record: def __init__(self, x, y, z): self.x = x self.y = y self.z = z result = Record(1, 2, 3) Just use a tuple or a namedtuple: the work is already done for you, you have a well-written, fast, rich data structure ready to use. For two or three items, or for short-lived results that only get used once, an ordinary tuple is fine, but otherwise a namedtuple is much better: from collections import namedtuple result = namedtuple('Record', 'x y z')(1, 2, 3) -- Steven From steve+comp.lang.python at pearwood.info Thu Oct 6 23:04:57 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 07 Oct 2011 14:04:57 +1100 Subject: Deleting files on a shared server References: <24959174.190.1317950066875.JavaMail.geo-discussion-forums@prho12> Message-ID: <4e8e6c5a$0$30002$c3e8da3$5496439d@news.astraweb.com> Josh English wrote: > This is a follow-up to some questions I posted a month or two ago. I have > two programs running on various Windows XP boxes, sharing several resource > files on a Windows 2003 server. It's a mapped drive on the workstations to > a shared folder. > > I am using a locking utility that works by creating ".lock" files in the > shared folder and deleting those files when the program is done with them. > > To delete the files, I am using os.unlink. How and when? If you are deleting the files using a __del__ handler in an instance, it is quick possible that it is never being run, or not being run when you think it is. For file locking, you should consider using a portable solution like this one: http://code.activestate.com/recipes/65203-portalocker-cross-platform-posixnt-api-for-flock-s/ > One lock file refuses to disappear, even though I have code at both > application startup and shutdown (on the OnInit and OnExit methods to the > wxPython Application object) that hunts down .lock files and deletes them. Perhaps the file is open and so can't be deleted under Windows. Are you getting an exception when you try to unlink the file? If so, what does it say? > Is there a better command than os.unlink to delete a file on Windows 2003 > server? No. os.unlink is a wrapper around your system's unlink command -- if it can't delete the file, you can't delete the file. -- Steven From miki.tebeka at gmail.com Thu Oct 6 23:05:30 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 6 Oct 2011 20:05:30 -0700 (PDT) Subject: L.A. user group? In-Reply-To: References: <9383115.2083.1317921852552.JavaMail.geo-discussion-forums@prma7> Message-ID: <2719923.311.1317956730911.JavaMail.geo-discussion-forums@prfp13> Thanks! From miki.tebeka at gmail.com Thu Oct 6 23:05:30 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 6 Oct 2011 20:05:30 -0700 (PDT) Subject: L.A. user group? In-Reply-To: References: <9383115.2083.1317921852552.JavaMail.geo-discussion-forums@prma7> Message-ID: <2719923.311.1317956730911.JavaMail.geo-discussion-forums@prfp13> Thanks! From wuwei23 at gmail.com Thu Oct 6 23:10:56 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 6 Oct 2011 20:10:56 -0700 (PDT) Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> <4e8bed30$0$29978$c3e8da3$5496439d@news.astraweb.com> <87wrcjzmql.fsf@benfinney.id.au> Message-ID: <65fb52c4-0b30-43c7-a9f4-153d18d72ed4@hd1g2000vbb.googlegroups.com> Dennis Lee Bieber wrote: > ? ? ? ? While I wouldn't want to write an FFT in COBOL, one can't deny that > laying out fixed width reports and moving blocks of decimal data between > record layouts is quite easy in COBOL. Well, sure, but there's still plenty of pain in the verbosity :) From Joshua.R.English at gmail.com Fri Oct 7 01:08:19 2011 From: Joshua.R.English at gmail.com (Josh English) Date: Thu, 6 Oct 2011 22:08:19 -0700 (PDT) Subject: Deleting files on a shared server In-Reply-To: <24959174.190.1317950066875.JavaMail.geo-discussion-forums@prho12> References: <24959174.190.1317950066875.JavaMail.geo-discussion-forums@prho12> Message-ID: <27274396.452.1317964099801.JavaMail.geo-discussion-forums@prib32> The problem shows up when the application starts. It tries to read the file but the lock mechanism times out because the file is still around after the last time the application ran. It's a wxPython program. The code to unlink the .lock files is run in the wxApp.OnInit method (before any code to open these resources) and in the wxApp.OnExit method. I know both of these methods are being called. The locking mechanism I am using can be found at http://www.evanfosmark.com/2009/01/cross-platform-file-locking-support-in-python/ The clearing code is: import os import fnmatch files = fnmatch.filter(os.listdir(self.Options.DataDir), "*.lock") for f in files: os.unlink(os.path.abspath(os.path.join(self.Options.DataDir, f))) The Options object has a property called DataDir. MMM... Now that I sit down to test abso-frikkin'-lutely that this code does what I want it to do, it appears not to do this at all. The files list I build doesn't work and returns an empty list. I may have found a workaround using glob. Now my face is red. From masood.524 at gmail.com Fri Oct 7 01:18:04 2011 From: masood.524 at gmail.com (masood shaik) Date: Thu, 6 Oct 2011 22:18:04 -0700 (PDT) Subject: database connection Message-ID: <618adb1f-73b4-4372-9ad4-4b2f8c312601@h10g2000yqd.googlegroups.com> Hi can u please tell me how we can connect to database without changing the permission of db file using sqlite3 From rustompmody at gmail.com Fri Oct 7 01:40:35 2011 From: rustompmody at gmail.com (rusi) Date: Thu, 6 Oct 2011 22:40:35 -0700 (PDT) Subject: PyDev 2.2.3 Released References: Message-ID: On Oct 6, 11:03?pm, Fabio Zadrozny wrote: > Hi All, > > PyDev 2.2.3 has been released > > Details on PyDev:http://pydev.org > Details on its development:http://pydev.blogspot.com On my debian box I get: $ /opt/Aptana\ Studio\ 3/AptanaStudio3 HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught ReferenceError: loadPortal is not defined,http://content.aptana.com/aptana/my_aptana/? content=start&id=83fef29f-0f3d-40db-8b9a-0f417b84cd8c&v=3.0.0.1316445268&ts=1317965412438&fg=f8f8f8&p=O&bg=141414&ch=edeceb: 59) HandleConsoleMessage(AJS.Confluence: run binder components,http:// wiki.appcelerator.org/s/en/2159/26/58/_/download/superbatch/js/ batch.js:436) HandleConsoleMessage(Dropdown width override occurred,http:// wiki.appcelerator.org/s/en/2159/26/58/_/download/superbatch/js/ batch.js:436) HandleConsoleMessage(Dropdown width override occurred,http:// wiki.appcelerator.org/s/en/2159/26/58/_/download/superbatch/js/ batch.js:436) HandleConsoleMessage(Drag and Drop: requesting translation,http:// wiki.appcelerator.org/s/en/2159/26/58/_/download/superbatch/js/ batch.js:436) HandleConsoleMessage(DragAndDropUtils: computed cache URL: /s/en/ 2159/26/1.0.16/_/plugins/drag-and-drop/i18n.action?locale=en_GB,http:// wiki.appcelerator.org/s/en/2159/26/58/_/download/superbatch/js/ batch.js:436) HandleConsoleMessage(Overriding default quick search,http:// wiki.appcelerator.org/s/en/2159/26/58/_/download/superbatch/js/ batch.js:436) HandleConsoleMessage(Applying doc-theme quick search,http:// wiki.appcelerator.org/s/en/2159/26/58/_/download/superbatch/js/ batch.js:436) HandleConsoleMessage(confluence-keyboard-shortcuts initialising,http:// wiki.appcelerator.org/s/en/2159/26/58/_/download/superbatch/js/ batch.js:436) [1007/110047:ERROR:base/native_library_linux.cc(28)] dlopen failed when trying to open /opt/jre1.6.0_20/lib/i386/libnpjp2.so: /opt/ jre1.6.0_20/lib/i386/libnpjp2.so: undefined symbol: __gxx_personality_v0 Job found still running after platform shutdown. Jobs should be canceled by the plugin that scheduled them during shutdown: com.aptana.usage.StudioAnalytics$1 From selahattin_ay at msn.com Fri Oct 7 02:23:57 2011 From: selahattin_ay at msn.com (selahattin ay) Date: Fri, 7 Oct 2011 06:23:57 +0000 Subject: sending ftp file list to mail??? Message-ID: hi all. I want to get my ftp list and send the list to my mail adress... my codes are from ftplib import FTP import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMETextbaglanti = FTP("ftp.guncelyorum.org") baglanti.login("******", "*******") print baglanti.dir() posta = MIMEMultipart()def posta_olustur(): posta['Subject']=konu posta['From']=gmail_kullanici posta['To']=kime posta.attach(MIMEText(baglanti.retrlines("LIST"))) <------ what can I do for here def posta_gonder(): smtpserver = smtplib.SMTP("smtp.gmail.com",587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(gmail_kullanici, gmail_sifre) print "baglanti saglandi" smtpserver.sendmail(gmail_kullanici, kime, posta.as_string()) print "Posta Gonderildi" smtpserver.close() # mail to kime = raw_input("Kime gonderecesiniz?: ") # gmail user namegmail_kullanici = raw_input("gmail kullanici adiniz: ") #gmail passgmail_sifre = raw_input("Gmail sifreniz: ") #subjectkonu = raw_input ("Posta Konusu: ") posta_olustur() posta_gonder() -------------- next part -------------- An HTML attachment was scrubbed... URL: From lucaberto at libero.it Fri Oct 7 03:19:35 2011 From: lucaberto at libero.it (luca72) Date: Fri, 7 Oct 2011 00:19:35 -0700 (PDT) Subject: matplotlib on osx 10.6 Message-ID: <3ba1a0ca-d959-4367-b5f8-fff283f577cf@g29g2000yqh.googlegroups.com> hello i try to install matplotlib on osx 10.6 , i have also installed freetype libpng and numpy but i get this error: BUILDING MATPLOTLIB matplotlib: 1.1.0 python: 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] platform: darwin REQUIRED DEPENDENCIES numpy: 1.2.1 freetype2: found, but unknown version (no pkg-config) * WARNING: Could not find 'freetype2' headers in any * of '.', './freetype2'. OPTIONAL BACKEND DEPENDENCIES libpng: found, but unknown version (no pkg-config) * Could not find 'libpng' headers in any of '.' Tkinter: Tkinter: 67083, Tk: 8.5, Tcl: 8.5 Gtk+: no * Building for Gtk+ requires pygtk; you must be able * to "import gtk" in your build/install environment Mac OS X native: yes Qt: no Qt4: Qt: 4.7.0, PyQt4: 4.8.2 Cairo: no OPTIONAL DATE/TIMEZONE DEPENDENCIES datetime: present, version unknown dateutil: present, version unknown pytz: matplotlib will provide adding pytz OPTIONAL USETEX DEPENDENCIES dvipng: no ghostscript: /bin/sh: gs: command not found latex: no [Edit setup.cfg to suppress the above messages] ============================================================================ pymods ['pylab'] packages ['matplotlib', 'matplotlib.backends', 'matplotlib.backends.qt4_editor', 'matplotlib.projections', 'matplotlib.testing', 'matplotlib.testing.jpl_units', 'matplotlib.tests', 'mpl_toolkits', 'mpl_toolkits.mplot3d', 'mpl_toolkits.axes_grid', 'mpl_toolkits.axes_grid1', 'mpl_toolkits.axisartist', 'matplotlib.sphinxext', 'matplotlib.tri', 'matplotlib.delaunay', 'pytz'] running build running build_py copying lib/matplotlib/mpl-data/matplotlibrc -> build/lib.macosx-10.6- universal-2.6/matplotlib/mpl-data copying lib/matplotlib/mpl-data/matplotlib.conf -> build/ lib.macosx-10.6-universal-2.6/matplotlib/mpl-data running build_ext building 'matplotlib.ft2font' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv - Os -Wall -DENABLE_DTRACE -arch i386 -arch ppc -arch x86_64 -pipe - DPY_ARRAY_UNIQUE_SYMBOL=MPL_ARRAY_API -DPYCXX_ISO_CPP_LIB=1 -I/System/ Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/ numpy/core/include -I. -I/System/Library/Frameworks/Python.framework/ Versions/2.6/Extras/lib/python/numpy/core/include/freetype2 -I./ freetype2 -I/System/Library/Frameworks/Python.framework/Versions/2.6/ include/python2.6 -c src/ft2font.cpp -o build/temp.macosx-10.6- universal-2.6/src/ft2font.o In file included from src/ft2font.h:16, from src/ft2font.cpp:3: /usr/local/include/ft2build.h:56:38: error: freetype/config/ ftheader.h: No such file or directory In file included from src/ft2font.cpp:3: src/ft2font.h:17:10: error: #include expects "FILENAME" or src/ft2font.h:18:10: error: #include expects "FILENAME" or src/ft2font.h:19:10: error: #include expects "FILENAME" or src/ft2font.h:20:10: error: #include expects "FILENAME" or src/ft2font.h:21:10: error: #include expects "FILENAME" or In file included from src/ft2font.cpp:3: src/ft2font.h:35: error: ?FT_Bitmap? has not been declared src/ft2font.h:35: error: ?FT_Int? has not been declared src/ft2font.h:35: error: ?FT_Int? has not been declared src/ft2font.h:91: error: expected ?,? or ?...? before ?&? token src/ft2font.h:91: error: ISO C++ forbids declaration of ?FT_Face? with no type src/ft2font.h:138: error: ?FT_Face? does not name a type src/ft2font.h:139: error: ?FT_Matrix? does not name a type src/ft2font.h:140: error: ?FT_Vector? does not name a type src/ft2font.h:141: error: ?FT_Error? does not name a type src/ft2font.h:142: error: ?FT_Glyph? was not declared in this scope src/ft2font.h:142: error: template argument 1 is invalid src/ft2font.h:142: error: template argument 2 is invalid src/ft2font.h:143: error: ?FT_Vector? was not declared in this scope src/ft2font.h:143: error: template argument 1 is invalid src/ft2font.h:143: error: template argument 2 is invalid src/ft2font.h:149: error: ?FT_BBox? does not name a type src/ft2font.cpp:51: error: ?FT_Library? does not name a type src/ft2font.cpp:114: error: variable or field ?draw_bitmap? declared void src/ft2font.cpp:114: error: ?FT_Bitmap? was not declared in this scope src/ft2font.cpp:114: error: ?bitmap? was not declared in this scope src/ft2font.cpp:115: error: ?FT_Int? was not declared in this scope src/ft2font.cpp:116: error: ?FT_Int? was not declared in this scope /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/ python/numpy/core/include/numpy/__multiarray_api.h:958: warning: ?int _import_array()? defined but not used In file included from src/ft2font.h:16, from src/ft2font.cpp:3: /usr/local/include/ft2build.h:56:38: error: freetype/config/ ftheader.h: No such file or directory In file included from src/ft2font.cpp:3: src/ft2font.h:17:10: error: #include expects "FILENAME" or src/ft2font.h:18:10: error: #include expects "FILENAME" or src/ft2font.h:19:10: error: #include expects "FILENAME" or src/ft2font.h:20:10: error: #include expects "FILENAME" or src/ft2font.h:21:10: error: #include expects "FILENAME" or In file included from src/ft2font.cpp:3: src/ft2font.h:35: error: ?FT_Bitmap? has not been declared src/ft2font.h:35: error: ?FT_Int? has not been declared src/ft2font.h:35: error: ?FT_Int? has not been declared src/ft2font.h:91: error: expected ?,? or ?...? before ?&? token src/ft2font.h:91: error: ISO C++ forbids declaration of ?FT_Face? with no type src/ft2font.h:138: error: ?FT_Face? does not name a type src/ft2font.h:139: error: ?FT_Matrix? does not name a type src/ft2font.h:140: error: ?FT_Vector? does not name a type src/ft2font.h:141: error: ?FT_Error? does not name a type src/ft2font.h:142: error: ?FT_Glyph? was not declared in this scope src/ft2font.h:142: error: template argument 1 is invalid src/ft2font.h:142: error: template argument 2 is invalid src/ft2font.h:143: error: ?FT_Vector? was not declared in this scope src/ft2font.h:143: error: template argument 1 is invalid src/ft2font.h:143: error: template argument 2 is invalid src/ft2font.h:149: error: ?FT_BBox? does not name a type src/ft2font.cpp:51: error: ?FT_Library? does not name a type src/ft2font.cpp:114: error: variable or field ?draw_bitmap? declared void src/ft2font.cpp:114: error: ?FT_Bitmap? was not declared in this scope src/ft2font.cpp:114: error: ?bitmap? was not declared in this scope src/ft2font.cpp:115: error: ?FT_Int? was not declared in this scope src/ft2font.cpp:116: error: ?FT_Int? was not declared in this scope /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/ python/numpy/core/include/numpy/__multiarray_api.h:958: warning: ?int _import_array()? defined but not used In file included from src/ft2font.h:16, from src/ft2font.cpp:3: /usr/local/include/ft2build.h:56:38: error: freetype/config/ ftheader.h: No such file or directory In file included from src/ft2font.cpp:3: src/ft2font.h:17:10: error: #include expects "FILENAME" or src/ft2font.h:18:10: error: #include expects "FILENAME" or src/ft2font.h:19:10: error: #include expects "FILENAME" or src/ft2font.h:20:10: error: #include expects "FILENAME" or src/ft2font.h:21:10: error: #include expects "FILENAME" or In file included from src/ft2font.cpp:3: src/ft2font.h:35: error: ?FT_Bitmap? has not been declared src/ft2font.h:35: error: ?FT_Int? has not been declared src/ft2font.h:35: error: ?FT_Int? has not been declared src/ft2font.h:91: error: expected ?,? or ?...? before ?&? token src/ft2font.h:91: error: ISO C++ forbids declaration of ?FT_Face? with no type src/ft2font.h:138: error: ?FT_Face? does not name a type src/ft2font.h:139: error: ?FT_Matrix? does not name a type src/ft2font.h:140: error: ?FT_Vector? does not name a type src/ft2font.h:141: error: ?FT_Error? does not name a type src/ft2font.h:142: error: ?FT_Glyph? was not declared in this scope src/ft2font.h:142: error: template argument 1 is invalid src/ft2font.h:142: error: template argument 2 is invalid src/ft2font.h:143: error: ?FT_Vector? was not declared in this scope src/ft2font.h:143: error: template argument 1 is invalid src/ft2font.h:143: error: template argument 2 is invalid src/ft2font.h:149: error: ?FT_BBox? does not name a type src/ft2font.cpp:51: error: ?FT_Library? does not name a type src/ft2font.cpp:114: error: variable or field ?draw_bitmap? declared void src/ft2font.cpp:114: error: ?FT_Bitmap? was not declared in this scope src/ft2font.cpp:114: error: ?bitmap? was not declared in this scope src/ft2font.cpp:115: error: ?FT_Int? was not declared in this scope src/ft2font.cpp:116: error: ?FT_Int? was not declared in this scope /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/ python/numpy/core/include/numpy/__multiarray_api.h:958: warning: ?int _import_array()? defined but not used lipo: can't open input file: /var/folders/wA/wAdFPXZ7FC0P4R1RaKSw3k++ +TI/-Tmp-//ccFESr3g.out (No such file or directory) error: command 'gcc-4.2' failed with exit status 1 Please help me From mail at timgolden.me.uk Fri Oct 7 03:45:32 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 07 Oct 2011 08:45:32 +0100 Subject: Deleting files on a shared server In-Reply-To: <24959174.190.1317950066875.JavaMail.geo-discussion-forums@prho12> References: <24959174.190.1317950066875.JavaMail.geo-discussion-forums@prho12> Message-ID: <4E8EAE1C.1050104@timgolden.me.uk> On 07/10/2011 02:14, Josh English wrote: > This is a follow-up to some questions I posted a month or two ago. I > have two programs running on various Windows XP boxes, sharing > several resource files on a Windows 2003 server. It's a mapped drive > on the workstations to a shared folder. > > I am using a locking utility that works by creating ".lock" files in > the shared folder and deleting those files when the program is done > with them. > > To delete the files, I am using os.unlink. > > One lock file refuses to disappear, even though I have code at both > application startup and shutdown (on the OnInit and OnExit methods to > the wxPython Application object) that hunts down .lock files and > deletes them. Assuming that your code paths succeed and that the unlink actually happens, it is possible for files to continue to exist after they have been successfully deleted. This happens if another process has opened them with share-delete mode; typically this will be a virus checker or a process like the TortoiseSVN cache (or its counterparts for other VCS). The file won't actually disappear until the last handle on it is released. TJG From gagsl-py2 at yahoo.com.ar Fri Oct 7 04:16:40 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Oct 2011 05:16:40 -0300 Subject: database connection References: <618adb1f-73b4-4372-9ad4-4b2f8c312601@h10g2000yqd.googlegroups.com> Message-ID: En Fri, 07 Oct 2011 02:18:04 -0300, masood shaik escribi?: > can u please tell me how we can connect to database without changing > the permission of db file using sqlite3 The OS user who executes the Python script must have read (and write, usually) access to the database file - *any* OS user who can read the database file can connect to it. sqlite does not have internal users, and does not implement GRANT/REVOKE statements. -- Gabriel Genellina From poalman at gmail.com Fri Oct 7 04:29:29 2011 From: poalman at gmail.com (Paul) Date: Fri, 7 Oct 2011 08:29:29 +0000 (UTC) Subject: Thread handling issue Message-ID: I'm wondering what the best solution for this problem is. I've got a wxpython app, in one part a user makes some selections then opens a dialog to select where to output. At which point the app starts a thread processing their selection while they're choosing an output location, hopefully ready for when they're done. My problem is if the user doesn't select an output location and cancels the dialog to go back to the selection I want to terminate the thread to avoid the user opening and closing the output selection firing off a ton of threads. As there's no inbuilt way of killing threads I was wondering the best way to prevent this? From lucaberto at libero.it Fri Oct 7 04:32:36 2011 From: lucaberto at libero.it (luca72) Date: Fri, 7 Oct 2011 01:32:36 -0700 (PDT) Subject: matplotlib on osx 10.6 References: <3ba1a0ca-d959-4367-b5f8-fff283f577cf@g29g2000yqh.googlegroups.com> Message-ID: <72680a34-62d1-47d2-b85f-b699900b8f77@f6g2000vbm.googlegroups.com> Hello i have solved installing gfortran and pkgconfig Luca From gagsl-py2 at yahoo.com.ar Fri Oct 7 04:34:58 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Oct 2011 05:34:58 -0300 Subject: How to inspect slot wrappers arguments in Python? References: Message-ID: En Sat, 01 Oct 2011 12:13:45 -0300, julian bilcke escribi?: > I would like to get the list of parameters I need to initialize an AST > node. > > I'm trying to use the `inspect` module, however it seems I can't use it > on a > built-in (native?) class, or else I misunderstood. [...] > > >>> import inspect > >>> import ast > >>> inspect.getargspec(ast.If.__init__) > Traceback (most recent call last): > File "", line 1, in > File > "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", > line 813, in getargspec > raise TypeError('{!r} is not a Python function'.format(func)) > TypeError: is not a > Python function > > I am wondering if there is another way to get these parameters > automatically? (ie. without compiling myself a dict) I'm afraid there is no way; this kind of introspection does not work for functions written in C. The function itself usually has a generic signature resembling (*args, **kw), and its parameters are usually unpacked calling a suitable variant of PyArg_ParseXXX. The information about the number and type of expected arguments is encoded in its 'format' parameter, and is not stored anywhere. -- Gabriel Genellina From mail at timgolden.me.uk Fri Oct 7 04:45:38 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 07 Oct 2011 09:45:38 +0100 Subject: Thread handling issue In-Reply-To: References: Message-ID: <4E8EBC32.9060000@timgolden.me.uk> On 07/10/2011 09:29, Paul wrote: > I'm wondering what the best solution for this problem is. > > I've got a wxpython app, in one part a user makes some selections then opens a > dialog to select where to output. At which point the app starts a thread > processing their selection while they're choosing an output location, hopefully > ready for when they're done. > > My problem is if the user doesn't select an output location and cancels the > dialog to go back to the selection I want to terminate the thread to avoid the > user opening and closing the output selection firing off a ton of threads. > > As there's no inbuilt way of killing threads I was wondering the best way to > prevent this? The most common approach is to have the thread monitor an event which is set if, for example, the user cancels. The thread may of course have to wait, for example, for a long-running database query to complete before it can discover that its time has been wasted :) The exact mechanism will depend on how your code is structured, what the thread is doing, and how it's passing anything back to the main thread. TJG From jyesudian at gmail.com Fri Oct 7 05:01:46 2011 From: jyesudian at gmail.com (Yesudian Rajkumar Johnkoilpillai) Date: Fri, 7 Oct 2011 14:31:46 +0530 Subject: Python selenium web driver Message-ID: Hi, I am looking into using Selenium 2.0 for launching Firefox and browse few sites. I am using Python APIs to talk to webdriver on Ubuntu 11.04. I am basically trying to follow the steps mentioned at http://pypi.python.org/pypi/selenium . When I run the program, it throws error as below. yesudian at yesudian-virtual-machine:~/Try$ sudo python five.py [sudo] password for yesudian: Traceback (most recent call last): File "five.py", line 6, in browser = webdriver.Firefox() # Get local session of firefox File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py", line 46, in __init__ self.binary, timeout), File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/extension_connection.py", line 46, in __init__ self.binary.launch_browser(self.profile) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 44, in launch_browser self._wait_until_connectable() File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 87, in _wait_until_connectable raise WebDriverException("Can't load the profile. Profile Dir : %s" % self.profile.path) selenium.common.exceptions.WebDriverException: Message: "Can't load the profile. Profile Dir : /tmp/tmpCR4CB7" I tried to launch chrome also and the same issue happens. Do you have any thoughts ? Regards Yesudian Rajkumar -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri Oct 7 05:16:48 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Oct 2011 06:16:48 -0300 Subject: sending ftp file list to mail??? References: Message-ID: En Fri, 07 Oct 2011 03:23:57 -0300, selahattin ay escribi?: > hi all. I want to get my ftp list and send the list to my mail adress... > my codes are And your problem is...? -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri Oct 7 05:28:28 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Oct 2011 06:28:28 -0300 Subject: sending ftp file list to mail??? References: Message-ID: En Fri, 07 Oct 2011 03:23:57 -0300, selahattin ay escribi?: > hi all. I want to get my ftp list and send the list to my mail adress... > my codes are > baglanti = FTP("ftp.guncelyorum.org") > baglanti.login("******", "*******") > print baglanti.dir() > posta = MIMEMultipart() > def posta_olustur(): > posta['Subject']=konu > posta['From']=gmail_kullanici > posta['To']=kime > posta.attach(MIMEText(baglanti.retrlines("LIST"))) <------ what > can I do for here Ah, I didn't notice that part. MIMEText expects a string. retrlines, by default, outputs to stdout, isn't very useful. Try this: def posta_olustur(): ... lines = [] baglanti.retrlines("LIST", lines.append) text = '\n'.join(lines) posta.attach(MIMEText(text)) -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri Oct 7 05:37:12 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Oct 2011 06:37:12 -0300 Subject: socket.getsockname is returning junk!! References: <02EA6D704E30CE499C5071776509A925F5C8F8@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: En Wed, 05 Oct 2011 08:56:08 -0300, Wong Wah Meng-R32813 escribi?: > I am migrating my application from python 1.5.2 to 2.7.1. One of the > existing code breaks. The getsockname method from socket object somehow > returns me with some number which I deem as junk, rather than the > listening port as I would have expected in the older python. Has anyone > seen the same thing or is it due to my python is built with some > corrupted library or something? > > > $ python > Python 2.7.1 (r271:86832, Oct 5 2011, 18:34:15) [C] on hp-ux11 > Type "help", "copyright", "credits" or "license" for more information. >>>> import socket >>>> sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) >>>> sock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 ) >>>> sock.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1 ) >>>> sock.setsockopt( socket.IPPROTO_TCP, 1, 1 ) >>>> server_address=('zmy02hp3', 11111) >>>> sock.bind(server_address) >>>> sock.getsockname() > (0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') > > In python 1.5.2 >>>> server_address=('zmy02aix04', 11111) >>>> sock.bind(server_address) >>>> sock.getsockname() > ('10.228.51.41', 11111) I'd say it's a problem with the _socket module; did the unit tests flag anything when you built Python? On Windows, Python 2.7.1: >>> server_address=('lepton', 11111) >>> sock.bind(server_address) >>> sock.getsockname() ('127.0.0.1', 11111) -- Gabriel Genellina From jeanmichel at sequans.com Fri Oct 7 05:43:30 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 07 Oct 2011 11:43:30 +0200 Subject: A tuple in order to pass returned values ? In-Reply-To: <4e8e5db3$0$29967$c3e8da3$5496439d@news.astraweb.com> References: <4e8e5db3$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E8EC9C2.1080306@sequans.com> Steven D'Aprano wrote: > Jean-Michel Pichavant wrote: > > >> In a general manner, ppl will tend to use the minimum arguments >> required. However, do not pack values into tuple if they are not related. >> > > How would you return multiple values if not in a tuple? > > Tuples are *the* mechanism for returning multiple values in Python. If > you're doing something else, you're wasting your time. > > > >> A better thing to do would be to use objects instead of tuples, tuples >> can serve as lazy structures for small application/script, they can >> become harmful in more complexe applications, especialy when used in >> public interfaces. >> > > First off, tuples *are* objects, like everything else in Python. > > If you are creating custom classes *just* to hold state, instead of using a > tuple, you are wasting time. Instead of this: > > class Record: > def __init__(self, x, y, z): > self.x = x > self.y = y > self.z = z > > result = Record(1, 2, 3) > > Just use a tuple or a namedtuple: the work is already done for you, you have > a well-written, fast, rich data structure ready to use. For two or three > items, or for short-lived results that only get used once, an ordinary > tuple is fine, but otherwise a namedtuple is much better: > > from collections import namedtuple > result = namedtuple('Record', 'x y z')(1, 2, 3) > > I don't have access to namedtuple, working with python 2.5 It sounds to me that namedtuple exactly tries to fix what I dislike in tuples : undocumented packing of unrelated data. However, I'm not sure it fixes the main issue: unpacking. Unpacking prevents you from adding any additional fields to your 'tuple' without breaking any line of code that was unpacking the tuple (to oppose to accessing an object attribute). And it did annoy me a lot when improving applications. Now I'm using tuples only in small applications, and try to avoid unpacking as much as possible. namedtuple sounds great (if you don't use unpacking :o) ), too bad it is available only from python 2.6. JM From r32813 at freescale.com Fri Oct 7 05:48:58 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Fri, 7 Oct 2011 09:48:58 +0000 Subject: socket.getsockname is returning junk!! In-Reply-To: References: <02EA6D704E30CE499C5071776509A925F5C8F8@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <02EA6D704E30CE499C5071776509A925F5D440@039-SN1MPN1-003.039d.mgd.msft.net> Thanks. Someone pointed out that this could be due to a corrupted build, which I revisited the process. I included -lxnet in the linking process of the build, and this problem is resolved. The -lxnet was stated in README file for HP-UX Itanium build, which I somehow dropped it out in the middle of the process and wasn't aware it was essential as excluding it cost me the junk I was seeing. Problem solved!! Thanks a lot for reverting. :) Regards, Wah Meng -----Original Message----- From: python-list-bounces+wahmeng=freescale.com at python.org [mailto:python-list-bounces+wahmeng=freescale.com at python.org] On Behalf Of Gabriel Genellina Sent: Friday, October 07, 2011 5:37 PM To: python-list at python.org Subject: Re: socket.getsockname is returning junk!! En Wed, 05 Oct 2011 08:56:08 -0300, Wong Wah Meng-R32813 escribi?: > I am migrating my application from python 1.5.2 to 2.7.1. One of the > existing code breaks. The getsockname method from socket object somehow > returns me with some number which I deem as junk, rather than the > listening port as I would have expected in the older python. Has anyone > seen the same thing or is it due to my python is built with some > corrupted library or something? > > > $ python > Python 2.7.1 (r271:86832, Oct 5 2011, 18:34:15) [C] on hp-ux11 > Type "help", "copyright", "credits" or "license" for more information. >>>> import socket >>>> sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) >>>> sock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 ) >>>> sock.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1 ) >>>> sock.setsockopt( socket.IPPROTO_TCP, 1, 1 ) >>>> server_address=('zmy02hp3', 11111) >>>> sock.bind(server_address) >>>> sock.getsockname() > (0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') > > In python 1.5.2 >>>> server_address=('zmy02aix04', 11111) >>>> sock.bind(server_address) >>>> sock.getsockname() > ('10.228.51.41', 11111) I'd say it's a problem with the _socket module; did the unit tests flag anything when you built Python? On Windows, Python 2.7.1: >>> server_address=('lepton', 11111) >>> sock.bind(server_address) >>> sock.getsockname() ('127.0.0.1', 11111) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list From poalman at gmail.com Fri Oct 7 06:15:05 2011 From: poalman at gmail.com (Paul) Date: Fri, 7 Oct 2011 10:15:05 +0000 (UTC) Subject: Thread handling issue References: <4E8EBC32.9060000@timgolden.me.uk> Message-ID: Tim Golden timgolden.me.uk> writes: > > On 07/10/2011 09:29, Paul wrote: > > I'm wondering what the best solution for this problem is. > > > > I've got a wxpython app, in one part a user makes some selections then opens a > > dialog to select where to output. At which point the app starts a thread > > processing their selection while they're choosing an output location, hopefully > > ready for when they're done. > > > > My problem is if the user doesn't select an output location and cancels the > > dialog to go back to the selection I want to terminate the thread to avoid the > > user opening and closing the output selection firing off a ton of threads. > > > > As there's no inbuilt way of killing threads I was wondering the best way to > > prevent this? > > The most common approach is to have the thread monitor an event which is > set if, for example, the user cancels. The thread may of course have to > wait, for example, for a long-running database query to complete before > it can discover that its time has been wasted :) > > The exact mechanism will depend on how your code is structured, > what the thread is doing, and how it's passing anything back > to the main thread. > > TJG > My first thought was to use a flag but wouldn't the new thread see the cancel flag and stop as well? I could set it back but then any other threads might have been busy and not seen it while the flag was on. The thread goes through the selection and does a few quick server calls for each one building up a data file. I guess as the server calls are quite fast the thread would be able to check flags quite often unless it's getting time-outs or something. The threads don't pass anything back they're passed a reference to a data object which is constructed before the thread starts. The thread makes updates to the data object and sets a complete attribute flag in the object before finishing. From cs at zip.com.au Fri Oct 7 06:24:29 2011 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 7 Oct 2011 21:24:29 +1100 Subject: A tuple in order to pass returned values ? In-Reply-To: <4E8EC9C2.1080306@sequans.com> References: <4E8EC9C2.1080306@sequans.com> Message-ID: <20111007102429.GA15713@cskk.homeip.net> On 07Oct2011 11:43, Jean-Michel Pichavant wrote: | namedtuple sounds great (if you don't use unpacking :o) ), too bad | it is available only from python 2.6. It is easy enough to roll your own. Here's some example code with several flaws (it claims tuplehood, but is actually a list; it is not immutable; it takes a list of field names instead of a space separated string as namedtuple does) and isn't very tested. But feel free to take it and adapt it: def NamedTupleClassFactory(*fields): ''' Construct classes for named tuples a bit like the named tuples coming in Python 2.6/3.0. NamedTupleClassFactory('a','b','c') returns a subclass of "list" whose instances have properties .a, .b and .c as references to elements 0, 1 and 2 respectively. ''' class NamedTuple(list): for i in range(len(fields)): f=fields[i] exec('def getx(self): return self[%d]' % i) exec('def setx(self,value): self[%d]=value' % i) exec('%s=property(getx,setx)' % f) return NamedTuple def NamedTuple(fields,iter=()): ''' Return a named tuple with the specified fields. Useful for one-off tuples/lists. ''' return NamedTupleClassFactory(*fields)(iter) More old code:-( I can see I need to go back to that and make it cleaner. Surely I can get rid of the exec(0s at least:-) Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Hacker: One who accidentally destroys. Wizard: One who recovers afterwards. From __peter__ at web.de Fri Oct 7 06:42:02 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Oct 2011 12:42:02 +0200 Subject: A tuple in order to pass returned values ? References: <4E8EC9C2.1080306@sequans.com> <20111007102429.GA15713@cskk.homeip.net> Message-ID: Cameron Simpson wrote: > On 07Oct2011 11:43, Jean-Michel Pichavant wrote: > | namedtuple sounds great (if you don't use unpacking :o) ), too bad > | it is available only from python 2.6. > > It is easy enough to roll your own. Or use Raymond Hettinger's implementation: http://code.activestate.com/recipes/500261-named-tuples/ From python.list at tim.thechases.com Fri Oct 7 07:46:46 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 07 Oct 2011 06:46:46 -0500 Subject: Testing properties that are date-related Message-ID: <4E8EE6A6.2010208@tim.thechases.com> Are there best practices for testing dates that are properties which take the current date into consideration? I have something like class Foo: def _get_year_range(self): return (self._min_year, self._max_year) def _set_year_range(self, year): if isinstance(year, tuple): _min, _max = map(window_date, year) if _min > _max: _min, _max = _max, _min else: # a raw int _min = _max = window_date(year) self._min_year, self._max_year = _min, _max year_range = property( fget=_get_year_range, fget=_get_year_range, ) The problem is that the behavior of the window_date function depends on the current date (the function makes a guess about adding the century if the year was <100). It *does* take an "around" parameter that defaults to the current date. So for pure testing of the window_date() function, I can hard-code some date where I know what the expected values should be. However if I want to write a test-harness for my property, I have no way (AFAIK) to pass in this fixed date to _set_year_range() so that the success/failure of my tests doesn't depend on the day I run them: class TestFoo: def test_year_range(self): around = date(2011,1,1) f = Foo() f.year_range = (97, 84) self.assertEqual(f.year_range, (1984, 1997)) Any suggestions/tips/hints? Thanks, -tkc From __peter__ at web.de Fri Oct 7 08:38:03 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Oct 2011 14:38:03 +0200 Subject: Testing properties that are date-related References: <4E8EE6A6.2010208@tim.thechases.com> Message-ID: Tim Chase wrote: > Are there best practices for testing dates that are properties > which take the current date into consideration? I have something > like > > class Foo: > def _get_year_range(self): > return (self._min_year, self._max_year) > def _set_year_range(self, year): > if isinstance(year, tuple): > _min, _max = map(window_date, year) > if _min > _max: _min, _max = _max, _min > else: # a raw int > _min = _max = window_date(year) > self._min_year, self._max_year = _min, _max > year_range = property( > fget=_get_year_range, > fget=_get_year_range, > ) > > The problem is that the behavior of the window_date function > depends on the current date (the function makes a guess about > adding the century if the year was <100). It *does* take an > "around" parameter that defaults to the current date. So for > pure testing of the window_date() function, I can hard-code some > date where I know what the expected values should be. > > However if I want to write a test-harness for my property, I have > no way (AFAIK) to pass in this fixed date to _set_year_range() so > that the success/failure of my tests doesn't depend on the day I > run them: > > class TestFoo: > def test_year_range(self): > around = date(2011,1,1) > f = Foo() > f.year_range = (97, 84) > self.assertEqual(f.year_range, (1984, 1997)) > > Any suggestions/tips/hints? Thanks, Temporarily replace the window_date() function with something that you can control completely. Assuming Foo and window_date are defined in foo.py: # untested import foo class TestFoo: def setUp(self): foo.window_date = functools.partial(foo.window_date, around=date(2011, 1, 1)) def tearDown(self): foo.window_date = foo.window_date.func def test_year_range(self): f = Foo() f.year_range = (97, 84) self.assertEqual(f.year_range, (1984, 1997)) See also http://www.voidspace.org.uk/python/mock/ From python.list at tim.thechases.com Fri Oct 7 09:41:18 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 07 Oct 2011 08:41:18 -0500 Subject: Testing properties that are date-related In-Reply-To: References: <4E8EE6A6.2010208@tim.thechases.com> Message-ID: <4E8F017E.8050403@tim.thechases.com> On 10/07/11 07:38, Peter Otten wrote: >> Are there best practices for testing dates that are properties >> which take the current date into consideration >> >> The problem is that the behavior of the window_date function >> depends on the current date (the function makes a guess about >> adding the century if the year was<100). It *does* take an >> "around" parameter that defaults to the current date. So for >> pure testing of the window_date() function, I can hard-code some >> date where I know what the expected values should be. >> >> However if I want to write a test-harness for my property, I have >> no way (AFAIK) to pass in this fixed date to _set_year_range() so >> that the success/failure of my tests doesn't depend on the day I >> run them > > Temporarily replace the window_date() function with something that you can > control completely. Assuming Foo and window_date are defined in foo.py: > > # untested > import foo > > class TestFoo: > def setUp(self): > foo.window_date = functools.partial(foo.window_date, > around=date(2011, 1, 1)) > def tearDown(self): > foo.window_date = foo.window_date.func > def test_year_range(self): > f = Foo() > f.year_range = (97, 84) > self.assertEqual(f.year_range, (1984, 1997)) I had to twiddle my class code a bit to make sure it referenced module.window_date() everywhere instead of just a raw window_date() (originally pulled in via "from module import window_date") so that it picked up the new function, but otherwise it worked like a charm. (there was also the matter of some function properties that were used for an undetailed parameter to allow for suggesting that the window_date bias backwards, forwards or around the current date, but a little hackery took care of that too, just copying the germane properties from the saved function object to the result of the partial() call) Thanks! -tkc From miki.tebeka at gmail.com Fri Oct 7 10:11:39 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 7 Oct 2011 07:11:39 -0700 (PDT) Subject: passing multiple string to a command line option In-Reply-To: References: <22850959.1256.1317925508336.JavaMail.geo-discussion-forums@prcs9> Message-ID: <22831825.757.1317996699182.JavaMail.geo-discussion-forums@prma7> Seems like self.ptype is a type that has __init__ with no arguments (other than self). You can add "print type(self.ptype)" as first line of "convert" to see what type it is (or place a breakpoint there). From miki.tebeka at gmail.com Fri Oct 7 10:11:39 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 7 Oct 2011 07:11:39 -0700 (PDT) Subject: passing multiple string to a command line option In-Reply-To: References: <22850959.1256.1317925508336.JavaMail.geo-discussion-forums@prcs9> Message-ID: <22831825.757.1317996699182.JavaMail.geo-discussion-forums@prma7> Seems like self.ptype is a type that has __init__ with no arguments (other than self). You can add "print type(self.ptype)" as first line of "convert" to see what type it is (or place a breakpoint there). From ethan at stoneleaf.us Fri Oct 7 10:45:49 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 07 Oct 2011 07:45:49 -0700 Subject: Testing properties that are date-related In-Reply-To: <4E8F017E.8050403@tim.thechases.com> References: <4E8EE6A6.2010208@tim.thechases.com> <4E8F017E.8050403@tim.thechases.com> Message-ID: <4E8F109D.4040604@stoneleaf.us> Tim Chase wrote: > On 10/07/11 07:38, Peter Otten wrote: >>> Are there best practices for testing dates that are properties >>> which take the current date into consideration >>> >>> The problem is that the behavior of the window_date function >>> depends on the current date (the function makes a guess about >>> adding the century if the year was<100). It *does* take an >>> "around" parameter that defaults to the current date. So for >>> pure testing of the window_date() function, I can hard-code some >>> date where I know what the expected values should be. >>> >>> However if I want to write a test-harness for my property, I have >>> no way (AFAIK) to pass in this fixed date to _set_year_range() so >>> that the success/failure of my tests doesn't depend on the day I >>> run them >> >> Temporarily replace the window_date() function with something that you >> can >> control completely. Assuming Foo and window_date are defined in foo.py: >> >> # untested >> import foo >> >> class TestFoo: >> def setUp(self): >> foo.window_date = functools.partial(foo.window_date, >> around=date(2011, 1, 1)) >> def tearDown(self): >> foo.window_date = foo.window_date.func >> def test_year_range(self): >> f = Foo() >> f.year_range = (97, 84) >> self.assertEqual(f.year_range, (1984, 1997)) > > I had to twiddle my class code a bit to make sure it referenced > module.window_date() everywhere instead of just a raw window_date() > (originally pulled in via "from module import window_date") so that it > picked up the new function, but otherwise it worked like a charm. Another option is injection: import foo def window_date(...): ... foo.window_date = window_date ~Ethan~ From mail at timgolden.me.uk Fri Oct 7 10:56:54 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 07 Oct 2011 15:56:54 +0100 Subject: Thread handling issue In-Reply-To: References: <4E8EBC32.9060000@timgolden.me.uk> Message-ID: <4E8F1336.3070907@timgolden.me.uk> On 07/10/2011 11:15, Paul wrote: > My first thought was to use a flag but wouldn't the new thread see the cancel > flag and stop as well? I could set it back but then any other threads might have > been busy and not seen it while the flag was on. > > The thread goes through the selection and does a few quick server calls for each > one building up a data file. I guess as the server calls are quite fast the > thread would be able to check flags quite often unless it's getting time-outs or > something. > > The threads don't pass anything back they're passed a reference to a data object > which is constructed before the thread starts. The thread makes updates to the > data object and sets a complete attribute flag in the object before finishing. Well a lot depends on how you're doing things. (ie "It Depends"). You could generate an event for each thread so a second thread started while the first was running down wouldn't cause confusion. It's not clear whether the data object is common to all threads -- in which case you need to make sure you're locking etc. -- or is a new instance for each thread. I did try a couple of passes at a code-sketch, but there are too many unknowns to do justice to it. Basically, have the thread poll an event as it moves through. Have the UI set the event and join to the existing thread (ie wait for it to finish) and then fire off a new one. Or -- if the data items are independent -- fire off the new one regardless and let the old one die when it sees its event, assuming that the data object it's populating is disposable. TJG From python.list at tim.thechases.com Fri Oct 7 12:28:55 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 07 Oct 2011 11:28:55 -0500 Subject: Testing properties that are date-related In-Reply-To: <4E8F109D.4040604@stoneleaf.us> References: <4E8EE6A6.2010208@tim.thechases.com> <4E8F017E.8050403@tim.thechases.com> <4E8F109D.4040604@stoneleaf.us> Message-ID: <4E8F28C7.3070502@tim.thechases.com> On 10/07/11 09:45, Ethan Furman wrote: > Tim Chase wrote: >> On 10/07/11 07:38, Peter Otten wrote: >>> def setUp(self): >>> foo.window_date = functools.partial(foo.window_date, >>> around=date(2011, 1, 1)) >> >> it worked like a charm. > > Another option is injection: > > import foo > > def window_date(...): > ... > > foo.window_date = window_date The problem is that I *want* the functionality of the existing window_date() because that's part of what's being tested. Peter's suggestion of injection to the module namespace via functools.partial() to specify the missing parameter was the tip I needed to be able to write tests that exercised things properly without overly invasive changes to the code. But thanks for your idea. -tkc From nt_mahmood at yahoo.com Fri Oct 7 12:52:16 2011 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Fri, 7 Oct 2011 09:52:16 -0700 (PDT) Subject: passing multiple string to a command line option In-Reply-To: <22831825.757.1317996699182.JavaMail.geo-discussion-forums@prma7> References: <22850959.1256.1317925508336.JavaMail.geo-discussion-forums@prcs9> <22831825.757.1317996699182.JavaMail.geo-discussion-forums@prma7> Message-ID: <1318006336.7951.YahooMailNeo@web111711.mail.gq1.yahoo.com> That print command generated a lot of errors. Since that error in my first post is related to the python code in simulator, I emailed them and consulted for help. Seems that it is going to be fixed.... Thanks for your kindness :) ? // Naderan *Mahmood; ----- Original Message ----- From: Miki Tebeka To: comp.lang.python at googlegroups.com Cc: python mailing list ; Miki Tebeka ; Mahmood Naderan Sent: Friday, October 7, 2011 5:41 PM Subject: Re: passing multiple string to a command line option Seems like self.ptype is a type that has __init__ with no arguments (other than self). You can add "print type(self.ptype)" as first line of "convert" to see what type it is (or place a breakpoint there). From redcat at streemit.net Fri Oct 7 12:56:33 2011 From: redcat at streemit.net (Redcat) Date: 7 Oct 2011 16:56:33 GMT Subject: help References: Message-ID: <9f8pa1Fsh8U3@mid.individual.net> On Fri, 07 Oct 2011 15:59:55 +0000, X1 wrote: > I have this program that fails: > > $ vapt > Traceback (most recent call last): > File "/usr/local/bin/vapt", line 3, in > from vapt import vapt > File "/usr/lib/python2.6/site-packages/vapt/__init__.py", line 11, in > > __import__(name, glob, loc, []) > File "/usr/lib/python2.6/site-packages/vapt/cadview.py", line 13, in > > import OpenGL.Tk as gltk > ImportError: No module named Tk > > > can you help me? > This is on fedora The OpenGL.Tk module is looking for the Tk module and not finding it. Install the Tk module. Try "sudo easy_install Tk". From dreyemi at gmail.com Fri Oct 7 13:16:59 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Fri, 7 Oct 2011 18:16:59 +0100 Subject: unsupported operand type(s) for pow(): 'unicode', 'long', 'long': Pycrypto Message-ID: Hello everyone, I'm writing a fairly large app which uses Oauth (python-oauth2). I am trying to generate a public/private key pair on user supplied parameters (whitespaced-delimited strings basically). When trying to encrypt the key, I'm getting the "unsupported operand type(s) for pow(): 'unicode', 'long', 'long'" >From Interactive shell, the program worked successfully. My question is do I have to make the user supplied data of a non-unicode string to make this work? Thanks -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Fri Oct 7 14:23:16 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 7 Oct 2011 12:23:16 -0600 Subject: unsupported operand type(s) for pow(): 'unicode', 'long', 'long': Pycrypto In-Reply-To: References: Message-ID: On Fri, Oct 7, 2011 at 11:16 AM, Kayode Odeyemi wrote: > Hello everyone, > > I'm writing a fairly large app which uses Oauth (python-oauth2). I am trying > to generate a > public/private key pair on user supplied parameters (whitespaced-delimited > strings basically). > > When trying to encrypt the key, I'm getting the "unsupported operand type(s) > for pow(): 'unicode', 'long', 'long'" > > From Interactive shell, the program worked successfully. > > My question is do I have to make the user supplied data of a non-unicode > string to make this work? Please include the traceback and the snippet of code where you make the call that is failing. Without that, it is not at all clear exactly what you are doing, especially since python-oauth2 does not seem to provide any encryption API. Cheers, Ian From redcat at streemit.net Fri Oct 7 14:45:52 2011 From: redcat at streemit.net (Redcat) Date: 7 Oct 2011 18:45:52 GMT Subject: help References: <9f8pa1Fsh8U3@mid.individual.net> Message-ID: <9f8vmvFsh8U5@mid.individual.net> > Thanks, > I have the Tk module installed, but the program still fails. Probably it > is a problem of path? That would be my guess - that the Tk module is installed somewhere other than where OpenGL.Tk is looking for it. From dreyemi at gmail.com Fri Oct 7 14:54:31 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Fri, 7 Oct 2011 19:54:31 +0100 Subject: unsupported operand type(s) for pow(): 'unicode', 'long', 'long': Pycrypto In-Reply-To: References: Message-ID: On Fri, Oct 7, 2011 at 7:23 PM, Ian Kelly wrote: > On Fri, Oct 7, 2011 at 11:16 AM, Kayode Odeyemi wrote: > > Hello everyone, > > > > I'm writing a fairly large app which uses Oauth (python-oauth2). I am > trying > > to generate a > > public/private key pair on user supplied parameters > (whitespaced-delimited > > strings basically). > > > > When trying to encrypt the key, I'm getting the "unsupported operand > type(s) > > for pow(): 'unicode', 'long', 'long'" > > > > From Interactive shell, the program worked successfully. > > > > My question is do I have to make the user supplied data of a non-unicode > > string to make this work? > > Please include the traceback and the snippet of code where you make > the call that is failing. Without that, it is not at all clear > exactly what you are doing, especially since python-oauth2 does not > seem to provide any encryption API. > Thanks for writing in. I had this: encrypted = public_key.encrypt(params, 16) I was able to fix it with: encrypted = public_key.encrypt(str(params), 16) pow() needs params in non-unicode. I understand python-oauth2 does not have encryption API built-in. I'm creating one before using it. -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinay_sajip at yahoo.co.uk Fri Oct 7 15:05:10 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 7 Oct 2011 12:05:10 -0700 (PDT) Subject: Advise on using logging.getLogger needed. References: Message-ID: <98847de7-63ee-4f4f-bfd8-e607066816db@k34g2000yqm.googlegroups.com> On Oct 2, 11:12?pm, "Steven W. Orr" wrote: > I hope I don't sound like I'm ranting :-( You don't, but neither is it absolutely clear what you're trying to achieve. BTW the term "root logger" in the logging docs refers to a logger internal to the logging package, and not to a logger that you create. For that, it's best to refer to "top level logger for my application/library". Supposing you want your top-level logger always to be the name of your main script, and you want other loggers to live below this logger. In your main script module, therefore, you do the equivalent of pname = compute_program_name(sys.argv[0]) logger = logging.getLogger(pname) # configure logging handlers, filters etc. for your application In your library modules, if you want them to live under that top-level logger, then you can do something like pname = compute_program_name(sys.argv[0]) logger = logging.getLogger('%s.%s' % pname, __name__) where you can use something other than __name__ for the logger name suffix, if you want. > My problem is that I just want the modules that I write, to be able to get the > ?named root logger and still be able to refer to possible sub-loggers. According to the scheme I describe, if you have two scripts called "foo" and "bar" which make use of a common module "baz", then events in the foo module would appear under logger "foo", and events in the baz module when run from foo would be logged under logger "foo.baz". When running "bar", events in the bar module would appear under logger "bar", whereas events in the baz module when run from bar would be logged under logger "bar.baz". This seems to be what you're asking for, but I may have misunderstood. > I am running 2.6, so I don't have access to logging.getChild, but I'm not > clear that I even want that. getChild is just a convenience method, you don't need it - you can just build the logger name as in my example above. > My modules are used by multiple programs. Does this mean that I should simply > use __name__ all the time? (That seems inelegant, no?) Actually __name__ is very elegant, as it is impervious to you moving your code around and follows the Python package hierarchy. Also, if you are using third party code (especially from various sources), using __name__ will make things unambiguous about where exactly events are being logged from. Third party code typically won't know about your top-level logger, and __name__ is the one scheme that everything can agree on - the point about logger names being that they're supposed to codify "where" in your application events occur, and the package hierarchy is the canonical representation of source locations in an application. Regards, Vinay Sajip From ramit.prasad at jpmorgan.com Fri Oct 7 15:05:27 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 7 Oct 2011 15:05:27 -0400 Subject: Thread handling issue In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F214444E2@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- From: python-list-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Paul Sent: Friday, October 07, 2011 3:29 AM To: python-list at python.org Subject: Thread handling issue I'm wondering what the best solution for this problem is. I've got a wxpython app, in one part a user makes some selections then opens a dialog to select where to output. At which point the app starts a thread processing their selection while they're choosing an output location, hopefully ready for when they're done. My problem is if the user doesn't select an output location and cancels the dialog to go back to the selection I want to terminate the thread to avoid the user opening and closing the output selection firing off a ton of threads. As there's no inbuilt way of killing threads I was wondering the best way to prevent this? -- http://mail.python.org/mailman/listinfo/python-list ============================================================================ Why not just wait until they are done with all user input and then fire threads after that? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From kurro.pipi at hotmail.com Fri Oct 7 15:29:15 2011 From: kurro.pipi at hotmail.com (txismis unzetabarrenetxeagoikolea) Date: Fri, 7 Oct 2011 12:29:15 -0700 Subject: deepcopy does not work for A subclassed list Message-ID: This is the issue I have created a mylist class by subclassing a List, added several attributes to mylist , and overrided the append method which takes into account one of the new attributes. mylist class is functional and works as I planned, but when I try to deepcopy objects from mylist I received errors because the attribute has not been copied and the override append raise an error. When I want to deepcopy one object from mylist the algorithm does not take into account the attributes I created; ergo, I have some errors from the copy module I can use pickle to dump and load objects from my subclass with no errors. Any ideas about how to make the copy module to behave as expected. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From ralf at systemexit.de Fri Oct 7 15:33:10 2011 From: ralf at systemexit.de (Ralf Schmitt) Date: Fri, 07 Oct 2011 21:33:10 +0200 Subject: [ANN] pypiserver 0.3.0 - minimal pypi server Message-ID: <87liswd2bt.fsf@myhost.localnet> Hi, I've just uploaded pypiserver 0.3.0 to the python package index. pypiserver is a minimal PyPI compatible server. It can be used to serve a set of packages and eggs to easy_install or pip. pypiserver is easy to install (i.e. just easy_install pypiserver). It doesn't have any external dependencies. http://pypi.python.org/pypi/pypiserver/ should contain enough information to easily get you started running your own PyPI server in a few minutes. The code is available on github: https://github.com/schmir/pypiserver Changes in version 0.3.0 ------------------------- - pypiserver now scans the given root directory and it's subdirectories recursively for packages. Files and directories starting with a dot are now being ignored. - /favicon.ico now returns a "404 Not Found" error - pypiserver now contains some unit tests to be run with tox -- Cheers, Ralf From frank.ruiz at gmail.com Fri Oct 7 15:39:53 2011 From: frank.ruiz at gmail.com (Frank Ruiz) Date: Fri, 7 Oct 2011 12:39:53 -0700 Subject: Memory Message-ID: Quick question, What is the best way for pulling resource information for a system running linux? Was wondering if there was a python only way. Methods I am aware of are: 1. Parsing contents of /proc 2. Running a system command like free, or dmidecode and parsing the output. Is there any other way to pull.. lets say memory information? i.e. Find how much total RAM a system has on it. Thanks you. From ed at leafe.com Fri Oct 7 16:00:41 2011 From: ed at leafe.com (Ed Leafe) Date: Fri, 7 Oct 2011 15:00:41 -0500 Subject: Dabo 0.9.4 Released! In-Reply-To: References: Message-ID: On Oct 6, 2011, at 12:18 PM, Neal Becker wrote: > What is it? Sorry, I guess I should have included that. We've been around for so long I sometimes assume that everyone knows what Dabo is. Dabo is a framework for building desktop applications. It is strongly geared toward database applications, although a database connection is completely optional. We wrap the wxPython GUI toolkit, hiding its C++ roots and presenting a more Pythonic interface for creating your UI. See more at http://dabodev.com, and feel free to ask any more questions. -- Ed Leafe From lists at cheimes.de Fri Oct 7 16:06:52 2011 From: lists at cheimes.de (Christian Heimes) Date: Fri, 07 Oct 2011 22:06:52 +0200 Subject: Memory In-Reply-To: References: Message-ID: Am 07.10.2011 21:39, schrieb Frank Ruiz: > Quick question, > > What is the best way for pulling resource information for a system > running linux? Was wondering if there was a python only way. > > Methods I am aware of are: > > 1. Parsing contents of /proc > 2. Running a system command like free, or dmidecode and parsing the output. > > Is there any other way to pull.. lets say memory information? i.e. > Find how much total RAM a system has on it. Yes, use psutil. http://code.google.com/p/psutil/ From a24061 at ducksburg.com Fri Oct 7 16:14:44 2011 From: a24061 at ducksburg.com (Adam Funk) Date: Fri, 07 Oct 2011 21:14:44 +0100 Subject: recommend a graphics library for plotting by the pixel? References: <9s1rl8xt8t.ln2@news.ducksburg.com> Message-ID: On 2011-10-04, Ian Kelly wrote: > On Tue, Oct 4, 2011 at 3:56 AM, Adam Funk wrote: >> I'd like to create a window with a "pause" button and a large plotting >> area, in which I'd like to draw a polygon, detect the pixel >> co?rdinates of a mouse click, and then start setting the colors of >> pixels by (x,y) co?rdinates. ?(This is just for my own amusement, to >> play with some formulas for generating fractals using random numbers.) >> >> There seems to be a large number of different python GUI libraries, >> and I wonder if someone can recommend the easiests one to learn for >> this purpose? ?(The only python graphics library I've used is PyGame, >> which I don't think is the way to go here.) > > You could use wxPython. You'll need to create a custom control and > have it paint itself by blitting from a wx.Bitmap, which you'll draw > on by using a wx.MemoryDC and then refreshing the control. > > I would probably just use pygame myself. I guess you're avoiding it > because of the requirement for a button, but there are GUI libraries > available for it, or if all you need are a couple of buttons you could > easily roll your own. Excellent suggestion. I got it to work, but using keypresses (pause, step, quit) instead of buttons, and a mouse event for letting the user pick the start point on the screen. -- I worry that 10 or 15 years from now, [my daughter] will come to me and say 'Daddy, where were you when they took freedom of the press away from the Internet?' [Mike Godwin] http://www.eff.org/ From a24061 at ducksburg.com Fri Oct 7 16:15:43 2011 From: a24061 at ducksburg.com (Adam Funk) Date: Fri, 07 Oct 2011 21:15:43 +0100 Subject: recommend a graphics library for plotting by the pixel? References: <9s1rl8xt8t.ln2@news.ducksburg.com> <2n2ul8xi9s.ln2@news.ducksburg.com> Message-ID: On 2011-10-05, Westley Mart?nez wrote: > On Wed, Oct 05, 2011 at 02:29:38PM +0100, Adam Funk wrote: >> I only know PyGame because we did an exercise in recreating the old >> breakout game and messing around with it at a local Python group. >> >> I was under the mistaken impression from that exercise that you have >> to maintain a set of all the objects on the screen and redraw them all >> every time through the loop that ends with pygame.display.flip() --- >> *but* I now see that the loop starts with these: >> >> clock.tick(tick_rate) >> screen.fill((0,0,0)) >> # comes from screen = pygame.display.set_mode((screen_width,screen_height)) >> # before the loop >> >> and that I was then deleting hit bricks, calculating the new positions >> of the balls, and then redrawing everything that was left on the >> secondary screen because things were moving around and disappearing. >> >> I guess if I don't clear the screen at the beginning of the loop but >> just blit pixels onto it, when I call display.flip(), it will add the >> new blittings to what was already there? If that's true, this will be >> much easier than I thought. > Yep. Blitting is replacing the old colors with new colors. It doesn't > replace colors unless you tell it to. My mistake was in sample code, running with it, & not looking at it too closely. ;-) -- Mathematiker sind wie Franzosen: Was man ihnen auch sagt, ?bersetzen sie in ihre eigene Sprache, so da? unverz?glich etwas v?llig anderes daraus wird. [Goethe] From python at mrabarnett.plus.com Fri Oct 7 16:37:00 2011 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 07 Oct 2011 21:37:00 +0100 Subject: deepcopy does not work for A subclassed list In-Reply-To: References: Message-ID: <4E8F62EC.603@mrabarnett.plus.com> On 07/10/2011 20:29, txismis unzetabarrenetxeagoikolea wrote: > This is the issue > > I have created a mylist class by subclassing a List, added several > attributes to mylIst , and overrided the append method which takes into > account one of the new attributes. > > mylist class is functional and works as I planned, but when I try to > deepcopy objects from mylist I received errors because the attribute has > not been copied and the override append raise an error. > > When I want to deepcopy one object from mylist the algorithm does not > take into account the attributes I created; ergo, I have some errors > from the copy module > > I can use pickle to dump and load objects from my subclass with no errors. > > Any ideas about how to make the copy module to behave as expected. > The documentation talks about defining a "__deepcopy__" method. From cs at zip.com.au Fri Oct 7 18:35:58 2011 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 8 Oct 2011 09:35:58 +1100 Subject: Thread handling issue In-Reply-To: References: Message-ID: <20111007223558.GA5616@cskk.homeip.net> On 07Oct2011 10:15, Paul wrote: | Tim Golden timgolden.me.uk> writes: | > On 07/10/2011 09:29, Paul wrote: | > > My problem is if the user doesn't select an output location and cancels the | > > dialog to go back to the selection I want to terminate the thread to avoid the | > > user opening and closing the output selection firing off a ton of threads. | > > | > > As there's no inbuilt way of killing threads I was wondering the best way to | > > prevent this? | > | > The most common approach is to have the thread monitor an event which is | > set if, for example, the user cancels. The thread may of course have to | > wait, for example, for a long-running database query to complete before | > it can discover that its time has been wasted :) [...] | My first thought was to use a flag but wouldn't the new thread see the cancel | flag and stop as well? I could set it back but then any other threads might have | been busy and not seen it while the flag was on. I'd be inclined to dispatch threads via a control object of some kind. You'd have a default one for your program as a whole, but when you have a circumstance such as you describe instantiate a new control object. Set the cancel flag in the control objects. Have threads poll their invoking control object. That way you can have a flag that applies to your desired set of threads. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ He's silly and he's ignorant, but he's got guts, and guts is enough. - Sgt. Hartmann From tjreedy at udel.edu Fri Oct 7 19:35:19 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 07 Oct 2011 19:35:19 -0400 Subject: deepcopy does not work for A subclassed list In-Reply-To: <4E8F62EC.603@mrabarnett.plus.com> References: <4E8F62EC.603@mrabarnett.plus.com> Message-ID: On 10/7/2011 4:37 PM, MRAB wrote: > On 07/10/2011 20:29, txismis unzetabarrenetxeagoikolea wrote: >> Any ideas about how to make the copy module to behave as expected. >> > The documentation talks about defining a "__deepcopy__" method. Specifically, in the copy module doc "In order for a class to define its own copy implementation, it can define special methods __copy__() and __deepcopy__(). The former is called to implement the shallow copy operation; no additional arguments are passed. The latter is called to implement the deep copy operation; it is passed one argument, the memo dictionary. If the __deepcopy__() implementation needs to make a deep copy of a component, it should call the deepcopy() function with the component as first argument and the memo dictionary as second argument." All the possible customization methods are discussed in Language Reference 3.3. Special method names -- Terry Jan Reedy From tjreedy at udel.edu Fri Oct 7 19:39:22 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 07 Oct 2011 19:39:22 -0400 Subject: help In-Reply-To: <9f8pa1Fsh8U3@mid.individual.net> References: <9f8pa1Fsh8U3@mid.individual.net> Message-ID: On 10/7/2011 12:56 PM, Redcat wrote: > On Fri, 07 Oct 2011 15:59:55 +0000, X1 wrote: > >> I have this program that fails: >> >> $ vapt >> Traceback (most recent call last): >> File "/usr/local/bin/vapt", line 3, in >> from vapt import vapt >> File "/usr/lib/python2.6/site-packages/vapt/__init__.py", line 11, in >> >> __import__(name, glob, loc, []) >> File "/usr/lib/python2.6/site-packages/vapt/cadview.py", line 13, in >> >> import OpenGL.Tk as gltk >> ImportError: No module named Tk >> >> >> can you help me? >> This is on fedora > > The OpenGL.Tk module is looking for the Tk module and not finding it. > Install the Tk module. Or there is no OpenGL.Tk module >>> import itertools.xxx Traceback (most recent call last): File "", line 1, in import itertools.xxx ImportError: No module named xxx > > Try "sudo easy_install Tk". -- Terry Jan Reedy From tjreedy at udel.edu Fri Oct 7 19:50:22 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 07 Oct 2011 19:50:22 -0400 Subject: unsupported operand type(s) for pow(): 'unicode', 'long', 'long': Pycrypto In-Reply-To: References: Message-ID: On 10/7/2011 2:54 PM, Kayode Odeyemi wrote: > pow() needs params in non-unicode. pow() need 2 or 3 numbers as args. The function that calls it must turn the (2.x) string into a number, either with hash() or its own hash function. That latter function probably want integers code in range(256). "pow(x, y[, z]) Return x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than pow(x, y) % z). The two-argument form pow(x, y) is equivalent to using the power operator: x**y. The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For int operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, 10**2 returns 100, but 10**-2 returns 0.01. If the second argument is negative, the third argument must be omitted. If z is present, x and y must be of integer types, and y must be non-negative. " -- Terry Jan Reedy From brandtrade08 at 126.com Fri Oct 7 22:27:50 2011 From: brandtrade08 at 126.com (jerser-2009) Date: Fri, 7 Oct 2011 19:27:50 -0700 (PDT) Subject: The hyper fused upper part of Nike Air Message-ID: <15dfd42d-dc9d-457d-90f3-8bb358982e8f@x21g2000prd.googlegroups.com> The hyper fused upper part of Nike Air Max displays the humanity of the designer because of its lightweight, breathability and a feeling of plusher fitness. The mesh inner collar, and the soft springy cushion http://www.outlet-nike-air-max.com/inside can protect the feet against most possible injures. Besides the rubber materials around the translucent perimeter displays a particular appearance of the shoes, which is a love of most women, especially those who pursuit to be in fashion. Meanwhile the rubber material is a guaranty of the durability and traction, which is fully the practice. With the {2}{/2}dynamic colors of Women?s Nike Air Max 2011, you will soon experience the vitality of sports when you are dressed in such a pair of classic nice cheap Nike running shoes, because it can not only create a healthy condition for feet, but also can restore the original active in the shortest time. What?s more, the Nike Air Max 2011 will not cause any exacerbation if you once were injured in feet. http://www.outlet-nike-air-max.com/ From gagsl-py2 at yahoo.com.ar Sat Oct 8 00:15:36 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 08 Oct 2011 01:15:36 -0300 Subject: Deleting files on a shared server References: <24959174.190.1317950066875.JavaMail.geo-discussion-forums@prho12> <4E8EAE1C.1050104@timgolden.me.uk> Message-ID: En Fri, 07 Oct 2011 04:45:32 -0300, Tim Golden escribi?: > On 07/10/2011 02:14, Josh English wrote: >> To delete the files, I am using os.unlink. >> >> One lock file refuses to disappear, even though I have code at both >> application startup and shutdown (on the OnInit and OnExit methods to >> the wxPython Application object) that hunts down .lock files and >> deletes them. > > Assuming that your code paths succeed and that the unlink actually > happens, it is possible for files to continue to exist after they > have been successfully deleted. This happens if another process > has opened them with share-delete mode; typically this will be > a virus checker or a process like the TortoiseSVN cache (or its > counterparts for other VCS). The file won't actually disappear > until the last handle on it is released. In such cases the openfiles command [1] is very useful for detecting who is holding the file open. [1] http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/openfiles.mspx -- Gabriel Genellina From k.sahithi2862 at gmail.com Sat Oct 8 00:49:19 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Fri, 7 Oct 2011 21:49:19 -0700 (PDT) Subject: TOP 15 HOT BOLLYWOOD KISSES Message-ID: <85a54345-cff4-44ec-927e-19dfd89f0980@c20g2000prc.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html KATRINA KAIF HOT IMAGES http://hotactress-katrina.blogspot.com/2011/08/katrina-kaif-hot.html TOP 15 HOT BOLLYWOOD KISSES http://hotactress-katrina.blogspot.com/2011/08/bollywood-kisses.html KAJAL AGARWAL HOT PICS http://hotactress-katrina.blogspot.com/2011/09/kajal-agarwal.html From dreyemi at gmail.com Sat Oct 8 04:45:09 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sat, 8 Oct 2011 09:45:09 +0100 Subject: unsupported operand type(s) for pow(): 'unicode', 'long', 'long': Pycrypto In-Reply-To: References: Message-ID: On Sat, Oct 8, 2011 at 12:50 AM, Terry Reedy wrote: > That latter function probably want integers code in range(256). Yes! Non-unicode. The source reads: def _encrypt(self, m): # compute m**d (mod n) return pow(m, self.e, self.n) >From the source, it is provided as is. The arguments must have numeric types > How come it accepts str type? -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Oct 8 05:37:41 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 08 Oct 2011 11:37:41 +0200 Subject: unsupported operand type(s) for pow(): 'unicode', 'long', 'long': Pycrypto References: Message-ID: Kayode Odeyemi wrote: > On Sat, Oct 8, 2011 at 12:50 AM, Terry Reedy wrote: > >> That latter function probably want integers code in range(256). > > > Yes! Non-unicode. The source reads: > > def _encrypt(self, m): > # compute m**d (mod n) > return pow(m, self.e, self.n) > >>From the source, it is provided as is. > > The arguments must have numeric types >> > > How come it accepts str type? pow() does not accept a str. Most likely there is conversion code similar to if isinstance(m, str): m = convert_to_int(m) that precedes the _encrypt() method call and lets unicode slip through. Grepping through the PyCrypto source for isinstance indeed finds a few candidates. Example: $ find . -name \*.py | xargs grep isinstance -A5 [...] ./PublicKey/pubkey.py: if isinstance(plaintext, types.StringType): ./PublicKey/pubkey.py- plaintext=bytes_to_long(plaintext) ; wasString=1 ./PublicKey/pubkey.py: if isinstance(K, types.StringType): ./PublicKey/pubkey.py- K=bytes_to_long(K) ./PublicKey/pubkey.py- ciphertext=self._encrypt(plaintext, K) ./PublicKey/pubkey.py- if wasString: return tuple(map(long_to_bytes, ciphertext)) ./PublicKey/pubkey.py- else: return ciphertext ./PublicKey/pubkey.py- [...] From dreyemi at gmail.com Sat Oct 8 05:55:23 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sat, 8 Oct 2011 10:55:23 +0100 Subject: unsupported operand type(s) for pow(): 'unicode', 'long', 'long': Pycrypto In-Reply-To: References: Message-ID: On Sat, Oct 8, 2011 at 10:37 AM, Peter Otten <__peter__ at web.de> wrote: > Kayode Odeyemi wrote: > > > On Sat, Oct 8, 2011 at 12:50 AM, Terry Reedy wrote: > > > >> That latter function probably want integers code in range(256). > > > > > > Yes! Non-unicode. The source reads: > > > > def _encrypt(self, m): > > # compute m**d (mod n) > > return pow(m, self.e, self.n) > > > >>From the source, it is provided as is. > > > > The arguments must have numeric types > >> > > > > How come it accepts str type? > > pow() does not accept a str. Most likely there is conversion code similar > to > > if isinstance(m, str): > m = convert_to_int(m) > Ah! I see the reason for the unsupported operand type error. It wants a str, so it can do a conversion to int. But since unicode, long etc is not allowed, shouldn't that been taken care of in _encrypt? Or is this by design? > that precedes the _encrypt() method call and lets unicode slip through. > Grepping through the PyCrypto source for isinstance indeed finds a few > candidates. Example: > > $ find . -name \*.py | xargs grep isinstance -A5 > [...] > ./PublicKey/pubkey.py: if isinstance(plaintext, types.StringType): > ./PublicKey/pubkey.py- plaintext=bytes_to_long(plaintext) ; > wasString=1 > ./PublicKey/pubkey.py: if isinstance(K, types.StringType): > ./PublicKey/pubkey.py- K=bytes_to_long(K) > ./PublicKey/pubkey.py- ciphertext=self._encrypt(plaintext, K) > ./PublicKey/pubkey.py- if wasString: return tuple(map(long_to_bytes, > ciphertext)) > ./PublicKey/pubkey.py- else: return ciphertext > ./PublicKey/pubkey.py- > [...] > > Thanks. This make things clearer > -- > http://mail.python.org/mailman/listinfo/python-list > -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From poalman at gmail.com Sat Oct 8 06:38:01 2011 From: poalman at gmail.com (Paul) Date: Sat, 8 Oct 2011 10:38:01 +0000 (UTC) Subject: Thread handling issue References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F214444E2@EMARC112VS01.exchad.jpmchase.net> Message-ID: Basically there can be quite a big job to do based on the user selection and I've pipelined it so after the user selects the output location the next job can get started so long as the first job (preparing the data) has been running for 5 or so seconds roughly. Its just a lot nicer to have this done by the time the user has selected an output folder so the main job can start instantly. Of course the user can kill the main job too and go back to the user input so I need to be able to kill the threads anyway. From candide at free.invalid Sat Oct 8 06:42:58 2011 From: candide at free.invalid (candide) Date: Sat, 08 Oct 2011 12:42:58 +0200 Subject: Usefulness of the "not in" operator Message-ID: <4e902932$0$23273$426a34cc@news.free.fr> Python provides -- the not operator, meaning logical negation -- the in operator, meaning membership On the other hand, Python provides the not in operator meaning non-membership. However, it seems we can reformulate any "not in" expression using only "not" and "in" operation. For instance >>> 'th' not in "python" False >>> not ('th' in "python") False >>> So what is the usefulness of the "not in" operator ? Recall what Zen of Python tells There should be one-- and preferably only one --obvious way to do it. From joncle at googlemail.com Sat Oct 8 06:50:00 2011 From: joncle at googlemail.com (Jon Clements) Date: Sat, 8 Oct 2011 03:50:00 -0700 (PDT) Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> Message-ID: <14fa9dc2-d4bb-4fc9-955d-ac28848d9380@n8g2000yqd.googlegroups.com> On Oct 8, 11:42?am, candide wrote: > Python provides > > ? ? ?-- the not operator, meaning logical negation > ? ? ?-- the in operator, meaning membership > > On the other hand, Python provides the not in operator meaning > non-membership. However, it seems we can reformulate any "not in" > expression using only "not" and "in" operation. For instance > > ?>>> 'th' not in "python" > False > > ?>>> not ('th' in "python") > False > ?>>> > > So what is the usefulness of the "not in" operator ? Recall what Zen of > Python tells > > There should be one-- and preferably only one --obvious way to do it. You would seriously prefer the later? Guess I'll have to start writing stuff like: 10 - 5 as 10 + -5 (as obviously the - is redundant as an operation), and 10 / 2 as int(10 * .5) or something, who needs a divide!? Jokely yours, Jon. From poalman at gmail.com Sat Oct 8 06:51:09 2011 From: poalman at gmail.com (Paul) Date: Sat, 8 Oct 2011 10:51:09 +0000 (UTC) Subject: Thread handling issue References: <4E8EBC32.9060000@timgolden.me.uk> <4E8F1336.3070907@timgolden.me.uk> Message-ID: Tim Golden timgolden.me.uk> writes: > > On 07/10/2011 11:15, Paul wrote: > > My first thought was to use a flag but wouldn't the new thread see the cancel > > flag and stop as well? I could set it back but then any other threads might have > > been busy and not seen it while the flag was on. > > > > The thread goes through the selection and does a few quick server calls for each > > one building up a data file. I guess as the server calls are quite fast the > > thread would be able to check flags quite often unless it's getting time- outs or > > something. > > > > The threads don't pass anything back they're passed a reference to a data object > > which is constructed before the thread starts. The thread makes updates to the > > data object and sets a complete attribute flag in the object before finishing. > > Well a lot depends on how you're doing things. (ie "It Depends"). You > could generate an event for each thread so a second thread started while > the first was running down wouldn't cause confusion. It's not clear > whether the data object is common to all threads -- in which case > you need to make sure you're locking etc. -- or is a new instance > for each thread. > > I did try a couple of passes at a code-sketch, but there are too > many unknowns to do justice to it. Basically, have the thread poll > an event as it moves through. Have the UI set the event and join to > the existing thread (ie wait for it to finish) and then fire off > a new one. Or -- if the data items are independent -- fire off > the new one regardless and let the old one die when it sees its > event, assuming that the data object it's populating is disposable. > > TJG Yea currently I create a new data object for each thread. I could make it a bit smarter and if the user goes back makes a change I could re-use the old data object and modify it but currently I'm not going to worry about that. I think I'll wait for the user to actually make a change after cancelling the output selection, in case they go straight back without making changes. If they make a change I think I'll try what you suggested and send off a new thread, and send an event to the previous thread. Would this mean I'd need to use wx.lib.newevent.NewCommandEvent() to get a new event for each thread I create? and I'd have to pass the second return value from that, the event binder to the thread to bind to a clean up and exit method? From stefaan.himpe at gmail.com Sat Oct 8 07:12:42 2011 From: stefaan.himpe at gmail.com (Stefaan Himpe) Date: Sat, 08 Oct 2011 13:12:42 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: <4e902932$0$23273$426a34cc@news.free.fr> References: <4e902932$0$23273$426a34cc@news.free.fr> Message-ID: > > So what is the usefulness of the "not in" operator ? Recall what Zen of > Python tells > > There should be one-- and preferably only one --obvious way to do it. the zen of python also says (amongst other things): ... Readability counts. ... Although practicality beats purity ... Best regards, Stefaan. From steve+comp.lang.python at pearwood.info Sat Oct 8 08:01:05 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 08 Oct 2011 23:01:05 +1100 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> Message-ID: <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> candide wrote: > So what is the usefulness of the "not in" operator ? Recall what Zen of > Python tells > > There should be one-- and preferably only one --obvious way to do it. And "not in" is the obvious way to do it. "If the key is not in the ignition, you won't be able to start the car." "If not the key is in the ignition, you won't be able to start the car." Who like that second one speaks? -- Steven From anssi.kaariainen at thl.fi Sat Oct 8 08:18:08 2011 From: anssi.kaariainen at thl.fi (=?iso-8859-1?Q?K=E4=E4ri=E4inen_Anssi?=) Date: Sat, 8 Oct 2011 15:18:08 +0300 Subject: PDB command <-> variable clashes Message-ID: I am currently debugging the django test cases, and there are a lot of variables names like w, q, where, condition and so on. Especially variables like w, q, c, r are really annoying. It would be cool if pdb would detect a clash and in that case ask you what to do. Nothing more annoying than stepping through the code, finally finding the problematic place and then trying to find out what c.somevar contains... I am using Python 2.6. Is there some way to do this? My googling didn't turn out anything. Or is it recommended to use something else instead of pdb? Thank you for your time, - Anssi K??ri?inen From alain at dpt-info.u-strasbg.fr Sat Oct 8 08:41:06 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sat, 08 Oct 2011 14:41:06 +0200 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> Message-ID: <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> candide writes: > Python provides > > -- the not operator, meaning logical negation > -- the in operator, meaning membership > > On the other hand, Python provides the not in operator meaning > non-membership. However, it seems we can reformulate any "not in" > expression using only "not" and "in" operation. Sure, but note that you can also reformulate != using not and ==, < using not and >=, etc. Operators like "not in" and "is not" should really be considered single tokens, even though they seem to use "not". And I think they are really convenient. -- Alain. From mwilson at the-wire.com Sat Oct 8 08:41:35 2011 From: mwilson at the-wire.com (Mel) Date: Sat, 08 Oct 2011 08:41:35 -0400 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > candide wrote: > >> So what is the usefulness of the "not in" operator ? Recall what Zen of >> Python tells >> >> There should be one-- and preferably only one --obvious way to do it. > > And "not in" is the obvious way to do it. > > > "If the key is not in the ignition, you won't be able to start the car." > > "If not the key is in the ignition, you won't be able to start the car." > > > Who like that second one speaks? :) "If the key is not in the ignition, you will be able to start the car, not." Mel. From jpiitula at ling.helsinki.fi Sat Oct 8 09:07:12 2011 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 08 Oct 2011 16:07:12 +0300 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: Mel writes: > Steven D'Aprano wrote: > > > candide wrote: > > > >> So what is the usefulness of the "not in" operator ? Recall what Zen of > >> Python tells > >> > >> There should be one-- and preferably only one --obvious way to do it. > > > > And "not in" is the obvious way to do it. > > > > > > "If the key is not in the ignition, you won't be able to start the car." > > > > "If not the key is in the ignition, you won't be able to start the car." > > > > > > Who like that second one speaks? > > :) > "If the key is not in the ignition, you will be able to start the car, not." Oh, be consistent. "If not the key is in the ignition, not you will be able to start the car." But both negations can be avoided by modus tollens. "If you are able to start the car, the key is in the ignition." And one could express "x not in s" as "(x in s) implies False" without making the "not" explicit if "implies" was in the language. (I know about <= but I also witnessed an unpleasant thread in another newsgroup where people insisted that <= should not be defined for truth values at all, and I also happen to like Python's "not in".) From roy at panix.com Sat Oct 8 09:31:10 2011 From: roy at panix.com (Roy Smith) Date: Sat, 08 Oct 2011 09:31:10 -0400 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> Message-ID: In article <87ehyn8xlp.fsf at dpt-info.u-strasbg.fr>, Alain Ketterlin wrote: > Sure, but note that you can also reformulate != using not and ==, < > using not and >=, etc. Operators like "not in" and "is not" should > really be considered single tokens, even though they seem to use "not". > And I think they are really convenient. If you want to take it one step further, all the boolean operators can be derived from nand (the dualists would insist on using nor). From candide at free.invalid Sat Oct 8 10:40:58 2011 From: candide at free.invalid (candide) Date: Sat, 08 Oct 2011 16:40:58 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> Message-ID: <4e9060fa$0$27980$426a34cc@news.free.fr> Le 08/10/2011 14:41, Alain Ketterlin a ?crit : > Operators like "not in" and "is not" should > really be considered single tokens, even though they seem to use "not". > And I think they are really convenient. I realize that I was confused by the lexical form of the "not in" operator : it is made by juxtaposing two other operators. Operators composed from two other operators exist, for instance != but the two cannot be separated, for instance 2 ! = 3 is not a valid expression. Said in another way, in Python syntax, usually a "lexically juxtaposed operator" is seen as a whole. This is not the case for an operator such as "is not" or "not in" because for example >>> 2 is not 3 is a valid statement. A notin operator or isnot operator would be less confusing (at least in my case ;) ). From candide at free.invalid Sat Oct 8 10:41:11 2011 From: candide at free.invalid (candide) Date: Sat, 08 Oct 2011 16:41:11 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: <4e902932$0$23273$426a34cc@news.free.fr> References: <4e902932$0$23273$426a34cc@news.free.fr> Message-ID: <4e906108$0$27980$426a34cc@news.free.fr> Le 08/10/2011 12:42, candide a ?crit : > >>> not ('th' in "python") > False > >>> After browsing source code, I realize that parenthesis are not necessary ("not" has higher precedence than "in"). From candide at free.invalid Sat Oct 8 10:41:43 2011 From: candide at free.invalid (candide) Date: Sat, 08 Oct 2011 16:41:43 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: <14fa9dc2-d4bb-4fc9-955d-ac28848d9380@n8g2000yqd.googlegroups.com> References: <4e902932$0$23273$426a34cc@news.free.fr> <14fa9dc2-d4bb-4fc9-955d-ac28848d9380@n8g2000yqd.googlegroups.com> Message-ID: <4e906128$0$27980$426a34cc@news.free.fr> Le 08/10/2011 12:50, Jon Clements a ?crit : > 10 - 5 as 10 + -5 (as obviously the - is redundant as an operation), > and 10 / 2 as int(10 * .5) or something, who needs a divide!? OK, I see your point but I was supposing non-membershipness seldom needed and in fact one can suppose that test membership is heavily more used than test non-membership. In fact, it seems that most Python operators have an "antonym" operator, for instance : == vs != < vs >= is vs is not + vs - etc From candide at free.invalid Sat Oct 8 10:41:51 2011 From: candide at free.invalid (candide) Date: Sat, 08 Oct 2011 16:41:51 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e90612f$0$27980$426a34cc@news.free.fr> Le 08/10/2011 14:01, Steven D'Aprano a ?crit : > And "not in" is the obvious way to do it. > > Obvious ? Not so. I performed some code mining and it appears that even good sources make use of "not (foo in bar)" expressions. ******** begin examples *************** from drpython/drPluginDialog.py ----------------------------- if not (plugin in self.parent.pluginstoremove): from numpy/f2py/crackfortran.py ------------------------------- if not (l[0] in spacedigits): from crunchy1.0alpha1/crunchy/src/plugins/vlam_editor.py ---------------------------------------------------------- if (("no_copy" in vlam) and not ("no_pre" in vlam)) or (not python_code): from Cpython/Python-3.1a1/Lib/logging/__init__.py -------------------------------------------------- if not (hdlr in self.handlers): from Cpython/Python-2.6.2/Lib/idlelib/configHandler.py ------------------------------------------------------- if not (configType in ('main','extensions','highlight','keys')): raise InvalidConfigType, 'Invalid configType specified' from pygtk-2.22.0/gtk/webkitgtk/WebKit-r93015/Source/JavaScriptCore/KeywordLookupGenerator.py --------------------------------------------------------------------------------------------- if not (key[0] in self.keys): from pypy/pypy-pypy-release-1.6/lib-python/2.7/logging/__init__.py ------------------------------------------------------------------ if not (hdlr in self.handlers): ******** end examples *************** _Many_ more examples of this type are avalaible. The obviousness of an "is not" operator is very debatable. Do you have standard functions or method such as isnotinstance, isnotsubset, isnotdir, isnotfile, isnotalpha, etc ? In my case, It took a long time to realize the existence of a "true" "not in" operator as I explain in my response to Alain. Imagine, /Dive Into Python/ book doesn't describe this operator per se and provides only one source file using it. Official Python tutorial at python.org didn't provide even one. > "If the key is not in the ignition, you won't be able to start the car." > > "If not the key is in the ignition, you won't be able to start the car." > > > Who like that second one speaks? > Depends if you are aware of negative form conjugation. From rosuav at gmail.com Sat Oct 8 10:51:03 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Oct 2011 01:51:03 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: <4e9060fa$0$27980$426a34cc@news.free.fr> References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e9060fa$0$27980$426a34cc@news.free.fr> Message-ID: On Sun, Oct 9, 2011 at 1:40 AM, candide wrote: > A notin operator or isnot operator would be less confusing (at least in my > case ;) ). > Let's replace both of them. in --> foo extant bar not in --> foo extinct bar That would solve the problem, wouldn't it? *ducking for cover* ChrisA From thorsten at thorstenkampe.de Sat Oct 8 11:13:18 2011 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 8 Oct 2011 17:13:18 +0200 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: * candide (Sat, 08 Oct 2011 16:41:11 +0200) > After browsing source code, I realize that parenthesis are not > necessary ("not" has higher precedence than "in"). Lower precedence. Thorsten From d at davea.name Sat Oct 8 11:16:54 2011 From: d at davea.name (Dave Angel) Date: Sat, 08 Oct 2011 11:16:54 -0400 Subject: Usefulness of the "not in" operator In-Reply-To: <4e906108$0$27980$426a34cc@news.free.fr> References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: <4E906966.4050600@davea.name> On 01/-10/-28163 02:59 PM, candide wrote: > Le 08/10/2011 12:42, candide a ?crit : > > >> >>> not ('th' in "python") >> False >> >>> > > > > After browsing source code, I realize that parenthesis are not > necessary ("not" has higher precedence than "in"). > You should say "... parenthesis are not necessary ("not" has LOWER precedence than "in")." -- DaveA From candide at free.invalid Sat Oct 8 11:18:23 2011 From: candide at free.invalid (candide) Date: Sat, 08 Oct 2011 17:18:23 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: <4e9069c0$0$648$426a74cc@news.free.fr> Le 08/10/2011 17:13, Thorsten Kampe a ?crit : > * candide (Sat, 08 Oct 2011 16:41:11 +0200) >> After browsing source code, I realize that parenthesis are not >> necessary ("not" has higher precedence than "in"). > > Lower precedence. > Ooops, thanks. From rosuav at gmail.com Sat Oct 8 11:20:01 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Oct 2011 02:20:01 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: <4E906966.4050600@davea.name> References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> <4E906966.4050600@davea.name> Message-ID: On Sun, Oct 9, 2011 at 2:16 AM, Dave Angel wrote: > You should say > ? ?"... parenthesis are not necessary ("not" has LOWER precedence than > "in")." > Is "are not" an operator in English, or should this be "not parentheses are necessary"? ChrisA From invalid at invalid.invalid Sat Oct 8 11:28:17 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Sat, 8 Oct 2011 15:28:17 +0000 (UTC) Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2011-10-08, Steven D'Aprano wrote: > candide wrote: > >> So what is the usefulness of the "not in" operator ? Recall what Zen of >> Python tells >> >> There should be one-- and preferably only one --obvious way to do it. > > And "not in" is the obvious way to do it. > > > "If the key is not in the ignition, you won't be able to start the car." > > "If not the key is in the ignition, you won't be able to start the car." > > > Who like that second one speaks? Yoda. -- Grant Edwards grant.b.edwards Yow! ... I don't like FRANK at SINATRA or his CHILDREN. gmail.com From nobody at nowhere.com Sat Oct 8 11:30:23 2011 From: nobody at nowhere.com (Nobody) Date: Sat, 08 Oct 2011 16:30:23 +0100 Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> <4e8d231e$0$29978$c3e8da3$5496439d@news.astraweb.com> <4aeb76e9-511f-4a46-94c7-bf2ab84877df@z12g2000yqz.googlegroups.com> Message-ID: On Wed, 05 Oct 2011 21:39:17 -0700, Greg wrote: > Here is the final code for those who are struggling with similar > problems: > > ## open and decode file > # In this case, the encoding comes from the charset argument in a meta > tag > # e.g. > fileObj = open(filePath,"r").read() > fileContent = fileObj.decode("iso-8859-2") > fileSoup = BeautifulSoup(fileContent) The fileObj.decode() step should be unnecessary, and is usually undesirable; Beautiful Soup should be doing the decoding itself. If you actually know the encoding (e.g. from a Content-Type header), you can specify it via the fromEncoding parameter to the BeautifulSoup constructor, e.g.: fileSoup = BeautifulSoup(fileObj.read(), fromEncoding="iso-8859-2") If you don't specify the encoding, it will be deduced from a meta tag if one is present, or a Unicode BOM, or using the chardet library if available, or using built-in heuristics, before finally falling back to Windows-1252 (which seems to be the preferred encoding of people who don't understand what an encoding is or why it needs to be specified). From candide at free.invalid Sat Oct 8 12:05:08 2011 From: candide at free.invalid (candide) Date: Sat, 08 Oct 2011 18:05:08 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: <4e9074b6$0$29120$426a74cc@news.free.fr> Le 08/10/2011 17:16, Dave Angel a ?crit : > You should say > "... parenthesis are not necessary ("not" has LOWER precedence than "in")." > I should, yes, I confess ;) In my defense, I must tell that Python document reference here : http://docs.python.org/reference/expressions.html#summary has an anti-iconic way to display the order precedence. If an operator OP1 has higher precedence than an operator OP2 , it means that, at evaluation time, you execute OP1 FIRST and operator OP2 later. So, its seems very natural to present FIRST operator with stronger precedence. So, if you iconically present this material in a tabular display, you present FIRST (ie at the top because usually we process tabular material starting on the upper part) what you need to calculate FIRST and, again, you present at the TOP the HIGHer precedence and at the BOTTOM the LOWer precedence. Documentations usually provide the table in this order (higher to lower), cf. the table in K&R book for C programing language or here for the C++ PL : http://en.cppreference.com/w/cpp/language/operator_precedence or again there for the Java PL : http://download.oracle.com/javase/tutorial/java/nutsandbolts/operators.html From steve+comp.lang.python at pearwood.info Sat Oct 8 12:08:35 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 09 Oct 2011 03:08:35 +1100 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> Message-ID: <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Roy Smith wrote: > If you want to take it one step further, all the boolean operators can > be derived from nand (the dualists would insist on using nor). Let's define the boolean values and operators using just two functions: def true(x, y): return x def false(x, y): return y That's all we need to define all of Boolean algebra. Unfortunately, it's a bit ugly in Python: >>> true So let's add a helper function to prettify the output: def pr(b): print(b(true, false).__name__) >>> pr(true) true Much nicer! Now define NAND: def Nand(a, b): return (lambda c: lambda x, y: c(y, x))(a(b, a)) and we're done. All of boolean algebra can now be derived from Nand. >>> def Not(b): ... return Nand(b, b) ... >>> pr(Not(true)) false >>> pr(Not(false)) true >>> def And(a, b): ... return Nand(Nand(a, b), Nand(a, b)) ... >>> pr(And(true, false)) false >>> pr(And(true, true)) true >>> def Or(a, b): ... return Nand(Nand(a, a), Nand(b, b)) ... >>> pr(Or(true, false)) true >>> pr(Or(false, false)) false >>> def Xor(a, b): ... return And(Nand(a, b), Or(a, b)) ... >>> pr(Xor(true, false)) true >>> pr(Xor(true, true)) false and so forth. -- Steven From steve+comp.lang.python at pearwood.info Sat Oct 8 12:18:36 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 09 Oct 2011 03:18:36 +1100 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> <4e90612f$0$27980$426a34cc@news.free.fr> Message-ID: <4e9077dd$0$29997$c3e8da3$5496439d@news.astraweb.com> candide wrote: > Le 08/10/2011 14:01, Steven D'Aprano a ?crit : > > > And "not in" is the obvious way to do it. > > Obvious ? Not so. I performed some code mining and it appears that even > good sources make use of "not (foo in bar)" expressions. All that proves is that even expert Python developers can, on occasion, write non-idiomatic Python -- or that they accept code contributed by non-expert Python developers, and don't bother adjusting trivial stylistic flaws. When I learned Pascal 20+ years ago, it took me a long time to stop writing "x not in y" and learn the non-English-like "not x in y". Then I learned Python, and it took me a while to stop writing Pascal code in Python. Bad habits take a while to disappear. (I never added superfluous semi-colons after each line though!) -- Steven From rustompmody at gmail.com Sat Oct 8 12:18:58 2011 From: rustompmody at gmail.com (rusi) Date: Sat, 8 Oct 2011 09:18:58 -0700 (PDT) Subject: help References: <9f8pa1Fsh8U3@mid.individual.net> Message-ID: On Oct 8, 2:51?pm, X1 wrote: > easy_install does not exist on Fedora. http://lmgtfy.com/?q=easy_install+fedora From rustompmody at gmail.com Sat Oct 8 12:31:59 2011 From: rustompmody at gmail.com (rusi) Date: Sat, 8 Oct 2011 09:31:59 -0700 (PDT) Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> Message-ID: On Oct 8, 6:31?pm, Roy Smith wrote: > In article <87ehyn8xlp.... at dpt-info.u-strasbg.fr>, > ?Alain Ketterlin wrote: > > > Sure, but note that you can also reformulate != using not and ==, < > > using not and >=, etc. Operators like "not in" and "is not" should > > really be considered single tokens, even though they seem to use "not". > > And I think they are really convenient. > > If you want to take it one step further, all the boolean operators can > be derived from nand (the dualists would insist on using nor). ^^^^^^^^^^^^ ???? From roy at panix.com Sat Oct 8 12:34:42 2011 From: roy at panix.com (Roy Smith) Date: Sat, 08 Oct 2011 12:34:42 -0400 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: In article <4e906108$0$27980$426a34cc at news.free.fr>, candide wrote: > After browsing source code, I realize that parenthesis are not necessary > ("not" has higher precedence than "in"). Here's my take on parenthesis: If you need to look up whether they're necessary or not, they are :-) From rosuav at gmail.com Sat Oct 8 12:43:31 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Oct 2011 03:43:31 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> Message-ID: On Sun, Oct 9, 2011 at 3:31 AM, rusi wrote: >> If you want to take it one step further, all the boolean operators can >> be derived from nand (the dualists would insist on using nor). > ? ? ? ? ? ? ? ? ? ? ? ?^^^^^^^^^^^^ > ???? > I'm not sure what you're questioning, but it's possible to derive all boolean operators from either nand or nor. Most hardware these days is built out of silicon NAND gates, but there's no reason not to do it as NOR gates. ChrisA From roy at panix.com Sat Oct 8 12:44:35 2011 From: roy at panix.com (Roy Smith) Date: Sat, 08 Oct 2011 12:44:35 -0400 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> Message-ID: In article , rusi wrote: > On Oct 8, 6:31?pm, Roy Smith wrote: > > In article <87ehyn8xlp.... at dpt-info.u-strasbg.fr>, > > ?Alain Ketterlin wrote: > > > > > Sure, but note that you can also reformulate != using not and ==, < > > > using not and >=, etc. Operators like "not in" and "is not" should > > > really be considered single tokens, even though they seem to use "not". > > > And I think they are really convenient. > > > > If you want to take it one step further, all the boolean operators can > > be derived from nand (the dualists would insist on using nor). > ^^^^^^^^^^^^ > ???? Dualist (noun): a made up word referring to wrong-thinking people who have rejected the teachings of the Prophet Nand and believe the nor is the One True Operation on which all over operations can be constructed. From g4b.org at gmail.com Sat Oct 8 15:19:40 2011 From: g4b.org at gmail.com (g4b) Date: Sat, 8 Oct 2011 12:19:40 -0700 (PDT) Subject: GUIs - A Modest Proposal In-Reply-To: <76d1$4c1c150a$4275d90a$2055@FUSE.NET> References: <6989fa9b-f642-4939-8ec9-c6e17eae42f5@y11g2000yqm.googlegroups.com> <61fe0cb7-e7a6-4f31-9a3e-5dfd2a6b8edf@j8g2000yqd.googlegroups.com> <66e22bca-17eb-43dd-b343-82278cb23cd8@x27g2000prf.googlegroups.com> <17111c68-694e-4a27-a1d2-30199ab67fe3@z13g2000prh.googlegroups.com> <76d1$4c1c150a$4275d90a$2055@FUSE.NET> Message-ID: <32365686.149.1318101580209.JavaMail.geo-discussion-forums@yqmn40> On the subject of the gui discussion mentioned here last year, which you get lead to if you read around in the pyjamas docs, I have to admit, since I know both development types (gwt, wx, qt) and (django, jquery), I have to state the fact, that pyjamas should also consider bonding with native javascript library developments. Excuse me if I accidentaly go a bit off track, but I guessed, I might bring in my thoughts (but I hope, not to get emotional responses which made this thread a bit hard to follow in the end) The interchange between fixed sized GUI applications and browsing technology as a whole could for example get very interesting for django development, if javascript operated functions would be taken over by native python. I was just looking at pyquery, a python implementation of jquery, which could easily backbone jquery itself on the python end. Now this is not pyjamas' task, but the pyjs compiler could be used, so that jquery code could be written for both languages. Since jquery DOM interfacing is way easier, and hot fixes can be made by javascript development teams, GUI elements of jquery libraries could be integrated into the application. While the functionality of the UI therefore still is GUI based in terms of fixed applications, like pyjamas desktop, concurrent efforts could take place from the so called "web-development" gui layouts. On that front, a lot of talented coders exist in younger generations, which would have the ability to develop the web frontend in closer relation to the web-designers, mainting the key issues for the world-wide-web: design, speed and small loading time. Long story short: if you could write jquery in python which actually compiles into jquery in javascript, and even runs on python itself, you could deploy widgets natively from python in django, and dont have to leave python to improve webapplications with its native strengths. You can free yourself up pretty soon from having too much problems with ui. the designer can do that. You focus on datasets, server-client-api, or you can expose one of your pyjamas widgets as jquery plugin integrating validation of data server and clientside. You can still develop a control application or other integrated software parts natively with pyjamas desktop, knowing the web uses correct code. Of course that depends on how much overhead pyjamas libraries have if you only take a piece of it out, like a richtext element or a fully bloated editor, but even then, internally you load the app anyway up front, externally the user transitions from being a human guest to being a system user only in certain occasions. Any thoughts? From jredgrave at capisco.com Sat Oct 8 16:57:09 2011 From: jredgrave at capisco.com (Jon Redgrave) Date: Sat, 8 Oct 2011 13:57:09 -0700 (PDT) Subject: PDB command <-> variable clashes References: Message-ID: <62e1b36f-7e5c-4e8e-9738-ea5e468c8332@dd6g2000vbb.googlegroups.com> On Oct 8, 1:18?pm, K??ri?inen Anssi wrote: > I am currently debugging the django test cases, and there are a lot of variables names like w, q, where, condition and so on. Especially variables like w, q, c, r are really annoying. It would be cool if pdb would detect a clash and in that case ask you what to do. Nothing more annoying than stepping through the code, finally finding the problematic place and then trying to find out what c.somevar contains... I am using Python 2.6. > > Is there some way to do this? My googling didn't turn out anything. Or is it recommended to use something else instead of pdb? > > Thank you for your time, > ?- Anssi K??ri?inen Its not perfect but I use in sitecustomize def precmd(self,l): if '.' in l: if l[:1]!='!':l='!'+l return l if l in self.curframe.f_locals: return '!'+l if l.startswith('@'): return l[1:] return l import pdb pdb.Pdb.precmd = precmd What this does is q ->variable q if it exists else quit command @q ->always quit !q ->always variable HTH Jon From timr at probo.com Sat Oct 8 18:20:44 2011 From: timr at probo.com (Tim Roberts) Date: Sat, 08 Oct 2011 15:20:44 -0700 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> <4e8bed30$0$29978$c3e8da3$5496439d@news.astraweb.com> <87wrcjzmql.fsf@benfinney.id.au> Message-ID: Dennis Lee Bieber wrote: > > While I wouldn't want to write an FFT in COBOL, one can't deny that >laying out fixed width reports and moving blocks of decimal data between >record layouts is quite easy in COBOL. Absolutely. I've always thought the Data Section in COBOL was conceptually ahead of its time. It makes you THINK about your data structures more than, say "struct" in C. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From timr at probo.com Sat Oct 8 19:35:50 2011 From: timr at probo.com (Tim Roberts) Date: Sat, 08 Oct 2011 16:35:50 -0700 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: <7in1975qnestbd79rlfkpfd62in3hum4km@4ax.com> Roy Smith wrote: >In article <4e906108$0$27980$426a34cc at news.free.fr>, > candide wrote: > >> After browsing source code, I realize that parenthesis are not necessary >> ("not" has higher precedence than "in"). > >Here's my take on parenthesis: If you need to look up whether they're >necessary or not, they are :-) Amen. +1 -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From alex.kapps at web.de Sat Oct 8 20:17:53 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Sun, 09 Oct 2011 02:17:53 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: <7in1975qnestbd79rlfkpfd62in3hum4km@4ax.com> References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> <7in1975qnestbd79rlfkpfd62in3hum4km@4ax.com> Message-ID: <4E90E831.4090300@web.de> On 09.10.2011 01:35, Tim Roberts wrote: > Roy Smith wrote: >> In article<4e906108$0$27980$426a34cc at news.free.fr>, >> candide wrote: >> >>> After browsing source code, I realize that parenthesis are not necessary >>> ("not" has higher precedence than "in"). >> >> Here's my take on parenthesis: If you need to look up whether they're >> necessary or not, they are :-) > > Amen. +1 So LISP (Lots of Irritating Superfluous Parentheses) was right all the time and is now finally vindicated? ;-) From alex.kapps at web.de Sat Oct 8 20:25:27 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Sun, 09 Oct 2011 02:25:27 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E90E9F7.9000300@web.de> On 08.10.2011 18:08, Steven D'Aprano wrote: > Let's define the boolean values and operators using just two functions: [SNIP] Have you just explained Church booleans in an understandable language? Awesome. I still have to chew on this, but I think this is the first time where I might understand it. Thanks! Even if it's off-topic, could you add some similar explanations for Church numerals (maybe Lambda calculus it isn't too much?) From rosuav at gmail.com Sat Oct 8 21:29:45 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Oct 2011 12:29:45 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: I sent this email twelve hours ago but to the wrong mailing list *blush*. Since nobody else has raised the point, I'll repost it. On Sun, Oct 9, 2011 at 12:07 AM, Jussi Piitulainen wrote: > But both negations can be avoided by modus tollens. > > "If you are able to start the car, the key is in the ignition." > But this translation implies looking at the result and ascertaining the state, which is less appropriate to a programming language. It's more like: "If you found that you were able to start the car, the key must have been in the ignition." and is thus quite inappropriate to the imperative style. A functional language MAY be able to use this style, but Python wants to have the condition and then the action. ChrisA From roy at panix.com Sat Oct 8 21:41:03 2011 From: roy at panix.com (Roy Smith) Date: Sat, 08 Oct 2011 21:41:03 -0400 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article , Chris Angelico wrote: > I sent this email twelve hours ago but to the wrong mailing list > *blush*. Since nobody else has raised the point, I'll repost it. > > On Sun, Oct 9, 2011 at 12:07 AM, Jussi Piitulainen > wrote: > > But both negations can be avoided by modus tollens. > > > > "If you are able to start the car, the key is in the ignition." > > > > But this translation implies looking at the result and ascertaining > the state, which is less appropriate to a programming language. It's > more like: > > "If you found that you were able to start the car, the key must have > been in the ignition." > > and is thus quite inappropriate to the imperative style. A functional > language MAY be able to use this style, but Python wants to have the > condition and then the action. > > ChrisA The key is in the ignition if you are able to start the car else you hot-wired it. From miki.tebeka at gmail.com Sat Oct 8 22:52:25 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Sat, 8 Oct 2011 19:52:25 -0700 (PDT) Subject: PDB command <-> variable clashes In-Reply-To: References: Message-ID: <23757466.646.1318128745524.JavaMail.geo-discussion-forums@prho12> If you want to view the variable, use the "p" (print) command. Then there is no name clash. From miki.tebeka at gmail.com Sat Oct 8 22:52:25 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Sat, 8 Oct 2011 19:52:25 -0700 (PDT) Subject: PDB command <-> variable clashes In-Reply-To: References: Message-ID: <23757466.646.1318128745524.JavaMail.geo-discussion-forums@prho12> If you want to view the variable, use the "p" (print) command. Then there is no name clash. From ericsnowcurrently at gmail.com Sun Oct 9 00:21:02 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Sat, 8 Oct 2011 22:21:02 -0600 Subject: "IX" as shorthand for "Interface" Message-ID: I'm writing a bunch of classes that have "Interface" in the name and find that the length of the subsequent names is starting to get in the way of readability (I don't really care about saving keystrokes). Is "IX" conventional enough to use in place of "Interface" in a class name? Thanks! -eric From clp2 at rebertia.com Sun Oct 9 00:31:10 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 8 Oct 2011 21:31:10 -0700 Subject: "IX" as shorthand for "Interface" In-Reply-To: References: Message-ID: On Sat, Oct 8, 2011 at 9:21 PM, Eric Snow wrote: > I'm writing a bunch of classes that have "Interface" in the name and > find that the length of the subsequent names is starting to get in the > way of readability (I don't really care about saving keystrokes). ?Is > "IX" conventional enough to use in place of "Interface" in a class > name? ?Thanks! But classes and interfaces are distinct concepts... - Chris From ericsnowcurrently at gmail.com Sun Oct 9 00:49:08 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Sat, 8 Oct 2011 22:49:08 -0600 Subject: "IX" as shorthand for "Interface" In-Reply-To: References: Message-ID: On Sat, Oct 8, 2011 at 10:31 PM, Chris Rebert wrote: > On Sat, Oct 8, 2011 at 9:21 PM, Eric Snow wrote: >> I'm writing a bunch of classes that have "Interface" in the name and >> find that the length of the subsequent names is starting to get in the >> way of readability (I don't really care about saving keystrokes). ?Is >> "IX" conventional enough to use in place of "Interface" in a class >> name? ?Thanks! > > But classes and interfaces are distinct concepts... > > - Chris > I saw what you did right there! Be that as it may, is "IX" a common enough abbreviation? -eric From ben+python at benfinney.id.au Sun Oct 9 01:52:56 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 09 Oct 2011 16:52:56 +1100 Subject: "IX" as shorthand for "Interface" References: Message-ID: <87aa9azp6v.fsf@benfinney.id.au> Eric Snow writes: > I'm writing a bunch of classes that have "Interface" in the name and > find that the length of the subsequent names is starting to get in the > way of readability (I don't really care about saving keystrokes). Is > "IX" conventional enough to use in place of "Interface" in a class > name? Thanks! Convention in which community? If you just mean in general programming community, I don't think ?IX? would suggest interface at all. The only common convention I've seen is the ?I? prefix: ?IFoo? to suggest ?the Foo interface?. But that's hopelessly ambiguous, and I don't recommend it. -- \ ?Sane people have an appropriate perspective on the relative | `\ importance of foodstuffs and human beings. Crazy people can't | _o__) tell the difference.? ?Paul Z. Myers, 2010-04-18 | Ben Finney From yasar11732 at gmail.com Sun Oct 9 02:30:58 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Sun, 9 Oct 2011 09:30:58 +0300 Subject: Working with spreadsheet files Message-ID: Hi, Does anyone know a good tutorial about working with Spreadsheet files (e.g. excel files) with Python. I have found xlutils, but there doesn't seem to be any documentation or tutorial about it that I could find. So, any suggestions? -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Sun Oct 9 04:09:12 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 09 Oct 2011 19:09:12 +1100 Subject: "IX" as shorthand for "Interface" References: Message-ID: <4e9156a8$0$29970$c3e8da3$5496439d@news.astraweb.com> Eric Snow wrote: > I'm writing a bunch of classes that have "Interface" in the name and > find that the length of the subsequent names is starting to get in the > way of readability (I don't really care about saving keystrokes). Is > "IX" conventional enough to use in place of "Interface" in a class > name? Thanks! I've never seen or heard of "IX" as an abbreviation for Interface. Apart from the fact that they both start with I, what is the connection? Is the fact that "IX" is pronounced Icks meant as commentary about Interfaces perhaps? -- Steven From mail at timgolden.me.uk Sun Oct 9 05:00:54 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 09 Oct 2011 10:00:54 +0100 Subject: Working with spreadsheet files In-Reply-To: References: Message-ID: <4E9162C6.80801@timgolden.me.uk> On 09/10/2011 07:30, Ya?ar Arabac? wrote: > Does anyone know a good tutorial about working with Spreadsheet files > (e.g. excel files) with Python. I have found xlutils, but there doesn't > seem to be any documentation or tutorial about it that I could find. So, > any suggestions? http://www.python-excel.org/ TJG From vishwasidthan at gmail.com Sun Oct 9 05:44:11 2011 From: vishwasidthan at gmail.com (vishwa nathan) Date: Sun, 9 Oct 2011 02:44:11 -0700 (PDT) Subject: vdfgdfg Message-ID: <81f3673d-3f4b-440e-b50d-078c9a626751@t23g2000prg.googlegroups.com> http://123maza.com/65/white725/ From mail at timgolden.me.uk Sun Oct 9 05:51:24 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 09 Oct 2011 10:51:24 +0100 Subject: Thread handling issue In-Reply-To: References: <4E8EBC32.9060000@timgolden.me.uk> <4E8F1336.3070907@timgolden.me.uk> Message-ID: <4E916E9C.3000908@timgolden.me.uk> On 08/10/2011 11:51, Paul wrote: > I think I'll wait for the user to actually make a change after cancelling the > output selection, in case they go straight back without making changes. If they > make a change I think I'll try what you suggested and send off a new thread, and > send an event to the previous thread. Would this mean I'd need to use > wx.lib.newevent.NewCommandEvent() to get a new event for each thread I create? > and I'd have to pass the second return value from that, the event binder to the > thread to bind to a clean up and exit method? I'm afraid I'm more-or-less completely unfamiliar with the wx way of doing things. You'd hopefully get useful answers from a wx-focused mailing list. (This is always the difficulty in translating between a "in theory you could do this" answer and a real-world "I've got this and that and the other " situation :) ) TJG From nobody at nowhere.com Sun Oct 9 06:12:59 2011 From: nobody at nowhere.com (Nobody) Date: Sun, 09 Oct 2011 11:12:59 +0100 Subject: "IX" as shorthand for "Interface" References: Message-ID: On Sat, 08 Oct 2011 22:21:02 -0600, Eric Snow wrote: > I'm writing a bunch of classes that have "Interface" in the name and > find that the length of the subsequent names is starting to get in the > way of readability (I don't really care about saving keystrokes). Is > "IX" conventional enough to use in place of "Interface" in a class > name? Thanks! I've only ever seen "ix" used as an abbreviation for "index". The common abbrevations for "interface" are "if" (e.g. the Linux networking headers), "iface", or the "I" prefix in Windows' COM. From python.list at tim.thechases.com Sun Oct 9 08:20:45 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 09 Oct 2011 07:20:45 -0500 Subject: DRY functions with named attributes used as default arguments Message-ID: <4E91919D.7010007@tim.thechases.com> My intent is to have a function object something like def foo(arg1, arg2=foo.DEFAULT): return int(do_stuff(arg1, arg2)) foo.SPECIAL = 42 foo.MONKEY = 31415 foo.DEFAULT = foo.SPECIAL so I can call it with either result = foo(myarg) or result = foo(myarg, foo.SPECIAL) However I can't do this because foo.DEFAULT isn't defined at the time the function is created. I'd like to avoid hard-coding things while staying DRY, so I don't like def foo(arg1, arg2=42) because the default might change due to business rule changes, I have a dangling "magic constant" and if the value of SPECIAL changes, I have to catch that it should be changed in two places. My current hack/abuse is to use __new__ in a class that can contain the information: class foo(object): SPECIAL = 42 MONKEY = 31415 DEFAULT = SPECIAL def __new__(cls, arg1, arg2=DEFAULT): return int(do_stuff(arg1, arg2)) i1 = foo("spatula") i2 = foo("tapioca", foo.MONKEY) 1) is this "icky" (a term of art ;-) 2) or is this reasonable 3) or is there a better way to do what I want? Thanks, -tkc From arnodel at gmail.com Sun Oct 9 09:19:34 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sun, 9 Oct 2011 14:19:34 +0100 Subject: DRY functions with named attributes used as default arguments In-Reply-To: <4E91919D.7010007@tim.thechases.com> References: <4E91919D.7010007@tim.thechases.com> Message-ID: On 9 October 2011 13:20, Tim Chase wrote: > My intent is to have a function object something like > > ?def foo(arg1, arg2=foo.DEFAULT): > ? ?return int(do_stuff(arg1, arg2)) > ?foo.SPECIAL = 42 > ?foo.MONKEY = 31415 > ?foo.DEFAULT = foo.SPECIAL > > so I can call it with either > > ?result = foo(myarg) > > or > > ?result = foo(myarg, foo.SPECIAL) > > However I can't do this because foo.DEFAULT isn't defined at the time the > function is created. ?I'd like to avoid hard-coding things while staying > DRY, so I don't like > > ?def foo(arg1, arg2=42) > > because the default might change due to business rule changes, I have a > dangling "magic constant" and if the value of SPECIAL changes, I have to > catch that it should be changed in two places. > > My current hack/abuse is to use __new__ in a class that can contain the > information: > > ?class foo(object): > ? ?SPECIAL = 42 > ? ?MONKEY = 31415 > ? ?DEFAULT = SPECIAL > ? ?def __new__(cls, arg1, arg2=DEFAULT): > ? ? ?return int(do_stuff(arg1, arg2)) > > ?i1 = foo("spatula") > ?i2 = foo("tapioca", foo.MONKEY) > > 1) is this "icky" (a term of art ;-) > 2) or is this reasonable > 3) or is there a better way to do what I want? > Why do you want these argument values to be attributes of the function? Anyway, simpler than abusing classes: foo_default = 42 def foo(arg1, arg2=foo_default): ... foo.DEFAULT = foo_default del foo_default ... Or get the default at function runtime: def foo(arg1, arg2=None): if arg2 is None: arg2 = foo.DEFAULT ... foo.DEFAULT = 42 ... But I'd probably simply go for foo_DEFAULT, foo_MONKEY and foo_SPECIAL. They're also quicker (1 dict lookup instead of 2) -- Arnaud From jpc at parallelthoughts.org Sun Oct 9 09:30:42 2011 From: jpc at parallelthoughts.org (John P. Crackett) Date: Sun, 09 Oct 2011 14:30:42 +0100 Subject: Using Python xmlrpclib to build XMLRPC clients for a server with variable RPC names Message-ID: <1318167042.3120.54.camel@ptlws01.config> I need to write prototype XMLRPC clients using xmlrpclib for a server that has variable RPC names and I'd like to use Python as the prototyping tool. I've searched but can't find any relevant advice online. Any pointers would be gratefully received; details follow. The server in question constructs method names dynamically using the names of objects created by the client. Since the xmlrpclib ServerProxy object uses methods mirroring the RPC names I would need to be able to do the following: api = xmlrpclib.ServerProxy(serverURL) api.createObject("foo") api.foo.callOne() where I don't know what "foo" will actually be in advance. As an added complication, object names need to be concatenated using "-" as a separator to form compound RPC names. Following on from the example above, this could lead to: api = xmlrpclib.ServerProxy(serverURL) api. createObjects("foo", "far") api.foo-bar.callOne() Where I don't know, again, what "foo" and "bar" will actually be in advance. "foo-bar" is obviously not a valid Python method name and this is preventing me from hard-coding just to get a prototype going. Is Python + xmlrpclib usable under these circumstances? If so, a pointer in the right direction would be appreciated. Apologies if there's some glaringly obvious way of doing this that I have overlooked - I'm new to Python. Many thanks in anticipation. -- /jpc From roy at panix.com Sun Oct 9 11:02:36 2011 From: roy at panix.com (Roy Smith) Date: Sun, 09 Oct 2011 11:02:36 -0400 Subject: "IX" as shorthand for "Interface" References: Message-ID: In article , Eric Snow wrote: > I saw what you did right there! Be that as it may, is "IX" a > common enough abbreviation? I would not recognize it at first glance. If anything, I think of X as standing for experience (UI -- User Interface, UX -- User Experience). But, if it's a big package and you adopt a uniform naming convention, it shouldn't be a problem. Especially if you have some kind of README that describes what conventions you are using. Or you could use I7E :-) From __peter__ at web.de Sun Oct 9 11:19:12 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 09 Oct 2011 17:19:12 +0200 Subject: "IX" as shorthand for "Interface" References: Message-ID: Roy Smith wrote: > In article , > Eric Snow wrote: > >> I saw what you did right there! Be that as it may, is "IX" a >> common enough abbreviation? What Roy really wanted to say: I w3d n1t r7e it at f3t g4e. If a6g, I t3k of X as s6g f1r e8e (UI -- U2r I7e, UX -- U2r E8e). B1t, if it's a b1g p5e a1d y1u a3t a u5m n4g c8n, it s5n't be a p5m. E8y if y1u h2e s2e k2d of R4E t2t d7s w2t c9s y1u a1e u3g. ;) From steve+comp.lang.python at pearwood.info Sun Oct 9 11:37:57 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 10 Oct 2011 02:37:57 +1100 Subject: DRY functions with named attributes used as default arguments References: Message-ID: <4e91bfd6$0$29989$c3e8da3$5496439d@news.astraweb.com> Tim Chase wrote: > My intent is to have a function object something like > > def foo(arg1, arg2=foo.DEFAULT): > return int(do_stuff(arg1, arg2)) > foo.SPECIAL = 42 > foo.MONKEY = 31415 > foo.DEFAULT = foo.SPECIAL What's the purpose of having both foo.SPECIAL and foo.DEFAULT? You could always use a callable instance instead of a function, what C++ calls a functor (not to be confused with what Haskell calls a functor, which is completely different). class Foo: SPECIAL = 42 MONKEY = 31215 DEFAULT = SPECIAL def __call__(self, arg1, arg2=DEFAULT): ... foo = Foo() del Foo The default value of arg2 is bound at class definition time, once. If you prefer late binding instead of early binding, it is easy to put off the assignment until the function is called: def __call__(self, arg1, arg2=None): if arg2 is None: arg2 = self.DEFAULT ... If None is a legitimate data value for arg2, you can create your own sentinel: SENTINEL = object() and use that instead of None. > so I can call it with either > > result = foo(myarg) > > or > > result = foo(myarg, foo.SPECIAL) > > However I can't do this because foo.DEFAULT isn't defined at the > time the function is created. I'd like to avoid hard-coding > things while staying DRY, so I don't like > > def foo(arg1, arg2=42) > > because the default might change due to business rule changes, If the business rule changes, you have to change foo.DEFAULT anyway. So why not cut out the middle man and change the default argument in the function signature? > I > have a dangling "magic constant" and if the value of SPECIAL > changes, I have to catch that it should be changed in two places. Then put it in one place. SPECIAL = 42 def foo(arg1, arg2=SPECIAL): ... and avoid the reference to foo. > My current hack/abuse is to use __new__ in a class that can > contain the information: > > class foo(object): > SPECIAL = 42 > MONKEY = 31415 > DEFAULT = SPECIAL > def __new__(cls, arg1, arg2=DEFAULT): > return int(do_stuff(arg1, arg2)) > > i1 = foo("spatula") > i2 = foo("tapioca", foo.MONKEY) > > 1) is this "icky" (a term of art ;-) > 2) or is this reasonable Seems okay to me. A little unusual, but only a little, not "WTF is this code doing???" territory. -- Steven From edcjones at comcast.net Sun Oct 9 11:43:18 2011 From: edcjones at comcast.net (thegripper) Date: Sun, 9 Oct 2011 08:43:18 -0700 (PDT) Subject: SciPy/NumPy: read, write images using Python3 Message-ID: <9ca46882-acb1-4a23-8b6b-69539ff37d08@n15g2000vbn.googlegroups.com> In SciPy / NumPy, the primary way to read and write images is PIL. But PIL does not yet support Python3. Is there some good way to read, write, and resize images in a NumPy and Python3 environment? From edcjones at comcast.net Sun Oct 9 11:43:44 2011 From: edcjones at comcast.net (thegripper) Date: Sun, 9 Oct 2011 08:43:44 -0700 (PDT) Subject: SciPy/NumPy: read, write images using Python3 Message-ID: <0d8c568e-28a7-441b-a5b0-281d1a7b14e1@j31g2000vbl.googlegroups.com> In SciPy / NumPy, the primary way to read and write images is PIL. But PIL does not yet support Python3. Is there some good way to read, write, and resize images in a NumPy and Python3 environment? From darcy at druid.net Sun Oct 9 11:51:05 2011 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 9 Oct 2011 11:51:05 -0400 Subject: "IX" as shorthand for "Interface" In-Reply-To: References: Message-ID: <20111009115105.206a492b@dilbert> On Sat, 8 Oct 2011 22:21:02 -0600 Eric Snow wrote: > I'm writing a bunch of classes that have "Interface" in the name and > find that the length of the subsequent names is starting to get in the > way of readability (I don't really care about saving keystrokes). Is > "IX" conventional enough to use in place of "Interface" in a class > name? Thanks! Here's a suggestion based on my complete ignorance of you application so take it for what it is worth. If keystrokes don't matter to you consider this. class INTERFACE: pass class Something(INTERFACE): ... It isn't in the name but the definition is clearly an "INTERFACE" (whatever that is) and you also have the option of gathering things in common to INTERFACEs in the superclass. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From albert at spenarnc.xs4all.nl Sun Oct 9 12:01:30 2011 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 09 Oct 2011 16:01:30 GMT Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> Message-ID: In article , DevPlayer wrote: >I still assert that contradiction is caused by narrow perspective. > >By that I mean: just because an objects scope may not see a certain >condition, doesn't mean that condition is non-existant. > >I also propose that just because something seems to contradict doesn't >mean it is false. Take for instance: > >Look out your window. Is it daylight or night time? You may say it is >daylight or you may say it is night time. I would disagree that only >one of those conditions are true. Both conditions are true. Always. It >is only day (or night) for YOU. But the opposite DOES in fact exist on >the other side of the world at the same time. This is a far cry from the bible stating that someone is his own grand father. Or going to great length to prove that Jezus (through Jozef) is a descendant of David. Then declaring it a dogma that Jozef has nothing to do with it. (It being ... well ... you know ...) (I have this book, it is called "the amusing bible" with all flippant and contradictory stuff pointed out by a French 1930 communist. Cartoons too. ) Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From albert at spenarnc.xs4all.nl Sun Oct 9 12:33:37 2011 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 09 Oct 2011 16:33:37 GMT Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article , Jussi Piitulainen wrote: >Mel writes: > >> Steven D'Aprano wrote: >> >> > candide wrote: >> > >> >> So what is the usefulness of the "not in" operator ? Recall what Zen of >> >> Python tells >> >> >> >> There should be one-- and preferably only one --obvious way to do it. >> > >> > And "not in" is the obvious way to do it. >> > >> > >> > "If the key is not in the ignition, you won't be able to start the car." >> > >> > "If not the key is in the ignition, you won't be able to start the car." >> > >> > >> > Who like that second one speaks? >> >> :) >> "If the key is not in the ignition, you will be able to start the car, not." > >Oh, be consistent. > >"If not the key is in the ignition, not you will be able to start the car." > >But both negations can be avoided by modus tollens. > >"If you are able to start the car, the key is in the ignition." This is not normal speach. The connotation of an if sentence is that the condition is something you have more control over than over the result. I sometime write if 0 == i : and get complaints, as if both sides of an identity are not equivalent. OTOH if i == j : and nobody cares it I wrote if j == i : > >And one could express "x not in s" as "(x in s) implies False" without >making the "not" explicit if "implies" was in the language. (I know >about <= but I also witnessed an unpleasant thread in another >newsgroup where people insisted that <= should not be defined for >truth values at all, and I also happen to like Python's "not in".) Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From clp2 at rebertia.com Sun Oct 9 14:00:01 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 9 Oct 2011 11:00:01 -0700 Subject: Using Python xmlrpclib to build XMLRPC clients for a server with variable RPC names In-Reply-To: <1318167042.3120.54.camel@ptlws01.config> References: <1318167042.3120.54.camel@ptlws01.config> Message-ID: On Sun, Oct 9, 2011 at 6:30 AM, John P. Crackett wrote: > I need to write prototype XMLRPC clients using xmlrpclib for a server > that has variable RPC names and I'd like to use Python as the > prototyping tool. ?I've searched but can't find any relevant advice > online. ?Any pointers would be gratefully received; details follow. > > The server in question constructs method names dynamically using the > names of objects created by the client. > As an added complication, object names need to be concatenated using "-" > as a separator to form compound RPC names. ?Following on from the > example above, this could lead to: > > api = xmlrpclib.ServerProxy(serverURL) > > api. createObjects("foo", "far") > > api.foo-bar.callOne() > > Where I don't know, again, what "foo" and "bar" will actually be in > advance. ?"foo-bar" is obviously not a valid Python method name and this > is preventing me from hard-coding just to get a prototype going. Try using getattr(): getattr(api, "foo-bar").callOne() For reference, getattr() satisfies the following identity: x.y === getattr(x, "y") except that getattr() does not itself enforce/require that its second argument be a valid Python identifier. Cheers, Chris -- http://rebertia.com From jpc at parallelthoughts.org Sun Oct 9 14:35:36 2011 From: jpc at parallelthoughts.org (JPC) Date: Sun, 09 Oct 2011 19:35:36 +0100 Subject: Using Python xmlrpclib to build XMLRPC clients for a server with variable RPC names In-Reply-To: References: <1318167042.3120.54.camel@ptlws01.config> Message-ID: <1318185336.8259.1.camel@ptlws01.config> That was the information I was missing many thanks. For the reference sake, a look through the source code indicates this solution; prior to your message I just didn't understand it that well. -- /jpc On Sun, 2011-10-09 at 11:00 -0700, Chris Rebert wrote: > On Sun, Oct 9, 2011 at 6:30 AM, John P. Crackett > wrote: > > I need to write prototype XMLRPC clients using xmlrpclib for a server > > that has variable RPC names and I'd like to use Python as the > > prototyping tool. I've searched but can't find any relevant advice > > online. Any pointers would be gratefully received; details follow. > > > > The server in question constructs method names dynamically using the > > names of objects created by the client. > > > As an added complication, object names need to be concatenated using "-" > > as a separator to form compound RPC names. Following on from the > > example above, this could lead to: > > > > api = xmlrpclib.ServerProxy(serverURL) > > > > api. createObjects("foo", "far") > > > > api.foo-bar.callOne() > > > > Where I don't know, again, what "foo" and "bar" will actually be in > > advance. "foo-bar" is obviously not a valid Python method name and this > > is preventing me from hard-coding just to get a prototype going. > > Try using getattr(): > getattr(api, "foo-bar").callOne() > > For reference, getattr() satisfies the following identity: > x.y === getattr(x, "y") > except that getattr() does not itself enforce/require that its second > argument be a valid Python identifier. > > Cheers, > Chris > -- > http://rebertia.com From python.list at tim.thechases.com Sun Oct 9 14:57:03 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 09 Oct 2011 13:57:03 -0500 Subject: DRY functions with named attributes used as default arguments In-Reply-To: <4e91bfd6$0$29989$c3e8da3$5496439d@news.astraweb.com> References: <4e91bfd6$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E91EE7F.9090407@tim.thechases.com> On 10/09/11 10:37, Steven D'Aprano wrote: >> My intent is to have a function object something like >> >> def foo(arg1, arg2=foo.DEFAULT): >> return int(do_stuff(arg1, arg2)) >> foo.SPECIAL = 42 >> foo.MONKEY = 31415 >> foo.DEFAULT = foo.SPECIAL > > What's the purpose of having both foo.SPECIAL and foo.DEFAULT? As you later ask... >> However I can't do this because foo.DEFAULT isn't defined at >> the time the function is created. I'd like to avoid >> hard-coding things while staying DRY, so I don't like >> >> def foo(arg1, arg2=42) >> >> because the default might change due to business rule >> changes, > > If the business rule changes, you have to change foo.DEFAULT > anyway. So why not cut out the middle man and change the > default argument in the function signature? By indirecting through DEFAULT, I can change DEFAULT to point at another behavior-tweaking option in one place ("DEFAULT = SPECIAL") rather than in multiple places. However, I can't give a very good argument for just using def foo(arg1, arg2=SPECIAL) and then, if it changes, just change *that* one location to def foo(arg1, arg2=MONKEY) because, well, Python calls them default arguments for a reason :) > class Foo: > SPECIAL = 42 > MONKEY = 31215 > DEFAULT = SPECIAL > def __call__(self, arg1, arg2=DEFAULT): > ... > > foo = Foo() > del Foo I did consider this (sorry I forgot to mention it) and it works well too. It's a little cleaner, as the magic happens in something named __call__ which is more obvious than overloading odd behavior into __new__. The instantiate-and-delete-the-class felt a little weird, and having both the class and the instance in the namespace felt weird. Granted the (ab)use of __new__ felt weird too, so neither wins by great margin. Which is part of my question: what's the least-worst way to do this? :) >> I have a dangling "magic constant" and if the value of >> SPECIAL changes, I have to catch that it should be changed >> in two places. > > Then put it in one place. > > SPECIAL = 42 > > def foo(arg1, arg2=SPECIAL): > ... > > and avoid the reference to foo. I guess part of my attempt was to keep from littering the module namespace with things that only apply to the one function (and this also applies to C-like prefixes such as FOO_SPECIAL) >> My current hack/abuse is to use __new__ in a class that can >> contain the information: >> >> class foo(object): >> SPECIAL = 42 >> MONKEY = 31415 >> DEFAULT = SPECIAL >> def __new__(cls, arg1, arg2=DEFAULT): >> return int(do_stuff(arg1, arg2)) >> >> i1 = foo("spatula") >> i2 = foo("tapioca", foo.MONKEY) >> >> 1) is this "icky" (a term of art ;-) >> 2) or is this reasonable > > Seems okay to me. A little unusual, but only a little, not > "WTF is this code doing???" territory. The code felt like it was riding the WTF-boundary, so I find your evaluation of "unusual but not WTF" encouraging. Thanks for your thoughts, -tkc From dihedral88888 at googlemail.com Sun Oct 9 16:31:56 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sun, 9 Oct 2011 13:31:56 -0700 (PDT) Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> <4e8bed30$0$29978$c3e8da3$5496439d@news.astraweb.com> <87wrcjzmql.fsf@benfinney.id.au> Message-ID: <18490275.937.1318192316512.JavaMail.geo-discussion-forums@prdw1> I do not think C is not good for functional programming, but C is hard to debug if one has to write programs to reload functional pointers and data structures that will grow in the run time for the possible cases. Thus, I love Python! From dihedral88888 at googlemail.com Sun Oct 9 16:34:27 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sun, 9 Oct 2011 13:34:27 -0700 (PDT) Subject: Thread handling issue In-Reply-To: References: Message-ID: <5016619.938.1318192467132.JavaMail.geo-discussion-forums@prdw1> TRY to get BOA with wxpython! Please check the example for the UI part in BOA. From dihedral88888 at googlemail.com Sun Oct 9 16:34:27 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sun, 9 Oct 2011 13:34:27 -0700 (PDT) Subject: Thread handling issue In-Reply-To: References: Message-ID: <5016619.938.1318192467132.JavaMail.geo-discussion-forums@prdw1> TRY to get BOA with wxpython! Please check the example for the UI part in BOA. From alahmar402 at gmail.com Sun Oct 9 16:38:30 2011 From: alahmar402 at gmail.com (cry angel) Date: Sun, 9 Oct 2011 13:38:30 -0700 (PDT) Subject: Amber riley - Mercedes Message-ID: <6b6ca45d-f102-4e17-a936-159aaca3f382@m37g2000yqc.googlegroups.com> New page for the singer Amber riley - Mercedes I wish to enter and enjoy and leave comments http://sunforsun.blogspot.com/p/amber-riley-mercedes.html From anikom15 at gmail.com Sun Oct 9 16:48:14 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Sun, 9 Oct 2011 13:48:14 -0700 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: <20111009204814.GA15277@Smoke> On Sat, Oct 08, 2011 at 12:34:42PM -0400, Roy Smith wrote: > In article <4e906108$0$27980$426a34cc at news.free.fr>, > candide wrote: > > > After browsing source code, I realize that parenthesis are not necessary > > ("not" has higher precedence than "in"). > > Here's my take on parenthesis: If you need to look up whether they're > necessary or not, they are :-) So we don't need precedence charts in the bathroom? From zaffino.p at gmail.com Sun Oct 9 16:59:11 2011 From: zaffino.p at gmail.com (Paolo Zaffino) Date: Sun, 9 Oct 2011 13:59:11 -0700 (PDT) Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows Message-ID: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Hello, I wrote a function that works on a numpy matrix and it works fine on Mac OS and GNU/Linux (I didn't test it on python 3) Now I have a problem with numpy: the same python file doesn't work on Windows (Windows xp, python 2.7 and numpy 2.6.1). I get this error: matrix=matrix.reshape(a, b, c) ValueError: total size of new array must be unchanged Why? Do anyone have an idea about this? Thank you very much. From yasar11732 at gmail.com Sun Oct 9 17:50:45 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Mon, 10 Oct 2011 00:50:45 +0300 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: I don't know about your problem, but did you compare numpy versions in windows and other platforms? You may have newer/older version in Windows. Otherwise, it looks like a platform spesific bug to me. 2011/10/9 Paolo Zaffino > Hello, > I wrote a function that works on a numpy matrix and it works fine on > Mac OS and GNU/Linux (I didn't test it on python 3) > Now I have a problem with numpy: the same python file doesn't work on > Windows (Windows xp, python 2.7 and numpy 2.6.1). > I get this error: > > matrix=matrix.reshape(a, b, c) > ValueError: total size of new array must be unchanged > > Why? Do anyone have an idea about this? > Thank you very much. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Sun Oct 9 21:14:53 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 10 Oct 2011 12:14:53 +1100 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: <4e92470d$0$29971$c3e8da3$5496439d@news.astraweb.com> Paolo Zaffino wrote: > Hello, > I wrote a function that works on a numpy matrix and it works fine on > Mac OS and GNU/Linux (I didn't test it on python 3) > Now I have a problem with numpy: the same python file doesn't work on > Windows (Windows xp, python 2.7 and numpy 2.6.1). > I get this error: > > matrix=matrix.reshape(a, b, c) > ValueError: total size of new array must be unchanged > > Why? Do anyone have an idea about this? > Thank you very much. Please give sample values for matrix, a, b and c that demonstrate the issue. What version of Python and numpy are you using on Mac and Linux? -- Steven From wuwei23 at gmail.com Mon Oct 10 00:02:40 2011 From: wuwei23 at gmail.com (alex23) Date: Sun, 9 Oct 2011 21:02:40 -0700 (PDT) Subject: A tuple in order to pass returned values ? References: <4e8e5db3$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: Jean-Michel Pichavant wrote: > However, I'm not sure it fixes the main issue: unpacking. Unpacking > prevents you from adding any additional fields to your 'tuple' without > breaking any line of code that was unpacking the tuple (to oppose to > accessing an object attribute). Generally, if it's a small, known, unlikely-to-change structure, I'd use a tuple. For anything else I'd use a class, namedtuple or bunch. However, pre-namedtuples I'd usually abstract away the field referencing with indices and lambdas: name = 0 role = 1 name_role = lambda t: (t[name], t[role]) name, role = name_role(record) etc From roy at panix.com Mon Oct 10 00:09:35 2011 From: roy at panix.com (Roy Smith) Date: Mon, 10 Oct 2011 00:09:35 -0400 Subject: A tuple in order to pass returned values ? References: <4e8e5db3$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article , alex23 wrote: > For anything else I'd use [...] bunch. Particularly useful for handing over lupins. From nobody at nowhere.com Mon Oct 10 01:35:22 2011 From: nobody at nowhere.com (Nobody) Date: Mon, 10 Oct 2011 06:35:22 +0100 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: On Sun, 09 Oct 2011 13:59:11 -0700, Paolo Zaffino wrote: > I wrote a function that works on a numpy matrix and it works fine on > Mac OS and GNU/Linux (I didn't test it on python 3) > Now I have a problem with numpy: the same python file doesn't work on > Windows (Windows xp, python 2.7 and numpy 2.6.1). > I get this error: > > matrix=matrix.reshape(a, b, c) > ValueError: total size of new array must be unchanged > > Why? What it says. The reshape()d array must have the same total number of elements as the original array. If it works on one platform and not on another, that indicates that either "matrix" has a different shape on different platforms, or a*b*c is different on different platforms. As no-one here (except you) has any idea how matrix, a, b and c are getting their values, it's impossible for us to say why they're getting different values on different platforms. From ladasky at my-deja.com Mon Oct 10 04:06:40 2011 From: ladasky at my-deja.com (John Ladasky) Date: Mon, 10 Oct 2011 01:06:40 -0700 (PDT) Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Oct 8, 5:01?am, Steven D'Aprano wrote: > Who like that second one speaks? Yoda his name is. Programs in Forth he must. From alec.taylor6 at gmail.com Mon Oct 10 08:16:55 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Mon, 10 Oct 2011 23:16:55 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Oct 9, 2011 at 3:08 AM, Steven D'Aprano wrote: > Roy Smith wrote: > >> If you want to take it one step further, all the boolean operators can >> be derived from nand (the dualists would insist on using nor). > > Let's define the boolean values and operators using just two functions: > > def true(x, y): > ? ?return x > > def false(x, y): > ? ?return y > > > That's all we need to define all of Boolean algebra. Unfortunately, it's a > bit ugly in Python: > >>>> true > > > So let's add a helper function to prettify the output: > > def pr(b): > ? ?print(b(true, false).__name__) > >>>> pr(true) > true > > Much nicer! > > > Now define NAND: > > def Nand(a, b): > ? ?return (lambda c: lambda x, y: c(y, x))(a(b, a)) > > > and we're done. All of boolean algebra can now be derived from Nand. > > >>>> def Not(b): > ... ? ? return Nand(b, b) > ... >>>> pr(Not(true)) > false >>>> pr(Not(false)) > true > > >>>> def And(a, b): > ... ? ? return Nand(Nand(a, b), Nand(a, b)) > ... >>>> pr(And(true, false)) > false >>>> pr(And(true, true)) > true > > >>>> def Or(a, b): > ... ? ? return Nand(Nand(a, a), Nand(b, b)) > ... >>>> pr(Or(true, false)) > true >>>> pr(Or(false, false)) > false > > >>>> def Xor(a, b): > ... ? ? return And(Nand(a, b), Or(a, b)) > ... >>>> pr(Xor(true, false)) > true >>>> pr(Xor(true, true)) > false > > > and so forth. > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > Awesome From alain at dpt-info.u-strasbg.fr Mon Oct 10 09:01:16 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Mon, 10 Oct 2011 15:01:16 +0200 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8762jx80gz.fsf@dpt-info.u-strasbg.fr> Alec Taylor writes: > On Sun, Oct 9, 2011 at 3:08 AM, Steven D'Aprano > wrote: >> def true(x, y): >> ? ?return x >> >> def false(x, y): >> ? ?return y [...] >> def Nand(a, b): >> ? ?return (lambda c: lambda x, y: c(y, x))(a(b, a)) >> >> and we're done. [...] > Awesome Yes, that's how Church defined booleans in the lambda calculus. See http://en.wikipedia.org/wiki/Church_encoding for encodings of natural numbers and lists. -- Alain. From alec.taylor6 at gmail.com Mon Oct 10 09:36:25 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 11 Oct 2011 00:36:25 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: <8762jx80gz.fsf@dpt-info.u-strasbg.fr> References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> <8762jx80gz.fsf@dpt-info.u-strasbg.fr> Message-ID: Unfortunately I don't know lambda [or for that matter, regular] calculus... On Tue, Oct 11, 2011 at 12:01 AM, Alain Ketterlin wrote: > Alec Taylor writes: > >> On Sun, Oct 9, 2011 at 3:08 AM, Steven D'Aprano >> wrote: > >>> def true(x, y): >>> ? ?return x >>> >>> def false(x, y): >>> ? ?return y > [...] >>> def Nand(a, b): >>> ? ?return (lambda c: lambda x, y: c(y, x))(a(b, a)) >>> >>> and we're done. [...] > >> Awesome > > Yes, that's how Church defined booleans in the lambda calculus. See > http://en.wikipedia.org/wiki/Church_encoding for encodings of natural > numbers and lists. > > -- Alain. > -- > http://mail.python.org/mailman/listinfo/python-list > From candide at free.invalid Mon Oct 10 09:58:01 2011 From: candide at free.invalid (candide) Date: Mon, 10 Oct 2011 15:58:01 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e92f9ea$0$13089$426a74cc@news.free.fr> Le 10/10/2011 10:06, John Ladasky a ?crit : >> Who like that second one speaks? > > Yoda his name is. Programs in Forth he must. ;) We can add to the list : -- Tarzan -- Geronimo -- don Alexandro de la Vega dying in the arms of Zorro ... From ulrich.eckhardt at dominalaser.com Mon Oct 10 09:58:43 2011 From: ulrich.eckhardt at dominalaser.com (Ulrich Eckhardt) Date: Mon, 10 Oct 2011 15:58:43 +0200 Subject: OpenGL.GLU.gluNewQuadric() segmentation fault on 64 bit systems In-Reply-To: References: Message-ID: Am 10.10.2011 14:18, schrieb X1: > has this bug been resolved? > if yes, which version on files to install? That seems to be part of PyOpenGL, so I'd check their bugtracking system. Uli From dihedral88888 at googlemail.com Mon Oct 10 11:13:15 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Mon, 10 Oct 2011 08:13:15 -0700 (PDT) Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str In-Reply-To: References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> <02EA6D704E30CE499C5071776509A925F5BABD@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <9684870.653.1318259595168.JavaMail.geo-discussion-forums@prib32> I am thinking with the power of python evolving in different versions, if a feature is not desired in the new version, then the new version could also provide some script tools, of course in python, to convert codes in old styles into new styles automatically. From dihedral88888 at googlemail.com Mon Oct 10 11:13:15 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Mon, 10 Oct 2011 08:13:15 -0700 (PDT) Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str In-Reply-To: References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> <02EA6D704E30CE499C5071776509A925F5BABD@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <9684870.653.1318259595168.JavaMail.geo-discussion-forums@prib32> I am thinking with the power of python evolving in different versions, if a feature is not desired in the new version, then the new version could also provide some script tools, of course in python, to convert codes in old styles into new styles automatically. From nobody at nowhere.com Mon Oct 10 13:29:49 2011 From: nobody at nowhere.com (Nobody) Date: Mon, 10 Oct 2011 18:29:49 +0100 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, 09 Oct 2011 02:25:27 +0200, Alexander Kapps wrote: > Even if it's off-topic, could you add some similar explanations for > Church numerals (maybe Lambda calculus it isn't too much?) The Church numeral for N is a function of two arguments which applies its first argument N times to its second, i.e. (f^N)(x) = f(f(...(f(x))...)). IOW: def zero(f, x): return x def one(f, x): return f(x) def two(f, x): return f(f(x)) def three(f, x): return f(f(f(x))) And so on. In general: def applyN(n, f, x): for i in xrange(n): x = f(x) return x def church(n): return lambda f, x: applyN(n, f, x) seven = church(7) # this is the Church numeral for 7 > seven(lambda x: x + 1, 0) 7 > seven(lambda x: x * 2, 1) 128 > seven(lambda x: x + ".", "") '.......' From rosuav at gmail.com Mon Oct 10 13:33:43 2011 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Oct 2011 04:33:43 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Oct 11, 2011 at 4:29 AM, Nobody wrote: > > The Church numeral for N is a function of two arguments which applies its > first argument N times to its second, i.e. (f^N)(x) = f(f(...(f(x))...)). > Thanks - nice clear explanation. Appreciated. For an encore, can you give an example of where this is actually useful? It seems a pretty narrow utility. ChrisA From ian.g.kelly at gmail.com Mon Oct 10 13:55:37 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 10 Oct 2011 11:55:37 -0600 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Oct 10, 2011 at 11:33 AM, Chris Angelico wrote: > On Tue, Oct 11, 2011 at 4:29 AM, Nobody wrote: >> >> The Church numeral for N is a function of two arguments which applies its >> first argument N times to its second, i.e. (f^N)(x) = f(f(...(f(x))...)). >> > > Thanks - nice clear explanation. Appreciated. For an encore, can you > give an example of where this is actually useful? It seems a pretty > narrow utility. It's useful for writing mathematical theorems about computability with regard to the natural numbers using lambda calculus. From zaffino.p at gmail.com Mon Oct 10 14:25:03 2011 From: zaffino.p at gmail.com (Paolo Zaffino) Date: Mon, 10 Oct 2011 20:25:03 +0200 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: On Mac OS there is numpy 1.2.1, on Fedora 14 64bits numpy 1.4.1 and on Ubuntu 10.04 64bits numpy 1.3.0. On these platforms my function runs without problems. Just on Windows it doesn't works. 2011/10/9 Ya?ar Arabac? > I don't know about your problem, but did you compare numpy versions in > windows and other platforms? You may have newer/older version in Windows. > Otherwise, it looks like a platform spesific bug to me. > > 2011/10/9 Paolo Zaffino > >> Hello, >> I wrote a function that works on a numpy matrix and it works fine on >> Mac OS and GNU/Linux (I didn't test it on python 3) >> Now I have a problem with numpy: the same python file doesn't work on >> Windows (Windows xp, python 2.7 and numpy 2.6.1). >> I get this error: >> >> matrix=matrix.reshape(a, b, c) >> ValueError: total size of new array must be unchanged >> >> Why? Do anyone have an idea about this? >> Thank you very much. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > http://yasar.serveblog.net/ > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon Oct 10 15:26:35 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 Oct 2011 15:26:35 -0400 Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str In-Reply-To: <9684870.653.1318259595168.JavaMail.geo-discussion-forums@prib32> References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> <02EA6D704E30CE499C5071776509A925F5BABD@039-SN1MPN1-003.039d.mgd.msft.net> <9684870.653.1318259595168.JavaMail.geo-discussion-forums@prib32> Message-ID: On 10/10/2011 11:13 AM, 88888 dihedral wrote: > I am thinking with the power of python evolving in different > versions, if a feature is not desired in the new version, then the > new version could also provide some script tools, of course in > python, to convert codes in old styles into new styles > automatically. That is what the 2to3 script does. It could use some updating. A 3to2 script using the same tools is available somewhere. Someone could write a 32to33 script for the few things removed in 3.3. -- Terry Jan Reedy From tjreedy at udel.edu Mon Oct 10 15:35:24 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 Oct 2011 15:35:24 -0400 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/10/2011 1:55 PM, Ian Kelly wrote: > On Mon, Oct 10, 2011 at 11:33 AM, Chris Angelico wrote: >> On Tue, Oct 11, 2011 at 4:29 AM, Nobody wrote: >>> >>> The Church numeral for N is a function of two arguments which applies its >>> first argument N times to its second, i.e. (f^N)(x) = f(f(...(f(x))...)). >>> >> >> Thanks - nice clear explanation. Appreciated. For an encore, can you >> give an example of where this is actually useful? It seems a pretty >> narrow utility. > > It's useful for writing mathematical theorems about computability with > regard to the natural numbers using lambda calculus. Whereas pure set theorists define counts as sets so they can work with counts within the context of pure set theory (in which everything is a set). Other mathematicians use an axiomatic definition which pretty much abstracts the common features of the set and function definitions. -- Terry Jan Reedy From galyle at gmail.com Mon Oct 10 17:57:49 2011 From: galyle at gmail.com (galyle) Date: Mon, 10 Oct 2011 14:57:49 -0700 (PDT) Subject: Question: Optional Regular Expression Grouping Message-ID: <8537a563-69d7-4bce-b192-d9427aad0a7c@i14g2000yqg.googlegroups.com> HI, I've looked through this forum, but I haven't been able to find a resolution to the problem I'm having (maybe I didn't look hard enough -- I have to believe this has come up before). The problem is this: I have a file which has 0, 2, or 3 groups that I'd like to record; however, in the case of 3 groups, the third group is correctly captured, but the first two groups get collapsed into just one group. I'm sure that I'm missing something in the way I've constructed my regular expression, but I can't figure out what's wrong. Does anyone have any suggestions? The demo below showcases the problem I'm having: import re valid_line = re.compile('^\[(\S+)\]\[(\S+)\](?:\s+|\[(\S+)\])=|\s+[\d\ [\']+.*$') line1 = "[field1][field2] = blarg" line2 = " 'a continuation of blarg'" line3 = "[field1][field2][field3] = blorg" m = valid_line.match(line1) print 'Expected: ' + m.group(1) + ', ' + m.group(2) m = valid_line.match(line2) print 'Expected: ' + str(m.group(1)) m = valid_line.match(line3) print 'Uh-oh: ' + m.group(1) + ', ' + m.group(2) From dotancohen at gmail.com Mon Oct 10 18:23:35 2011 From: dotancohen at gmail.com (Dotan Cohen) Date: Tue, 11 Oct 2011 00:23:35 +0200 Subject: Regex to match all trailing whitespace _and_ newlines. In-Reply-To: References: Message-ID: On Thu, Sep 1, 2011 at 13:30, Peter Otten <__peter__ at web.de> wrote: > Dotan Cohen wrote: > >> In the terrific Anki [1] application I am trying to remove trailing >> whitespace from form fields. This is my regex: >> [\n+\s+]$ > > My attempt: > >>>> sub = re.compile(r"\s*?(\n|$)").sub >>>> sub("", "alpha ? \nbeta ? \r\n\ngamma\n") > 'alphabetagamma' >>>> sub("", "alpha ? \nbeta ? \r\n\ngamma") > 'alphabetagamma' >>>> sub("", "alpha ? \nbeta ? \r\n\ngamma\t") > 'alphabetagamma' > Hi Peter, sorry for the _late_ reply. It turns out that Anki stores newlines internally as
, since its display model is based on HTML. Thanks, though! -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From python at mrabarnett.plus.com Mon Oct 10 18:49:13 2011 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 10 Oct 2011 23:49:13 +0100 Subject: Question: Optional Regular Expression Grouping In-Reply-To: <8537a563-69d7-4bce-b192-d9427aad0a7c@i14g2000yqg.googlegroups.com> References: <8537a563-69d7-4bce-b192-d9427aad0a7c@i14g2000yqg.googlegroups.com> Message-ID: <4E937669.9060308@mrabarnett.plus.com> On 10/10/2011 22:57, galyle wrote: > HI, I've looked through this forum, but I haven't been able to find a > resolution to the problem I'm having (maybe I didn't look hard enough > -- I have to believe this has come up before). The problem is this: > I have a file which has 0, 2, or 3 groups that I'd like to record; > however, in the case of 3 groups, the third group is correctly > captured, but the first two groups get collapsed into just one group. > I'm sure that I'm missing something in the way I've constructed my > regular expression, but I can't figure out what's wrong. Does anyone > have any suggestions? > > The demo below showcases the problem I'm having: > > import re > > valid_line = re.compile('^\[(\S+)\]\[(\S+)\](?:\s+|\[(\S+)\])=|\s+[\d\ > [\']+.*$') > line1 = "[field1][field2] = blarg" > line2 = " 'a continuation of blarg'" > line3 = "[field1][field2][field3] = blorg" > > m = valid_line.match(line1) > print 'Expected: ' + m.group(1) + ', ' + m.group(2) > m = valid_line.match(line2) > print 'Expected: ' + str(m.group(1)) > m = valid_line.match(line3) > print 'Uh-oh: ' + m.group(1) + ', ' + m.group(2) Instead of "\S" I'd recommend using "[^\]]", or using a lazy repetition "\S+?". You'll also need to handle the space before the "=" in line3. valid_line = re.compile(r'^\[(\[^\]]+)\]\[(\[^\]]+)\](?:\s+|\[(\[^\]]+)\])\s*=|\s+[\d\[\']+.*$') From vlastimil.brom at gmail.com Mon Oct 10 18:59:46 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Tue, 11 Oct 2011 00:59:46 +0200 Subject: Question: Optional Regular Expression Grouping In-Reply-To: <8537a563-69d7-4bce-b192-d9427aad0a7c@i14g2000yqg.googlegroups.com> References: <8537a563-69d7-4bce-b192-d9427aad0a7c@i14g2000yqg.googlegroups.com> Message-ID: 2011/10/10 galyle : > HI, I've looked through this forum, but I haven't been able to find a > resolution to the problem I'm having (maybe I didn't look hard enough > -- I have to believe this has come up before). ?The problem is this: > I have a file which has 0, 2, or 3 groups that I'd like to record; > however, in the case of 3 groups, the third group is correctly > captured, but the first two groups get collapsed into just one group. > I'm sure that I'm missing something in the way I've constructed my > regular expression, but I can't figure out what's wrong. ?Does anyone > have any suggestions? > > The demo below showcases the problem I'm having: > > import re > > valid_line = re.compile('^\[(\S+)\]\[(\S+)\](?:\s+|\[(\S+)\])=|\s+[\d\ > [\']+.*$') > line1 = "[field1][field2] = blarg" > line2 = " ? ?'a continuation of blarg'" > line3 = "[field1][field2][field3] = blorg" > > m = valid_line.match(line1) > print 'Expected: ' + m.group(1) + ', ' + m.group(2) > m = valid_line.match(line2) > print 'Expected: ' + str(m.group(1)) > m = valid_line.match(line3) > print 'Uh-oh: ' + m.group(1) + ', ' + m.group(2) > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, I believe, the space before = is causing problems (or the pattern missing it); you also need non greedy quantifiers +? to match as little as possible as opposed to the greedy default: valid_line = re.compile('^\[(\S+?)\]\[(\S+?)\](?:\s+|\[(\S+)\])\s*=|\s+[\d\[\']+.*$') or you can use word-patterns explicitely excluding the closing ], like: valid_line = re.compile('^\[([^\]]+)\]\[([^\]]+)\](?:\s+|\[([^\]]+)\])\s*=|\s+[\d\[\']+.*$') hth vbr From ian.g.kelly at gmail.com Mon Oct 10 19:03:02 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 10 Oct 2011 17:03:02 -0600 Subject: Question: Optional Regular Expression Grouping In-Reply-To: <4E937669.9060308@mrabarnett.plus.com> References: <8537a563-69d7-4bce-b192-d9427aad0a7c@i14g2000yqg.googlegroups.com> <4E937669.9060308@mrabarnett.plus.com> Message-ID: On Mon, Oct 10, 2011 at 4:49 PM, MRAB wrote: > Instead of "\S" I'd recommend using "[^\]]", or using a lazy repetition > "\S+?". Preferably the former. The core problem is that the regex matches ambiguously on the problem string. Lazy repetition doesn't remove that ambiguity; it merely attempts to make the module prefer the match that you prefer. Other notes to the OP: Always use raw strings (r'') when writing regex patterns, to make sure the backslashes are escape characters in the pattern rather than in the string literal. The '^foo|bar$' construct you're using is wonky. I think you're writing this to mean "match if the entire string is either 'foo' or 'bar'". But what that actually matches is "anything that either starts with 'foo' or ends with 'bar'". The correct way to do the former would be either '^foo$|^bar$' or '^(?:foo|bar)$'. From python at bdurham.com Mon Oct 10 19:08:37 2011 From: python at bdurham.com (python at bdurham.com) Date: Mon, 10 Oct 2011 19:08:37 -0400 Subject: Any tradeoffs or cautions in using virtualenv? Message-ID: <1318288117.32413.140258153280877@webmail.messagingengine.com> We're thinking about using virtualenv to isolate our development enivronments. Are there any tradeoffs or cautions we should consider before going this route? Are there other alternatives to virtualenv that we should consider? We are using Python 2.7 (32-bit) on Windows 7 Professional and Windows Server 2008. Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From galyle at gmail.com Mon Oct 10 19:24:13 2011 From: galyle at gmail.com (galyle) Date: Mon, 10 Oct 2011 16:24:13 -0700 (PDT) Subject: Question: Optional Regular Expression Grouping References: <8537a563-69d7-4bce-b192-d9427aad0a7c@i14g2000yqg.googlegroups.com> Message-ID: <9e526b44-c0ba-48c2-8e21-66f54856fe7c@b6g2000vbz.googlegroups.com> On Oct 10, 4:59?pm, Vlastimil Brom wrote: > 2011/10/10 galyle : > > > > > > > > > > > HI, I've looked through this forum, but I haven't been able to find a > > resolution to the problem I'm having (maybe I didn't look hard enough > > -- I have to believe this has come up before). ?The problem is this: > > I have a file which has 0, 2, or 3 groups that I'd like to record; > > however, in the case of 3 groups, the third group is correctly > > captured, but the first two groups get collapsed into just one group. > > I'm sure that I'm missing something in the way I've constructed my > > regular expression, but I can't figure out what's wrong. ?Does anyone > > have any suggestions? > > > The demo below showcases the problem I'm having: > > > import re > > > valid_line = re.compile('^\[(\S+)\]\[(\S+)\](?:\s+|\[(\S+)\])=|\s+[\d\ > > [\']+.*$') > > line1 = "[field1][field2] = blarg" > > line2 = " ? ?'a continuation of blarg'" > > line3 = "[field1][field2][field3] = blorg" > > > m = valid_line.match(line1) > > print 'Expected: ' + m.group(1) + ', ' + m.group(2) > > m = valid_line.match(line2) > > print 'Expected: ' + str(m.group(1)) > > m = valid_line.match(line3) > > print 'Uh-oh: ' + m.group(1) + ', ' + m.group(2) > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Hi, > I believe, the space before = is causing problems (or the pattern missing it); > you also need non greedy quantifiers +? to match as little as possible > as opposed to the greedy default: > > valid_line = re.compile('^\[(\S+?)\]\[(\S+?)\](?:\s+|\[(\S+)\])\s*=|\s+[\d\[\']+.*$') > > or you can use word-patterns explicitely excluding the closing ], like: > > valid_line = re.compile('^\[([^\]]+)\]\[([^\]]+)\](?:\s+|\[([^\]]+)\])\s*=|\s+[\d\[\']+. *$') > > hth > ?vbr Thanks, I had a feeling that greedy matching in my expression was causing problem. Your suggestion makes sense to me, and works quite well. From timr at probo.com Tue Oct 11 01:50:39 2011 From: timr at probo.com (Tim Roberts) Date: Mon, 10 Oct 2011 22:50:39 -0700 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: Westley Mart?nez wrote: >On Sat, Oct 08, 2011 at 12:34:42PM -0400, Roy Smith wrote: >> >> Here's my take on parenthesis: If you need to look up whether they're >> necessary or not, they are :-) > >So we don't need precedence charts in the bathroom? Yes, we do, because I'm always reading code from other people that didn't follow that rule. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steve+comp.lang.python at pearwood.info Tue Oct 11 02:44:31 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 11 Oct 2011 17:44:31 +1100 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: <4e93e5cf$0$29983$c3e8da3$5496439d@news.astraweb.com> Tim Roberts wrote: > Westley Mart?nez wrote: >>On Sat, Oct 08, 2011 at 12:34:42PM -0400, Roy Smith wrote: >>> >>> Here's my take on parenthesis: If you need to look up whether they're >>> necessary or not, they are :-) >> >>So we don't need precedence charts in the bathroom? > > Yes, we do, because I'm always reading code from other people that didn't > follow that rule. No no no, they *do* follow the rule. They just have a better memory for operator precedence than you do :) -- Steven From dreyemi at gmail.com Tue Oct 11 04:16:57 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 11 Oct 2011 09:16:57 +0100 Subject: Implementing Python-OAuth2 In-Reply-To: <4E8DD438.20207@ncsa.illinois.edu> References: <4E8DD438.20207@ncsa.illinois.edu> Message-ID: On Thu, Oct 6, 2011 at 5:15 PM, Jeff Gaynor wrote: > On 10/06/2011 08:34 AM, Kayode Odeyemi wrote: > >> Hello friends, >> >> I'm working on a pretty large application that I will like to use oauth2 >> on as an authentication and authorization mechanism. >> >> I understand fairly the technology and I have written my own >> implementation before I stumbled on python-oauth2. >> >> I need advise on leveraging python-oauth2 api for creating consumer key, >> creating consumer secret, access token and token secret. >> >> This works well, but be advised that the original python oauth library > had some serious issues, so was redone as python-oauth2. What is confusing > is that it refers to OAuth version 1.0a, not the upcoming OAuth version 2.0, > so make sure you read the right spec before using it, since they are very > different indeed. > > There are *no* usable OAuth version 2..0 implementation in any language > (usually Java comes first) that I know of, so you will get to role your own, > which is hard. There are a few beta-level versions E.g. Twitter) but these > are special cased to the author's needs. The spec itself is not quite ready > either and since it has changed quite substantially in the last year, I > suspect that everyone is waiting to see it settle to a steady state. > > Jeff, I'm in the middle of a big confusion here and will need your help. I will like to know, can the request be signed just once and for all subsequent request made, I can use the stored nonce, signature method and token? My kind of setup is such that, I want the client app to be registered once, such that for every request to a resource, as long as the required parameters are available in the header (which would have been gotten at the initial request), access is granted. Is this a correct interpretation of Oauth? Thanks -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From ovidiudeac at gmail.com Tue Oct 11 04:26:03 2011 From: ovidiudeac at gmail.com (Ovidiu Deac) Date: Tue, 11 Oct 2011 11:26:03 +0300 Subject: regexp compilation error In-Reply-To: References: Message-ID: Thanks for the answer. I will give a try to pypy regex. On Fri, Sep 30, 2011 at 4:56 PM, Vlastimil Brom wrote: > 2011/9/30 Ovidiu Deac : >> This is only part of a regex taken from an old perl application which >> we are trying to understand/port to our new Python implementation. >> >> The original regex was considerably more complex and it didn't compile >> in python so I removed all the parts I could in order to isolate the >> problem such that I can ask help here. >> >> So the problem is that this regex doesn't compile. On the other hand >> I'm not really sure it should. It's an anchor on which you apply *. >> I'm not sure if this is legal. >> >> On the other hand if I remove one of the * it compiles. >> >>>>> re.compile(r"""^(?: [^y]* )*""", re.X) >> Traceback (most recent call last): >> ?File "", line 1, in >> ?File "/usr/lib/python2.6/re.py", line 190, in compile >> ? ?return _compile(pattern, flags) >> ?File "/usr/lib/python2.6/re.py", line 245, in _compile >> ? ?raise error, v # invalid expression >> sre_constants.error: nothing to repeat >>>>> re.compile(r"""^(?: [^y] )*""", re.X) >> <_sre.SRE_Pattern object at 0x7f4069cc36b0> >>>>> re.compile(r"""^(?: [^y]* )""", re.X) >> <_sre.SRE_Pattern object at 0x7f4069cc3730> >> >> Is this a bug in python regex engine? Or maybe some incompatibility with Perl? >> >> On Fri, Sep 30, 2011 at 12:29 PM, Chris Angelico wrote: >>> On Fri, Sep 30, 2011 at 7:26 PM, Ovidiu Deac wrote: >>>> $ python --version >>>> Python 2.6.6 >>> >>> Ah, I think I was misinterpreting the traceback. You do actually have >>> a useful message there; it's the same error that my Py3.2 produced: >>> >>> sre_constants.error: nothing to repeat >>> >>> I'm not sure what your regex is trying to do, but the problem seems to >>> be connected with the * at the end of the pattern. >>> >>> ChrisA >>> -- > > I believe, this is a limitation of the builtin re engine concerning > nested infinite quantifiers - (...*)* ?- in your pattern. > You can try a more powerful recent regex implementation, which appears > to handle it: > > http://pypi.python.org/pypi/regex > > using the VERBOSE flag - re.X all (unescaped) whitespace outside of > character classes is ignored, > http://docs.python.org/library/re.html#re.VERBOSE > the pattern should be equivalent to: > r"^(?:[^y]*)*" > ie. you are not actually gaining anything with double quantifier, as > there isn't anything "real" in the pattern outside [^y]* > > It appears, that you have oversimplified the pattern (if it had worked > in the original app), > however, you may simply try with > import regex as re > and see, if it helps. > > Cf: >>>> >>>> regex.findall(r"""^(?: [^y]* )*""", "a bcd e", re.X) > ['a bcd e'] >>>> re.findall(r"""^(?: [^y]* )*""", "a bcd e", re.X) > Traceback (most recent call last): > ?File "", line 1, in > ?File "re.pyc", line 177, in findall > ?File "re.pyc", line 244, in _compile > error: nothing to repeat >>>> >>>> re.findall(r"^(?:[^y]*)*", "a bcd e") > Traceback (most recent call last): > ?File "", line 1, in > ?File "re.pyc", line 177, in findall > ?File "re.pyc", line 244, in _compile > error: nothing to repeat >>>> regex.findall(r"^(?:[^y]*)*", "a bcd e") > ['a bcd e'] >>>> regex.findall(r"^[^y]*", "a bcd e") > ['a bcd e'] >>>> > > > hth, > ?vbr > -- > http://mail.python.org/mailman/listinfo/python-list > From alec.taylor6 at gmail.com Tue Oct 11 04:27:42 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 11 Oct 2011 19:27:42 +1100 Subject: Implementing Python-OAuth2 In-Reply-To: References: <4E8DD438.20207@ncsa.illinois.edu> Message-ID: Maybe use CAS instead of OAuth? https://wiki.jasig.org/display/CASC/Pycas On Tue, Oct 11, 2011 at 7:16 PM, Kayode Odeyemi wrote: > On Thu, Oct 6, 2011 at 5:15 PM, Jeff Gaynor > wrote: >> >> On 10/06/2011 08:34 AM, Kayode Odeyemi wrote: >>> >>> Hello friends, >>> >>> I'm working on a pretty large application that I will like to use oauth2 >>> on as an authentication and authorization mechanism. >>> >>> I understand fairly the technology and I have written my own >>> implementation before I stumbled on python-oauth2. >>> >>> I need advise on leveraging python-oauth2 api for creating consumer key, >>> creating consumer secret, access token and token secret. >>> >> This works well, but be advised that the original python oauth library had >> some serious issues, so was redone as python-oauth2. What is confusing is >> that it refers to OAuth version 1.0a, not the upcoming OAuth version 2.0, so >> make sure you read the right spec before using it, since they are very >> different indeed. >> >> There are *no* usable OAuth version 2..0 implementation in any language >> (usually Java comes first) that I know of, so you will get to role your own, >> which is hard. There are a few beta-level versions E.g. Twitter) but these >> are special cased to the author's needs. The spec itself is not quite ready >> either and since it has changed quite substantially in the last year, I >> suspect that everyone is waiting to see it settle to a steady state. >> > Jeff, I'm in the middle of a big confusion here and will need your help. > > I will like to know, can the request be signed just once and for all > subsequent request made, I can use the stored nonce, signature method and > token? My kind of setup is such that, I want the client app to be registered > once, such that for every request to a resource, as long as the required > parameters are available in the header (which would have been gotten at the > initial request), access is granted. > > Is this a correct interpretation of Oauth? > > Thanks > > > > -- > Odeyemi 'Kayode O. > http://www.sinati.com. t: @charyorde > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From nobody at nowhere.com Tue Oct 11 04:28:51 2011 From: nobody at nowhere.com (Nobody) Date: Tue, 11 Oct 2011 09:28:51 +0100 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, 11 Oct 2011 04:33:43 +1100, Chris Angelico wrote: >> The Church numeral for N is a function of two arguments which applies its >> first argument N times to its second, i.e. (f^N)(x) = f(f(...(f(x))...)). >> > > Thanks - nice clear explanation. Appreciated. For an encore, can you > give an example of where this is actually useful? It seems a pretty > narrow utility. It's useful insofar as it allows you to define "numbers" given nothing other than abstraction and application, which are the only operations available in the lambda calculus. The particular formulation makes it easy to define addition, which is just composition: (f^(M+N))(x) = (f^M)((f^N)(x)) I.e.: def church_add(a, b): return lambda f, x: a(f, b(f, x)) From alex.vanderspek at tno.nl Tue Oct 11 04:31:29 2011 From: alex.vanderspek at tno.nl (Alex van der Spek) Date: Tue, 11 Oct 2011 10:31:29 +0200 Subject: xml tree writing with ElementTree; prepends elements with ns0 Message-ID: <4e93fee1$0$2512$e4fe514c@news2.news.xs4all.nl> When reading a tree and writing it back to a new file all the elements are prepended with the string ns0: Why is it prepended and how can I suppress this? Thanks, Alex van der Spek From lucaberto at libero.it Tue Oct 11 04:39:39 2011 From: lucaberto at libero.it (luca72) Date: Tue, 11 Oct 2011 01:39:39 -0700 (PDT) Subject: installeventfilter Message-ID: helo i have this form how i can install the event filter: Class Form(QWidget, Ui_Form): """ Class documentation goes here. """ def __init__(self, parent = None): """ Constructor """ QWidget.__init__(self, parent) self.setupUi(self) Thanks From rosuav at gmail.com Tue Oct 11 04:46:58 2011 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Oct 2011 19:46:58 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Oct 11, 2011 at 7:28 PM, Nobody wrote: > It's useful insofar as it allows you to define "numbers" given nothing > other than abstraction and application, which are the only operations > available in the lambda calculus. > Heh. This is why mathematicians ALWAYS make use of previously-defined objects! In pure lambda calculus, constants are even more painful than in SPL[1]... ChrisA [1] http://shakespearelang.sourceforge.net/report/shakespeare/shakespeare.html#SECTION00045000000000000000 From alain at dpt-info.u-strasbg.fr Tue Oct 11 05:40:48 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Tue, 11 Oct 2011 11:40:48 +0200 Subject: xml tree writing with ElementTree; prepends elements with ns0 References: <4e93fee1$0$2512$e4fe514c@news2.news.xs4all.nl> Message-ID: <87ty7f7tnj.fsf@dpt-info.u-strasbg.fr> "Alex van der Spek" writes: > When reading a tree and writing it back to a new file all the elements are > prepended with the string ns0: That's a namespace prefix. > > Why is it prepended and how can I suppress this? See http://effbot.org/zone/element-namespaces.htm I'm not sure you can define the default namespace (i.e., avoid prefixes on element names). However, any conformant XML processor should have no problem with the output of ElementTree. If you're actually producing HTML, then you should say so when calling tostring(), by giving the appropriate value to the method argument. -- Alain. From alain at dpt-info.u-strasbg.fr Tue Oct 11 05:46:11 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Tue, 11 Oct 2011 11:46:11 +0200 Subject: xml tree writing with ElementTree; prepends elements with ns0 References: <4e93fee1$0$2512$e4fe514c@news2.news.xs4all.nl> <87ty7f7tnj.fsf@dpt-info.u-strasbg.fr> Message-ID: <87pqi37tek.fsf@dpt-info.u-strasbg.fr> Alain Ketterlin writes: > "Alex van der Spek" writes: > >> When reading a tree and writing it back to a new file all the elements are >> prepended with the string ns0: > > That's a namespace prefix. > >> >> Why is it prepended and how can I suppress this? > > See http://effbot.org/zone/element-namespaces.htm > > I'm not sure you can define the default namespace (i.e., avoid prefixes > on element names). However, any conformant XML processor should have no > problem with the output of ElementTree. Sorry, it looks like you can with ET 1.3: see http://effbot.org/zone/elementtree-13-intro.htm > If you're actually producing HTML, then you should say so when calling > tostring(), by giving the appropriate value to the method argument. > > -- Alain. From vincent.vandevyvre at swing.be Tue Oct 11 05:57:28 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Tue, 11 Oct 2011 11:57:28 +0200 Subject: installeventfilter In-Reply-To: References: Message-ID: <4E941308.6070903@swing.be> An HTML attachment was scrubbed... URL: From phil at riverbankcomputing.com Tue Oct 11 06:34:02 2011 From: phil at riverbankcomputing.com (Phil Thompson) Date: Tue, 11 Oct 2011 11:34:02 +0100 Subject: installeventfilter In-Reply-To: <4E941308.6070903@swing.be> References: <4E941308.6070903@swing.be> Message-ID: <7975e5bd1532e5dcfa0b76320eae142c@localhost> On Tue, 11 Oct 2011 11:57:28 +0200, Vincent Vande Vyvre wrote: > Le 11/10/11 10:39, luca72 a ?crit?: > helo i have this form how i can install the event filter: > Class Form(QWidget, Ui_Form): > """ > Class documentation goes here. > """ > def __init__(self, parent = None): > """ > Constructor > """ > QWidget.__init__(self, parent) > self.setupUi(self) > > Thanks > > MainWindow.eventFilter = self.event_filter > > ... > > def event_filter(self, object, event): > ??????? # example: window is resized > ??????? if event.type() == 14: > ??????????? resize() > ??????????? return True > > In your case, 'MainWindow' seems to be 'parent' Monkey patching is not a good idea. class EventFilter(QObject): def eventFilter(self, object, event): # example: window is resized if event.type() == QEvent.Resize: object.resize() return True event_filter = EventFilter() form = Form() form.installEventFilter(event_filter) Phil From ydrocourt at gmail.com Tue Oct 11 06:44:54 2011 From: ydrocourt at gmail.com (yo) Date: Tue, 11 Oct 2011 03:44:54 -0700 (PDT) Subject: python script to add a field and edit it for several shapefiles in arcgis Message-ID: dear All i m trying to write a python script supposed to create a new field in a shapefile, and then fill it with a value extracted from the name of the file... I have to do that for several hundreds of files...I am almost there it is kind of working for one file but once i put a loop in the story, then everything crashes... could anybody here offer some help ??? regards Yoann From selahattin_ay at msn.com Tue Oct 11 07:32:40 2011 From: selahattin_ay at msn.com (selahattin ay) Date: Tue, 11 Oct 2011 11:32:40 +0000 Subject: creating a code with two list Message-ID: hi all, I want to create a code with two lists like this code = ['234', '333' .............. ] liste = []a = 0 while a<999 :a+=1liste.append(a) now I want to create this sample : the first element of codes list is 234 than the all elements of liste are 1,2,3 ...... 9999 now I want to this 2341, 2342, 2343, .................... 234999 when this finishes after the second element of code begins 3331,3332, 3333, ....................333999 what can I do for this? thx ... -------------- next part -------------- An HTML attachment was scrubbed... URL: From alec.taylor6 at gmail.com Tue Oct 11 08:08:48 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 11 Oct 2011 23:08:48 +1100 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] Message-ID: Good afternoon, I'm looking for a Python library for generating SQL queries [selects, alters, inserts and commits]. I can write them by hand, but thought it would be more useful writing them in Python (i.e. client-side referential integrity checking before insert commit + test data generation) I'm running Oracle 10g and Oracle 11gR2. Do you know of a Python library which can facilitate this? Thanks for all suggestions, Alec Taylor From alec.taylor6 at gmail.com Tue Oct 11 08:11:10 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 11 Oct 2011 23:11:10 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: As you see, this way of writing constants gives you much more poetic freedom than in other programming languages. On Tue, Oct 11, 2011 at 7:46 PM, Chris Angelico wrote: > On Tue, Oct 11, 2011 at 7:28 PM, Nobody wrote: >> It's useful insofar as it allows you to define "numbers" given nothing >> other than abstraction and application, which are the only operations >> available in the lambda calculus. >> > > Heh. This is why mathematicians ALWAYS make use of previously-defined > objects! In pure lambda calculus, constants are even more painful than > in SPL[1]... > > ChrisA > [1] http://shakespearelang.sourceforge.net/report/shakespeare/shakespeare.html#SECTION00045000000000000000 > -- > http://mail.python.org/mailman/listinfo/python-list > From zaffino.p at gmail.com Tue Oct 11 09:20:36 2011 From: zaffino.p at gmail.com (Paolo Zaffino) Date: Tue, 11 Oct 2011 15:20:36 +0200 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: Nobody can help me? 2011/10/10 Paolo Zaffino > On Mac OS there is numpy 1.2.1, on Fedora 14 64bits numpy 1.4.1 and on > Ubuntu 10.04 64bits numpy 1.3.0. > On these platforms my function runs without problems. > Just on Windows it doesn't works. > > > > 2011/10/9 Ya?ar Arabac? > >> I don't know about your problem, but did you compare numpy versions in >> windows and other platforms? You may have newer/older version in Windows. >> Otherwise, it looks like a platform spesific bug to me. >> >> 2011/10/9 Paolo Zaffino >> >>> Hello, >>> I wrote a function that works on a numpy matrix and it works fine on >>> Mac OS and GNU/Linux (I didn't test it on python 3) >>> Now I have a problem with numpy: the same python file doesn't work on >>> Windows (Windows xp, python 2.7 and numpy 2.6.1). >>> I get this error: >>> >>> matrix=matrix.reshape(a, b, c) >>> ValueError: total size of new array must be unchanged >>> >>> Why? Do anyone have an idea about this? >>> Thank you very much. >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> >> >> -- >> http://yasar.serveblog.net/ >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From drobinow at gmail.com Tue Oct 11 09:34:54 2011 From: drobinow at gmail.com (David Robinow) Date: Tue, 11 Oct 2011 09:34:54 -0400 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: 2011/10/11 Paolo Zaffino : > Nobody can help me? Nope, not unless you post some code. Your problem description is too vague. From jacktradespublic at gmail.com Tue Oct 11 09:49:25 2011 From: jacktradespublic at gmail.com (Nick Zarr) Date: Tue, 11 Oct 2011 08:49:25 -0500 Subject: creating a code with two list In-Reply-To: References: Message-ID: > > liste = [] > > a = 0 > > > > while a<999 : > > a+=1 > > liste.append(a) > > I'm not sure I understand what you're trying to do here, but I don't have much time to answer right now. I just want to say there's an easier way to build a list of consecutive integers: range(1, n+1) >>> range(1, 1000) [1, 2, ..., 999] -- Nick Zarczynski Blog 4 -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Oct 11 09:56:22 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Oct 2011 15:56:22 +0200 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: Paolo Zaffino wrote: > Nobody can help me? Add the lines print "a=%r, b=%r, c=%r" % (a, b, c) print "type=%s, shape=%r, size=%r" % (type(matrix), matrix.shape, matrix.size) before this one >>>> matrix = matrix.reshape(a, b, c) and tell us what it prints both on a system where it works and where it doesn't. If a, b, and c are all integers and a * b * c == matrix.size try passing a tuple: matrix = matrix.reshape((a, b, c)) # note the double parens From rosuav at gmail.com Tue Oct 11 09:59:41 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Oct 2011 00:59:41 +1100 Subject: creating a code with two list In-Reply-To: References: Message-ID: On Wed, Oct 12, 2011 at 12:49 AM, Nick Zarr wrote: >>>> range(1, 1000) > [1, 2, ..., 999] > Or for Python 3 compat: >>> list(range(1,1000)) ChrisA From yasar11732 at gmail.com Tue Oct 11 10:11:04 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Tue, 11 Oct 2011 17:11:04 +0300 Subject: Fwd: creating a code with two list In-Reply-To: References: Message-ID: your_final_list = [[str(i) + str(k) for i in range(len(liste))] for k in range(len(code))] -- http://yasar.serveblog.net/ -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From yasar11732 at gmail.com Tue Oct 11 10:18:36 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Tue, 11 Oct 2011 17:18:36 +0300 Subject: creating a code with two list In-Reply-To: References: Message-ID: And also, I should recommend you to use Turkish speaking mail groups in here: python-programcilar at googlegroups.com since your English is a little hard to comprehend. There are less people there, but, still would be more helpful for you. 11 Ekim 2011 17:11 tarihinde Ya?ar Arabac? yazd?: > > > > your_final_list = [[str(i) + str(k) for i in range(len(liste))] for k in > range(len(code))] > > > -- > http://yasar.serveblog.net/ > > > > > -- > http://yasar.serveblog.net/ > > -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From yasar11732 at gmail.com Tue Oct 11 10:34:09 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Tue, 11 Oct 2011 17:34:09 +0300 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] In-Reply-To: References: Message-ID: Are you looking for something like this? http://www.sqlalchemy.org/ 2011/10/11 Alec Taylor > Good afternoon, > > I'm looking for a Python library for generating SQL queries [selects, > alters, inserts and commits]. > > I can write them by hand, but thought it would be more useful writing > them in Python (i.e. client-side referential integrity checking before > insert commit + test data generation) > > I'm running Oracle 10g and Oracle 11gR2. Do you know of a Python > library which can facilitate this? > > Thanks for all suggestions, > > Alec Taylor > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Tue Oct 11 11:12:22 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 11 Oct 2011 10:12:22 -0500 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] In-Reply-To: References: Message-ID: <4E945CD6.3040502@tim.thechases.com> On 10/11/11 07:08, Alec Taylor wrote: > I'm looking for a Python library for generating SQL queries > [selects, alters, inserts and commits]. The popular ones are SQLObject and SQLAlchemy, both just a web-search away. Additionally, if you're working with Django, it has its own built-in ORM. -tkc From alec.taylor6 at gmail.com Tue Oct 11 11:14:15 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Wed, 12 Oct 2011 02:14:15 +1100 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] In-Reply-To: <4E945CD6.3040502@tim.thechases.com> References: <4E945CD6.3040502@tim.thechases.com> Message-ID: They look good, but I'm looking for something which can "compile" down to normal SQL code. So that I can just plug that .sql file into any environment [i.e. non-python env] On Wed, Oct 12, 2011 at 2:12 AM, Tim Chase wrote: > On 10/11/11 07:08, Alec Taylor wrote: >> >> I'm looking for a Python library for generating SQL queries >> [selects, alters, inserts and commits]. > > The popular ones are SQLObject and SQLAlchemy, both just a web-search away. > > Additionally, if you're working with Django, it has its own built-in ORM. > > -tkc > > > From awilliam at whitemice.org Tue Oct 11 11:33:46 2011 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Tue, 11 Oct 2011 11:33:46 -0400 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] In-Reply-To: References: <4E945CD6.3040502@tim.thechases.com> Message-ID: <20111011113346.Horde.QM5RR5eICrNOlGHaedHkKTA@aleph.wmmi.net> Quoting Alec Taylor > They look good, but I'm looking for something which can "compile" down > to normal SQL code. > So that I can just plug that .sql file into any environment [i.e. > non-python env] SQLalchemy will happily give you statements and argument lists if that is what you want. query = db.query(Task).filter(Task.objectid==10100) print str(query) From apirker at gmail.com Tue Oct 11 12:09:29 2011 From: apirker at gmail.com (Anton Pirker) Date: Tue, 11 Oct 2011 09:09:29 -0700 (PDT) Subject: Freelance Django developer needed Message-ID: <29103438.2615.1318349369262.JavaMail.geo-discussion-forums@yqnk41> Hi! (First to everyone not into Django: sorry for the shameless job advertisement!) We are searching for a Freelance Django developer to help us out! We are: - creativesociety.com - based in Vienna, Austria - small team of 4 - pretty cool What you should have: - passion for writing beautiful code - getting things done attitude - knowledge of django, postgres, json, rest, - some knowledge of html/css - good english (talking and reading/writing documentation) What you will have to do: - develop a RESTful api that talks to a partner site - talk to the partners (humands, based in london and/or paris) to specify the api - import a LOT of data from the partner site - implement an upload and post the video files to the partner site - implement a single sign on solution so if the users are logged in on one site, are automatically logged in on the other site. - implement some html templates in django We think the project will take about 8-12 weeks, starting November 1th. If you are interested, send your CV, a "why i am the best for the job"-letter and your rates to: development [at] creativesociety [dot] com Thanks, Anton From wm at localhost.localdomain Tue Oct 11 13:02:15 2011 From: wm at localhost.localdomain (Waldek M.) Date: Tue, 11 Oct 2011 19:02:15 +0200 Subject: Freelance Django developer needed References: <29103438.2615.1318349369262.JavaMail.geo-discussion-forums@yqnk41> Message-ID: <1s95cqbh76szn.dlg@localhost.localdomain> > (First to everyone not into Django: sorry for the shameless job advertisement!) > > We are searching for a Freelance Django developer to help us out! Well, if you're sorry then why do you go on? There's a much better place to post the job offer: http://www.python.org/community/jobs/ There, you'd probably even earn credit for your posting :-) Best regards, Waldek From apirker at gmail.com Tue Oct 11 13:24:58 2011 From: apirker at gmail.com (Anton Pirker) Date: Tue, 11 Oct 2011 10:24:58 -0700 (PDT) Subject: Freelance Django developer needed In-Reply-To: <1s95cqbh76szn.dlg@localhost.localdomain> References: <29103438.2615.1318349369262.JavaMail.geo-discussion-forums@yqnk41> <1s95cqbh76szn.dlg@localhost.localdomain> Message-ID: <760129.192.1318353898238.JavaMail.geo-discussion-forums@yqnv12> Hi Waldek! On Tuesday, 11 October 2011 19:02:15 UTC+2, Waldek M. wrote: > > (First to everyone not into Django: sorry for the shameless job advertisement!) > > > Well, if you're sorry then why do you go on? > > There's a much better place to post the job offer: > http://www.python.org/community/jobs/ > > There, you'd probably even earn credit for your posting :-) Ah thanks for the pointer! Posted the job ad on the the website you mentioned. I still posted it here, so i have the most people to read my job ad. Because i want to find the best one, and i think they are not browsing job boards.. ;) greetings from vienna, Anton > > Best regards, > Waldek From warren at washresearch.com Tue Oct 11 14:16:50 2011 From: warren at washresearch.com (WR) Date: Tue, 11 Oct 2011 18:16:50 -0000 Subject: Seven Python Developers Needed $125K Message-ID: Top Global Consulting Firm in NYC needs 7 Python Developers Up to $125K depending on experience Solid knowledge of fundamental Python concepts. At least three years Python experience required. For more info email Joseph at Washresearch.com Joseph Ryan Washington Research Associates Inc (202) 408-7025 From chris at simplistix.co.uk Tue Oct 11 15:00:42 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 11 Oct 2011 20:00:42 +0100 Subject: TestFixtures 2.3.0 Released! Message-ID: <4E94925A.5020507@simplistix.co.uk> Hi All, Another TestFixtures release. This release adds warning backstops when you forget to clean up LogCapture, Replacer, TempDirectory and TestComponents instances. A replacer which didn't get its .restore() method called when it should have been caused me a lot of pain recently, so this release is here to stop others having to suffer the same ;-) The package is on PyPI and a full list of all the links to docs, issue trackers and the like can be found here: http://www.simplistix.co.uk/software/python/testfixtures Any questions, please do ask here or on the Simplistix open source mailing lists... cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From andrea.crotti.0 at gmail.com Tue Oct 11 16:15:15 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Tue, 11 Oct 2011 21:15:15 +0100 Subject: profiling big project Message-ID: <87lisrxp2k.fsf@gmail.com> Hi everyone, I am in the situation that I'll have to profile huge python programs, huge because they use many external libraries like numpy / pyqt / ETS etc etc... The applications are very slow and we wanted to understand what is actually going on. I like to use normally pycallgraph, but in this case is quite useless, because the graph would be huge, so I had the following thought, if I'm able to serialize the generate a text representation of the graph I should be then able to actually understand something. So I forked pycallgraph (https://github.com/AndreaCrotti/pycallgraph) and my idea is to create an org-mode or RST file instead of a graph, adding also links to the source code maybe. For example (in org mode) * function1 50% ** function2 25% ** function3 22% ... and so on, in RST maybe I could even use autodoc to get also the doc from the functions. Any idea / suggestions / comment? Maybe there is something like this already? From ben+python at benfinney.id.au Tue Oct 11 17:20:09 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Oct 2011 08:20:09 +1100 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] References: Message-ID: <87botnxm2e.fsf@benfinney.id.au> Alec Taylor writes: > I'm looking for a Python library for generating SQL queries [selects, > alters, inserts and commits]. SQLAlchemy is the leader in this field. It allows your code to interact with the database at different levels: you can write raw SQL, you can construct queries using a query builder, you can use an entirely-optional ORM; and they're all compatible. > I'm running Oracle 10g and Oracle 11gR2. Do you know of a Python > library which can facilitate this? Yes, . -- \ ?[W]e are still the first generation of users, and for all that | `\ we may have invented the net, we still don't really get it.? | _o__) ?Douglas Adams | Ben Finney From ben+python at benfinney.id.au Tue Oct 11 17:23:12 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Oct 2011 08:23:12 +1100 Subject: Freelance Django developer needed References: <29103438.2615.1318349369262.JavaMail.geo-discussion-forums@yqnk41> <1s95cqbh76szn.dlg@localhost.localdomain> <760129.192.1318353898238.JavaMail.geo-discussion-forums@yqnv12> Message-ID: <877h4bxlxb.fsf@benfinney.id.au> Anton Pirker writes: > I still posted it here, so i have the most people to read my job ad. That's a justification used by spammers, and it's wrong for the same reasons (this forum is inappropriate for the job posting regardless of your desires). Please don't become a spammer. -- \ ?Perchance you who pronounce my sentence are in greater fear | `\ than I who receive it.? ?Giordano Bruno, burned at the stake by | _o__) the Catholic church for the heresy of heliocentrism, 1600-02-16 | Ben Finney From kwebb at teradactyl.com Tue Oct 11 19:04:45 2011 From: kwebb at teradactyl.com (Kristen J. Webb) Date: Tue, 11 Oct 2011 17:04:45 -0600 Subject: shipping python Message-ID: <4E94CB8D.5010806@teradactyl.com> I am new to python coming from the C/shell side. We have been experimenting with some code samples and now I'm looking at some command line argument processing. I find getopt older optparse new in 2.3 argparse new in 2.7 I search around on some of my client systems and find lots of people in the 2.4 - 2.6 range. After some more digging I see that I can easy_install argparse on my development system. My question is will I be able to ship this to a customer? Can I create .pyc files so that the customer does not have to install the argparse module? If not, and I want to go back into the 2.3+ range, should I just use optparse? I guess what I am asking here is are there any guidelines/recommendations for shipping python programs to customers? Thanks in advance, Kris -- Mr. Kristen J. Webb Teradactyl LLC. PHONE: 1-505-242-1091 EMAIL: kwebb at teradactyl.com VISIT: http://www.teradactyl.com Home of the True incremental Backup System From skippy.hammond at gmail.com Tue Oct 11 21:06:59 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Wed, 12 Oct 2011 12:06:59 +1100 Subject: Implementing Python-OAuth2 In-Reply-To: References: <4E8DD438.20207@ncsa.illinois.edu> Message-ID: <4E94E833.6000705@gmail.com> On 11/10/2011 7:16 PM, Kayode Odeyemi wrote: > On Thu, Oct 6, 2011 at 5:15 PM, Jeff Gaynor > wrote: > > On 10/06/2011 08:34 AM, Kayode Odeyemi wrote: > > Hello friends, > > I'm working on a pretty large application that I will like to > use oauth2 on as an authentication and authorization mechanism. > > I understand fairly the technology and I have written my own > implementation before I stumbled on python-oauth2. > > I need advise on leveraging python-oauth2 api for creating > consumer key, creating consumer secret, access token and token > secret. > > This works well, but be advised that the original python oauth > library had some serious issues, so was redone as python-oauth2. > What is confusing is that it refers to OAuth version 1.0a, not the > upcoming OAuth version 2.0, so make sure you read the right spec > before using it, since they are very different indeed. > > There are *no* usable OAuth version 2..0 implementation in any > language (usually Java comes first) that I know of, so you will get > to role your own, which is hard. There are a few beta-level versions > E.g. Twitter) but these are special cased to the author's needs. The > spec itself is not quite ready either and since it has changed quite > substantially in the last year, I suspect that everyone is waiting > to see it settle to a steady state. > > Jeff, I'm in the middle of a big confusion here and will need your help. > > I will like to know, can the request be signed just once and for all > subsequent request made, I can use the stored nonce, signature method > and token? My kind of setup is such that, I want the client app to be > registered once, such that for every request to a resource, as long as > the required parameters are available in the header (which would have > been gotten at the initial request), access is granted. > > Is this a correct interpretation of Oauth? I believe every request must be resigned with a new nonce and new timestamp using the tokens it initially fetched during the auth step so "replay" attacks can be prevented. It might be true that some server implementations don't check the timestamp or nonce, so it *might* work for some servers if the exact same request parameters are used, but such servers are simply insecure and broken. Mark From anikom15 at gmail.com Tue Oct 11 21:08:06 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Tue, 11 Oct 2011 18:08:06 -0700 Subject: shipping python In-Reply-To: <4E94CB8D.5010806@teradactyl.com> References: <4E94CB8D.5010806@teradactyl.com> Message-ID: <20111012010806.GA27288@Smoke> On Tue, Oct 11, 2011 at 05:04:45PM -0600, Kristen J. Webb wrote: > I am new to python coming from the C/shell side. > We have been experimenting with some code > samples and now I'm looking at some command line > argument processing. I find > > getopt older > optparse new in 2.3 > argparse new in 2.7 > > I search around on some of my client systems and > find lots of people in the 2.4 - 2.6 range. > > After some more digging I see that I can > easy_install argparse on my development system. > > My question is will I be able to ship this > to a customer? Can I create .pyc files so > that the customer does not have to install the argparse > module? > > If not, and I want to go back into the 2.3+ range, > should I just use optparse? > > I guess what I am asking here is are there any > guidelines/recommendations for shipping python > programs to customers? > > Thanks in advance, > Kris If you intend for the software to run on Python <2.7 the user must have argparse installed. Python included argparse in the standard library in 2.7. Understand that getopt is analog to the getopt found in the POSIX library; optparse and argparse are designed to handle more "complex" arguments. Basically it depends on your needs. If you're concerned about portability it's very easy to deal with arguments with getopt or just sys.argv on your own. From debatem1 at gmail.com Tue Oct 11 21:29:29 2011 From: debatem1 at gmail.com (geremy condra) Date: Tue, 11 Oct 2011 18:29:29 -0700 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List In-Reply-To: References: Message-ID: On Fri, Sep 30, 2011 at 8:25 PM, Navkirat Singh wrote: > Lol you all sound like google's angry birds with their feathers ruffled by a > comment. You guys should open up another mailing list to extinguish your > virtually bruised egos. . . . Google does not produce Angry Birds. There is another mailinglist for OT conversation. Extinguishing does not help either bruises or egos. You smell like a troll. You top-posted. Your post was nonsensical, error-filled, ill-formatted, grouchy, pointless, and dumb. You've earned my contempt, and may God have mercy on your troll. Geremy Condra From steve+comp.lang.python at pearwood.info Tue Oct 11 21:31:46 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 12 Oct 2011 01:31:46 GMT Subject: shipping python References: Message-ID: <4e94ee02$0$29978$c3e8da3$5496439d@news.astraweb.com> On Tue, 11 Oct 2011 17:04:45 -0600, Kristen J. Webb wrote: > After some more digging I see that I can easy_install argparse on my > development system. > > My question is will I be able to ship this to a customer? Can I create > .pyc files so that the customer does not have to install the argparse > module? Yes, and yes. The licence of argparse is a very liberal licence, so you can just include it in your application. There's no need for the user to install it separately. You could include just the .pyc file if you insist, but I personally don't like or recommend .pyc only installations. > If not, and I want to go back into the 2.3+ range, should I just use > optparse? That depends on how complex your command line arguments are. -- Steven From wuwei23 at gmail.com Tue Oct 11 23:13:56 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 11 Oct 2011 20:13:56 -0700 (PDT) Subject: Python library for generating SQL queries [selects, alters, inserts and commits] References: <4E945CD6.3040502@tim.thechases.com> Message-ID: On Oct 12, 1:14?am, Alec Taylor wrote: > They look good, but I'm looking for something which can "compile" down > to normal SQL code. Then you're not looking hard enough. SQLAlchemy does this. From alec.taylor6 at gmail.com Wed Oct 12 00:05:03 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Wed, 12 Oct 2011 15:05:03 +1100 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] In-Reply-To: References: <4E945CD6.3040502@tim.thechases.com> Message-ID: Great, I'll learn how to use it over the next few days :] On Wed, Oct 12, 2011 at 2:13 PM, alex23 wrote: > On Oct 12, 1:14?am, Alec Taylor wrote: >> They look good, but I'm looking for something which can "compile" down >> to normal SQL code. > > Then you're not looking hard enough. SQLAlchemy does this. > > -- > http://mail.python.org/mailman/listinfo/python-list > From jackdied at gmail.com Wed Oct 12 00:07:05 2011 From: jackdied at gmail.com (Jack Diederich) Date: Wed, 12 Oct 2011 00:07:05 -0400 Subject: Implementing Python-OAuth2 In-Reply-To: <4E8DD438.20207@ncsa.illinois.edu> References: <4E8DD438.20207@ncsa.illinois.edu> Message-ID: On Thu, Oct 6, 2011 at 12:15 PM, Jeff Gaynor wrote: > On 10/06/2011 08:34 AM, Kayode Odeyemi wrote: >> I'm working on a pretty large application that I will like to use oauth2 >> on as an authentication and authorization mechanism. > > There are *no* usable OAuth version 2..0 implementation in any language > (usually Java comes first) that I know of, so you will get to role your own, > which is hard. There are a few beta-level versions E.g. Twitter) but these > are special cased to the author's needs. The spec itself is not quite ready > either and since it has changed quite substantially in the last year, I > suspect that everyone is waiting to see it settle to a steady state. I got bit hard by oauth libraries, especially because pre-OAuth2.0 someone started a forked OAuth1.0 library and named it "oauth2". Lots of forked copies of that one pollute the searches. Google has one but it is impossibly over engineered - 15,000 lines of code in a hundred files. I got frustrated and wrote one that only does 2.0 "bearer token" and has only been tested against goo.gl (the google URL shortener). But it works for me, weighs in at 200 lines of code, and only needs stdlib + json libraries. Using the official google API required me to write more than 200 lines of code, so I'm a happy camper. https://github.com/jackdied/python-foauth2 Patches-welcome-ly, -Jack NB, the name can be pronounced "faux-auth 2" or "Eff Oauth 2" at your discretion. From mdaglow at daglowconsulting.com Wed Oct 12 00:49:30 2011 From: mdaglow at daglowconsulting.com (Marta) Date: Tue, 11 Oct 2011 21:49:30 -0700 (PDT) Subject: Want to make the transition to games? Message-ID: Hi, I'm working as an onsite recruiting consultant and we are looking for top engineers who want to work with other very accomplished engineers. If you have a CS degree, strong in C++ and want to make the transition to games, please email me your resume. Cheers, Marta Daglow From christian.wutte at gmx.at Wed Oct 12 04:22:34 2011 From: christian.wutte at gmx.at (Christian Wutte) Date: Wed, 12 Oct 2011 01:22:34 -0700 (PDT) Subject: os.startfile: Why is there no arguments option? Message-ID: Hello all, as stated in the docs [1] os.startfile relies on Win32 ShellExecute(). So maybe someone can explain it to me, why there is no support for program arguments. That's quite a pity since os.startfile is the easiest way for an elevated run (with 'runas' as option) and without arguments of limited use. [1] http://docs.python.org/library/os.html?highlight=startfile#os.startfile Thanks, Christian From iamforufriends at gmail.com Wed Oct 12 05:05:36 2011 From: iamforufriends at gmail.com (hot girl) Date: Wed, 12 Oct 2011 02:05:36 -0700 (PDT) Subject: his wife need dating with other man Message-ID: his wife need dating with other man http://tinyurl.com/44s5ewx http://tinyurl.com/44s5ewx http://tinyurl.com/44s5ewx http://tinyurl.com/44s5ewx From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Wed Oct 12 05:27:48 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Wed, 12 Oct 2011 11:27:48 +0200 Subject: os.startfile: Why is there no arguments option? In-Reply-To: References: Message-ID: Am 12.10.2011 10:22 schrieb Christian Wutte: > Hello all, > as stated in the docs [1] os.startfile relies on Win32 ShellExecute(). > So maybe someone can explain it to me, why there is no support for > program arguments. Because it is intended to start an arbitrary file of any type (.txt, .doc, ...) For this operations, there is no parameter support. > That's quite a pity since os.startfile is the easiest way for an > elevated run (with 'runas' as option) Obviously not. > and without arguments of limited use. So it isn't the asiest way. Have you tried os.system() and/or subprocess.Popen() resp. .call()? Thomas From ben+python at benfinney.id.au Wed Oct 12 05:41:28 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Oct 2011 20:41:28 +1100 Subject: Seven Python Developers Needed $125K In-Reply-To: (WR's message of "Tue, 11 Oct 2011 18:16:50 -0000") References: Message-ID: <87mxd6wnqv.fsf@benfinney.id.au> "WR" writes: > Top Global Consulting Firm in NYC needs 7 Python Developers Please do not use this discussion forum for recruitment. Instead, use the Python Job board for that purpose. -- \ ?If the desire to kill and the opportunity to kill came always | `\ together, who would escape hanging?? ?Mark Twain, _Following | _o__) the Equator_ | Ben Finney From theller at ctypes.org Wed Oct 12 05:45:18 2011 From: theller at ctypes.org (Thomas Heller) Date: Wed, 12 Oct 2011 11:45:18 +0200 Subject: os.startfile: Why is there no arguments option? In-Reply-To: References: Message-ID: <9fl5teFavpU1@mid.individual.net> Am 12.10.2011 10:22, schrieb Christian Wutte: > Hello all, > as stated in the docs [1] os.startfile relies on Win32 ShellExecute(). > So maybe someone can explain it to me, why there is no support for > program arguments. > That's quite a pity since os.startfile is the easiest way for an > elevated run (with 'runas' as option) and without arguments of limited > use. > > [1] http://docs.python.org/library/os.html?highlight=startfile#os.startfile > > Thanks, > Christian It is trivial to call ShellExecute with ctypes. Thomas From moky.math at gmail.com Wed Oct 12 06:14:20 2011 From: moky.math at gmail.com (Laurent Claessens) Date: Wed, 12 Oct 2011 12:14:20 +0200 Subject: 1/2 evaluates to 0 Message-ID: Hi all This is well known : >>> 1/2 0 This is because the division is an "integer division". My question is : how can I evaluate 1/2 to 0.5 ? Is there some non integer division operator ? Up to now I workarounded writing float(1)/2. Is there an other way ? My Zen of python says : There should be one-- and preferably only one --obvious way to do it. and I don't believe that float(1)/2 is an "obvious way" (I'm not Dutch) Have a good afternoon Laurent From jeanmichel at sequans.com Wed Oct 12 06:24:23 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 12 Oct 2011 12:24:23 +0200 Subject: 1/2 evaluates to 0 In-Reply-To: References: Message-ID: <4E956AD7.5070309@sequans.com> Laurent Claessens wrote: > Hi all > > > This is well known : > > >>> 1/2 > 0 > > This is because the division is an "integer division". > > My question is : how can I evaluate 1/2 to 0.5 ? Is there some non > integer division operator ? > Up to now I workarounded writing float(1)/2. Is there an other way ? > > My Zen of python says : > There should be one-- and preferably only one --obvious way to do it. > > and I don't believe that float(1)/2 is an "obvious way" (I'm not Dutch) > > Have a good afternoon > Laurent Hi, 1./2 JM From enalicho at gmail.com Wed Oct 12 06:25:34 2011 From: enalicho at gmail.com (Noah Hall) Date: Wed, 12 Oct 2011 11:25:34 +0100 Subject: 1/2 evaluates to 0 In-Reply-To: References: Message-ID: On Wed, Oct 12, 2011 at 11:14 AM, Laurent Claessens wrote: > This is well known : > >>>> 1/2 > 0 > > This is because the division is an "integer division". > > My question is : how can I evaluate 1/2 to 0.5 ? Is there some non integer Include from __future__ import division on the top of your file >>> from __future__ import division >>> 1/2 0.5 From aaan at email.dk Wed Oct 12 06:27:03 2011 From: aaan at email.dk (Aage Andersen (REMOVE)) Date: Wed, 12 Oct 2011 12:27:03 +0200 Subject: 1/2 evaluates to 0 References: Message-ID: <4e956b7a$0$56792$edfadb0f@dtext02.news.tele.dk> "Laurent Claessens" skrev i en meddelelse news:j73p9s$baa$1 at news.univ-fcomte.fr... > Hi all > > > This is well known : > > >>> 1/2 > 0 > > This is because the division is an "integer division". > > My question is : how can I evaluate 1/2 to 0.5 ? Is there some non integer > division operator ? > Up to now I workarounded writing float(1)/2. Is there an other way ? what about 1.0/2 ? From paul.nospam at rudin.co.uk Wed Oct 12 06:28:51 2011 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Wed, 12 Oct 2011 11:28:51 +0100 Subject: 1/2 evaluates to 0 References: Message-ID: <87ipnuh5b0.fsf@no-fixed-abode.cable.virginmedia.net> Laurent Claessens writes: > Hi all > > > This is well known : > >>>> 1/2 > 0 > > This is because the division is an "integer division". > > My question is : how can I evaluate 1/2 to 0.5 ? Is there some non > integer division operator ? > Up to now I workarounded writing float(1)/2. Is there an other way ? from __future__ import division Or use operator.truediv Or use python 3. From rosuav at gmail.com Wed Oct 12 06:29:58 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Oct 2011 21:29:58 +1100 Subject: 1/2 evaluates to 0 In-Reply-To: References: Message-ID: On Wed, Oct 12, 2011 at 9:14 PM, Laurent Claessens wrote: > Hi all > > This is well known : > >>>> 1/2 > 0 Only in Python 2. > This is because the division is an "integer division". > > My question is : how can I evaluate 1/2 to 0.5 ? Is there some non integer > division operator ? 1.0/2 is floating point division, but you can also use: >>> from __future__ import division >>> 1/2 0.5 >>> 1//2 0 This is the most portable option. Stick with // for integer division and tell / to produce a float (which it will do even if the result would have fitted into an integer). Note that the __future__ directive needs to be at the top of your program. ChrisA From __peter__ at web.de Wed Oct 12 06:34:58 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 12 Oct 2011 12:34:58 +0200 Subject: 1/2 evaluates to 0 References: Message-ID: Laurent Claessens wrote: > This is well known : > > >>> 1/2 > 0 > > This is because the division is an "integer division". > > My question is : how can I evaluate 1/2 to 0.5 ? Is there some non > integer division operator ? > Up to now I workarounded writing float(1)/2. Is there an other way ? > > My Zen of python says : > There should be one-- and preferably only one --obvious way to do it. > > and I don't believe that float(1)/2 is an "obvious way" (I'm not Dutch) In Python 3 there is an obvious way: >>> 1/2 0.5 In Python 2 you can trigger that behaviour with the magic incantation >>> from __future__ import division >>> 1/2 0.5 In both cases the traditional integer division can be forced with >>> 1//2 0 From alec.taylor6 at gmail.com Wed Oct 12 07:06:08 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Wed, 12 Oct 2011 22:06:08 +1100 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] In-Reply-To: References: <4E945CD6.3040502@tim.thechases.com> Message-ID: That's why I said "over the next few days", because learning it for that last assignment would've been too much effort :P On Wed, Oct 12, 2011 at 3:45 PM, wu wei wrote: > Just don't use it for the first time in a demo and then blame me when it > fails ;) > > On Wed, Oct 12, 2011 at 2:05 PM, Alec Taylor wrote: >> >> Great, I'll learn how to use it over the next few days >> >> :] >> >> On Wed, Oct 12, 2011 at 2:13 PM, alex23 wrote: >> > On Oct 12, 1:14?am, Alec Taylor wrote: >> >> They look good, but I'm looking for something which can "compile" down >> >> to normal SQL code. >> > >> > Then you're not looking hard enough. SQLAlchemy does this. >> > >> > -- >> > http://mail.python.org/mailman/listinfo/python-list >> > > > From selahattin_ay at msn.com Wed Oct 12 07:15:26 2011 From: selahattin_ay at msn.com (selahattin ay) Date: Wed, 12 Oct 2011 11:15:26 +0000 Subject: file processing question Message-ID: hi all, I wrote these codes but the program must write the prints to a text file... code = [100, 200, 300, 400, 500] list= [] a = 0 while a < 9: a+=1 list.append(a) last_list = [[int(str(i) + str(k)) for i in code] for k in list] list2= [] b = 0 while b < 9: b+=1 list2.append(b) the thing that I want to do is, I want to create text files from 1 to 9 as in list2 1.txt, 2.txt ....9.txt like thatsample of a text file is : X:CA VERSION:2.5 P:(here will be the first value of list2 );;;; L;C: (here will be the first value of last_list ) the first sample X:CA VERSION:2.5 P: 1 ;;;; L;C: 1001 the first sample X:CA VERSION:2.5 P: 8 ;;;; L;C: 1008 can you help me about this thx for all.. -------------- next part -------------- An HTML attachment was scrubbed... URL: From installman at 189.cn Wed Oct 12 07:18:25 2011 From: installman at 189.cn (installman at 189.cn) Date: Wed, 12 Oct 2011 04:18:25 -0700 (PDT) Subject: why msvcrt.printf show the first char only? Message-ID: <88550536-6cc5-452c-8bca-ba91b175323a@l39g2000pro.googlegroups.com> from ctypes import * msvcrt = cdll.msvcrt message_string = "Hello world!\n" print(msvcrt.printf("Testing: %s", message_string)) when running in eclipse, the result is: 1 T when running in IDLE, then result is: 1 why is that? From moky.math at gmail.com Wed Oct 12 07:28:35 2011 From: moky.math at gmail.com (Laurent) Date: Wed, 12 Oct 2011 13:28:35 +0200 Subject: 1/2 evaluates to 0 In-Reply-To: References: Message-ID: <4E9579E3.9090303@gmail.com> > Include from __future__ import division on the top of your file > >>>> from __future__ import division >>>> 1/2 > 0.5 > Wohaw. This means that this behavior is going to be default in a foreseeable future ? Thanks Laurent From nobody at nowhere.com Wed Oct 12 07:34:21 2011 From: nobody at nowhere.com (Nobody) Date: Wed, 12 Oct 2011 12:34:21 +0100 Subject: 1/2 evaluates to 0 References: Message-ID: On Wed, 12 Oct 2011 13:28:35 +0200, Laurent wrote: >>>>> from __future__ import division >>>>> 1/2 >> 0.5 >> > > Wohaw. This means that this behavior is going to be default in a > foreseeable future ? It's the default in 3.x. I can't imagine it ever being the default in 2.x. From enalicho at gmail.com Wed Oct 12 07:41:05 2011 From: enalicho at gmail.com (Noah Hall) Date: Wed, 12 Oct 2011 12:41:05 +0100 Subject: 1/2 evaluates to 0 In-Reply-To: <4E9579E3.9090303@gmail.com> References: <4E9579E3.9090303@gmail.com> Message-ID: On Wed, Oct 12, 2011 at 12:28 PM, Laurent wrote: > >> Include from __future__ import division on the top of your file >> >>>>> ?from __future__ import division >>>>> ?1/2 >> >> 0.5 >> > > Wohaw. This means that this behavior is going to be default in a foreseeable > future ? Never in Python 2.x, but it already is in Python 3.x [1] [1] - http://www.python.org/dev/peps/pep-0238/ From nobody at nowhere.com Wed Oct 12 07:50:34 2011 From: nobody at nowhere.com (Nobody) Date: Wed, 12 Oct 2011 12:50:34 +0100 Subject: why msvcrt.printf show the first char only? References: <88550536-6cc5-452c-8bca-ba91b175323a@l39g2000pro.googlegroups.com> Message-ID: On Wed, 12 Oct 2011 04:18:25 -0700, installman at 189.cn wrote: > from ctypes import * > msvcrt = cdll.msvcrt > message_string = "Hello world!\n" > print(msvcrt.printf("Testing: %s", message_string)) > > when running in eclipse, the result is: > 1 > T > > when running in IDLE, then result is: > 1 > > why is that? Odd. I get 22 when running from IDLE. Also, when using the console, it actually prints the text. I suspect that stdout gets block-buffered when using an IDE. I can't see any way to get a reference to stdout, so you can't fflush() it. From steve+comp.lang.python at pearwood.info Wed Oct 12 07:56:27 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 12 Oct 2011 22:56:27 +1100 Subject: 1/2 evaluates to 0 References: Message-ID: <4e95806c$0$29986$c3e8da3$5496439d@news.astraweb.com> Nobody wrote: > On Wed, 12 Oct 2011 13:28:35 +0200, Laurent wrote: > >>>>>> from __future__ import division >>>>>> 1/2 >>> 0.5 >>> >> >> Wohaw. This means that this behavior is going to be default in a >> foreseeable future ? > > It's the default in 3.x. I can't imagine it ever being the default in 2.x. 2.7 is now in "bug-fix only" mode, so no new features, and there won't be a 2.8, so true division will never be the default in 2.x. -- Steven From christian.wutte at gmx.at Wed Oct 12 08:18:00 2011 From: christian.wutte at gmx.at (Christian Wutte) Date: Wed, 12 Oct 2011 05:18:00 -0700 (PDT) Subject: os.startfile: Why is there no arguments option? References: Message-ID: On Oct 12, 11:27?am, Thomas Rachel wrote: > Am 12.10.2011 10:22 schrieb Christian Wutte: > > > Hello all, > > as stated in the docs [1] os.startfile relies on Win32 ShellExecute(). > > So maybe someone can explain it to me, why there is no support for > > program arguments. > > Because it is intended to start an arbitrary file of any type (.txt, > .doc, ...) For this operations, there is no parameter support. > Yes, but isn't that also the case for ShellExecute()? In the MSDN page [1] for the parameters can be read: "If lpFile specifies an executable file, this parameter is a pointer to a null-terminated string that specifies the parameters to be passed to the application. The format of this string is determined by the verb that is to be invoked. If lpFile specifies a document file, lpParameters should be NULL." So the parameter should be optional for sure. > > That's quite a pity since os.startfile is the easiest way for an > > elevated run (with 'runas' as option) > > Obviously not. > > ?> and without arguments of limited use. > > So it isn't the asiest way. > > Have you tried os.system() and/or subprocess.Popen() resp. .call()? > Yes. I should have noticed, that in my case I want to make a manual elevated call. With programs that need elevated rights in the first place os.start() or subprocess.Popen(.. , shell=True) is fine. Chrisitan From christian.wutte at gmx.at Wed Oct 12 08:28:32 2011 From: christian.wutte at gmx.at (Christian Wutte) Date: Wed, 12 Oct 2011 05:28:32 -0700 (PDT) Subject: os.startfile: Why is there no arguments option? References: <9fl5teFavpU1@mid.individual.net> Message-ID: On Oct 12, 11:45?am, Thomas Heller wrote: > > It is trivial to call ShellExecute with ctypes. > Yes, but it would be easier to use os.startfile() instead of ctypes.windll.shell32.ShellExecute(), not? Further one must for sure check the MSDN page for ShellExecute for the five parameters. Then on error it is more comfortable that os.startfile already throws an WindowsError. [1] http://msdn.microsoft.com/en-us/library/windows/desktop/bb762153%28v=vs.85%29.aspx Christian From ramapraba2653 at gmail.com Wed Oct 12 08:52:44 2011 From: ramapraba2653 at gmail.com (SUPREME) Date: Wed, 12 Oct 2011 05:52:44 -0700 (PDT) Subject: HOT ACTRESSES Message-ID: <36dcd84b-9341-4d51-840a-64d9493425fa@l30g2000pro.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html From python.list at tim.thechases.com Wed Oct 12 11:33:04 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 12 Oct 2011 10:33:04 -0500 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] In-Reply-To: References: <4E945CD6.3040502@tim.thechases.com> Message-ID: <4E95B330.6070903@tim.thechases.com> On 10/11/11 22:13, alex23 wrote: >> They look good, but I'm looking for something which can >> "compile" down to normal SQL code. > > Then you're not looking hard enough. SQLAlchemy does this. I'm not sure it can entirely be chalked up to not looking hard enough. Because so many keywords of what's desired are overloaded (e.g. "raw", "sql", "result", etc), it took me several passes to learn that str(query_object) did this in SQLAlchemy, and while I know there has to be SOME way to coerce it out of SQLObject, I was unable to find anything other than setting the connection-debug to True and having it print to the debugging sink. And I had the advantage of years of programming Python & SQL, and some pretty good Google-fu to guide me. For somebody coming fresh to the field, it would be easy to miss. -tkc From maxc at me.com Wed Oct 12 11:59:07 2011 From: maxc at me.com (Max Countryman) Date: Wed, 12 Oct 2011 11:59:07 -0400 Subject: Code Review: a framework for writing IRC applications or bots Message-ID: <7D6AE088-3EC7-4976-B739-A66A777E4390@me.com> Hi all, I'm still very much a learner when it comes to Python but I've been working on a little framework the past few weeks to help me in the learning process and I would like it if the more experienced members of the community could give me some advice on the design considerations and general quality of the code. The goal was to create a framework for writing IRC applications or bots. I modeled the API after Flask. It was important to me that I include a number of features: such as automatic on-the-fly reloading, threaded plugins, and the ability to reconnect to a network should the connection be lost. I'd really appreciate any feedback, tips, advice, and so forth. Please understand this isn't necessarily meant to be a utility of high value: IRC isn't exactly the most happening place after all and my main goal was to hone my skills so if your reaction is that this is essentially useless that wasn't necessarily my goal. Nonetheless I really would appreciate any kind of code review the community might be willing to provide. The project is available here: https://github.com/maxcountryman/irctk Thanks for your time! Max From andreas.perstinger at gmx.net Wed Oct 12 12:38:10 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Wed, 12 Oct 2011 18:38:10 +0200 Subject: file processing question In-Reply-To: References: Message-ID: <4E95C272.1020407@gmx.net> On 2011-10-12 13:15, selahattin ay wrote: > > hi all, I wrote these codes but the program must write the prints to a text file... > code = [100, 200, 300, 400, 500] > > > list= [] > a = 0 > while a< 9: > a+=1 > list.append(a) > last_list = [[int(str(i) + str(k)) for i in code] for k in list] > list2= [] > b = 0 > while b< 9: > b+=1 > list2.append(b) Others have already told you yesterday that you don't need while-loops: list = range(1, 10) list2 = list[:] (you probably don't need "list2" at all) > the thing that I want to do is, I want to create text files from 1 to 9 as in list2 > 1.txt, 2.txt ....9.txt like thatsample of a text file is : > > X:CA > VERSION:2.5 > P:(here will be the first value of list2 );;;; > L;C: (here will be the first value of last_list ) > > > the first sample > X:CA > VERSION:2.5 > P: 1 ;;;; > L;C: 1001 > > the first sample > > X:CA > VERSION:2.5 > P: 8 ;;;; > L;C: 1008 You want to write 9 files but last_list has 45 elements. What will happen with the rest of them? BTW: Your last_list is a list of 9 lists, each containing 5 elements ([[1001, 2001, ...], [1002, 2002, ...], ...]). Don't you really want a list of 5 lists, each containing 9 elements ([[1001, 1002, ...], [2001, 2002, ...], ...])? At least I get this impression from your samples. Bye, Andreas From yasar11732 at gmail.com Wed Oct 12 12:47:31 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Wed, 12 Oct 2011 19:47:31 +0300 Subject: file processing question In-Reply-To: <4E95C272.1020407@gmx.net> References: <4E95C272.1020407@gmx.net> Message-ID: And also, I higly recommend against using lists named list. That means overwriting builtin list object. 2011/10/12 Andreas Perstinger > On 2011-10-12 13:15, selahattin ay wrote: > >> >> hi all, I wrote these codes but the program must write the prints to a >> text file... >> code = [100, 200, 300, 400, 500] >> >> >> list= [] >> a = 0 >> while a< 9: >> a+=1 >> list.append(a) >> last_list = [[int(str(i) + str(k)) for i in code] for k in list] >> list2= [] >> b = 0 >> while b< 9: >> b+=1 >> list2.append(b) >> > > Others have already told you yesterday that you don't need while-loops: > list = range(1, 10) > list2 = list[:] > (you probably don't need "list2" at all) > > the thing that I want to do is, I want to create text files from 1 to 9 as >> in list2 >> 1.txt, 2.txt ....9.txt like thatsample of a text file is : >> >> >> X:CA >> VERSION:2.5 >> P:(here will be the first value of list2 );;;; >> L;C: (here will be the first value of last_list ) >> >> >> the first sample >> X:CA >> VERSION:2.5 >> P: 1 ;;;; >> L;C: 1001 >> >> the first sample >> >> X:CA >> VERSION:2.5 >> P: 8 ;;;; >> L;C: 1008 >> > > You want to write 9 files but last_list has 45 elements. What will happen > with the rest of them? > > BTW: Your last_list is a list of 9 lists, each containing 5 elements > ([[1001, 2001, ...], [1002, 2002, ...], ...]). Don't you really want a list > of 5 lists, each containing 9 elements ([[1001, 1002, ...], [2001, 2002, > ...], ...])? At least I get this impression from your samples. > > Bye, Andreas > -- > http://mail.python.org/**mailman/listinfo/python-list > -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Wed Oct 12 13:51:16 2011 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 12 Oct 2011 18:51:16 +0100 Subject: [Python-ideas] Implement comparison operators for range objects In-Reply-To: <4E95CF7D.6000000@pearwood.info> References: <20111012163144.GB6393@pantoffel-wg.de> <4E95CF7D.6000000@pearwood.info> Message-ID: <4E95D394.9000205@mrabarnett.plus.com> On 12/10/2011 18:33, Steven D'Aprano wrote: > Sven Marnach wrote: >> There are circumstances, for example in unit testing, when it might be >> useful to check if two range objects describe the same range. >> Currently, this can't be done using the '==' operator: >> >> >>> range(5) == range(5) >> False > [...] >> All other built-in sequence types (that is bytearray, bytes, list, >> str, and tuple) define equality by "all items of the sequence are >> equal". I think it would be both more consistent and more useful if >> range objects would pick up the same semantics. > > I can see how that would be useful and straightforward, and certainly > more useful than identity based equality. +1 > > >> When implementing '==' and '!=' for range objects, it would be natural >> to implement the other comparison operators, too (lexicographically, >> as for all other sequence types). > > I don't agree. Equality makes sense for ranges: two ranges are equal if > they have the same start, stop and step values. But order comparisons > don't have any sensible meaning: range objects are numeric ranges, > integer-valued intervals, not generic lists, and it is meaningless to > say that one range is less than or greater than another. > > Which is greater? > > range(1, 1000000, 1000) > range(1000, 10000) > > The question makes no sense, and should be treated as an error, just as > it is for complex numbers. > > -1 on adding order comparison operators. > > > > Aside: > > I'm astonished to see that range objects have a count method! What's the > purpose of that? Any value's count will either be 0 or 1, and a more > appropriate test would be `value in range`: > > >>> 17 in range(2, 30, 3) # like r.count(17) => 1 > True > >>> 18 in range(2, 30, 3) # like r.count(18) => 0 > False > In Python 2, range returns a list, and lists have a .count method. Could that be the reason? From ramit.prasad at jpmorgan.com Wed Oct 12 13:53:51 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 12 Oct 2011 13:53:51 -0400 Subject: Code Review: a framework for writing IRC applications or bots In-Reply-To: <7D6AE088-3EC7-4976-B739-A66A777E4390@me.com> References: <7D6AE088-3EC7-4976-B739-A66A777E4390@me.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F215C882F@EMARC112VS01.exchad.jpmchase.net> > It was important to me that I include a number of features: such as automatic on-the-fly reloading, If you are referring to reloading python modules (and not configuration files), I can tell you that this is a difficult feature to implement, much less do it correctly. I have experienced troubles with this in Python2 (not sure about Python3). For example: If you have two modules A and B, where B imports A. Reloading A works fine for new instances of A, but this will not automatically reload the version of A already imported by B. Note: This has been my experience with apps that try to do this, not from firsthand experience in development. Your mileage (kilometerage?) may vary. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From 1jason.whatford at gmail.com Wed Oct 12 14:27:51 2011 From: 1jason.whatford at gmail.com (J) Date: Wed, 12 Oct 2011 11:27:51 -0700 (PDT) Subject: Embedding a "frame" into a movie using python Message-ID: <18514149.192.1318444071734.JavaMail.geo-discussion-forums@vbbfh29> Hi there, I'm currently experimenting with python by putting together a little webapp running on appengine. My objective is to have the user put together some images html and embed the image as a frame into a video file (any embeddable format e.g. swf). So there are three steps: (1) Convert the html to a "frame" (2) Insert the frame into the existing movie (3) save the new movie with the frame For example, I have a film of a sunrise. I want to embed a "frame" which has a little poem about sunrises into the film much like windows movie maker and other such programs allow you to do. Is there a way I can do this with python? Cheers, J From ian.g.kelly at gmail.com Wed Oct 12 15:24:31 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 12 Oct 2011 13:24:31 -0600 Subject: [Python-ideas] Implement comparison operators for range objects In-Reply-To: <4E95D394.9000205@mrabarnett.plus.com> References: <20111012163144.GB6393@pantoffel-wg.de> <4E95CF7D.6000000@pearwood.info> <4E95D394.9000205@mrabarnett.plus.com> Message-ID: On Wed, Oct 12, 2011 at 11:51 AM, MRAB wrote: >> Aside: >> >> I'm astonished to see that range objects have a count method! What's the >> purpose of that? Any value's count will either be 0 or 1, and a more >> appropriate test would be `value in range`: >> >> ?>>> 17 in range(2, 30, 3) # like r.count(17) => 1 >> True >> ?>>> 18 in range(2, 30, 3) # like r.count(18) => 0 >> False >> > In Python 2, range returns a list, and lists have a .count method. > Could that be the reason? Python 2 xrange objects do not have a .count method. Python 3 range objects do have a .count method. The addition is curious, to say the least. From rosuav at gmail.com Wed Oct 12 16:06:45 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Oct 2011 07:06:45 +1100 Subject: Embedding a "frame" into a movie using python In-Reply-To: <18514149.192.1318444071734.JavaMail.geo-discussion-forums@vbbfh29> References: <18514149.192.1318444071734.JavaMail.geo-discussion-forums@vbbfh29> Message-ID: On Thu, Oct 13, 2011 at 5:27 AM, J <1jason.whatford at gmail.com> wrote: > My objective is to have the user put together some images html and embed the image as a frame into a video file (any embeddable format e.g. swf). So there are three steps: > SWF isn't the easiest format to work with; it's not necessarily a video, but might be a scripted object. Try working with real video formats such as avi, mpg, or ogv. You may wish to look into PiTiVi, an open source video editor; it's written in Python. I'm not sure if you can achieve what you want by simply driving PiTiVi externally, but at very least, it's worth a peek. ChrisA From pengyu.ut at gmail.com Wed Oct 12 16:42:09 2011 From: pengyu.ut at gmail.com (Peng Yu) Date: Wed, 12 Oct 2011 15:42:09 -0500 Subject: How add class name to format of the logging module? Message-ID: Hi, The following attributes does not include the class name. Is there a way to add class name to the format string? Thanks! http://docs.python.org/library/logging.html#logrecord-attributes -- Regards, Peng From zaffino.p at gmail.com Wed Oct 12 17:06:47 2011 From: zaffino.p at gmail.com (Paolo Zaffino) Date: Wed, 12 Oct 2011 23:06:47 +0200 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: I wrote a function thaht works on a 3D matrix. As first thing I have an array and I want reshape it into a 3D matrix (for further manipulations). For this reason I wrote in a row: matrix=matrix.reshape(a, b, c).T It work fine on GNU/Linux and Mac OS but not on Windows. In Windows I get this error: matrix=matrix.reshape(a, b, c).T ValueError: total size of new array must be unchanged Thank you. 2011/10/11 David Robinow > 2011/10/11 Paolo Zaffino : > > Nobody can help me? > Nope, not unless you post some code. Your problem description is too > vague. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwebb at teradactyl.com Wed Oct 12 17:10:08 2011 From: kwebb at teradactyl.com (Kristen J. Webb) Date: Wed, 12 Oct 2011 15:10:08 -0600 Subject: shipping python In-Reply-To: <4e94ee02$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <4e94ee02$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E960230.9000407@teradactyl.com> I tried experimenting with .pyc files only to end up at: RuntimeError: Bad magic number in .pyc file can't run 2.5 pyc files on 2.6 :( My main motivation to use .pyc is to keep end users from changing scripts, breaking things, and then calling us. Tamper proofing may be an alternative approach if anyone has suggestions. Otherwise, trying to summarize my goals: 1. Distribute python (and other stuff) across many platforms (Linux, UNIXes, OSX, Windows) 2. Support the current 2.X version of python installed on the system 3. Take advantage of python modules that use shared OS libraries (e.g. libssl.so.whatever) 4. For linux especially, support many distributions/versions (getting openssl to work right, for example, is a tricky problem) 5. Take advantage of the latest python modules whenever possible (hence the argparse testing). I realize that I may be able to go back so far for this to make sense... 6. Provide additional product functionality through our own shared libraries (c code). I'm assuming that the customer system has python 2.X installed, otherwise they can use their favorite OS method to get it in the standard way. Looking at methods that try to package and run without python installed at all do not look appealing, anywhere from does it work, to export issues, to needing a C compiler on the client system..... Shipping .py files and support for modules like argparse for backward compatibility is what I've come up with so far. Then they have everything I need to create and install a .pyc file. (The can modify the installer .py files, but I expect this to be less of an issue and may be able to make my own simple tamper detecting for this). Can anyone suggest better strategies, or point out where this just won't work? Is distutils a good starting point? Many thanks! Kris On 10/11/11 7:31 PM, Steven D'Aprano wrote: > On Tue, 11 Oct 2011 17:04:45 -0600, Kristen J. Webb wrote: > >> After some more digging I see that I can easy_install argparse on my >> development system. >> >> My question is will I be able to ship this to a customer? Can I create >> .pyc files so that the customer does not have to install the argparse >> module? > > Yes, and yes. The licence of argparse is a very liberal licence, so you > can just include it in your application. There's no need for the user to > install it separately. > > You could include just the .pyc file if you insist, but I personally > don't like or recommend .pyc only installations. > > >> If not, and I want to go back into the 2.3+ range, should I just use >> optparse? > > That depends on how complex your command line arguments are. > > -- Mr. Kristen J. Webb Teradactyl LLC. PHONE: 1-505-242-1091 EMAIL: kwebb at teradactyl.com VISIT: http://www.teradactyl.com Home of the True incremental Backup System From rosuav at gmail.com Wed Oct 12 17:26:44 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Oct 2011 08:26:44 +1100 Subject: shipping python In-Reply-To: <4E960230.9000407@teradactyl.com> References: <4e94ee02$0$29978$c3e8da3$5496439d@news.astraweb.com> <4E960230.9000407@teradactyl.com> Message-ID: On Thu, Oct 13, 2011 at 8:10 AM, Kristen J. Webb wrote: > My main motivation to use .pyc is to keep end users from changing scripts, > breaking things, and then calling us. ?Tamper proofing may be an > alternative approach if anyone has suggestions. > I wouldn't bother; if you're worried about that, try a tamper-evident system rather than tamper-proof - for instance, MD5 checksums of everything: $ md5sum * >checksum.txt $ md5sum checksum.txt 123412341234123412341234 md5sum Save that meta-checksum and have an easy way to read it back - that way, you can be sure they haven't just rebuilt the checksum file. If that one checksum has changed, you know something else has; to find out which: $ md5sum -c --quiet checksum.txt No need to restrict what you send out that way, and you can still get a guarantee that they haven't fiddled with anything. ChrisA From vinay_sajip at yahoo.co.uk Wed Oct 12 18:03:53 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Wed, 12 Oct 2011 15:03:53 -0700 (PDT) Subject: How add class name to format of the logging module? References: Message-ID: <8cd5490c-7bb6-4e3f-829c-518c163db436@m15g2000vbk.googlegroups.com> On Oct 12, 9:42?pm, Peng Yu wrote: > Hi, > > The following attributes does not include the class name. Is there a > way to add class name to the format string? Thanks! Not in the general case without a reasonable run-time cost. Since you can find the exact line number a logging call was made from, you can always figure out the class. Regards, Vinay Sajip From andrea.crotti.0 at gmail.com Wed Oct 12 20:02:55 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Thu, 13 Oct 2011 01:02:55 +0100 Subject: shipping python In-Reply-To: <4E960230.9000407@teradactyl.com> References: <4e94ee02$0$29978$c3e8da3$5496439d@news.astraweb.com> <4E960230.9000407@teradactyl.com> Message-ID: <4E962AAF.3090109@gmail.com> On 10/12/2011 10:10 PM, Kristen J. Webb wrote: > I tried experimenting with .pyc files only to end up at: > > RuntimeError: Bad magic number in .pyc file > > can't run 2.5 pyc files on 2.6 :( > > My main motivation to use .pyc is to keep end users from changing > scripts, > breaking things, and then calling us. Tamper proofing may be an > alternative approach if anyone has suggestions. > > Otherwise, trying to summarize my goals: > > 1. Distribute python (and other stuff) across many platforms > (Linux, UNIXes, OSX, Windows) > > 2. Support the current 2.X version of python installed on the system > > 3. Take advantage of python modules that use shared OS libraries > (e.g. libssl.so.whatever) > > 4. For linux especially, support many distributions/versions > (getting openssl to work right, for example, is a tricky problem) > > 5. Take advantage of the latest python modules whenever possible > (hence the argparse testing). I realize that I may be able > to go back so far for this to make sense... > > 6. Provide additional product functionality through our own > shared libraries (c code). > > I'm assuming that the customer system has python 2.X installed, > otherwise they > can use their favorite OS method to get it in the standard way. > > Looking at methods that try to package and run without python > installed at > all do not look appealing, anywhere from does it work, to export issues, > to needing a C compiler on the client system..... > > Shipping .py files and support for modules like argparse for > backward compatibility is what I've come up with so far. > Then they have everything I need to create and install a .pyc file. > (The can modify the installer .py files, but I expect this to be > less of an issue and may be able to make my own simple tamper detecting > for this). > > Can anyone suggest better strategies, or point out where this just > won't work? > > Is distutils a good starting point? > > Many thanks! > > Kris Why do you want to use the system python and system libraries? If you want to avoid too much troubles and compatibility hell maybe give PyInstaller a try, you ship just one big executable and you're done. But apart from that setuptools is very good to know. And also the world is a funny place, but does it really happen that a customer changes the code in your python scripts, and the *complain* if it doens't work anymore?? From roy at panix.com Wed Oct 12 20:30:33 2011 From: roy at panix.com (Roy Smith) Date: Wed, 12 Oct 2011 20:30:33 -0400 Subject: shipping python References: <4e94ee02$0$29978$c3e8da3$5496439d@news.astraweb.com> <4E960230.9000407@teradactyl.com> Message-ID: In article , Andrea Crotti wrote: > And also the world is a funny place, but does it really happen that > a customer changes the code in your python scripts, and the *complain* > if it doens't work anymore?? You sound like somebody who has never had to support paying customers :-) From tim at akwebsoft.com Wed Oct 12 20:52:44 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Wed, 12 Oct 2011 16:52:44 -0800 Subject: MySQLdb on Mac Lion Message-ID: <20111013005244.GK6671@johnsons-web.com> I'm most experienced with MySQLdb on ubuntu, which is installed via apt-get or synaptic. I am setting up a mac mini with osX 10.7 (Lion). Macports makes py27-mysql 1.2.2 available, but are there any .dmg packages available? thanks -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From nad at acm.org Wed Oct 12 22:00:10 2011 From: nad at acm.org (Ned Deily) Date: Wed, 12 Oct 2011 19:00:10 -0700 Subject: MySQLdb on Mac Lion References: <20111013005244.GK6671@johnsons-web.com> Message-ID: In article <20111013005244.GK6671 at johnsons-web.com>, Tim Johnson wrote: > I'm most experienced with MySQLdb on ubuntu, which is installed via > apt-get or synaptic. > > I am setting up a mac mini with osX 10.7 (Lion). Macports makes > py27-mysql 1.2.2 available, but are there any .dmg packages > available? I strongly recommend you stick with MacPorts or Homebrew. There are too many things that can go wrong on OS X 10.6 or 10.7 if you try to install MySQL client libraries, MySQLdb, and Python from different places. IME, the binary installers for OS X provided by the MySQL are inconsistently built between versions and often need the library paths need to be tweaked. The only major drawback of using MacPorts is that it will download (and possibly build) its own version of Python but it's a small price to pay: search the archives of Stackoverflow to see how dismayingly often this topic comes up. -- Ned Deily, nad at acm.org From kwebb at teradactyl.com Wed Oct 12 22:09:38 2011 From: kwebb at teradactyl.com (Kristen J. Webb) Date: Wed, 12 Oct 2011 20:09:38 -0600 Subject: shipping python In-Reply-To: <4E962AAF.3090109@gmail.com> References: <4e94ee02$0$29978$c3e8da3$5496439d@news.astraweb.com> <4E960230.9000407@teradactyl.com> <4E962AAF.3090109@gmail.com> Message-ID: <4E964862.9090701@teradactyl.com> On 10/12/11 6:02 PM, Andrea Crotti wrote: > > Why do you want to use the system python and system libraries? It is a standard, just like glibc on linux, I'd like my code should work on the OS with minimal intrusion. > If you want to avoid too much troubles and compatibility hell maybe > give PyInstaller a try, you ship just one big executable and you're done. > But apart from that setuptools is very good to know. What about Solaris, NetBSD, FreeBSD, etc, etc. If the executable includes bits from the openssl library, what about export restrictions? I'll take a look at setuptools, thanks. > > And also the world is a funny place, but does it really happen that > a customer changes the code in your python scripts, and the *complain* > if it doens't work anymore?? > Yes, support costs with very knowledgeable clients is a very important factor. Thank you for the feedback! K -- Mr. Kristen J. Webb Teradactyl LLC. PHONE: 1-505-242-1091 EMAIL: kwebb at teradactyl.com VISIT: http://www.teradactyl.com Home of the True incremental Backup System From kwebb at teradactyl.com Wed Oct 12 22:43:06 2011 From: kwebb at teradactyl.com (Kristen J. Webb) Date: Wed, 12 Oct 2011 20:43:06 -0600 Subject: shipping python In-Reply-To: References: <4e94ee02$0$29978$c3e8da3$5496439d@news.astraweb.com> <4E960230.9000407@teradactyl.com> Message-ID: <4E96503A.7090502@teradactyl.com> On 10/12/11 3:26 PM, Chris Angelico wrote: > On Thu, Oct 13, 2011 at 8:10 AM, Kristen J. Webb wrote: >> My main motivation to use .pyc is to keep end users from changing scripts, >> breaking things, and then calling us. Tamper proofing may be an >> alternative approach if anyone has suggestions. >> > > I wouldn't bother; if you're worried about that, try a tamper-evident > system rather than tamper-proof - for instance, MD5 checksums of > everything: > > $ md5sum *>checksum.txt > $ md5sum checksum.txt > 123412341234123412341234 md5sum > > Save that meta-checksum and have an easy way to read it back - that > way, you can be sure they haven't just rebuilt the checksum file. If > that one checksum has changed, you know something else has; to find > out which: > > $ md5sum -c --quiet checksum.txt > > No need to restrict what you send out that way, and you can still get > a guarantee that they haven't fiddled with anything. > > ChrisA So you could think of the meta-checksum as a script wide version control of what is installed. Then, at key entry points, take the hit and re-generate the meta-checksum and compare. If bad, you have a major version control error, do not process further. Makes sense, so long as the user does not bother to regenerate the meta-checksum as well. Would be more extensible if in debugging, users can disable this feature. or have a tool that updates the meta-checksum so that they can run one-off code to fix problems. Oddly, this feature would make it easier to change code and still keep things running. But we could use the value in the support chain to say, "something changed, what's going on?". Thoughts? K -- Mr. Kristen J. Webb Teradactyl LLC. PHONE: 1-505-242-1091 EMAIL: kwebb at teradactyl.com VISIT: http://www.teradactyl.com Home of the True incremental Backup System From pousadas.trancoso at reservas.trancoso.ba Wed Oct 12 23:54:32 2011 From: pousadas.trancoso at reservas.trancoso.ba (pousadas trancoso reservas bahia) Date: Thu, 13 Oct 2011 03:54:32 +0000 (UTC) Subject: reservastrancoso@gmail.com Pousadas em Trancoso, reservas, agencia virtual, turismo Bahia - 75469 Message-ID: reservastrancoso at gmail.com reservastrancoso @ gmail.com (reservastrancoso at gmail.com) Pousadas em Trancoso, agencia virtual em Tancoso - Bahia. Fa?a ja sua reserva nas pousadas mais badaladas da cidade. Contato reservastrancoso @ gmail.com reservastrancoso at gmail.com (reservastrancoso at gmail.com) >S^LnssPFTXZL_TreGzKVV+k. From jpiitula at ling.helsinki.fi Thu Oct 13 04:19:16 2011 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 13 Oct 2011 11:19:16 +0300 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: Chris Angelico writes: > On Sun, Oct 9, 2011 at 12:07 AM, Jussi Piitulainen wrote: > > But both negations can be avoided by modus tollens. > > > > "If you are able to start the car, the key is in the ignition." > > But this translation implies looking at the result and ascertaining > the state, which is less appropriate to a programming language. It's > more like: > > "If you found that you were able to start the car, the key must have > been in the ignition." > > and is thus quite inappropriate to the imperative style. A > functional language MAY be able to use this style, but Python wants > to have the condition and then the action. This is not in an imperative context. The context is (generalized) Boolean expressions, where there should not be any action, just expressions returning values that are combined to produce a (generalized) Boolean value. Defined order of evaluation and short-circuiting complicate the picture, but as a matter of style, I think there should not be any action part in such an expression. Usually. And "not in" is fine as far as I am concerned. From 1jason.whatford at gmail.com Thu Oct 13 04:51:36 2011 From: 1jason.whatford at gmail.com (J) Date: Thu, 13 Oct 2011 01:51:36 -0700 (PDT) Subject: Embedding a "frame" into a movie using python In-Reply-To: References: <18514149.192.1318444071734.JavaMail.geo-discussion-forums@vbbfh29> Message-ID: <11518268.545.1318495896114.JavaMail.geo-discussion-forums@vbat14> >> My objective is to have the user put together some images html and embed the image as a frame into a video file (any embeddable format e.g. swf). >SWF isn't the easiest format to work with; it's not necessarily a video, but might be a scripted object. Try working with real video formats such as avi, mpg, or ogv. >You may wish to look into PiTiVi, an open source video editor; it's written in Python. I'm not sure if you can achieve what you want by simply driving PiTiVi externally, but at very least, it's worth a peek. >ChrisA Hi Chris, thank you for your response. I am format agnostic for processing so am happy to work with avi etc., however in displaying the final film to the user I think I'd need to convert whatever I've made to swf to make it a little less downloadable. I'll check out PiTiVi - perhaps I can hack it to work on the back of appengine... Cheers, J From 1jason.whatford at gmail.com Thu Oct 13 04:51:36 2011 From: 1jason.whatford at gmail.com (J) Date: Thu, 13 Oct 2011 01:51:36 -0700 (PDT) Subject: Embedding a "frame" into a movie using python In-Reply-To: References: <18514149.192.1318444071734.JavaMail.geo-discussion-forums@vbbfh29> Message-ID: <11518268.545.1318495896114.JavaMail.geo-discussion-forums@vbat14> >> My objective is to have the user put together some images html and embed the image as a frame into a video file (any embeddable format e.g. swf). >SWF isn't the easiest format to work with; it's not necessarily a video, but might be a scripted object. Try working with real video formats such as avi, mpg, or ogv. >You may wish to look into PiTiVi, an open source video editor; it's written in Python. I'm not sure if you can achieve what you want by simply driving PiTiVi externally, but at very least, it's worth a peek. >ChrisA Hi Chris, thank you for your response. I am format agnostic for processing so am happy to work with avi etc., however in displaying the final film to the user I think I'd need to convert whatever I've made to swf to make it a little less downloadable. I'll check out PiTiVi - perhaps I can hack it to work on the back of appengine... Cheers, J From peter.mosley at talk21.com Thu Oct 13 04:52:50 2011 From: peter.mosley at talk21.com (peter) Date: Thu, 13 Oct 2011 01:52:50 -0700 (PDT) Subject: Reading screen width of a Tkinter widget. Message-ID: <2f7eee89-9be2-4405-8d92-c1545385c33f@e4g2000vbw.googlegroups.com> I recently had a problem while trying to set up a Tkinter Canvas widget as a progress bar. Everything seemed to be working, except that at 100% completion the progress bar spanned only about 75% of the canvas width. Eventually I tracked the problem down to the canvas bar 'width' property as read using w=cnvProgess['width']. It turned out the value returned was the original width of the canvas bar, and not the screen width after the canvas had been gridded using 'sticky=W+E'. Once I realised this it was not a show stopper, as I replaced the grid sticky option with a specific width instruction. But this is a bit less flexible than my original method. Is there any Tkinter command which will return the actual dimensions of a widget which has had the grid sticky option applied? Peter From candide at free.invalid Thu Oct 13 05:45:06 2011 From: candide at free.invalid (candide) Date: Thu, 13 Oct 2011 11:45:06 +0200 Subject: Opportunity missed by Python ? Message-ID: <4e96b324$0$1007$426a34cc@news.free.fr> Dart is the very new language created by Google to replace Javascript. So Python was not able to do the job? Or may be they don't know about Python at Google ;) ? From zapyon at gmx.net Thu Oct 13 05:56:58 2011 From: zapyon at gmx.net (Andreas Neudecker) Date: Thu, 13 Oct 2011 11:56:58 +0200 Subject: Opportunity missed by Python ? In-Reply-To: <4e96b324$0$1007$426a34cc@news.free.fr> References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: Am 13.10.2011 11:45, schrieb candide: > Dart is the very new language created by Google to replace Javascript. > So Python was not able to do the job? Or may be they don't know about > Python at Google ;) ? What needs to be done to make Python replace JS in Browsers/HTML? (or at least make it a viable alternative to JS) Can the Python community do this without involvment in browser development? Regards Andreas From moky.math at gmail.com Thu Oct 13 06:04:24 2011 From: moky.math at gmail.com (Laurent Claessens) Date: Thu, 13 Oct 2011 12:04:24 +0200 Subject: 1/2 evaluates to 0 In-Reply-To: <4e95806c$0$29986$c3e8da3$5496439d@news.astraweb.com> References: <4e95806c$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E96B7A8.5050203@gmail.com> >>> Wohaw. This means that this behavior is going to be default in a >>> foreseeable future ? >> >> It's the default in 3.x. I can't imagine it ever being the default in 2.x. > > > 2.7 is now in "bug-fix only" mode, so no new features, and there won't be a > 2.8, so true division will never be the default in 2.x. Thanks all for your ansers. I'll import division from __future__ Most of what I'm using in Python is with Sage[1]. Thus I'm not about to step to 3.x :( Laurent [1] www.sagemath.org From rosuav at gmail.com Thu Oct 13 06:07:09 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Oct 2011 21:07:09 +1100 Subject: Opportunity missed by Python ? In-Reply-To: <4e96b324$0$1007$426a34cc@news.free.fr> References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: On Thu, Oct 13, 2011 at 8:45 PM, candide wrote: > Dart is the very new language created by Google to replace Javascript. > So Python was not able to do the job? Or may be they don't know about Python > at Google ;) ? > Python, as I found out to my detriment, is practically impossible to sandbox effectively. Any language that hopes to gain full traction in a browser-based environment MUST be secure against scripts gaining too much control over the browser chrome. Also, Dart is looking to support (optional) strict typing, which Python doesn't do. That's a fairly major performance enhancement. ChrisA From rosuav at gmail.com Thu Oct 13 06:09:31 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Oct 2011 21:09:31 +1100 Subject: Embedding a "frame" into a movie using python In-Reply-To: <11518268.545.1318495896114.JavaMail.geo-discussion-forums@vbat14> References: <18514149.192.1318444071734.JavaMail.geo-discussion-forums@vbbfh29> <11518268.545.1318495896114.JavaMail.geo-discussion-forums@vbat14> Message-ID: On Thu, Oct 13, 2011 at 7:51 PM, J <1jason.whatford at gmail.com> wrote: > thank you for your response. I am format agnostic for processing so am happy to work with avi etc., however in displaying the final film to the user I think I'd need to convert whatever I've made to swf to make it a little less downloadable. I'll check out PiTiVi - perhaps I can hack it to work on the back of appengine... SWF is just as downloadable as any other format. I recommend doing the fewest translations you can get away with, to avoid unnecessary loss of quality. ChrisA From tjreedy at udel.edu Thu Oct 13 06:45:04 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Oct 2011 06:45:04 -0400 Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: On 10/13/2011 6:07 AM, Chris Angelico wrote: > On Thu, Oct 13, 2011 at 8:45 PM, candide wrote: >> Dart is the very new language created by Google to replace Javascript. >> So Python was not able to do the job? Or may be they don't know about Python >> at Google ;) ? >> > > Python, as I found out to my detriment, is practically impossible to > sandbox effectively. Any language that hopes to gain full traction in > a browser-based environment MUST be secure against scripts gaining too > much control over the browser chrome. I believe there was some idea of translating Dart into Javascript, which can be done with Python also (Pyjamas). > > Also, Dart is looking to support (optional) strict typing, which > Python doesn't do. That's a fairly major performance enhancement. Cython support optional typing. -- Terry Jan Reedy From clp2 at rebertia.com Thu Oct 13 07:12:14 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 13 Oct 2011 04:12:14 -0700 Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: On Thu, Oct 13, 2011 at 3:07 AM, Chris Angelico wrote: > On Thu, Oct 13, 2011 at 8:45 PM, candide wrote: >> Dart is the very new language created by Google to replace Javascript. >> So Python was not able to do the job? Or may be they don't know about Python >> at Google ;) ? >> > > Python, as I found out to my detriment, is practically impossible to > sandbox effectively. Any language that hopes to gain full traction in > a browser-based environment MUST be secure against scripts gaining too > much control over the browser chrome. > > Also, Dart is looking to support (optional) strict typing, which > Python doesn't do. That's a fairly major performance enhancement. Actually, they can't use it as much more than an optimization hint, per their own spec (see Sec 13.1 of the draft): "Static type annotations are used during static checking and when running programs in checked mode. They have no effect whatsoever in production mode. [...] A Dart implementation must provide a static checker that detects and reports exactly those situations this specification identifies as static warnings. However: ? Running the static checker on a program P is not required for compiling and running P. ? Running the static checker on a program P must not prevent successful compilation of P nor may it prevent the execution of P, regardless of whether any static warnings occur." Cheers, Chris -- http://rebertia.com From duncan.booth at invalid.invalid Thu Oct 13 07:20:21 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Oct 2011 11:20:21 GMT Subject: Opportunity missed by Python ? References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: candide wrote: > Dart is the very new language created by Google to replace Javascript. > So Python was not able to do the job? Or may be they don't know about > Python at Google ;) ? I take it you haven't actually looked at the Dart tools then? They're largely written in Python. -- Duncan Booth http://kupuguy.blogspot.com From anssi.kaariainen at thl.fi Thu Oct 13 07:25:52 2011 From: anssi.kaariainen at thl.fi (=?iso-8859-1?Q?K=E4=E4ri=E4inen_Anssi?=) Date: Thu, 13 Oct 2011 14:25:52 +0300 Subject: Dynamically altering __init__ Message-ID: Hello all, I am trying to alter the init method of a class by source to AST -> alter AST -> AST back to code -> f = types.FunctionType(code, {}, '__init__') -> mt = types.MethodType(f, None, Foo) -> Foo.__init__ = mt I have two problems, first I haven't yet figured out how to make the AST back to code, so that it will be accepted by types.FunctionType. Also, I can't make the Foo.__init__ be callable with arguments. Here is an example without using AST: class Foo(object): def __init__(self): pass src = """ def my_init_func(self, *args): print "here" """ class Foo(object): pass import parser import types st = parser.suite(src) dyn_func = parser.compilest(st) f = types.FunctionType(dyn_func, {}, '__init__') im = types.MethodType(f, None, Foo) Foo() Foo.__init__ = im Foo(1, 2, 3) The result is: TypeError: () takes no arguments (4 given). I have figured out that when I call f(), I am actually executing the src as is, not the defined function in the src. But I can't figure out how to get a reference to my_init_func. You might be wondering why I am doing this. I am trying to rewrite this: class Foo(object): attrs = ['spam', 'eggs'] def __init__(self, *args): for attname, val in izip(Foo.attrs, args): setattr(self, attname, val) into this: ... def __init__(self, *args): self.spam, self.eggs = args This is done for performance reasons. There is about 2x difference when creating 10000 objects. While it is a nice improvement, this is still mostly just for learning purposes. If you can help me it would be great. I am probably doing a lot of things wrong, but there isn't too much information available about these shorts of things. Link to example code would be perfect. - Anssi K??ri?inen From ydrocourt at gmail.com Thu Oct 13 08:00:39 2011 From: ydrocourt at gmail.com (yo) Date: Thu, 13 Oct 2011 05:00:39 -0700 (PDT) Subject: Python gp.ListFeatureClasses return only one file Message-ID: <6ef915f7-6419-41e1-bb0f-83cddad33300@f11g2000yqf.googlegroups.com> Hi All, I m using the gp.ListFeatureClasses to make a list of file in my directory (containing several hundreds of file) however when I print the variable in which the List is supposed to be stored, the print just return one file name.... does any one have an idea???? # Import system modules import sys, string, os, arcgisscripting, glob, arcpy # Create the Geoprocessor object gp = arcgisscripting.create() # define the workspace gp.Workspace = r"F:\front\shp_Files\calving_front" # list the file in the workspace try: shpList = gp.ListFeatureClasses("*.shp") shp = shpList.Next() print shp except: print arcpy.GetMessages() # allows to get error message when they happen From martin.hellwig at gmail.com Thu Oct 13 08:35:30 2011 From: martin.hellwig at gmail.com (Martin P. Hellwig) Date: Thu, 13 Oct 2011 13:35:30 +0100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) Message-ID: First of all let me say that I have no authority or knowledge of language design or multi-processing except from a user point of view, having a decade or so experience. I would like your opinion and appreciate any feedback and value any hints to documentation, procedures or related ramblings :-). I was wondering if there could be an advantage to add another control flow statement. For the purpose of this writing let's say "ooo" which stands for 'out of order'. For example; def do_something(): a = 4 b = 2 c = 1 ooo: a += 1 b += 2 c += 3 print(a, b, c) What I would expect to happen that all statements within the ooo block may be executed out of order. The block itself waits till all statements are returned before continuing. What do you think? From sigmundv at gmail.com Thu Oct 13 08:50:07 2011 From: sigmundv at gmail.com (SigmundV) Date: Thu, 13 Oct 2011 05:50:07 -0700 (PDT) Subject: 1/2 evaluates to 0 References: <4e95806c$0$29986$c3e8da3$5496439d@news.astraweb.com> <4E96B7A8.5050203@gmail.com> Message-ID: <02dcde33-1b25-4a46-8cb6-65bfccc007e8@n18g2000vbv.googlegroups.com> On Oct 13, 10:04?am, Laurent Claessens wrote: > Thanks all for your ansers. I'll import division from __future__ > Most of what I'm using in Python is with Sage[1]. Thus I'm not about to > step to 3.x :( You should get in touch with the Sage developers. In the Sage FAQ they say that "until SciPy is ported to run with Python 3.x and Cython supports Python 3.x, Sage will continue to use Python 2.x." However, both SciPy and Cython are currently compatible with Python 3.2. From the Cython FAQ: "As of 0.14, the Cython compiler runs in all Python versions from 2.3 to 3.2 inclusive." NumPy has supported Python 3 since version 1.5.0. From the release notes: "This is the first NumPy release which is compatible with Python 3." SciPy has supported Python 3 since version 0.9.0. From the release notes: "Scipy 0.9.0 is the first SciPy release to support Python 3. The only module that is not yet ported is ``scipy.weave``." So according to the Sage FAQ there is no reason why Sage shouldn't support Python 3. Sigmund From rosuav at gmail.com Thu Oct 13 09:09:13 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Oct 2011 00:09:13 +1100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: References: Message-ID: On Thu, Oct 13, 2011 at 11:35 PM, Martin P. Hellwig wrote: > What I would expect to happen that all statements within the ooo block may > be executed out > of order. The block itself waits till all statements are returned before > continuing. > In a statically-typed language such as C, this can be done by an optimizing compiler, without any hints from the programmer. But in Python, what you're looking for is either a guarantee from the programmer that none of the statements has a side effect that affects any other, or that you're prepared to wear it and have a horrendous debugging job if anyone monkey-patches your code or you do anything that makes a, b, or c into something more complex than an integer. ChrisA From andreas.perstinger at gmx.net Thu Oct 13 09:49:23 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Thu, 13 Oct 2011 15:49:23 +0200 Subject: Python gp.ListFeatureClasses return only one file In-Reply-To: <6ef915f7-6419-41e1-bb0f-83cddad33300@f11g2000yqf.googlegroups.com> References: <6ef915f7-6419-41e1-bb0f-83cddad33300@f11g2000yqf.googlegroups.com> Message-ID: <4E96EC63.1060306@gmx.net> On 2011-10-13 14:00, yo wrote: > Hi All, > I m using the gp.ListFeatureClasses to make a list of file in my > directory (containing several hundreds of file) > however when I print the variable in which the List is supposed to be > stored, the print just return one file name.... > does any one have an idea???? Depending on the version you are using, "ListFeatureClasses()" returns either a list or an enumeration object: http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=ListFeatureClasses_method You are just printing the first item. To print all, something like the following should work (assuming you are using version 9.2): shpList = gp.ListFeatureClasses("*.shp") shp = shpList.Next() while shp: print shp shp = shpList.Next() Bye, Andreas From alain at dpt-info.u-strasbg.fr Thu Oct 13 09:59:58 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Thu, 13 Oct 2011 15:59:58 +0200 Subject: Opportunity missed by Python ? References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: <87vcrtuh41.fsf@dpt-info.u-strasbg.fr> Chris Angelico writes: > On Thu, Oct 13, 2011 at 8:45 PM, candide wrote: >> Dart is the very new language created by Google to replace Javascript. >> So Python was not able to do the job? Or may be they don't know about Python >> at Google ;) ? > > Python, as I found out to my detriment, is practically impossible to > sandbox effectively. Any language that hopes to gain full traction in > a browser-based environment MUST be secure against scripts gaining too > much control over the browser chrome. A first step in that direction would be to have a specification for a python virtual machine. I guess engineers at Google know very well the limitations of Python in its current state. After all, python's inventor works there. Also, they've tried the optimization road with unladden-swallow. And failed. > Also, Dart is looking to support (optional) strict typing, which > Python doesn't do. That's a fairly major performance enhancement. I think you're absolutely right. They've already included a "better DOM". The use of typing will let them provide a very efficient standard library. I am willing to bet that Google's next step will be to provide a plugin/extension/whatever to directly execute Dart programs in the browsers. And then a JIT compiler inside the VM. And then everybody will want to move, for performance reason. All the Javascript compatibility is transitional stuff. -- Alain. From stefan_ml at behnel.de Thu Oct 13 10:13:27 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 13 Oct 2011 16:13:27 +0200 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: References: Message-ID: Martin P. Hellwig, 13.10.2011 14:35: > I was wondering if there could be an advantage to add another control flow > statement. Changes at that level must be very well justified, are often rejected for the reason of being not too complicated to write in some other form and are close to impossible to get accepted when requiring a new keyword. Also, the right place to discuss (and, more importantly, search for previous) ideas about language changes is the python-ideas mailing list. > For the purpose of this writing let's say "ooo" which stands for 'out of > order'. > > For example; > > def do_something(): > a = 4 > b = 2 > c = 1 > ooo: > a += 1 > b += 2 > c += 3 > print(a, b, c) > > What I would expect to happen that all statements within the ooo block may > be executed out > of order. The block itself waits till all statements are returned before > continuing. This looks like a rather special case. What if you need more than one statement to accomplish a single step? What if the number of parallel tasks is not fixed at coding time? I don't think there are many problems that you can solve with this feature. Also: the GIL will not allow you to take a major advantage from the parallel execution of a set of statements, as only one of the statements can use the interpreter at a time. And, on a related note: Cython has freshly gained support for parallel loops based on OpenMP, so you may be able to solve your problem with Cython instead of using plain Python. Stefan From jkn_gg at nicorp.f9.co.uk Thu Oct 13 10:33:27 2011 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Thu, 13 Oct 2011 07:33:27 -0700 (PDT) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: Message-ID: <07d3c24c-608c-4721-8fce-2b0c2a96493e@u2g2000yqc.googlegroups.com> FWIW, this looks rather like the 'PAR' construct of Occam to me. http://en.wikipedia.org/wiki/Occam_%28programming_language%29 J^n From tim at akwebsoft.com Thu Oct 13 11:22:49 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Thu, 13 Oct 2011 07:22:49 -0800 Subject: MySQLdb on Mac Lion In-Reply-To: References: <20111013005244.GK6671@johnsons-web.com> Message-ID: <20111013152249.GL6671@johnsons-web.com> * Ned Deily [111012 18:12]: > In article <20111013005244.GK6671 at johnsons-web.com>, > Tim Johnson wrote: > > I'm most experienced with MySQLdb on ubuntu, which is installed via > > apt-get or synaptic. > > > > I am setting up a mac mini with osX 10.7 (Lion). Macports makes > > py27-mysql 1.2.2 available, but are there any .dmg packages > > available? > > I strongly recommend you stick with MacPorts or Homebrew. There are too > many things that can go wrong on OS X 10.6 or 10.7 if you try to install > MySQL client libraries, MySQLdb, and Python from different places. IME, > the binary installers for OS X provided by the MySQL are inconsistently > built between versions and often need the library paths need to be > tweaked. The only major drawback of using MacPorts is that it will > download (and possibly build) its own version of Python but it's a small > price to pay: search the archives of Stackoverflow to see how > dismayingly often this topic comes up. Thanks for that Ned. -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From anikom15 at gmail.com Thu Oct 13 12:10:45 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 13 Oct 2011 09:10:45 -0700 Subject: Opportunity missed by Python ? In-Reply-To: <4e96b324$0$1007$426a34cc@news.free.fr> References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: <20111013161045.GA4100@Smoke> On Thu, Oct 13, 2011 at 11:45:06AM +0200, candide wrote: > Dart is the very new language created by Google to replace Javascript. > So Python was not able to do the job? Or may be they don't know > about Python at Google ;) ? Google's a big supporter for Python...I think Guido working being employed there has something to do with it, but I could be conspiring. Python is not an appropriate language for client-side web scripts, it's just too good for such a lowly job. ;) From anikom15 at gmail.com Thu Oct 13 12:12:44 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 13 Oct 2011 09:12:44 -0700 Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: <20111013161244.GB4100@Smoke> On Thu, Oct 13, 2011 at 09:07:09PM +1100, Chris Angelico wrote: > On Thu, Oct 13, 2011 at 8:45 PM, candide wrote: > > Dart is the very new language created by Google to replace Javascript. > > So Python was not able to do the job? Or may be they don't know about Python > > at Google ;) ? > > > > Python, as I found out to my detriment, is practically impossible to > sandbox effectively. Any language that hopes to gain full traction in > a browser-based environment MUST be secure against scripts gaining too > much control over the browser chrome. > > Also, Dart is looking to support (optional) strict typing, which > Python doesn't do. That's a fairly major performance enhancement. > > ChrisA You mean static typing? From moky.math at gmail.com Thu Oct 13 12:31:39 2011 From: moky.math at gmail.com (Laurent Claessens) Date: Thu, 13 Oct 2011 18:31:39 +0200 Subject: 1/2 evaluates to 0 In-Reply-To: <02dcde33-1b25-4a46-8cb6-65bfccc007e8@n18g2000vbv.googlegroups.com> References: <4e95806c$0$29986$c3e8da3$5496439d@news.astraweb.com> <4E96B7A8.5050203@gmail.com> <02dcde33-1b25-4a46-8cb6-65bfccc007e8@n18g2000vbv.googlegroups.com> Message-ID: <4E97126B.2090504@gmail.com> > You should get in touch with the Sage developers. In the Sage FAQ they > say that "until SciPy is ported to run with Python 3.x and Cython > supports Python 3.x, Sage will continue to use Python 2.x." ``scipy.weave``." > > So according to the Sage FAQ there is no reason why Sage shouldn't > support Python 3. Maybe the FAQ is not up to date. Nowadays the reason for not stepping to 3.x is "manpower" ;) (this question comes back two or three times a year on the Sages' list. Next time the question arises, I'll point out your remark) Scipy and Cython are just two of the biggest python parts in Sage, but there are many others ... 'till sage itself. Have a good afternoon Laurent From ian.g.kelly at gmail.com Thu Oct 13 13:14:23 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 13 Oct 2011 11:14:23 -0600 Subject: Dynamically altering __init__ In-Reply-To: References: Message-ID: 2011/10/13 K??ri?inen Anssi : > import parser > import types > st = parser.suite(src) > dyn_func = parser.compilest(st) > f = types.FunctionType(dyn_func, {}, '__init__') > im = types.MethodType(f, None, Foo) > Foo() > Foo.__init__ = im > Foo(1, 2, 3) > > The result is: TypeError: () takes no arguments (4 given). I have > figured out that when I call f(), I am actually executing the src as is, not > the defined function in the src. But I can't figure out how to get a > reference to my_init_func. You can either pull the function code object out of the module code object constants: ... st_code = parser.compilest(st) func_code = st_code.co_consts[0] f = types.FunctionType(func_code, {}, '__init__') ... But you should take care to ensure that the function code object actually is the first constant. Or you can just exec your suite and pull the function from its globals. src_globals = {} exec src in src_globals my_init_func = src_globals['my_init_func'] Cheers, Ian From anssi.kaariainen at thl.fi Thu Oct 13 14:00:39 2011 From: anssi.kaariainen at thl.fi (=?iso-8859-1?Q?K=E4=E4ri=E4inen_Anssi?=) Date: Thu, 13 Oct 2011 21:00:39 +0300 Subject: Dynamically altering __init__ In-Reply-To: References: , Message-ID: Ian Kelly wrote: """ You can either pull the function code object out of the module code object constants: ... st_code = parser.compilest(st) func_code = st_code.co_consts[0] f = types.FunctionType(func_code, {}, '__init__') ... But you should take care to ensure that the function code object actually is the first constant. Or you can just exec your suite and pull the function from its globals. src_globals = {} exec src in src_globals my_init_func = src_globals['my_init_func'] """ Thank you very much. I will post a link to a complete example once I have done the AST transformations etc. I hope this will be useful to readers of this list. I didn't find such an example, so maybe the next asker will find it... And when I inevitably do something the wrong way in my example, I am sure you will correct me :) However, this might take some time before ready, I am new to this stuff. If there is already an example somewhere, that would be really helpful to me. Just a quick note, I tested this on Python2.6, and got around 2.3 seconds per million objects. With an init doing the setattr loop, I got around 4.7 seconds. So the speed difference is there, but as expected, it isn't that big. Python3 had similar results. - Anssi K??ri?inen From martin.hellwig at gmail.com Thu Oct 13 16:20:13 2011 From: martin.hellwig at gmail.com (Martin P. Hellwig) Date: Thu, 13 Oct 2011 21:20:13 +0100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: References: Message-ID: On 13/10/2011 15:13, Stefan Behnel wrote: > Martin P. Hellwig, 13.10.2011 14:35: >> I was wondering if there could be an advantage to add another control >> flow >> statement. > > Changes at that level must be very well justified, are often rejected > for the reason of being not too complicated to write in some other form > and are close to impossible to get accepted when requiring a new keyword. > > Also, the right place to discuss (and, more importantly, search for > previous) ideas about language changes is the python-ideas mailing list. > > >> For the purpose of this writing let's say "ooo" which stands for 'out of >> order'. >> >> For example; >> >> def do_something(): >> a = 4 >> b = 2 >> c = 1 >> ooo: >> a += 1 >> b += 2 >> c += 3 >> print(a, b, c) >> >> What I would expect to happen that all statements within the ooo block >> may >> be executed out >> of order. The block itself waits till all statements are returned before >> continuing. > > This looks like a rather special case. What if you need more than one > statement to accomplish a single step? Aah yes haven't thought about that, was more thinking like wrap multiple steps in a function and put that as one line, but yeah that kind of stuff gets very unpythonic very quickly. > What if the number of parallel > tasks is not fixed at coding time? I don't think there are many problems > that you can solve with this feature. > > Also: the GIL will not allow you to take a major advantage from the > parallel execution of a set of statements, as only one of the statements > can use the interpreter at a time. Well I was more or less thinking in the line that the interpreter when parsing such a statement can, if there are multiple cpu's available, fire the appropriate amount of other interpreters and do all the passing and locking of data for you. > > And, on a related note: Cython has freshly gained support for parallel > loops based on OpenMP, so you may be able to solve your problem with > Cython instead of using plain Python. > Well funny enough I don't really have a problem with it, I am a happy consumer of multiprocessing, but I was just wondering if there would be a way to do it simpler and more pythonic. > Stefan > Thanks for your feedback it was very enlightening although for what the idea is concerned disappointing as it more or less makes it obvious that such a thing is a no-go. Cheers, Martin From bc at freeuk.com Thu Oct 13 17:38:43 2011 From: bc at freeuk.com (BartC) Date: Thu, 13 Oct 2011 22:38:43 +0100 Subject: Opportunity missed by Python ? In-Reply-To: <4e96b324$0$1007$426a34cc@news.free.fr> References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: "candide" wrote in message news:4e96b324$0$1007$426a34cc at news.free.fr... > Dart is the very new language created by Google to replace Javascript. > So Python was not able to do the job? Or may be they don't know about > Python at Google ;) ? The entire resources of Google available, and they re-invent C! https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/client/samples/spirodraw/Spirodraw.dart -- Bartc From rosuav at gmail.com Thu Oct 13 17:45:23 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Oct 2011 08:45:23 +1100 Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: On Fri, Oct 14, 2011 at 8:38 AM, BartC wrote: > The entire resources of Google available, and they re-invent C! Syntactically, C has a lot going for it. If you want to invent a new language and have developers grok it easily, borrowing syntax from C will help a lot. But in this case, I think the derivation is from JavaScript (which itself derives from C), making Dart a more-similar replacement. ChrisA From tdsimpson at gmail.com Thu Oct 13 17:59:22 2011 From: tdsimpson at gmail.com (MrPink) Date: Thu, 13 Oct 2011 14:59:22 -0700 (PDT) Subject: Reading a file into a data structure.... Message-ID: This is a continuing to a post I made in August: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b072cfadf998deae/ce6d4d09911e4107?lnk=gst&q=MrPink#ce6d4d09911e4107 I got some free time to work with Python again and have some followup questions. For example, I have a list in a text file like this: Example list of lottery drawings: date,wb,wb,wb,wb,wb,bb 4/1/2011,5,1,45,23,27,27 5/1/2011,15,23,8,48,22,32 6/1/2011,33,49,21,16,34,1 7/1/2011,9,3,13,22,45,41 8/1/2011,54,1,24,39,35,18 .... Ticket: startdate,enddate,wb,wb,wb,wb,wb,bb 4/1/2011,8/1/2011,5,23,32,21,3,27 I am trying to determine the optimal way to organize the data structure of the drawing list, search the drawing list, and mark the matches in the drawing list. f = open("C:\temp\drawinglist.txt", "r") lines = f.readlines() f.close() drawing = lines[1].split() The results in drawing is this: drawing[0] = '4/1/2011' drawing[1] = '5' drawing[2] = '1' drawing[3] = '45' drawing[4] = '23' drawing[5] = '27' drawing[6] = '27' I need to convert drawing[0] to a date datatype. This works, but I'm sure there is a better way. from datetime import date month, day, year = drawing[0].split('/') drawing[0] = date(int(year), int(month), int(day)) For searching, I need to determine if the date of the drawing is within the date range of the ticket. If yes, then mark which numbers in the drawing match the numbers in the ticket. ticket[0] = '4/1/2011' ticket[0] = '8/1/2011' ticket[0] = '5' ticket[0] = '23' ticket[0] = '32' ticket[0] = '21' ticket[0] = '3' ticket[0] = 27' drawing[0] = '4/1/2011' (match) drawing[1] = '5' (match) drawing[2] = '1' drawing[3] = '45' drawing[4] = '23' (match) drawing[5] = '27' drawing[6] = '27' (match) I'm debating on structuring the drawing list like this: drawing[0] = '4/1/2011' drawing[1][0] = '5' drawing[1][1] = '1' drawing[1][2] = '45' drawing[1][3] = '23' drawing[1][4] = '27' drawing[2] = '27' Sort drawing[1] from low to high drawing[1][0] = '1' drawing[1][1] = '5' drawing[1][2] = '23' drawing[1][3] = '27' drawing[1][4] = '45' I want to keep the drawing list in memory for reuse. Any guidance would be most helpful and appreciated. BTW, I want to learn, so be careful not to do too much of the work for me. I'm using WingIDE to do my work. Thanks, From dihedral88888 at googlemail.com Thu Oct 13 18:05:55 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Thu, 13 Oct 2011 15:05:55 -0700 (PDT) Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: <21380825.697.1318543555990.JavaMail.geo-discussion-forums@prdw1> As long as there are tools to translate scripts or source code between the two languages. More new evolved powerful programming languages arenot problems at all for experienced programmers. From dihedral88888 at googlemail.com Thu Oct 13 18:05:55 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Thu, 13 Oct 2011 15:05:55 -0700 (PDT) Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: <21380825.697.1318543555990.JavaMail.geo-discussion-forums@prdw1> As long as there are tools to translate scripts or source code between the two languages. More new evolved powerful programming languages arenot problems at all for experienced programmers. From nhodgson at iinet.net.au Thu Oct 13 18:21:31 2011 From: nhodgson at iinet.net.au (Neil Hodgson) Date: Fri, 14 Oct 2011 09:21:31 +1100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: <07d3c24c-608c-4721-8fce-2b0c2a96493e@u2g2000yqc.googlegroups.com> References: <07d3c24c-608c-4721-8fce-2b0c2a96493e@u2g2000yqc.googlegroups.com> Message-ID: <6-ednfDRIusm-QrTnZ2dnUVZ_uednZ2d@westnet.com.au> jkn: > FWIW, this looks rather like the 'PAR' construct of Occam to me. > > http://en.wikipedia.org/wiki/Occam_%28programming_language%29 Earlier than that, 'par' is from Algol 68: http://en.wikipedia.org/wiki/ALGOL_68#par:_Parallel_processing Neil From rhodri at wildebst.demon.co.uk Thu Oct 13 18:21:48 2011 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Thu, 13 Oct 2011 23:21:48 +0100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: <07d3c24c-608c-4721-8fce-2b0c2a96493e@u2g2000yqc.googlegroups.com> Message-ID: On Thu, 13 Oct 2011 15:33:27 +0100, jkn wrote: > FWIW, this looks rather like the 'PAR' construct of Occam to me. > > http://en.wikipedia.org/wiki/Occam_%28programming_language%29 I was going to say the same thing. Occam's answer to Stefan's question about what to do if you want more than one statement executed per step was to wrap sequences of statements in a SEQ construct. You end up indenting a long way very fast if you aren't careful. I'm afraid much as I love PAR, Python's dynamicism makes it rather more 'exciting' than it was in occam. -- Rhodri James *-* Wildebeest Herder to the Masses From ian.g.kelly at gmail.com Thu Oct 13 18:28:24 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 13 Oct 2011 16:28:24 -0600 Subject: Reading a file into a data structure.... In-Reply-To: References: Message-ID: On Thu, Oct 13, 2011 at 3:59 PM, MrPink wrote: > This is a continuing to a post I made in August: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/b072cfadf998deae/ce6d4d09911e4107?lnk=gst&q=MrPink#ce6d4d09911e4107 > > I got some free time to work with Python again and have some followup > questions. > > For example, I have a list in a text file like this: > Example list of lottery drawings: > date,wb,wb,wb,wb,wb,bb > 4/1/2011,5,1,45,23,27,27 > 5/1/2011,15,23,8,48,22,32 > 6/1/2011,33,49,21,16,34,1 > 7/1/2011,9,3,13,22,45,41 > 8/1/2011,54,1,24,39,35,18 > .... > > Ticket: > startdate,enddate,wb,wb,wb,wb,wb,bb > 4/1/2011,8/1/2011,5,23,32,21,3,27 > > I am trying to determine the optimal way to organize the data > structure of the drawing list, search the drawing list, and mark the > matches in the drawing list. > > f = open("C:\temp\drawinglist.txt", "r") > lines = f.readlines() > f.close() > drawing = lines[1].split() That looks like a CSV file. If the contents are tightly constrained then it may not matter, but if not then you should consider using the csv module to read the lines, which will handle inconvenient details like quoting and escape characters for you. > I need to convert drawing[0] to a date datatype. ?This works, but I'm > sure there is a better way. > from datetime import date > month, day, year = drawing[0].split('/') > drawing[0] = date(int(year), int(month), int(day)) If you already know the format: from datetime import datetime drawing[0] = datetime.strptime(drawing[0], '%m/%d/%Y').date() If you can't be sure of the format, then I recommend using the python-dateutil parser.parse() function, which will try to work it out on the fly. From joncle at googlemail.com Thu Oct 13 19:42:22 2011 From: joncle at googlemail.com (Jon Clements) Date: Thu, 13 Oct 2011 16:42:22 -0700 (PDT) Subject: Reading a file into a data structure.... References: Message-ID: On Oct 13, 10:59?pm, MrPink wrote: > This is a continuing to a post I made in August:http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > I got some free time to work with Python again and have some followup > questions. > > For example, I have a list in a text file like this: > Example list of lottery drawings: > date,wb,wb,wb,wb,wb,bb > 4/1/2011,5,1,45,23,27,27 > 5/1/2011,15,23,8,48,22,32 > 6/1/2011,33,49,21,16,34,1 > 7/1/2011,9,3,13,22,45,41 > 8/1/2011,54,1,24,39,35,18 > .... > > Ticket: > startdate,enddate,wb,wb,wb,wb,wb,bb > 4/1/2011,8/1/2011,5,23,32,21,3,27 > > I am trying to determine the optimal way to organize the data > structure of the drawing list, search the drawing list, and mark the > matches in the drawing list. > > f = open("C:\temp\drawinglist.txt", "r") > lines = f.readlines() > f.close() > drawing = lines[1].split() > > The results in drawing is this: > drawing[0] = '4/1/2011' > drawing[1] = '5' > drawing[2] = '1' > drawing[3] = '45' > drawing[4] = '23' > drawing[5] = '27' > drawing[6] = '27' > > I need to convert drawing[0] to a date datatype. ?This works, but I'm > sure there is a better way. > from datetime import date > month, day, year = drawing[0].split('/') > drawing[0] = date(int(year), int(month), int(day)) > > For searching, I need to determine if the date of the drawing is > within the date range of the ticket. ?If yes, then mark which numbers > in the drawing match the numbers in the ticket. > > ticket[0] = '4/1/2011' > ticket[0] = '8/1/2011' > ticket[0] = '5' > ticket[0] = '23' > ticket[0] = '32' > ticket[0] = '21' > ticket[0] = '3' > ticket[0] = 27' > > drawing[0] = '4/1/2011' (match) > drawing[1] = '5' (match) > drawing[2] = '1' > drawing[3] = '45' > drawing[4] = '23' (match) > drawing[5] = '27' > drawing[6] = '27' (match) > > I'm debating on structuring the drawing list like this: > drawing[0] = '4/1/2011' > drawing[1][0] = '5' > drawing[1][1] = '1' > drawing[1][2] = '45' > drawing[1][3] = '23' > drawing[1][4] = '27' > drawing[2] = '27' > > Sort drawing[1] from low to high > drawing[1][0] = '1' > drawing[1][1] = '5' > drawing[1][2] = '23' > drawing[1][3] = '27' > drawing[1][4] = '45' > > I want to keep the drawing list in memory for reuse. > > Any guidance would be most helpful and appreciated. > BTW, I want to learn, so be careful not to do too much of the work for > me. > I'm using WingIDE to do my work. > > Thanks, - Use the csv module to read the file - Use strptime to process the date field - Use a set for draw numbers (you'd have to do pure equality on the bb) - Look at persisting in a sqlite3 DB (maybe with a custom convertor) hth, Jon. From dihedral88888 at googlemail.com Thu Oct 13 20:11:27 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Thu, 13 Oct 2011 17:11:27 -0700 (PDT) Subject: [Python-ideas] Implement comparison operators for range objects In-Reply-To: References: <20111012163144.GB6393@pantoffel-wg.de> <4E95CF7D.6000000@pearwood.info> <4E95D394.9000205@mrabarnett.plus.com> Message-ID: <19444957.1328.1318551088183.JavaMail.geo-discussion-forums@prho12> How about iterable objects supported in python? Is a countable object iterable definitely? Also the tail recursion technique is useful for the same function with few arguments that calls itself. The lisp compiler would emit machine codes with fast jumps and passing arguments in registers or stacks very efficiently. From steve+comp.lang.python at pearwood.info Thu Oct 13 22:16:37 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 14 Oct 2011 13:16:37 +1100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: Message-ID: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> Martin P. Hellwig wrote: > I was wondering if there could be an advantage to add another control > flow statement. > For the purpose of this writing let's say "ooo" which stands for 'out of > order'. [...] > What I would expect to happen that all statements within the ooo block > may be executed out > of order. The block itself waits till all statements are returned before > continuing. Why do you think this needs to be a language statement? You can have that functionality *right now*, without waiting for a syntax update, by use of the multiprocessing module, or a third party module. http://docs.python.org/library/multiprocessing.html http://wiki.python.org/moin/ParallelProcessing There's no need for forcing language changes on everyone, whether they need it or not, for features that can easily be implemented as library code. -- Steven From roy at panix.com Thu Oct 13 22:19:05 2011 From: roy at panix.com (Roy Smith) Date: Thu, 13 Oct 2011 22:19:05 -0400 Subject: Looking for browser emulator Message-ID: I've got to write some tests in python which simulate getting a page of HTML from an http server, finding a link, clicking on it, and then examining the HTML on the next page to make sure it has certain features. I can use urllib to do the basic fetching, and lxml gives me the tools to find the link I want and extract its href attribute. What's missing is dealing with turning the href into an absolute URL that I can give to urlopen(). Browsers implement all sorts of stateful logic such as "if the URL has no hostname, use the same hostname as the current page". I'm talking about something where I can execute this sequence of calls: urlopen("http://foo.com:9999/bar") urlopen("/baz") and have the second one know that it needs to get "http://foo.com:9999/baz". Does anything like that exist? I'm really trying to stay away from Selenium and go strictly with something I can run under unittest. From joncle at googlemail.com Thu Oct 13 22:42:31 2011 From: joncle at googlemail.com (Jon Clements) Date: Thu, 13 Oct 2011 19:42:31 -0700 (PDT) Subject: Looking for browser emulator References: Message-ID: <2323f3d7-42ff-4de5-9006-4741e865f09c@a9g2000yqo.googlegroups.com> On Oct 14, 3:19?am, Roy Smith wrote: > I've got to write some tests in python which simulate getting a page of > HTML from an http server, finding a link, clicking on it, and then > examining the HTML on the next page to make sure it has certain features. > > I can use urllib to do the basic fetching, and lxml gives me the tools > to find the link I want and extract its href attribute. ?What's missing > is dealing with turning the href into an absolute URL that I can give to > urlopen(). ?Browsers implement all sorts of stateful logic such as "if > the URL has no hostname, use the same hostname as the current page". ? > I'm talking about something where I can execute this sequence of calls: > > urlopen("http://foo.com:9999/bar") > urlopen("/baz") > > and have the second one know that it needs to get > "http://foo.com:9999/baz". ?Does anything like that exist? > > I'm really trying to stay away from Selenium and go strictly with > something I can run under unittest. lxml.html.make_links_absolute() ? From joncle at googlemail.com Thu Oct 13 22:43:16 2011 From: joncle at googlemail.com (Jon Clements) Date: Thu, 13 Oct 2011 19:43:16 -0700 (PDT) Subject: Looking for browser emulator References: Message-ID: On Oct 14, 3:19?am, Roy Smith wrote: > I've got to write some tests in python which simulate getting a page of > HTML from an http server, finding a link, clicking on it, and then > examining the HTML on the next page to make sure it has certain features. > > I can use urllib to do the basic fetching, and lxml gives me the tools > to find the link I want and extract its href attribute. ?What's missing > is dealing with turning the href into an absolute URL that I can give to > urlopen(). ?Browsers implement all sorts of stateful logic such as "if > the URL has no hostname, use the same hostname as the current page". ? > I'm talking about something where I can execute this sequence of calls: > > urlopen("http://foo.com:9999/bar") > urlopen("/baz") > > and have the second one know that it needs to get > "http://foo.com:9999/baz". ?Does anything like that exist? > > I'm really trying to stay away from Selenium and go strictly with > something I can run under unittest. lxml.html.make_links_absolute() ? From roy at panix.com Thu Oct 13 22:53:06 2011 From: roy at panix.com (Roy Smith) Date: Thu, 13 Oct 2011 22:53:06 -0400 Subject: Looking for browser emulator References: <2323f3d7-42ff-4de5-9006-4741e865f09c@a9g2000yqo.googlegroups.com> Message-ID: In article <2323f3d7-42ff-4de5-9006-4741e865f09c at a9g2000yqo.googlegroups.com>, Jon Clements wrote: > On Oct 14, 3:19?am, Roy Smith wrote: > > I've got to write some tests in python which simulate getting a page of > > HTML from an http server, finding a link, clicking on it, and then > > examining the HTML on the next page to make sure it has certain features. > > > > I can use urllib to do the basic fetching, and lxml gives me the tools > > to find the link I want and extract its href attribute. ?What's missing > > is dealing with turning the href into an absolute URL that I can give to > > urlopen(). ?Browsers implement all sorts of stateful logic such as "if > > the URL has no hostname, use the same hostname as the current page". ? > > I'm talking about something where I can execute this sequence of calls: > > > > urlopen("http://foo.com:9999/bar") > > urlopen("/baz") > > > > and have the second one know that it needs to get > > "http://foo.com:9999/baz". ?Does anything like that exist? > > > > I'm really trying to stay away from Selenium and go strictly with > > something I can run under unittest. > > lxml.html.make_links_absolute() ? Interesting. That might be exactly what I'm looking for. Thanks! From miki.tebeka at gmail.com Thu Oct 13 23:31:10 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 13 Oct 2011 20:31:10 -0700 (PDT) Subject: Looking for browser emulator In-Reply-To: References: Message-ID: <10390190.52.1318563071117.JavaMail.geo-discussion-forums@prfp13> IIRC mechanize can do that. From gherron at islandtraining.com Thu Oct 13 23:55:31 2011 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 13 Oct 2011 20:55:31 -0700 Subject: Looking for browser emulator In-Reply-To: References: Message-ID: <4E97B2B3.7060505@islandtraining.com> On 10/13/2011 07:19 PM, Roy Smith wrote: > I've got to write some tests in python which simulate getting a page of > HTML from an http server, finding a link, clicking on it, and then > examining the HTML on the next page to make sure it has certain features. > > I can use urllib to do the basic fetching, and lxml gives me the tools > to find the link I want and extract its href attribute. What's missing > is dealing with turning the href into an absolute URL that I can give to > urlopen(). Browsers implement all sorts of stateful logic such as "if > the URL has no hostname, use the same hostname as the current page". > I'm talking about something where I can execute this sequence of calls: > > urlopen("http://foo.com:9999/bar") > urlopen("/baz") > > and have the second one know that it needs to get > "http://foo.com:9999/baz". Does anything like that exist? > > I'm really trying to stay away from Selenium and go strictly with > something I can run under unittest. Try mechanize http://wwwsearch.sourceforge.net/mechanize/ billed as Stateful programmatic web browsing in Python. I handles clicking on links, cookies, logging in/out, and filling in of forms in the same way as a "real" browser, but it's all under programmatic control from Python. In Ubuntu, it's the python-mechanize package. From roy at panix.com Fri Oct 14 00:13:17 2011 From: roy at panix.com (Roy Smith) Date: Fri, 14 Oct 2011 00:13:17 -0400 Subject: Looking for browser emulator References: Message-ID: In article , Gary Herron wrote: > Try mechanize > http://wwwsearch.sourceforge.net/mechanize/ > billed as > Stateful programmatic web browsing in Python. Wow, this is cool, thanks! It even does cookies! From pavlovevidence at gmail.com Fri Oct 14 02:05:26 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 13 Oct 2011 23:05:26 -0700 (PDT) Subject: argparse zero-length switch Message-ID: <17016857.666.1318572326692.JavaMail.geo-discussion-forums@prmi2> Is it possible to specify a zero-length switch? Here's what I mean. I have a use case where some users would have to enter a section name on the command line almost every time, whereas other users (the ones using only one section) will never have to enter the section name. I don't want to burden users with only one "section" to always enter the section name as a required argument, but I also want to make it as convenient as possible to enter the section name for those who need to. My thought, on the thinking that practicality beats purity, was to create a zero-length switch using a different prefix character (say, @) to indicate the section name. So instead of typing this: sp subcommand -s abc foo bar they could type this: sp subcommand @abc foo bar Admittedly a small benefit. I tried the following but argparse doesn't seem to do what I'd hoped: p = argparse.ArgumentParser(prefix_chars='-@') p.add_argument('@',type=str,dest='section') ar = p.parse_args(['@abc']) This throws an exception claiming unrecognized arguments. Is there a way (that's not a hack) to do this? Since the current behavior of the above code seems to do nothing useful, it could be added to argparse with very low risk of backwards incompatibility. Carl Banks From pavlovevidence at gmail.com Fri Oct 14 02:56:20 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 13 Oct 2011 23:56:20 -0700 (PDT) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> Message-ID: <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> On Thursday, October 13, 2011 7:16:37 PM UTC-7, Steven D'Aprano wrote: > > What I would expect to happen that all statements within the ooo block > > may be executed out > > of order. The block itself waits till all statements are returned before > > continuing. > > Why do you think this needs to be a language statement? > > You can have that functionality *right now*, without waiting for a syntax > update, by use of the multiprocessing module, or a third party module. > > http://docs.python.org/library/multiprocessing.html > http://wiki.python.org/moin/ParallelProcessing > > There's no need for forcing language changes on everyone, whether they need > it or not, for features that can easily be implemented as library code. This goes a little beyond a simple threading mechanism, though. It's more like guidance to the compiler that you don't care what order these are executed in; the compiler is then free to take advantage of this advice however it like. That could be to spawn threads, but it could also compile instructions to optimize pipelining and cacheing. The compiler could also ignore it. But you can see that, fully realized, syntax like that can do much more than can be done with library code. Obviously that extra capability is a very long way off for being useful in CPython. Carl Banks From pavlovevidence at gmail.com Fri Oct 14 03:06:15 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 14 Oct 2011 00:06:15 -0700 (PDT) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: References: Message-ID: <6347919.1520.1318575975788.JavaMail.geo-discussion-forums@prng5> On Thursday, October 13, 2011 5:35:30 AM UTC-7, Martin P. Hellwig wrote: > What I would expect to happen that all statements within the ooo block > may be executed out > of order. The block itself waits till all statements are returned before > continuing. > > What do you think? The statement is kind of limiting as a unit of uncaring. What if you have two statements that you do want to be executed in order, but still don't care what order they are executed in relative to other sets of two statements? Better would be to have a set of blocks that the compiler is free to execute asynchronously relative to each other (I'll call it async). async: a += 1 f *= a async: b += 1 e *= b async: c += 1 d *= c There is utterly no chance of this syntax entering Python. Carl Banks From __peter__ at web.de Fri Oct 14 03:41:26 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 Oct 2011 09:41:26 +0200 Subject: argparse zero-length switch References: <17016857.666.1318572326692.JavaMail.geo-discussion-forums@prmi2> Message-ID: Carl Banks wrote: > Is it possible to specify a zero-length switch? Here's what I mean. > > I have a use case where some users would have to enter a section name on > the command line almost every time, whereas other users (the ones using > only one section) will never have to enter the section name. I don't want > to burden users with only one "section" to always enter the section name > as a required argument, but I also want to make it as convenient as > possible to enter the section name for those who need to. > > My thought, on the thinking that practicality beats purity, was to create > a zero-length switch using a different prefix character (say, @) to > indicate the section name. So instead of typing this: > > sp subcommand -s abc foo bar > > they could type this: > > sp subcommand @abc foo bar > > Admittedly a small benefit. I tried the following but argparse doesn't > seem to do what I'd hoped: > > p = argparse.ArgumentParser(prefix_chars='-@') > p.add_argument('@',type=str,dest='section') > ar = p.parse_args(['@abc']) > > This throws an exception claiming unrecognized arguments. > > Is there a way (that's not a hack) to do this? Since the current behavior > of the above code seems to do nothing useful, it could be added to > argparse with very low risk of backwards incompatibility. If the number of positional arguments is otherwise fixed you could make section a positional argument with nargs="?" >>> import argparse >>> parser = argparse.ArgumentParser() >>> _ = parser.add_argument("section", nargs="?") >>> _ = parser.add_argument("foo") >>> _ = parser.add_argument("bar") >>> parser.parse_args(["alpha", "beta"]) Namespace(bar='beta', foo='alpha', section=None) >>> parser.parse_args(["alpha", "beta", "gamma"]) Namespace(bar='gamma', foo='beta', section='alpha') From librarama at gmail.com Fri Oct 14 03:45:14 2011 From: librarama at gmail.com (Libra) Date: Fri, 14 Oct 2011 00:45:14 -0700 (PDT) Subject: Graph editor Message-ID: <7ce425e6-0831-4c71-a2e1-d6f6d0b4ee4b@o19g2000vbk.googlegroups.com> Hi, I would like to build a simple graph editor, allowing me to add nodes and edges via the mouse, along with the possibility to edit it (delete/ move nodes and edges, double click on object to pop-up a form where I can insert object related info, and so forth) and bind edges to nodes (that is, when I move a node, the attached edges move accordingly). I should also put an image (a bitmap of png) in the background of the graph. I've seen many GUI libraries (from TkInter to wxPython) but I was wondering if there is a specific graphic library (with good documentation and maybe examples) simplifying the rapid development of such an application. Thanks Libra From peter.marczis at nsn.com Fri Oct 14 04:19:31 2011 From: peter.marczis at nsn.com (Peter G. Marczis) Date: Fri, 14 Oct 2011 11:19:31 +0300 Subject: Fwd: os.statvfs bug or my incompetence ? In-Reply-To: <4E97DB66.50302@nsn.com> References: <4E97DB66.50302@nsn.com> Message-ID: <4E97F093.4000203@nsn.com> An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Fri Oct 14 05:33:49 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 14 Oct 2011 20:33:49 +1100 Subject: argparse zero-length switch References: <17016857.666.1318572326692.JavaMail.geo-discussion-forums@prmi2> Message-ID: <87pqhzvrwi.fsf@benfinney.id.au> Carl Banks writes: > I have a use case where some users would have to enter a section name > on the command line almost every time, whereas other users (the ones > using only one section) will never have to enter the section name. Sounds like a typical case where you want an option that takes an argument, with a default for when the option is not specified. As you probably know, ?argparse? already handles this fine. > I don't want to burden users with only one "section" to always enter > the section name as a required argument, but I also want to make it as > convenient as possible to enter the section name for those who need > to. Yes. The latter need only specify the section explicitly, with ?-s foo? or whatever. > My thought, on the thinking that practicality beats purity, was to > create a zero-length switch using a different prefix character (say, > @) to indicate the section name. So instead of typing this: > > sp subcommand -s abc foo bar What's wrong with that? That's a normal way to do it, consistent with other command-line interfaces. Why deviate from that? > they could type this: > > sp subcommand @abc foo bar > > Admittedly a small benefit. I don't see the benefit of that which would be worth teaching that unconventional command-line syntax. -- \ ?Two paradoxes are better than one; they may even suggest a | `\ solution.? ?Edward Teller | _o__) | Ben Finney From atalucas at gmail.com Fri Oct 14 06:30:51 2011 From: atalucas at gmail.com (atalucas at gmail.com) Date: Fri, 14 Oct 2011 03:30:51 -0700 (PDT) Subject: Something works in Python but not in cgi. Message-ID: <6e4551eb-20c4-4dcb-8e69-c5fefb47f3e1@q9g2000yqm.googlegroups.com> Hi, I need to make work a programm on the Web. I make tests like Hello World and also with GET and it works good. The problem comes in the line gas = importPhase("gri30.cti") The computer don?t find the file "gri30.cti"(this file was not in workspace), then I put it in the same folder and the program crash. Knows someone where is the problem??? #!D:\Python25\python.exe print "Content-Type: text/html\n" import cgitb; cgitb.enable() import cgi from workplace import * gas = importPhase("gri30.cti") print "Cantera" print '' print '' print "" From miki.tebeka at gmail.com Fri Oct 14 09:37:02 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 14 Oct 2011 06:37:02 -0700 (PDT) Subject: Something works in Python but not in cgi. In-Reply-To: <6e4551eb-20c4-4dcb-8e69-c5fefb47f3e1@q9g2000yqm.googlegroups.com> References: <6e4551eb-20c4-4dcb-8e69-c5fefb47f3e1@q9g2000yqm.googlegroups.com> Message-ID: <19751516.906.1318599422237.JavaMail.geo-discussion-forums@prmi2> The working directory of the webserver is probably not the one of the script. You should specify full path to the file. One way to do it is: from os.path import dirname, join filename = join(dirname(__file__), 'gri30.cti') HTH -- Miki Tebeka http://pythonwise.blogspot.com From tjreedy at udel.edu Fri Oct 14 10:11:50 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Oct 2011 10:11:50 -0400 Subject: Fwd: os.statvfs bug or my incompetence ? In-Reply-To: <4E97F093.4000203@nsn.com> References: <4E97DB66.50302@nsn.com> <4E97F093.4000203@nsn.com> Message-ID: On 10/14/2011 4:19 AM, Peter G. Marczis wrote: > import os > os.statvfs('/') ... > os.statvfs('/') > *OSError: [Errno 0] Error: '/'* > > # python --version > Python 2.6.2 > > # arch > mips64 > > os.stat works fine. 2.6.2 is a few years old. If there is a bug, it might have been fixed by 2.6.6 released a year ago, or 2.7.2 just a few months ago. -- Terry Jan Reedy From k.sahithi2862 at gmail.com Fri Oct 14 10:14:23 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Fri, 14 Oct 2011 07:14:23 -0700 (PDT) Subject: FOR ONLY HOT GUYS SEE THIS Message-ID: FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html From buzzard at urubu.freeserve.co.uk Fri Oct 14 10:37:13 2011 From: buzzard at urubu.freeserve.co.uk (duncan smith) Date: Fri, 14 Oct 2011 15:37:13 +0100 Subject: Graph editor In-Reply-To: <7ce425e6-0831-4c71-a2e1-d6f6d0b4ee4b@o19g2000vbk.googlegroups.com> References: <7ce425e6-0831-4c71-a2e1-d6f6d0b4ee4b@o19g2000vbk.googlegroups.com> Message-ID: On 14/10/11 08:45, Libra wrote: > Hi, > I would like to build a simple graph editor, allowing me to add nodes > and edges via the mouse, along with the possibility to edit it (delete/ > move nodes and edges, double click on object to pop-up a form where I > can insert object related info, and so forth) and bind edges to nodes > (that is, when I move a node, the attached edges move accordingly). I > should also put an image (a bitmap of png) in the background of the > graph. > > I've seen many GUI libraries (from TkInter to wxPython) but I was > wondering if there is a specific graphic library (with good > documentation and maybe examples) simplifying the rapid development of > such an application. > I've used wxPython and ogl (http://www.wxpython.org/docs/api/wx.lib.ogl-module.html) for my graph editors; in conjunction with graphviz for the layout. There are ogl examples in the wxPython demo. Duncan From ramit.prasad at jpmorgan.com Fri Oct 14 10:45:41 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 14 Oct 2011 10:45:41 -0400 Subject: Opportunity missed by Python ? In-Reply-To: <21380825.697.1318543555990.JavaMail.geo-discussion-forums@prdw1> References: <4e96b324$0$1007$426a34cc@news.free.fr> <21380825.697.1318543555990.JavaMail.geo-discussion-forums@prdw1> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F216FAD8E@EMARC112VS01.exchad.jpmchase.net> >As long as there are tools to translate scripts or source code between the two languages. More new evolved powerful programming >languages arenot problems at all for experienced programmers. More often than not, these conversion utilities are a source of terrible code. They are good for getting a quick job done, but not for code that has long term use. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From dihedral88888 at googlemail.com Fri Oct 14 11:02:07 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Fri, 14 Oct 2011 08:02:07 -0700 (PDT) Subject: 1/2 evaluates to 0 In-Reply-To: References: Message-ID: <19699772.1760.1318604527365.JavaMail.geo-discussion-forums@prng5> How about fractions to be computed in hundreds or even thousands of digits in precision? OK, just write programs to compute PI and the Euler number in hundreds or even thousands of digits to test various kind of programming languages. This is a sophomore school home work for gifted kids to play with programmings. From dihedral88888 at googlemail.com Fri Oct 14 11:20:31 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Fri, 14 Oct 2011 08:20:31 -0700 (PDT) Subject: 1/2 evaluates to 0 In-Reply-To: <19699772.1760.1318604527365.JavaMail.geo-discussion-forums@prng5> References: <19699772.1760.1318604527365.JavaMail.geo-discussion-forums@prng5> Message-ID: <13198363.1773.1318605631288.JavaMail.geo-discussion-forums@prng5> Maybe one should try to compute C(n,k) in additions only by the Pascal triangle first! This is simpler for senior high school kids to play with python! From dickinsm at gmail.com Fri Oct 14 11:33:01 2011 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 14 Oct 2011 08:33:01 -0700 (PDT) Subject: Implement comparison operators for range objects References: <20111012163144.GB6393@pantoffel-wg.de> <4E95CF7D.6000000@pearwood.info> <4E95D394.9000205@mrabarnett.plus.com> Message-ID: On Oct 12, 8:24?pm, Ian Kelly wrote: > On Wed, Oct 12, 2011 at 11:51 AM, MRAB wrote: > >> Aside: > > >> I'm astonished to see that range objects have a count method! What's the > >> purpose of that? Any value's count will either be 0 or 1, and a more > >> appropriate test would be `value in range`: > > >> ?>>> 17 in range(2, 30, 3) # like r.count(17) => 1 > >> True > >> ?>>> 18 in range(2, 30, 3) # like r.count(18) => 0 > >> False > > > In Python 2, range returns a list, and lists have a .count method. > > Could that be the reason? > > Python 2 xrange objects do not have a .count method. ?Python 3 range > objects do have a .count method. ?The addition is curious, to say the > least. See http://bugs.python.org/issue9213 -- Mark From steve+comp.lang.python at pearwood.info Fri Oct 14 11:48:35 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 15 Oct 2011 02:48:35 +1100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> Message-ID: <4e9859d4$0$30003$c3e8da3$5496439d@news.astraweb.com> Carl Banks wrote: > On Thursday, October 13, 2011 7:16:37 PM UTC-7, Steven D'Aprano wrote: >> > What I would expect to happen that all statements within the ooo block >> > may be executed out >> > of order. The block itself waits till all statements are returned >> > before continuing. >> >> Why do you think this needs to be a language statement? >> >> You can have that functionality *right now*, without waiting for a syntax >> update, by use of the multiprocessing module, or a third party module. >> >> http://docs.python.org/library/multiprocessing.html >> http://wiki.python.org/moin/ParallelProcessing >> >> There's no need for forcing language changes on everyone, whether they >> need it or not, for features that can easily be implemented as library >> code. > > This goes a little beyond a simple threading mechanism, though. The multiprocessing module is not a simple threading mechanism, and neither are the libraries listed in the ParallelProcessing page. -- Steven From subscriber at antifraud.irs.gov Fri Oct 14 12:01:39 2011 From: subscriber at antifraud.irs.gov (Internal Revenue Service United States Department of the Treasury) Date: Fri, 14 Oct 2011 10:01:39 -0600 Subject: U.S. Department of the Treasury IRS.gov Message-ID: <6011251481.S7LOLOL8323380@lzgoory.icywmnqgwwsqgnq.net> Taxpayer ID: commensurate-00000700955060USTax Type: INCOME TAXIssue: Unreported/Underreported Income (Fraud Application)Please review your tax statement on Internal Revenue Service (IRS) website (click on the link below):download tax statement: report-00000700952560US.DOChttp://www.irs.gov. -------------- next part -------------- An HTML attachment was scrubbed... URL: From twestley at gmail.com Fri Oct 14 14:04:40 2011 From: twestley at gmail.com (Terry) Date: Fri, 14 Oct 2011 11:04:40 -0700 (PDT) Subject: .py and .pyc files in read-only directory Message-ID: <33c406fa-c563-440f-83f5-99557b2e0643@h5g2000vbf.googlegroups.com> I'm having a problem with my iPhone/iPad app, Python Math, a Python 2.7 interpreter. All the Python modules are delivered in what Apple calls the app bundle. They are in a read-only directory. This means that Python cannot write .pyc files to that directory. (I get a deny write error when doing this.) I tried using compileall to precompile all the modules, but now I get an unlink error because Python apparently wants to rebuild the .pyc files. I've considered two solutions: 1) Delete all the .py files, delivering only the .pyc, or 2) Redirecting the .pyc files into a separate, writable directory. Will solution 1) work? I don't know how to do 2) and the only reference I can find to that are a withdrawn PEP, 304. Suggestions? From no.email at nospam.invalid Fri Oct 14 14:17:44 2011 From: no.email at nospam.invalid (Paul Rubin) Date: Fri, 14 Oct 2011 11:17:44 -0700 Subject: Fwd: os.statvfs bug or my incompetence ? References: <4E97DB66.50302@nsn.com> <4E97F093.4000203@nsn.com> Message-ID: <7x39evwi7r.fsf@ruckus.brouhaha.com> Terry Reedy writes: >> os.statvfs('/') >> *OSError: [Errno 0] Error: '/'* >> >> # python --version >> Python 2.6.2 > > 2.6.2 is a few years old. If there is a bug, it might have been fixed > by 2.6.6 released a year ago, or 2.7.2 just a few months ago. os.statvfs('/') works fine or me on Python 2.6.2 (r262:71600, Jun 4 2010, 18:28:58) [GCC 4.4.3 20100127 (Red Hat 4.4.3-4)] on linux2 From anikom15 at gmail.com Fri Oct 14 14:24:49 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Fri, 14 Oct 2011 11:24:49 -0700 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> Message-ID: <20111014182448.GB9255@Smoke> On Thu, Oct 13, 2011 at 11:56:20PM -0700, Carl Banks wrote: > On Thursday, October 13, 2011 7:16:37 PM UTC-7, Steven D'Aprano wrote: > > > What I would expect to happen that all statements within the ooo block > > > may be executed out > > > of order. The block itself waits till all statements are returned before > > > continuing. > > > > Why do you think this needs to be a language statement? > > > > You can have that functionality *right now*, without waiting for a syntax > > update, by use of the multiprocessing module, or a third party module. > > > > http://docs.python.org/library/multiprocessing.html > > http://wiki.python.org/moin/ParallelProcessing > > > > There's no need for forcing language changes on everyone, whether they need > > it or not, for features that can easily be implemented as library code. > > This goes a little beyond a simple threading mechanism, though. It's more like guidance to the compiler that you don't care what order these are executed in; the compiler is then free to take advantage of this advice however it like. That could be to spawn threads, but it could also compile instructions to optimize pipelining and cacheing. The compiler could also ignore it. But you can see that, fully realized, syntax like that can do much more than can be done with library code. > > Obviously that extra capability is a very long way off for being useful in CPython. > > While we're at it, let's throw in the register keyword. From chris at simplistix.co.uk Fri Oct 14 14:33:35 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 14 Oct 2011 19:33:35 +0100 Subject: Seven Python Developers Needed $125K In-Reply-To: References: Message-ID: <4E98807F.7090909@simplistix.co.uk> I'd suggest you post to the job board rather than spamming the list: http://www.python.org/community/jobs/howto/ cheers, Chris On 11/10/2011 19:16, WR wrote: > Top Global Consulting Firm in NYC needs 7 Python Developers > > Up to $125K depending on experience > > Solid knowledge of fundamental Python concepts. At least three years Python experience required. > > For more info email Joseph at Washresearch.com > > Joseph Ryan > Washington Research Associates Inc > (202) 408-7025 > -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From chris at simplistix.co.uk Fri Oct 14 14:34:27 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 14 Oct 2011 19:34:27 +0100 Subject: Want to make the transition to games? In-Reply-To: References: Message-ID: <4E9880B3.7000706@simplistix.co.uk> Please don't spam this list with jobs, especially if they have nothing to do with Python. If they do, use the job board instead: http://www.python.org/community/jobs/howto/ cheers, Chris On 12/10/2011 05:49, Marta wrote: > Hi, > > I'm working as an onsite recruiting consultant and we are looking for > top engineers who want to work with other very accomplished > engineers. If you have a CS degree, strong in C++ and want to make > the transition to games, please email me your resume. > > Cheers, > > Marta Daglow -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From clp2 at rebertia.com Fri Oct 14 15:31:46 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 14 Oct 2011 12:31:46 -0700 Subject: .py and .pyc files in read-only directory In-Reply-To: <33c406fa-c563-440f-83f5-99557b2e0643@h5g2000vbf.googlegroups.com> References: <33c406fa-c563-440f-83f5-99557b2e0643@h5g2000vbf.googlegroups.com> Message-ID: On Fri, Oct 14, 2011 at 11:04 AM, Terry wrote: > I'm having a problem with my iPhone/iPad app, Python Math, a Python > 2.7 interpreter. All the Python modules are delivered in what Apple > calls the app bundle. They are in a read-only directory. This means > that Python cannot write .pyc files to that directory. (I get a deny > write error when doing this.) I tried using compileall to precompile > all the modules, but now I get an unlink error because Python > apparently wants to rebuild the .pyc files. You can stop Python from trying to write .pyc files by using the environment variable PYTHONDONTWRITEBYTECODE, the interpreter's -B command line option, or by setting sys.dont_write_bytecode to True. Cheers, Chris From ian.g.kelly at gmail.com Fri Oct 14 15:48:38 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Oct 2011 13:48:38 -0600 Subject: .py and .pyc files in read-only directory In-Reply-To: References: <33c406fa-c563-440f-83f5-99557b2e0643@h5g2000vbf.googlegroups.com> Message-ID: On Fri, Oct 14, 2011 at 1:31 PM, Chris Rebert wrote: > On Fri, Oct 14, 2011 at 11:04 AM, Terry wrote: >> I'm having a problem with my iPhone/iPad app, Python Math, a Python >> 2.7 interpreter. All the Python modules are delivered in what Apple >> calls the app bundle. They are in a read-only directory. This means >> that Python cannot write .pyc files to that directory. (I get a deny >> write error when doing this.) I tried using compileall to precompile >> all the modules, but now I get an unlink error because Python >> apparently wants to rebuild the .pyc files. > > You can stop Python from trying to write .pyc files by using the > environment variable PYTHONDONTWRITEBYTECODE, the interpreter's -B > command line option, or by setting sys.dont_write_bytecode to True. This won't make Python use the .pyc files provided, though. It will just recompile the .py files and then not try to write out the bytecode. If you really want to force it to use the .pyc's, then don't include the .py files. Note that if you do this, you'll need to make sure that the version of Python used to compile the .pyc files is the same minor release as the version used to run them (more specifically, the two versions must return the same string from imp.get_magic()). HTH, Ian From twestley at gmail.com Fri Oct 14 16:39:24 2011 From: twestley at gmail.com (Terry) Date: Fri, 14 Oct 2011 13:39:24 -0700 (PDT) Subject: .py and .pyc files in read-only directory In-Reply-To: References: <33c406fa-c563-440f-83f5-99557b2e0643@h5g2000vbf.googlegroups.com> Message-ID: <25190838.4422.1318624764846.JavaMail.geo-discussion-forums@vbmh5> Thanks, that's very useful. And it explains why Python Math wants to rewrite the .pyc files: imp.get_magic() returns (null) whereas on my Mac where I compiled them, get_magic() returns '\x03\xf3\r\n'. Now I just have to figure out why I'm getting nothing useful from get_magic(). I assume this would have to be fixed to try solution 1), i.e., leaving out the .py files and delivering only the .pyc. Terry From zaffino.p at gmail.com Fri Oct 14 16:55:23 2011 From: zaffino.p at gmail.com (Paolo Zaffino) Date: Fri, 14 Oct 2011 22:55:23 +0200 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: Nobody can help me? 2011/10/12 Paolo Zaffino > I wrote a function thaht works on a 3D matrix. > As first thing I have an array and I want reshape it into a 3D matrix (for > further manipulations). > For this reason I wrote in a row: > > matrix=matrix.reshape(a, b, c).T > > It work fine on GNU/Linux and Mac OS but not on Windows. > In Windows I get this error: > > matrix=matrix.reshape(a, b, c).T > > ValueError: total size of new array must be unchanged > > Thank you. > > > > > 2011/10/11 David Robinow > >> 2011/10/11 Paolo Zaffino : >> > Nobody can help me? >> Nope, not unless you post some code. Your problem description is too >> vague. >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pengyu.ut at gmail.com Fri Oct 14 17:29:50 2011 From: pengyu.ut at gmail.com (Peng Yu) Date: Fri, 14 Oct 2011 16:29:50 -0500 Subject: How to generate error when argument are not supplied and there is no explicit defults (in optparse)? Message-ID: Hi, The following code doesn't give me error, even I don't specify the value of filename from the command line arguments. filename gets 'None'. I checked the manual, but I don't see a way to let OptionParser fail if an argument's value (which has no default explicitly specified) is not specified. I may miss some thing in the manual. Could any expert let me know if there is a way to do so? Thanks! #!/usr/bin/env python from optparse import OptionParser usage = 'usage: %prog [options] arg1 arg2' parser = OptionParser(usage=usage) parser.set_defaults(verbose=True) parser.add_option('-f', '--filename') #(options, args) = parser.parse_args(['-f', 'file.txt']) (options, args) = parser.parse_args() print options.filename -- Regards, Peng From ramit.prasad at jpmorgan.com Fri Oct 14 17:30:57 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 14 Oct 2011 17:30:57 -0400 Subject: Re-raise different exception with original stack trace Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F217865A4@EMARC112VS01.exchad.jpmchase.net> Hi all, Hopefully you guys can help me with my problem. Basically I have a UI program that can "save" information. The UI passes the save to the controller and the controller saves a file and does some post processing. If saving the file fails, I want to handle the error differently than if the error was in post processing. In both cases the possible exceptions are varied and unknown so I cannot pick and choose certain exception. The problem with the sample program below is that the stack trace is replaced by the re-raise. What would be the best way(s) to get the original stack trace in save_from_UI if the exception occurs in post_process? Using Python 2.6 and Windows(XP and 7) / Linux. Def save_from_model(): save() # do not catch exception (could be any exception) try: post_process() except Exception as e: #do something raise CustomException() # "wrap" exception so bar knows to handle it differently def save_from_UI(): try: foo() except CustomException() as e: # How do I get the original stacktrace instead of the reraise? except Exception as e: # do something else with this exception Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From python at mrabarnett.plus.com Fri Oct 14 17:54:27 2011 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Oct 2011 22:54:27 +0100 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: <4E98AF93.4030908@mrabarnett.plus.com> On 14/10/2011 21:55, Paolo Zaffino wrote: > Nobody can help me? > Others have already tried to help you. What is the shape and size of 'matrix' before, and what are the values of 'a', 'b' and 'c'? Print them in the ones which work (GNU/Linux and Mac OS) and the one which doesn't (Windows). Do they print the same values? Do not assume that they are the same. Print them to make sure. > > 2011/10/12 Paolo Zaffino > > > I wrote a function thaht works on a 3D matrix. > As first thing I have an array and I want reshape it into a 3D > matrix (for further manipulations). > For this reason I wrote in a row: > > matrix=matrix.reshape(a, b, c).T > > It work fine on GNU/Linux and Mac OS but not on Windows. > In Windows I get this error: > > matrix=matrix.reshape(a, b, c).T > > ValueError: total size of new array must be unchanged > > Thank you. > > 2011/10/11 David Robinow > > > 2011/10/11 Paolo Zaffino >: > > Nobody can help me? > Nope, not unless you post some code. Your problem description > is too vague. > From ramit.prasad at jpmorgan.com Fri Oct 14 17:55:07 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 14 Oct 2011 17:55:07 -0400 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F217865FA@EMARC112VS01.exchad.jpmchase.net> From: python-list-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Paolo Zaffino Sent: Friday, October 14, 2011 3:55 PM To: python-list at python.org Subject: Re: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows Nobody can help me? 2011/10/12 Paolo Zaffino I wrote a function thaht works on a 3D matrix. As first thing I have an array and I want reshape it into a 3D matrix (for further manipulations). For this reason I wrote in a row: matrix=matrix.reshape(a, b, c).T It work fine on GNU/Linux and Mac OS but not on Windows. In Windows I get this error: matrix=matrix.reshape(a, b, c).T ValueError: total size of new array must be unchanged Thank you. 2011/10/11 David Robinow 2011/10/11 Paolo Zaffino : > Nobody can help me? ?Nope, not unless you post some code. Your problem description is too vague. ============================================================================== You can do this by converting to an array. >>> mat = numpy.matrix( [[1,2,],[3,4],[5,6],[7,8]] ) >>> numpy.array( mat ) array([[1, 2], [3, 4], [5, 6], [7, 8]]) >>> a = _ >>> numpy.reshape( a, (2,2,2)) array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From tdsimpson at gmail.com Fri Oct 14 18:10:05 2011 From: tdsimpson at gmail.com (MrPink) Date: Fri, 14 Oct 2011 15:10:05 -0700 (PDT) Subject: Can I search a list for a range of values? Message-ID: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> I have a list like so: a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14] I would like to get a subset from the list with value between 10 and 20 (inclusive). b = [10,13,15,14,20] Is there a way to do this with a list or other data type? Thanks, From rosuav at gmail.com Fri Oct 14 18:20:33 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Oct 2011 09:20:33 +1100 Subject: Can I search a list for a range of values? In-Reply-To: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> Message-ID: On Sat, Oct 15, 2011 at 9:10 AM, MrPink wrote: > I have a list like so: > > a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14] > > I would like to get a subset from the list with value between 10 and > 20 (inclusive). > > b = [10,13,15,14,20] > > Is there a way to do this with a list or other data type? Try a list comprehension: >>> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14] >>> [i for i in a if i>=10 if i<=20] [10, 20, 15, 13, 14] This preserves order from the original list. I don't know what order your result list is in, but you can always rejig things after. ChrisA From ian.g.kelly at gmail.com Fri Oct 14 18:24:00 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Oct 2011 16:24:00 -0600 Subject: Can I search a list for a range of values? In-Reply-To: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> Message-ID: On Fri, Oct 14, 2011 at 4:10 PM, MrPink wrote: > I have a list like so: > > a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14] > > I would like to get a subset from the list with value between 10 and > 20 (inclusive). > > b = [10,13,15,14,20] > > Is there a way to do this with a list or other data type? Use a list comprehension: b = [x for x in a if 10 <= x <= 20] Cheers, Ian From python.list at tim.thechases.com Fri Oct 14 18:30:25 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 14 Oct 2011 17:30:25 -0500 Subject: Can I search a list for a range of values? In-Reply-To: References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> Message-ID: <4E98B801.7090900@tim.thechases.com> On 10/14/11 17:20, Chris Angelico wrote: > Try a list comprehension: > >>>> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14] >>>> [i for i in a if i>=10 if i<=20] > [10, 20, 15, 13, 14] The double-if is new to me. I thought it was an error when I first saw it, but it seems to be legit syntax (or at least one that 2.7 tolerates, intentionally or otherwise...). I think I'd make it clearer with either [i for i in a if i>=10 and i<=20] or even more clearly: [i for i in a if 10 <= i <= 20] -tkc From rosuav at gmail.com Fri Oct 14 18:48:05 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Oct 2011 09:48:05 +1100 Subject: Can I search a list for a range of values? In-Reply-To: <4E98B801.7090900@tim.thechases.com> References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> Message-ID: On Sat, Oct 15, 2011 at 9:30 AM, Tim Chase wrote: > The double-if is new to me. ?I thought it was an error when I first saw it, > but it seems to be legit syntax (or at least one that 2.7 tolerates, > intentionally or otherwise...). ?I think I'd make it clearer with either > > Yeah, it's legal because you can nest fors and ifs in a list comp. Stylistic difference, I used "if" instead of "and" because there's no way that it could be a bitwise and. (It's a cross-language safety net that I sometimes use.) Although the 10<=i<=20 option is definitely superior to both. ChrisA From python at mrabarnett.plus.com Fri Oct 14 18:49:53 2011 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Oct 2011 23:49:53 +0100 Subject: Re-raise different exception with original stack trace In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F217865A4@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F217865A4@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4E98BC91.3010207@mrabarnett.plus.com> On 14/10/2011 22:30, Prasad, Ramit wrote: > Hi all, > Hopefully you guys can help me with my problem. > > Basically I have a UI program that can "save" information. The UI passes the save to the controller and the controller saves a file and does some post processing. If saving the file fails, I want to handle the error differently than if the error was in post processing. In both cases the possible exceptions are varied and unknown so I cannot pick and choose certain exception. The problem with the sample program below is that the stack trace is replaced by the re-raise. What would be the best way(s) to get the original stack trace in save_from_UI if the exception occurs in post_process? Using Python 2.6 and Windows(XP and 7) / Linux. > > Def save_from_model(): > save() # do not catch exception (could be any exception) > try: > post_process() > except Exception as e: > #do something > raise CustomException() # "wrap" exception so bar knows to handle it differently > > def save_from_UI(): > try: > foo() > except CustomException() as e: > # How do I get the original stacktrace instead of the reraise? > except Exception as e: > # do something else with this exception > You could save a reference to the exception in the custom exception: class CustomException(Exception): def __init__(self, e): Exception.__init__(self) self.exc = e def save_from_model(): save() # do not catch exception (could be any exception) try: post_process() except Exception as e: #do something raise CustomException(e) def save_from_UI(): try: foo() except CustomException as e: # Original exception is e.exc except Exception as e: # do something else with this exception From ian.g.kelly at gmail.com Fri Oct 14 18:58:42 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Oct 2011 16:58:42 -0600 Subject: Can I search a list for a range of values? In-Reply-To: References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> Message-ID: On Fri, Oct 14, 2011 at 4:48 PM, Chris Angelico wrote: > On Sat, Oct 15, 2011 at 9:30 AM, Tim Chase > wrote: >> The double-if is new to me. ?I thought it was an error when I first saw it, >> but it seems to be legit syntax (or at least one that 2.7 tolerates, >> intentionally or otherwise...). ?I think I'd make it clearer with either >> >> > > Yeah, it's legal because you can nest fors and ifs in a list comp. > Stylistic difference, I used "if" instead of "and" because there's no > way that it could be a bitwise and. (It's a cross-language safety net > that I sometimes use.) Although the 10<=i<=20 option is definitely > superior to both. At least in Python, there is no way that "and" could be a bitwise and either, since it cannot be overloaded. From ian.g.kelly at gmail.com Fri Oct 14 19:01:04 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Oct 2011 17:01:04 -0600 Subject: Can I search a list for a range of values? In-Reply-To: <4E98B801.7090900@tim.thechases.com> References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> Message-ID: On Fri, Oct 14, 2011 at 4:30 PM, Tim Chase wrote: > On 10/14/11 17:20, Chris Angelico wrote: >> >> Try a list comprehension: >> >>>>> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14] >>>>> [i for i in a if i>=10 if i<=20] >> >> [10, 20, 15, 13, 14] > > The double-if is new to me. ?I thought it was an error when I first saw it, > but it seems to be legit syntax (or at least one that 2.7 tolerates, > intentionally or otherwise...). ?I think I'd make it clearer with either > > ?[i for i in a if i>=10 and i<=20] > > or even more clearly: > > ?[i for i in a if 10 <= i <= 20] As long as we're nitpicking, I'll point out that "i" is an inappropriate variable name here, since it is normally used to denote indices, not data. That's why I used "x" in my response instead. ;-) Cheers, Ian From python.list at tim.thechases.com Fri Oct 14 19:24:13 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 14 Oct 2011 18:24:13 -0500 Subject: Can I search a list for a range of values? In-Reply-To: References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> Message-ID: <4E98C49D.50402@tim.thechases.com> On 10/14/11 18:01, Ian Kelly wrote: > On Fri, Oct 14, 2011 at 4:30 PM, Tim Chase >> or even more clearly: >> >> [i for i in a if 10<= i<= 20] > > As long as we're nitpicking, I'll point out that "i" is an > inappropriate variable name here, since it is normally used to > denote indices, not data. That's why I used "x" in my > response instead. ;-) Depending on your historical programming-language baggage, "i" is usually either an index or integer data, and since the source was a list of integers, "i" didn't seem inappropriate. Same for other common data-types: [f for f in (1.1, 2.2, 3.3) if 2.0 <= f < 3.0] [s for s in ("cat", "hat", "mat") if "bat" < s < "fat"] [c for c in "hello, world!" if 'a' <= c <= 'z'] -tkc From tdsimpson at gmail.com Fri Oct 14 19:36:27 2011 From: tdsimpson at gmail.com (Troy S) Date: Fri, 14 Oct 2011 19:36:27 -0400 Subject: Can I search a list for a range of values? In-Reply-To: References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> Message-ID: Can something like this be done with dictionarys? For example, these are the keys in the dictionary from the call: dict.keys() ['20110601', '20110604', '20110608', '20110611', '20110615', '20110618', '20110622', '20110625', '20110629', '20110702', '20110706','20110709', '20110713', '20110716', '20110720', '20110723', '20110727', '20110730', '20110803', '20110806', '20110810','20110813', '20110817', '20110820', '20110824', '20110827', '20110831', '20110903', '20110907', '20110910', '20110914','20110917', '20110921', '20110924', '20110928', '20111001', '20111005', '20111008'] Is there a way to find all items between '20110809' and '20110911'? So the subset would be: ['20110810','20110813', '20110817', '20110820', '20110824', '20110827', '20110831', '20110903', '20110907', '20110910'] The keys are strings that represent a date in the format: 'YYYYMMDD'. Thanks, On Fri, Oct 14, 2011 at 6:24 PM, Ian Kelly wrote: > On Fri, Oct 14, 2011 at 4:10 PM, MrPink wrote: >> I have a list like so: >> >> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14] >> >> I would like to get a subset from the list with value between 10 and >> 20 (inclusive). >> >> b = [10,13,15,14,20] >> >> Is there a way to do this with a list or other data type? > > Use a list comprehension: > > b = [x for x in a if 10 <= x <= 20] > > Cheers, > Ian > -- Troy S From ian.g.kelly at gmail.com Fri Oct 14 19:37:51 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Oct 2011 17:37:51 -0600 Subject: Can I search a list for a range of values? In-Reply-To: <4E98C49D.50402@tim.thechases.com> References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> <4E98C49D.50402@tim.thechases.com> Message-ID: On Fri, Oct 14, 2011 at 5:24 PM, Tim Chase wrote: > Depending on your historical programming-language baggage, "i" is usually > either an index or integer data, and since the source was a list of > integers, "i" didn't seem inappropriate. ?Same for other common data-types: > > ?[f for f in (1.1, 2.2, 3.3) if 2.0 <= f < 3.0] > ?[s for s in ("cat", "hat", "mat") if "bat" < s < "fat"] > ?[c for c in "hello, world!" if 'a' <= c <= 'z'] "f" makes me think "function", not "float". As a general rule, though, I prefer to name variables for what they represent, not for their type. From tdsimpson at gmail.com Fri Oct 14 19:44:07 2011 From: tdsimpson at gmail.com (MrPink) Date: Fri, 14 Oct 2011 16:44:07 -0700 (PDT) Subject: How to test if object is an integer? Message-ID: Is there a function in Python that can be used to test if the value in a string is an integer? I had to make one up for myself and it looks like this: def isInt(s): try: i = int(s) return True except ValueError: return False From vim at tim.thechases.com Fri Oct 14 19:45:12 2011 From: vim at tim.thechases.com (Tim Chase) Date: Fri, 14 Oct 2011 18:45:12 -0500 Subject: Can I search a list for a range of values? In-Reply-To: References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> Message-ID: <4E98C988.3070707@tim.thechases.com> On 10/14/11 18:36, Troy S wrote: > Can something like this be done with dictionarys? > > For example, these are the keys in the dictionary from the call: dict.keys() > > ['20110601', '20110604', '20110608', '20110611', '20110615', > '20110618', '20110622', '20110625', '20110629', '20110702', > '20110706','20110709', '20110713', '20110716', '20110720', '20110723', > '20110727', '20110730', '20110803', '20110806', '20110810','20110813', > '20110817', '20110820', '20110824', '20110827', '20110831', > '20110903', '20110907', '20110910', '20110914','20110917', '20110921', > '20110924', '20110928', '20111001', '20111005', '20111008'] > > Is there a way to find all items between '20110809' and '20110911'? > So the subset would be: > ['20110810','20110813', '20110817', '20110820', '20110824', > '20110827', '20110831', '20110903', '20110907', '20110910'] > > The keys are strings that represent a date in the format: 'YYYYMMDD'. Since strings are comparable, you certainly can: keys = [k for k in d.keys() if '20110809' < k < '20110911'] -tkc From ian.g.kelly at gmail.com Fri Oct 14 19:46:28 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Oct 2011 17:46:28 -0600 Subject: Can I search a list for a range of values? In-Reply-To: References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> Message-ID: On Fri, Oct 14, 2011 at 5:36 PM, Troy S wrote: > Can something like this be done with dictionarys? > > For example, these are the keys in the dictionary from the call: dict.keys() > > ['20110601', '20110604', '20110608', '20110611', '20110615', > '20110618', '20110622', '20110625', '20110629', '20110702', > '20110706','20110709', '20110713', '20110716', '20110720', '20110723', > '20110727', '20110730', '20110803', '20110806', '20110810','20110813', > '20110817', '20110820', '20110824', '20110827', '20110831', > '20110903', '20110907', '20110910', '20110914','20110917', '20110921', > '20110924', '20110928', '20111001', '20111005', '20111008'] > > Is there a way to find all items between '20110809' and '20110911'? > So the subset would be: > ['20110810','20110813', '20110817', '20110820', '20110824', > '20110827', '20110831', '20110903', '20110907', '20110910'] Sure, dictionaries also support iteration. date_range = [d for d in source_dict if '20110809' <= d <= '20110911'] Or if you want the result to also be a dictionary: (Python 3) date_range = {d:v for d, v in source_dict.items() if '20110809' <= d <= '20110911'} (Python 2) date_range = dict((d,v) for d, v in source_dict.iteritems() if '20110809' <= d <= '20110911') You might also want to consider storing your dates as datetime.date objects rather than strings, but since you already have them formatted for lexicographical sorting it's not important for this. Cheers, Ian From rosuav at gmail.com Fri Oct 14 19:47:12 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Oct 2011 10:47:12 +1100 Subject: Can I search a list for a range of values? In-Reply-To: References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> Message-ID: On Sat, Oct 15, 2011 at 9:58 AM, Ian Kelly wrote: > At least in Python, there is no way that "and" could be a bitwise and > either, since it cannot be overloaded. Like I said, cross-language safety-net. Sure it's not an issue here, but when I write code in multiple languages, it's less embarrassing to use an odd construct like that than to post code that outright doesn't work. :) ChrisA From wuwei23 at gmail.com Fri Oct 14 20:49:04 2011 From: wuwei23 at gmail.com (alex23) Date: Fri, 14 Oct 2011 17:49:04 -0700 (PDT) Subject: Opportunity missed by Python ? References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: <1dd5aa8c-7a41-4108-8940-ef666cd2ddb9@t38g2000prg.googlegroups.com> On Oct 13, 8:07?pm, Chris Angelico wrote: > Python, as I found out to my detriment, is practically impossible to > sandbox effectively. The latest version of PyPy introduces a prototype sandbox: http://pypy.org/features.html#sandboxing It'll be interesting to see how effective this is. From rosuav at gmail.com Fri Oct 14 20:55:46 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Oct 2011 11:55:46 +1100 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: On Sat, Oct 15, 2011 at 10:44 AM, MrPink wrote: > Is there a function in Python that can be used to test if the value in > a string is an integer? ?I had to make one up for myself and it looks > like this: > > def isInt(s): > ? ?try: > ? ? ? ?i = int(s) > ? ? ? ?return True > ? ?except ValueError: > ? ? ? ?return False There's some ambiguity in the definition of "is an integer". For instance, is "0x100" an integer? Is "0800"? If your definition of "is an integer" is "can be passed to int() without triggering an exception" (which is probably the most useful), then your above code is about perfect. The only change I'd make is to not have an isInt function at all, but simply to try/except at the point where you need to make the conversion. ChrisA From wauue at qq.com Fri Oct 14 21:00:11 2011 From: wauue at qq.com (=?gbk?B?z6fD9Q==?=) Date: Sat, 15 Oct 2011 09:00:11 +0800 Subject: How to test if object is an integer? Message-ID: retrun True if type(i) is int else False ------------------ Original ------------------ From: "Chris Angelico"; Date: Sat, Oct 15, 2011 08:55 AM To: "python-list"; Subject: Re: How to test if object is an integer? On Sat, Oct 15, 2011 at 10:44 AM, MrPink wrote: > Is there a function in Python that can be used to test if the value in > a string is an integer? I had to make one up for myself and it looks > like this: > > def isInt(s): > try: > i = int(s) > return True > except ValueError: > return False There's some ambiguity in the definition of "is an integer". For instance, is "0x100" an integer? Is "0800"? If your definition of "is an integer" is "can be passed to int() without triggering an exception" (which is probably the most useful), then your above code is about perfect. The only change I'd make is to not have an isInt function at all, but simply to try/except at the point where you need to make the conversion. ChrisA -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Fri Oct 14 21:05:53 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Oct 2011 12:05:53 +1100 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: 2011/10/15 ?? : > retrun True if type(i) is int else False That tests if the object is already an int; the OP asked if a string contains an integer. ChrisA From clp2 at rebertia.com Fri Oct 14 21:10:56 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 14 Oct 2011 18:10:56 -0700 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: On Fri, Oct 14, 2011 at 6:05 PM, Chris Angelico wrote: > 2011/10/15 ?? : >> retrun True if type(i) is int else False > > That tests if the object is already an int; the OP asked if a string > contains an integer. Additionally: * the if-then-else there is unnecessary since `type(i) is int` already returns a bool * such a type test is normally and better written `isinstance(i, int)` Cheers, Chris R. From wuwei23 at gmail.com Fri Oct 14 21:23:15 2011 From: wuwei23 at gmail.com (alex23) Date: Fri, 14 Oct 2011 18:23:15 -0700 (PDT) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> Message-ID: <7c0baafc-70df-46ec-8482-8bbf267c8231@t38g2000prg.googlegroups.com> On Oct 14, 4:56?pm, Carl Banks wrote: > But you can see that, fully realized, syntax like that can do much more > than can be done with library code. Well sure, but imaginary syntax can do _anything_. That doesn't mean it's possible within CPython. From tjreedy at udel.edu Fri Oct 14 21:27:26 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Oct 2011 21:27:26 -0400 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: On 10/14/2011 9:05 PM, Chris Angelico wrote: > 2011/10/15 ??: >> retrun True if type(i) is int else False > > That tests if the object is already an int; the OP asked if a string > contains an integer. The misleading subject line did not. It should have been "How to test if a string contains an integer?" -- Terry Jan Reedy From ben+python at benfinney.id.au Fri Oct 14 21:51:41 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 15 Oct 2011 12:51:41 +1100 Subject: How to test if object is an integer? References: Message-ID: <87hb3buimq.fsf@benfinney.id.au> Terry Reedy writes: > On 10/14/2011 9:05 PM, Chris Angelico wrote: > > That tests if the object is already an int; the OP asked if a string > > contains an integer. > > The misleading subject line did not. It should have been "How to test > if a string contains an integer?" Which would still be misleading :-) Even better is ?How to test whether a string is a valid representation of an integer?? I say that's better because it gets to the relevant point of asking *which* representations you want to test for ? what qualifies as valid for your particular use case, and what does not. There's no single right answer; the programmer must choose exactly what they want to test for. -- \ ?When I was a little kid we had a sand box. It was a quicksand | `\ box. I was an only child... eventually.? ?Steven Wright | _o__) | Ben Finney From ben+python at benfinney.id.au Fri Oct 14 21:52:44 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 15 Oct 2011 12:52:44 +1100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> <7c0baafc-70df-46ec-8482-8bbf267c8231@t38g2000prg.googlegroups.com> Message-ID: <87d3dzuikz.fsf@benfinney.id.au> alex23 writes: > On Oct 14, 4:56?pm, Carl Banks wrote: > > But you can see that, fully realized, syntax like that can do much more > > than can be done with library code. > > Well sure, but imaginary syntax can do _anything_. That doesn't mean > it's possible within CPython. +1 QotW -- \ ?The opposite of a correct statement is a false statement. But | `\ the opposite of a profound truth may well be another profound | _o__) truth.? ?Niels Bohr | Ben Finney From clp2 at rebertia.com Fri Oct 14 22:15:59 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 14 Oct 2011 19:15:59 -0700 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: <7c0baafc-70df-46ec-8482-8bbf267c8231@t38g2000prg.googlegroups.com> References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> <7c0baafc-70df-46ec-8482-8bbf267c8231@t38g2000prg.googlegroups.com> Message-ID: On Fri, Oct 14, 2011 at 6:23 PM, alex23 wrote: > On Oct 14, 4:56?pm, Carl Banks wrote: >> But you can see that, fully realized, syntax like that can do much more >> than can be done with library code. > > Well sure, but imaginary syntax can do _anything_. That doesn't mean > it's possible within CPython. But it's The Future now! Where are my jetpack and `dwim` statement, dammit?! :-) Cheers, Chris From wuwei23 at gmail.com Fri Oct 14 22:32:35 2011 From: wuwei23 at gmail.com (alex23) Date: Fri, 14 Oct 2011 19:32:35 -0700 (PDT) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: Message-ID: <4c79d47c-c6ce-49b5-931e-c1bf5e94af75@c14g2000pro.googlegroups.com> On Oct 13, 10:35?pm, "Martin P. Hellwig" wrote: > def do_something(): > ? ? ?a = 4 > ? ? ?b = 2 > ? ? ?c = 1 > ? ? ?ooo: > ? ? ? ? ?a += 1 > ? ? ? ? ?b += 2 > ? ? ? ? ?c += 3 > ? ? ?print(a, b, c) > > What I would expect to happen that all statements within the ooo block > may be executed out > of order. The block itself waits till all statements are returned before > continuing. > > What do you think? You can do this right now with Python 3.2+ and concurrent.futures: from concurrent.futures import ThreadPoolExecutor from functools import partial import time class DoSomething: a = 4 b = 2 c = 1 def add(self, prop, val): cur = getattr(self, prop) time.sleep(cur) print('Adding %d to %s' % (val, prop)) setattr(self, prop, cur + val) def __init__(self): with ThreadPoolExecutor(max_workers=3) as pool: pool.submit(self.add, 'a', 1) pool.submit(self.add, 'b', 2) pool.submit(self.add, 'c', 3) print(self.a, self.b, self.c) DoSomething() Here we call 'ooo' the ThreadPoolExecutor context manager :) From wuwei23 at gmail.com Fri Oct 14 22:35:17 2011 From: wuwei23 at gmail.com (alex23) Date: Fri, 14 Oct 2011 19:35:17 -0700 (PDT) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: <4c79d47c-c6ce-49b5-931e-c1bf5e94af75@c14g2000pro.googlegroups.com> Message-ID: <9f5ca51b-2dd6-46cb-b3e5-02560c11f1c5@31g2000prz.googlegroups.com> On Oct 15, 12:32?pm, alex23 wrote: > from functools import partial You can ignore this, sorry, leftover from earlier code :) From wuwei23 at gmail.com Fri Oct 14 22:44:44 2011 From: wuwei23 at gmail.com (alex23) Date: Fri, 14 Oct 2011 19:44:44 -0700 (PDT) Subject: Python library for generating SQL queries [selects, alters, inserts and commits] References: <4E945CD6.3040502@tim.thechases.com> Message-ID: <46e6f128-cc7e-4232-a286-ef3ef8fc36b6@t38g2000prg.googlegroups.com> Tim Chase wrote: > I'm not sure it can entirely be chalked up to not looking hard > enough. It's explicitly cited in the feature list: Raw SQL statement mapping SQLA's object relational query facilities can accommodate raw SQL statements as well as plain result sets, and object instances can be generated from these results in the same manner as any other ORM operation. Any hyper-optimized query that you or your DBA can cook up, you can run in SQLAlchemy http://www.sqlalchemy.org/features.html That it's expression language translates down to pure SQL is also shown within the first few sections of the tutorial too: http://www.sqlalchemy.org/docs/core/tutorial.html I'm not sure how they could make it more obvious. From tdsimpson at gmail.com Fri Oct 14 22:59:38 2011 From: tdsimpson at gmail.com (MrPink) Date: Fri, 14 Oct 2011 19:59:38 -0700 (PDT) Subject: Reading a file into a data structure.... References: Message-ID: <763d6391-fc4d-4b47-b0c3-d3ad16e0fc38@gy7g2000vbb.googlegroups.com> This is what I have been able to accomplish: def isInt(s): try: i = int(s) return True except ValueError: return False f = open("powerball.txt", "r") lines = f.readlines() f.close() dDrawings = {} for line in lines: if isInt(line[0]): t = line.split() d = t[0] month,day,year = t[0].split("/") i = int(year + month + day) wb = t[1:6] wb.sort() pb = t[6] r = {'d':d,'wb':wb,'pb':pb} dDrawings[i] = r The dictionary dDrawings contains records like this: dDrawings[19971101] {'pb': '20', 'd': '11/01/1997', 'wb': ['22', '25', '28', '33', '37']} I am now able to search for ticket in a date range. keys = dDrawings.keys() b = [key for key in keys if 20110909 <= key <= 20111212] How would I search for matching wb (White Balls) in the drawings? Is there a better way to organize the data so that it will be flexible enough for different types of searches? Search by date range, search by pb, search by wb matches, etc. I hope this all makes sense. Thanks, On Oct 13, 7:42?pm, Jon Clements wrote: > On Oct 13, 10:59?pm,MrPink wrote: > > > > > > > > > > > This is a continuing to a post I made in August:http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > > I got some free time to work with Python again and have some followup > > questions. > > > For example, I have a list in a text file like this: > > Example list of lottery drawings: > > date,wb,wb,wb,wb,wb,bb > > 4/1/2011,5,1,45,23,27,27 > > 5/1/2011,15,23,8,48,22,32 > > 6/1/2011,33,49,21,16,34,1 > > 7/1/2011,9,3,13,22,45,41 > > 8/1/2011,54,1,24,39,35,18 > > .... > > > Ticket: > > startdate,enddate,wb,wb,wb,wb,wb,bb > > 4/1/2011,8/1/2011,5,23,32,21,3,27 > > > I am trying to determine the optimal way to organize the data > > structure of the drawing list, search the drawing list, and mark the > > matches in the drawing list. > > > f = open("C:\temp\drawinglist.txt", "r") > > lines = f.readlines() > > f.close() > > drawing = lines[1].split() > > > The results in drawing is this: > > drawing[0] = '4/1/2011' > > drawing[1] = '5' > > drawing[2] = '1' > > drawing[3] = '45' > > drawing[4] = '23' > > drawing[5] = '27' > > drawing[6] = '27' > > > I need to convert drawing[0] to a date datatype. ?This works, but I'm > > sure there is a better way. > > from datetime import date > > month, day, year = drawing[0].split('/') > > drawing[0] = date(int(year), int(month), int(day)) > > > For searching, I need to determine if the date of the drawing is > > within the date range of the ticket. ?If yes, then mark which numbers > > in the drawing match the numbers in the ticket. > > > ticket[0] = '4/1/2011' > > ticket[0] = '8/1/2011' > > ticket[0] = '5' > > ticket[0] = '23' > > ticket[0] = '32' > > ticket[0] = '21' > > ticket[0] = '3' > > ticket[0] = 27' > > > drawing[0] = '4/1/2011' (match) > > drawing[1] = '5' (match) > > drawing[2] = '1' > > drawing[3] = '45' > > drawing[4] = '23' (match) > > drawing[5] = '27' > > drawing[6] = '27' (match) > > > I'm debating on structuring the drawing list like this: > > drawing[0] = '4/1/2011' > > drawing[1][0] = '5' > > drawing[1][1] = '1' > > drawing[1][2] = '45' > > drawing[1][3] = '23' > > drawing[1][4] = '27' > > drawing[2] = '27' > > > Sort drawing[1] from low to high > > drawing[1][0] = '1' > > drawing[1][1] = '5' > > drawing[1][2] = '23' > > drawing[1][3] = '27' > > drawing[1][4] = '45' > > > I want to keep the drawing list in memory for reuse. > > > Any guidance would be most helpful and appreciated. > > BTW, I want to learn, so be careful not to do too much of the work for > > me. > > I'm using WingIDE to do my work. > > > Thanks, > > - Use the csv module to read the file > - Use strptime to process the date field > - Use a set for draw numbers (you'd have to do pure equality on the > bb) > - Look at persisting in a sqlite3 DB (maybe with a custom convertor) > > hth, > > Jon. From rosuav at gmail.com Sat Oct 15 00:24:40 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Oct 2011 15:24:40 +1100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> <7c0baafc-70df-46ec-8482-8bbf267c8231@t38g2000prg.googlegroups.com> Message-ID: On Sat, Oct 15, 2011 at 1:15 PM, Chris Rebert wrote: > On Fri, Oct 14, 2011 at 6:23 PM, alex23 wrote: >> Well sure, but imaginary syntax can do _anything_. That doesn't mean >> it's possible within CPython. > > But it's The Future now! Where are my jetpack and `dwim` statement, > dammit?! ?:-) If you can imagine something your language can't do, you're not using enough preprocessors. ChrisA who, frustrated by Java about ten years ago, started running his .java files through the C preprocessor... and it can get a lot worse than that From rosuav at gmail.com Sat Oct 15 00:30:44 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Oct 2011 15:30:44 +1100 Subject: Reading a file into a data structure.... In-Reply-To: <763d6391-fc4d-4b47-b0c3-d3ad16e0fc38@gy7g2000vbb.googlegroups.com> References: <763d6391-fc4d-4b47-b0c3-d3ad16e0fc38@gy7g2000vbb.googlegroups.com> Message-ID: On Sat, Oct 15, 2011 at 1:59 PM, MrPink wrote: > def isInt(s): > ? ?try: > ? ? ? ?i = int(s) > ? ? ? ?return True > ? ?except ValueError: > ? ? ? ?return False > > f = open("powerball.txt", "r") > lines = f.readlines() > f.close() > > dDrawings = {} > for line in lines: > ? ?if isInt(line[0]): > ? ? ? ?t = line.split() > ? ? ? ?d = t[0] > ? ? ? ?month,day,year = t[0].split("/") > ? ? ? ?i = int(year + month + day) > ? ? ? ?wb = t[1:6] > ? ? ? ?wb.sort() > ? ? ? ?pb = t[6] > ? ? ? ?r = {'d':d,'wb':wb,'pb':pb} > ? ? ? ?dDrawings[i] = r > Here's a quick rejig: dDrawings = {} for line in open("powerball.txt"): try: t = line.split() d = t[0] month,day,year = t[0].split("/") i = int(year + month + day) wb = t[1:6] wb.sort() pb = t[6] r = {'d':d,'wb':wb,'pb':pb} dDrawings[i] = r except ValueError: pass There are two significant differences. One is that the file is kept open until processing is complete, rather than reading the file into a list and then iterating over the list. Your processing is pretty simple, so it's unlikely to make a difference, but if you're doing a lengthy operation on the lines of text, or conversely if you're reading in gigs and gigs of file, you may want to take that into consideration. The other change is that a ValueError _anywhere_ in processing will cause the line to be silently ignored. If this isn't what you want, then shorten the try/except block and make it use 'continue' instead of 'pass' (which will then silently ignore that line, but leave the rest of processing unguarded by try/except). The most likely cause of another ValueError is this line: month,day,year = t[0].split("/") If there are not precisely two slashes, this will: >>> a,b,c="asdf/qwer".split("/") Traceback (most recent call last): File "", line 1, in a,b,c="asdf/qwer".split("/") ValueError: need more than 2 values to unpack Do you want this to cause the line to be ignored, or to noisily abort the whole script? ChrisA From clp2 at rebertia.com Sat Oct 15 00:47:53 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 14 Oct 2011 21:47:53 -0700 Subject: Reading a file into a data structure.... In-Reply-To: <763d6391-fc4d-4b47-b0c3-d3ad16e0fc38@gy7g2000vbb.googlegroups.com> References: <763d6391-fc4d-4b47-b0c3-d3ad16e0fc38@gy7g2000vbb.googlegroups.com> Message-ID: On Fri, Oct 14, 2011 at 7:59 PM, MrPink wrote: > This is what I have been able to accomplish: > > def isInt(s): > ? ?try: > ? ? ? ?i = int(s) > ? ? ? ?return True > ? ?except ValueError: > ? ? ? ?return False > > f = open("powerball.txt", "r") > lines = f.readlines() > f.close() > > dDrawings = {} > for line in lines: > ? ?if isInt(line[0]): > ? ? ? ?t = line.split() > ? ? ? ?d = t[0] > ? ? ? ?month,day,year = t[0].split("/") > ? ? ? ?i = int(year + month + day) > ? ? ? ?wb = t[1:6] > ? ? ? ?wb.sort() > ? ? ? ?pb = t[6] > ? ? ? ?r = {'d':d,'wb':wb,'pb':pb} > ? ? ? ?dDrawings[i] = r > > The dictionary dDrawings contains records like this: > dDrawings[19971101] > {'pb': '20', 'd': '11/01/1997', 'wb': ['22', '25', '28', '33', '37']} > > I am now able to search for ticket in a date range. > keys = dDrawings.keys() > b = [key for key in keys if 20110909 <= key <= 20111212] > > How would I search for matching wb (White Balls) in the drawings? > > Is there a better way to organize the data so that it will be flexible > enough for different types of searches? > Search by date range, search by pb, search by wb matches, etc. > > I hope this all makes sense. from datetime import datetime from collections import namedtuple, defaultdict # for efficient searching by date: import bisect DATE_FORMAT = "%m/%d/%Y" Ticket = namedtuple('Ticket', "white_balls powerball date".split()) powerball2ticket = defaultdict(set) whiteball2ticket = defaultdict(set) tickets_by_date = [] with open("powerball.txt", "r") as f: for line in f: if not line[0].isdigit(): # what are these other lines anyway? continue # skip such lines fields = line.split() date = datetime.strptime(fields[0], DATE_FORMAT).date() white_balls = frozenset(int(num_str) for num_str in fields[1:6]) powerball = int(fields[6]) ticket = Ticket(white_balls, powerball, date) powerball2ticket[powerball].add(ticket) for ball in white_balls: whiteball2ticket[ball].add(ticket) tickets_by_date.append(ticket) tickets_by_date.sort(key=lambda ticket: ticket.date) print(powerball2ticket[7]) # all tickets with a 7 powerball print(whiteball2ticket[3]) # all tickets with a non-power 3 ball Cheers, Chris -- http://rebertia.com From miki.tebeka at gmail.com Sat Oct 15 01:20:53 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 14 Oct 2011 22:20:53 -0700 (PDT) Subject: How to generate error when argument are not supplied and there is no explicit defults (in optparse)? In-Reply-To: References: Message-ID: <25425134.106.1318656053412.JavaMail.geo-discussion-forums@prho12> Don't specify it as an option, but as an argument. If you're on a new version of python, you should probably use argparse. From miki.tebeka at gmail.com Sat Oct 15 01:20:53 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 14 Oct 2011 22:20:53 -0700 (PDT) Subject: How to generate error when argument are not supplied and there is no explicit defults (in optparse)? In-Reply-To: References: Message-ID: <25425134.106.1318656053412.JavaMail.geo-discussion-forums@prho12> Don't specify it as an option, but as an argument. If you're on a new version of python, you should probably use argparse. From sathyapriyavikash at gmail.com Sat Oct 15 01:43:52 2011 From: sathyapriyavikash at gmail.com (sathya priya) Date: Fri, 14 Oct 2011 22:43:52 -0700 (PDT) Subject: Dear friends find ur life partner here visit now Message-ID: http://123maza.com/48/share486/ From tjreedy at udel.edu Sat Oct 15 02:03:50 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 15 Oct 2011 02:03:50 -0400 Subject: How to test if object is an integer? In-Reply-To: <87hb3buimq.fsf@benfinney.id.au> References: <87hb3buimq.fsf@benfinney.id.au> Message-ID: On 10/14/2011 9:51 PM, Ben Finney wrote: > Terry Reedy writes: > >> On 10/14/2011 9:05 PM, Chris Angelico wrote: > >>> That tests if the object is already an int; the OP asked if a string >>> contains an integer. >> >> The misleading subject line did not. It should have been "How to test >> if a string contains an integer?" > Which would still be misleading :-) > > Even better is ?How to test whether a string is a valid representation > of an integer?? I agree, but that is more than I would ask of a newbie, whereas asking people to ask the same question in subject line and text, even if the question is inadequate, is reasonable. > I say that's better because it gets to the relevant point of asking > *which* representations you want to test for ? what qualifies as valid > for your particular use case, and what does not. There's no single right > answer; the programmer must choose exactly what they want to test for. Yes. Even the wrong subject line question is ambiguous, as any of int, bool, float, complex, decimal.Decimal, and fractions.Fraction can have an integer value, as might user class instances, and, of course, depending on context, bytes and strings. -- Terry Jan Reedy From anikom15 at gmail.com Sat Oct 15 02:04:12 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Fri, 14 Oct 2011 23:04:12 -0700 Subject: Can I search a list for a range of values? In-Reply-To: References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> Message-ID: <20111015060412.GA12454@Smoke> On Fri, Oct 14, 2011 at 05:01:04PM -0600, Ian Kelly wrote: > On Fri, Oct 14, 2011 at 4:30 PM, Tim Chase > wrote: > > On 10/14/11 17:20, Chris Angelico wrote: > >> > >> Try a list comprehension: > >> > >>>>> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14] > >>>>> [i for i in a if i>=10 if i<=20] > >> > >> [10, 20, 15, 13, 14] > > > > The double-if is new to me. ?I thought it was an error when I first saw it, > > but it seems to be legit syntax (or at least one that 2.7 tolerates, > > intentionally or otherwise...). ?I think I'd make it clearer with either > > > > ?[i for i in a if i>=10 and i<=20] > > > > or even more clearly: > > > > ?[i for i in a if 10 <= i <= 20] > > As long as we're nitpicking, I'll point out that "i" is an > inappropriate variable name here, since it is normally used to denote > indices, not data. That's why I used "x" in my response instead. ;-) > O that's what i stands for. I always thought it was integer o_O From aaabbb16 at hotmail.com Sat Oct 15 02:20:22 2011 From: aaabbb16 at hotmail.com (aaabbb16 at hotmail.com) Date: Fri, 14 Oct 2011 23:20:22 -0700 (PDT) Subject: I am a newbie for python and try to understand class Inheritance. Message-ID: Test.py #!/usr/bin/python from my_lib import my_function class my_class(my_function.name): def __initial__(self, name); pass def test(): print "this is a test" If __name__ == '__maim__': my_class.main() --------------------------------------------------- my_lib.py class my_function() ....... ........ Can anyone finish above code and let me try to understand Class inheritance? TIA. -david From clp2 at rebertia.com Sat Oct 15 03:04:13 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 15 Oct 2011 00:04:13 -0700 Subject: I am a newbie for python and try to understand class Inheritance. In-Reply-To: References: Message-ID: On Fri, Oct 14, 2011 at 11:20 PM, wrote: > Test.py > #!/usr/bin/python > from my_lib import my_function > class my_class(my_function.name): Why are you subclassing my_function.name and not just my_function? > ? ?def __initial__(self, name); > ? ? ? ? pass The initializer method should be named "__init__", not "__initial__". > ? ?def test(): You forgot to include "self" as a parameter, like so: def test(self): > ? ? ? print "this is a test" > > If __name__ == '__maim__': That should be "__main__" with an N, not "__maim__" with an M. And "if" must be in all-lowercase. > ? ?my_class.main() Your class doesn't define any method named "main" (you only defined test() and __initial__() ), so this call will fail. > --------------------------------------------------- > my_lib.py > class my_function() You're missing a colon after the parentheses. Also, you're writing a class, not a function, so please rename the class something less confusing. > Can anyone finish above code and let me try to understand > Class inheritance? > TIA. Have you read any Python tutorial? There are several basic errors in your code which would suggest that you haven't. You really ought to; it's well worth it. The Beginner's Guide links to 2 lists of tutorials: http://wiki.python.org/moin/BeginnersGuide There's also the python-tutor mailing list, which is specifically geared towards answering beginner questions: http://mail.python.org/mailman/listinfo/tutor Cheers, Chris -- http://rebertia.com From jason.swails at gmail.com Sat Oct 15 03:09:09 2011 From: jason.swails at gmail.com (Jason Swails) Date: Sat, 15 Oct 2011 03:09:09 -0400 Subject: I am a newbie for python and try to understand class Inheritance. In-Reply-To: References: Message-ID: On Sat, Oct 15, 2011 at 2:20 AM, wrote: > Test.py > #!/usr/bin/python > from my_lib import my_function > class my_class(my_function.name): > Classes must inherit from other classes -- not variables or functions. > def __initial__(self, name); > This should be "def __init__(self, name):" (: not ; and __init__, not __initial__) pass > def test(): > print "this is a test" > > If __name__ == '__maim__': > I think this should be '__main__' > my_class.main() > This only makes sense if your my_class has a main() attribute function to it. Note that the typical way of dealing with classes is to instantiate different classes. > > Can anyone finish above code and let me try to understand > Class inheritance? > You appear to be confusing functions and classes. Functions are chunks of code that you (optionally) pass variables to in order to perform a specific task. Classes, on the other hand, are the heart of OOP. They are useful for creating an abstraction layer to make certain problems easier and reading code easier as well. (It also helps break down the problem into more manageable pieces, which facilitates collaborative projects). For instance, let's say you want to deal with shapes. You can define a shape via a class class Shape(object): """ Base shape class """ def __init__(self, vertices): """ Obviously if any of the vertices are collinear num_sides will be wrong. This is an example """ self.vertices = vertices self.num_sides = len(vertices) def draw(self, canvas): """ Draws the given shape on a passed canvas. Pretend there is working code here """ def area(self): """ Calculates the area of this shape and returns it as a floating point number """ return Now you can create different shapes as you need them user_shape_1 = Shape( ((0,0), (0,1), (1,1), (1,0)) ) user_shape_2 = Shape( ((-1,-1), (0,0), (-1,0)) ) Now you have 2 different shapes. If you have some kind of canvas object (from Tk, perhaps), you can draw either shape up there by calling one of its functions: user_shape_1.draw(my_canvas) As you can see, the simple call user_shape_1.draw(my_canvas) is self explanatory -- it draws the shape on the given canvas. This allows easy re-use of code. Now we get into inheritance. Let's suppose that we want a specific type of shape. For instance, a circle (that is defined by an infinite number of vertices). In this case, a circle is still a shape, so it should have every attribute that a normal shape has. Thus, we can define a circle class as follows: class Circle(Shape): """ Circle inherits from Shape """ number_vertex_points = 1000 # Default number of vertex points I want to define a circle def __init__(self, center, radius): """ Define the self.vertices here to trace out a circle as closely as you want """ Now, each time we instantiate a Circle class, that class has every attribute that Shape has, in addition to any additional attribute you give to Circle (and if the same attribute is defined in both places, the definition in Circle overrides that definition). Thus, in this case we can define a Circle with a center and radius (much easier than vertices!), and we can tell Circle how we want the vertices defined to get as close an approximation to a circle as we want. HTH (I'm sure others can explain this better than I can), Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sat Oct 15 03:37:35 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 15 Oct 2011 00:37:35 -0700 Subject: I am a newbie for python and try to understand class Inheritance. In-Reply-To: References: Message-ID: On Sat, Oct 15, 2011 at 12:09 AM, Jason Swails wrote: > For instance, let's say you want to deal with shapes.? You can define a > shape via a class > > class Shape(object): > ?? """ Base shape class """ > Now we get into inheritance.? Let's suppose that we want a specific type of > shape.? For instance, a circle (that is defined by an infinite number of > vertices).? In this case, a circle is still a shape, so it should have every > attribute that a normal shape has.? Thus, we can define a circle class as > follows: > > class Circle(Shape): > ?? """ Circle inherits from Shape """ > ?? number_vertex_points = 1000 # Default number of vertex points I want to > define a circle > ?? def __init__(self, center, radius): > ????? """ Define the self.vertices here to trace out a circle as closely as > you want """ > > Now, each time we instantiate a Circle class, that class has every attribute > that Shape has, in addition to any additional attribute you give to Circle > (and if the same attribute is defined in both places, the definition in > Circle overrides that definition).? Thus, in this case we can define a > Circle with a center and radius (much easier than vertices!), and we can > tell Circle how we want the vertices defined to get as close an > approximation to a circle as we want. Sidenote: It's funny that the shapes example gets used so often, despite the fact that pursuing it much further so easily leads to the Circle-Ellipse / Rectangle-Square problem. Cheers, Chris From aaabbb16 at hotmail.com Sat Oct 15 03:59:48 2011 From: aaabbb16 at hotmail.com (aaabbb16 at hotmail.com) Date: Sat, 15 Oct 2011 00:59:48 -0700 (PDT) Subject: I am a newbie for python and try to understand class Inheritance. References: Message-ID: <751ee720-652c-4ea2-9521-a9017a9be679@k16g2000prb.googlegroups.com> On 10?15?, ??12?04?, Chris Rebert wrote: > On Fri, Oct 14, 2011 at 11:20 PM, ? wrote: > > Test.py > > #!/usr/bin/python > > from my_lib import test > > class my_class(my_function.name): > > Why are you subclassing my_function.name and not just my_function? try to inherit or change "name" attribute in "my_function". > > > ? ?def __initial__(self, name); > > ? ? ? ? pass > > The initializer method should be named "__init__", not "__initial__". ipad is so smart, it thinks I have spelling problem and correct it. haha. sorry about it. > > > ? ?def test(): > > You forgot to include "self" as a parameter, like so: > ? ? def test(self): right thanks! > > > ? ? ? print "this is a test" > > > If __name__ == '__maim__': > > That should be "__main__" with an N, not "__maim__" with an M. > And "if" must be in all-lowercase. mistyping > > ? ?my_class.main() > > Your class doesn't define any method named "main" (you only defined > test() and __initial__() ), so this call will fail. how to do it? > > --------------------------------------------------- > > my_lib.py > > class my_function() > > You're missing a colon after the parentheses. Also, you're writing a > class, not a function, so please rename the class something less > confusing. sure. i like call it from my_lib > > > Can anyone finish above code and let me try to understand > > Class inheritance? > > TIA. > > Have you read any Python tutorial? There are several basic errors in > your code which would suggest that you haven't. You really ought to; > it's well worth it. > The Beginner's Guide links to 2 lists of tutorials:http://wiki.python.org/moin/BeginnersGuide > > There's also the python-tutor mailing list, which is specifically > geared towards answering beginner questions:http://mail.python.org/mailman/listinfo/tutor > > Cheers, > Chris > --http://rebertia.com Thanks Chris! I'll check that link. Test.py #!/usr/bin/python from my_lib import p_test class my_class(p_test.name): def __initial__(self, name): pass def test(self): print "this is a test" If __name__ == '__main__': my_class.main() --------------------------------------------------- my_lib.py class p_test() ....... ........ Can anyone finish it and give me a demo. Class inheritance? for this case, it inherit/change p_test "name" attribute. I try to quick understand how to inherit parent attribute TIA. david From clp2 at rebertia.com Sat Oct 15 04:11:53 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 15 Oct 2011 01:11:53 -0700 Subject: I am a newbie for python and try to understand class Inheritance. In-Reply-To: <751ee720-652c-4ea2-9521-a9017a9be679@k16g2000prb.googlegroups.com> References: <751ee720-652c-4ea2-9521-a9017a9be679@k16g2000prb.googlegroups.com> Message-ID: On Sat, Oct 15, 2011 at 12:59 AM, wrote: > On 10?15?, ??12?04?, Chris Rebert wrote: >> On Fri, Oct 14, 2011 at 11:20 PM, ? wrote: >> > ? ?my_class.main() >> >> Your class doesn't define any method named "main" (you only defined >> test() and __initial__() ), so this call will fail. > how to do it? You'd define a method named "main", just like with "test". You would then call it by doing: my_class().main() > Test.py > #!/usr/bin/python > from my_lib import p_test > class my_class(p_test.name): > ? ?def __initial__(self, name): > ? ? ? ? pass > ? ?def test(self): > ? ? ? print "this is a test" > > If __name__ == '__main__': > ? ?my_class.main() > --------------------------------------------------- > my_lib.py > class p_test() > ....... > ........ > > Can anyone finish it and give me a demo. > Class inheritance? > for this case, it inherit/change p_test "name" attribute. > I try to quick understand how to inherit parent attribute my_lib.py: class ParentClass(object): def __init__(self, name): self.name = name self.species = "Human" test.py: from my_lib import ParentClass class MyClass(ParentClass): def __init__(self, name): super(MyClass, self).__init__(name + " Jones") def print_name(self): print "My name is", self.name print "And I am a", self.species MyClass("Bob").print_name() Note that classes are conventionally named using CamelCaseLikeThis instead of underscore_separated_words. Cheers, Chris From gagsl-py2 at yahoo.com.ar Sat Oct 15 04:21:04 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 15 Oct 2011 01:21:04 -0700 (PDT) Subject: why msvcrt.printf show the first char only? References: <88550536-6cc5-452c-8bca-ba91b175323a@l39g2000pro.googlegroups.com> Message-ID: On 12 oct, 08:50, Nobody wrote: > On Wed, 12 Oct 2011 04:18:25 -0700, install... at 189.cn wrote: > > from ctypes import * > > msvcrt = cdll.msvcrt > > message_string = "Hello world!\n" > > print(msvcrt.printf("Testing: %s", message_string)) > > > when running in eclipse, the result is: > > 1 > > T > > > when running in IDLE, then result is: > > 1 > > > why is that? > > Odd. I get 22 when running from IDLE. > > Also, when using the console, it actually prints the text. I suspect that > stdout gets block-buffered when using an IDE. I can't see any way to get a > reference to stdout, so you can't fflush() it. Launch IDLE from the command line and you'll see the text output. To the OP: I bet your Eclipse runs Python 2.x and IDLE is 3.x. In Python 3.x, "Test..." is a Unicode string, internally represented using two bytes per character. (In contrast, in Python 2.x, "Test..." is a byte string, and u"Test..." is unicode). All ASCII characters have a 0 as their second byte in its internal representation. printf expects a byte string, and stops as soon as it sees the '\0' following the 'T' in 'Testing'. Either use wprintf("Testing..."), or encode the Unicode object into a byte string before calling: printf("Testing...".encode(sys.stdout.encoding)), or tell ctypes about the right parameter type: printf = msvcrt.printf printf.argtypes = [c_char_p] printf("Testing\n") -- Gabriel Genellina From love_ram2040 at yahoo.com Sat Oct 15 04:44:33 2011 From: love_ram2040 at yahoo.com (porxy) Date: Sat, 15 Oct 2011 01:44:33 -0700 (PDT) Subject: Site to open blocked sites, and prohibited and encoded Message-ID: <426ed123-e11a-484f-9d7c-3699b3d84715@h14g2000yqi.googlegroups.com> Site to open blocked sites, and prohibited and encoded http://myway.x90x.net/ From alec.taylor6 at gmail.com Sat Oct 15 04:49:57 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 15 Oct 2011 19:49:57 +1100 Subject: Site to open blocked sites, and prohibited and encoded In-Reply-To: <426ed123-e11a-484f-9d7c-3699b3d84715@h14g2000yqi.googlegroups.com> References: <426ed123-e11a-484f-9d7c-3699b3d84715@h14g2000yqi.googlegroups.com> Message-ID: Large list: http://proxy.org/ On Sat, Oct 15, 2011 at 7:44 PM, porxy wrote: > Site to open blocked sites, and prohibited and encoded > > http://myway.x90x.net/ > -- > http://mail.python.org/mailman/listinfo/python-list > From steve+comp.lang.python at pearwood.info Sat Oct 15 07:53:16 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 15 Oct 2011 22:53:16 +1100 Subject: Can I search a list for a range of values? References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> Message-ID: <4e99742d$0$29979$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > Yeah, it's legal because you can nest fors and ifs in a list comp. > Stylistic difference, I used "if" instead of "and" because there's no > way that it could be a bitwise and. If you're using Python, there's no way that it could be a bitwise and. > (It's a cross-language safety net that I sometimes use.) I'm not familiar with a language that uses Python syntax but "and" is a bitwise and. Which language is that? -- Steven From steve+comp.lang.python at pearwood.info Sat Oct 15 07:54:46 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 15 Oct 2011 22:54:46 +1100 Subject: argparse zero-length switch References: <17016857.666.1318572326692.JavaMail.geo-discussion-forums@prmi2> Message-ID: <4e997487$0$29979$c3e8da3$5496439d@news.astraweb.com> Carl Banks wrote: > So instead of typing this: > > sp subcommand -s abc foo bar > > they could type this: > > sp subcommand @abc foo bar > > Admittedly a small benefit. I would call it a *cost* and not a benefit at all. Instead of using a standard, familiar user interface for entering command options, you introduce a second special purpose mechanism *just* for entering a section name. -s is at least a mnemonic for "section", @ is not. And it isn't like you gain any extra clarity or expressiveness, or even a major saving of typing! "-s" vs "@". You don't even save a key stroke: "@" requires two keystrokes, just as "-s" does. (Okay, perhaps you save a key stroke if you type a space after the -s.) -s section_name is pretty simple already. Spelling it @section_name is not sufficiently more simple to make up for the burden of introducing unfamiliar syntax. -- Steven From dihedral88888 at googlemail.com Sat Oct 15 08:16:02 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sat, 15 Oct 2011 05:16:02 -0700 (PDT) Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> <21380825.697.1318543555990.JavaMail.geo-discussion-forums@prdw1> Message-ID: <7741987.1212.1318680962678.JavaMail.geo-discussion-forums@prmr13> Conversion utilities are used to ease the burdens for programmers to translate source scripts and codes into different languages or even the same language with revisions. Check for translators for C, C++, PASCAL, BASIC, and FORTRAN and also SWIG, PYREX, CYTHON, JYTHON and etc.. From dihedral88888 at googlemail.com Sat Oct 15 08:16:02 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sat, 15 Oct 2011 05:16:02 -0700 (PDT) Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> <21380825.697.1318543555990.JavaMail.geo-discussion-forums@prdw1> Message-ID: <7741987.1212.1318680962678.JavaMail.geo-discussion-forums@prmr13> Conversion utilities are used to ease the burdens for programmers to translate source scripts and codes into different languages or even the same language with revisions. Check for translators for C, C++, PASCAL, BASIC, and FORTRAN and also SWIG, PYREX, CYTHON, JYTHON and etc.. From rosuav at gmail.com Sat Oct 15 08:45:28 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Oct 2011 23:45:28 +1100 Subject: Can I search a list for a range of values? In-Reply-To: <4e99742d$0$29979$c3e8da3$5496439d@news.astraweb.com> References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> <4e99742d$0$29979$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Oct 15, 2011 at 10:53 PM, Steven D'Aprano wrote: > I'm not familiar with a language that uses Python syntax but "and" is a > bitwise and. Which language is that? > I'm not familiar with any either, it's just that I have a few habits that I slip into. ChrisA From invalid at invalid.invalid Sat Oct 15 09:47:07 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Sat, 15 Oct 2011 13:47:07 +0000 (UTC) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> Message-ID: On 2011-10-14, Westley Mart?nez wrote: > On Thu, Oct 13, 2011 at 11:56:20PM -0700, Carl Banks wrote: > > While we're at it, let's throw in the register keyword. Yah! C compilers have been ignoring it for ages, and I miss it. -- Grant From kevin.p.dwyer at gmail.com Sat Oct 15 10:46:57 2011 From: kevin.p.dwyer at gmail.com (Kev Dwyer) Date: Sat, 15 Oct 2011 15:46:57 +0100 Subject: Fwd: os.statvfs bug or my incompetence ? References: <4E97DB66.50302@nsn.com> <4E97F093.4000203@nsn.com> Message-ID: Peter G. Marczis wrote: Hello Peter, Welcome to the list. Have you tried calling statvfs from a C program? What happens if you do? Best regards, Kev From chris.cocuzzo at gmail.com Sat Oct 15 11:03:21 2011 From: chris.cocuzzo at gmail.com (pngrv) Date: Sat, 15 Oct 2011 08:03:21 -0700 (PDT) Subject: Help with beginner form using lpthw.web Message-ID: <19577343.847.1318691001313.JavaMail.geo-discussion-forums@vbzc27> Hey -- I'm still learning what all of the different exceptions and errors mean. What I'd like to do is grab a bit of assistance figuring out the error I'm getting so that I can keep moving. My python code for this particular part of the app looks like this: class rs_request: def GET(self): return render.rs_request() def POST(self): form = web.input(name='Dood', project='Awesome', locations='1', engines='1') request_string = 'Request: %s, %s, %s, %s' % (form.name, form.project, form.locations, form.engines) return render.index(request_string = request_string) My HTML: Please Use This Form To Request Resources
Name:
Project:
# of Locations:
# of Engines:



$def with (request_string) $if request_string: I just wanted to say $request_string. $else: Hello, world! And seeing this error: at /rs_request invalid syntax Template traceback: File 'templates/rs_request.html', line 30 (rs_request.html, line 30) Python /Library/Python/2.7/site-packages/web/template.py in compile_template, line 909 Web GET http://localhost:8080/rs_request So, it seems to be indicating that my GET request is broken, but I don't really understand why. Can anyone help? From eswint at vt.edu Sat Oct 15 11:17:17 2011 From: eswint at vt.edu (Ethan Swint) Date: Sat, 15 Oct 2011 11:17:17 -0400 Subject: Python hangs: Problem with wxPython, threading, pySerial, or events? Message-ID: <4E99A3FD.1010708@vt.edu> Hi- I'm experiencing crashes in my Win32 Python 2.7 application which appear to be linked to pyzmq. At the moment, I can't even kill the "python.exe *32" process in the Windows Task Manager. At the moment I'm running the script using Ipython by calling C:\Python27\pythonw.exe "/python27/scripts/ipython-qtconsole-script.pyw" -pylab but I also experience similar behavior when running within Eclipse. I've included an error message at the end which appears in the Windows 'cmd' window, but the message is not reflected in the pylab window. My attached device is transmitting <160><1><2><3><4><80> and is received correctly when I run the sample pyserial script 'wxTerminal.py'. In my application, however, the message appears to get characters out of order or drop bytes. If there's a better place to post or if you'd like more info, let me know. Thanks, Ethan ------------------Serial Port Listening Thread---------------------------------------- def MotorRxThread(self): """Thread that handles the incoming traffic. Does buffer input and generates an SerialRxEvent""" while self.alive.isSet(): #loop while alive event is true text = self.serMotor.read(1) #read one, with timeout if text: #check if not timeout n = self.serMotor.inWaiting() #look if there is more to read if n: text = text + self.serMotor.read(n) #get it #log to terminal printstring = "MotorRxThread: " for b in text: printstring += str(ord(b)) + " " print printstring #pdb.set_trace() if self.motorRx0.proc_string(text): print "Message: cmd: " + str(self.motorRx0.cmd) + " data: " + str(self.motorRx0.data) event = SerialRxSpeedEvent(self.GetId(), text) self.GetEventHandler().AddPendingEvent(event) -----------------\Serial Port Listening Thread---------------------------------------- ----------------Thread Start&Stop------------------------------------------------------ def StartMotorThread(self): """Start the receiver thread""" self.motorThread = threading.Thread(target=self.MotorRxThread) self.motorThread.setDaemon(1) self.alive.set() self.motorThread.start() def StopMotorThread(self): """Stop the receiver thread, wait until it's finished.""" if self.motorThread is not None: self.alive.clear() #clear alive event for thread self.motorThread.join() #wait until thread has finished self.motorThread = None self.serMotor.close() #close the serial port connection ----------------\Thread Start&Stop------------------------------------------------------ -------------------Error message -------------------------------------------------------- ValueError: '' is not in list ([], ['', '', '', '{"date":"2011-10-15T10:24:27.231000","username":"kernel","session":"82906c8a-1235-44d0-b65d- 0882955305c1","msg_id":"7cfcd155-bc05-4f47-9c39-094252223dab","msg_type":"stream"}', '{"date":"2011-10-15T10:24:27.23100 0","username":"kernel","session":"82906c8a-1235-44d0-b65d-0882955305c1","msg_id":"f4b88228-b353-4cfb-9bbe-ae524ee1ac38", "msg_type":"stream"}', '{"date":"2011-10-15T10:24:00.774000","username":"username","session":"9f393860-c2ab-44e9-820d-8f 08ae35044e","msg_id":"13a46e93-8da2-487b-ab12-6cae47b1ac34","msg_type":"execute_request"}', '{"date":"2011-10-15T10:24:0 0.774000","username":"username","session":"9f393860-c2ab-44e9-820d-8f08ae35044e","msg_id":"13a46e93-8da2-487b-ab12-6cae4 7b1ac34","msg_type":"execute_request"}', '{"data":"\\nMotorRxThread: 0 MotorRxThread: 4 ","name":"stdout"}']) ERROR:root:Exception in I/O handler for fd Traceback (most recent call last): File "C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\ioloop.py", line 291, in start self._handlers[fd](fd, events) File "C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\stack_context.py", line 133, in wrapped callback(*args, **kwargs) File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", line 448, in _handle_events self._handle_recv() File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", line 458, in _handle_recv ident,msg = self.session.recv(self.socket) File "C:\Python27\lib\site-packages\IPython\zmq\session.py", line 585, in recv raise e ValueError: No JSON object could be decoded ERROR:root:Exception in I/O handler for fd Traceback (most recent call last): File "C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\ioloop.py", line 291, in start self._handlers[fd](fd, events) File "C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\stack_context.py", line 133, in wrapped callback(*args, **kwargs) File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", line 448, in _handle_events self._handle_recv() File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", line 458, in _handle_recv ident,msg = self.session.recv(self.socket) File "C:\Python27\lib\site-packages\IPython\zmq\session.py", line 579, in recv idents, msg_list = self.feed_identities(msg_list, copy) File "C:\Python27\lib\site-packages\IPython\zmq\session.py", line 609, in feed_identities idx = msg_list.index(DELIM) ValueError: '' is not in list --------------------------------------------------------------------------- ZMQError Traceback (most recent call last) C:\Users\Ethan\ in () C:\Python27\lib\site-packages\IPython\zmq\ipkernel.pyc in main() 671 """Run an IPKernel as an application""" 672 app = IPKernelApp.instance() --> 673 app.initialize() 674 app.start() 675 C:\Python27\lib\site-packages\IPython\zmq\ipkernel.pyc in initialize(self=, arg v=None) 604 ) 605 def initialize(self, argv=None): --> 606 super(IPKernelApp, self).initialize(argv) 607 self.init_shell() 608 self.init_extensions() C:\Python27\lib\site-packages\IPython\zmq\kernelapp.pyc in initialize(self=, ar gv=None) 213 self.init_session() 214 self.init_poller() --> 215 self.init_sockets() 216 self.init_io() 217 self.init_kernel() C:\Python27\lib\site-packages\IPython\zmq\kernelapp.pyc in init_sockets(self=) 148 149 self.shell_socket = context.socket(zmq.XREP) --> 150 self.shell_port = self._bind_socket(self.shell_socket, self.shell_port) 151 self.log.debug("shell XREP Channel on port: %i"%self.shell_port) 152 C:\Python27\lib\site-packages\IPython\zmq\kernelapp.pyc in _bind_socket(self=, s=, port=50104) 137 port = s.bind_to_random_port(iface) 138 else: --> 139 s.bind(iface + ':%i'%port) 140 return port 141 C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\core\socket.pyd in zmq.core.socket.Socket.bind (zmq\core\s ocket.c:4527)() ZMQError: Address in use ---------\ERROR MESSAGE-------------------------------------------------- From debatem1 at gmail.com Sat Oct 15 13:12:22 2011 From: debatem1 at gmail.com (geremy condra) Date: Sat, 15 Oct 2011 10:12:22 -0700 Subject: Opportunity missed by Python ? In-Reply-To: <1dd5aa8c-7a41-4108-8940-ef666cd2ddb9@t38g2000prg.googlegroups.com> References: <4e96b324$0$1007$426a34cc@news.free.fr> <1dd5aa8c-7a41-4108-8940-ef666cd2ddb9@t38g2000prg.googlegroups.com> Message-ID: On Fri, Oct 14, 2011 at 5:49 PM, alex23 wrote: > On Oct 13, 8:07?pm, Chris Angelico wrote: >> Python, as I found out to my detriment, is practically impossible to >> sandbox effectively. > > The latest version of PyPy introduces a prototype sandbox: > > http://pypy.org/features.html#sandboxing > > It'll be interesting to see how effective this is. Please note that their sandbox, while a good idea, is not a guaranteed jail. It's enforced by replacing calls to external libraries with trampoline stubs, but does not appear to have any intrinsic mechanism to prevent calls from being issued without it. That means that if you were able to successfully inject code you would be no more protected here than with any other process. Geremy Condra > -- > http://mail.python.org/mailman/listinfo/python-list > From dihedral88888 at googlemail.com Sat Oct 15 13:27:39 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sat, 15 Oct 2011 10:27:39 -0700 (PDT) Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> <1dd5aa8c-7a41-4108-8940-ef666cd2ddb9@t38g2000prg.googlegroups.com> Message-ID: <13798736.1338.1318699659752.JavaMail.geo-discussion-forums@prmr13> The undetected recursive call loop in some states that can be hacked or would hang and crush! Every program has to be run in a VM is just one solution but that will slow down a lot. From dihedral88888 at googlemail.com Sat Oct 15 13:27:39 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sat, 15 Oct 2011 10:27:39 -0700 (PDT) Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> <1dd5aa8c-7a41-4108-8940-ef666cd2ddb9@t38g2000prg.googlegroups.com> Message-ID: <13798736.1338.1318699659752.JavaMail.geo-discussion-forums@prmr13> The undetected recursive call loop in some states that can be hacked or would hang and crush! Every program has to be run in a VM is just one solution but that will slow down a lot. From woodygar at sky.com Sat Oct 15 13:30:59 2011 From: woodygar at sky.com (Gary) Date: Sat, 15 Oct 2011 18:30:59 +0100 Subject: hi can someone help please key bind Message-ID: <4E99C353.6070602@sky.com> Hi im trying to use key bind on Tkinter to call this function def Start(): for i in range(60,-1,-1): ent['text'] = i time.sleep(1) root.update() ent['text'] = 'Time Out!' root.update() i know the function is ok as i have assigned a button and i calls the function as i expect but root.bind('',Start) gives the following error Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__ return self.func(*args) TypeError: Start() takes no arguments (1 given) Thanks From gnarlodious at gmail.com Sat Oct 15 14:00:17 2011 From: gnarlodious at gmail.com (Gnarlodious) Date: Sat, 15 Oct 2011 11:00:17 -0700 (PDT) Subject: Loop through a dict changing keys Message-ID: What is the best way (Python 3) to loop through dict keys, examine the string, change them if needed, and save the changes to the same dict? So for input like this: {'Mobile': 'string', 'context': '', 'order': '7', 'time': 'True'} I want to booleanize 'True', turn '7' into an integer, escape '', and ignore 'string'. Any elegant Python way to do this? -- Gnarlie From alex.kapps at web.de Sat Oct 15 15:31:06 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Sat, 15 Oct 2011 21:31:06 +0200 Subject: Loop through a dict changing keys In-Reply-To: References: Message-ID: <4E99DF7A.6060707@web.de> On 15.10.2011 20:00, Gnarlodious wrote: > What is the best way (Python 3) to loop through dict keys, examine the > string, change them if needed, and save the changes to the same dict? > > So for input like this: > {'Mobile': 'string', 'context': '', 'order': '7', > 'time': 'True'} > > I want to booleanize 'True', turn '7' into an integer, escape > '', and ignore 'string'. > > Any elegant Python way to do this? > > -- Gnarlie I think JSON could be of some use, but I've not used it yet, otherwise something like this could do it: #!/usr/bin/python from cgi import escape def convert(string): for conv in (int, lambda x: {'True': True, 'False': False}[x], escape): try: return conv(string) except (KeyError, ValueError): pass return string d = {'Mobile': 'string', 'context': '', 'order': '7', 'time': 'True'} print d for key in d: d[key] = convert(d[key]) print d $ ./conv.py {'Mobile': 'string', 'order': '7', 'context': '', 'time': 'True'} {'Mobile': 'string', 'order': 7, 'context': '<malicious code>', 'time': True} From python at mrabarnett.plus.com Sat Oct 15 15:34:14 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 15 Oct 2011 20:34:14 +0100 Subject: hi can someone help please key bind In-Reply-To: <4E99C353.6070602@sky.com> References: <4E99C353.6070602@sky.com> Message-ID: <4E99E036.4060102@mrabarnett.plus.com> On 15/10/2011 18:30, Gary wrote: > Hi im trying to use key bind on Tkinter to call this function > > def Start(): > for i in range(60,-1,-1): > ent['text'] = i > time.sleep(1) > root.update() > ent['text'] = 'Time Out!' > root.update() > > i know the function is ok as i have assigned a button and i calls the > function as i expect > but > root.bind('',Start) > gives the following error > > Exception in Tkinter callback > Traceback (most recent call last): > File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__ > return self.func(*args) > TypeError: Start() takes no arguments (1 given) > The function will be called with an 'event' parameter, but you've defined it function to accept no parameters, hence the error message. From alex.kapps at web.de Sat Oct 15 15:35:08 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Sat, 15 Oct 2011 21:35:08 +0200 Subject: hi can someone help please key bind In-Reply-To: <4E99C353.6070602@sky.com> References: <4E99C353.6070602@sky.com> Message-ID: <4E99E06C.9050904@web.de> On 15.10.2011 19:30, Gary wrote: > Hi im trying to use key bind on Tkinter to call this function > > def Start(): > for i in range(60,-1,-1): > ent['text'] = i > time.sleep(1) > root.update() > ent['text'] = 'Time Out!' > root.update() > > i know the function is ok as i have assigned a button and i calls > the function as i expect > but > root.bind('',Start) > gives the following error > > Exception in Tkinter callback > Traceback (most recent call last): > File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__ > return self.func(*args) > TypeError: Start() takes no arguments (1 given) > > Thanks As the error indicates, the callback function is called with an argument, but you don't provide one. That argument is an Event instance, so you can get details about the event. Use def Start(event): ... BTW. functions, unlike classes should be all lower-case. From python at mrabarnett.plus.com Sat Oct 15 15:37:38 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 15 Oct 2011 20:37:38 +0100 Subject: Loop through a dict changing keys In-Reply-To: References: Message-ID: <4E99E102.2050904@mrabarnett.plus.com> On 15/10/2011 19:00, Gnarlodious wrote: > What is the best way (Python 3) to loop through dict keys, examine the > string, change them if needed, and save the changes to the same dict? > > So for input like this: > {'Mobile': 'string', 'context': '', 'order': '7', > 'time': 'True'} > > I want to booleanize 'True', turn '7' into an integer, escape > '', and ignore 'string'. > > Any elegant Python way to do this? > How about: for key, value in my_dict.items(): if value == "True": my_dict[key] = True From alex.kapps at web.de Sat Oct 15 15:48:54 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Sat, 15 Oct 2011 21:48:54 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E99E3A6.7030001@web.de> On 10.10.2011 19:29, Nobody wrote: > On Sun, 09 Oct 2011 02:25:27 +0200, Alexander Kapps wrote: > >> Even if it's off-topic, could you add some similar explanations for >> Church numerals (maybe Lambda calculus it isn't too much?) > > The Church numeral for N is a function of two arguments which applies its > first argument N times to its second, i.e. (f^N)(x) = f(f(...(f(x))...)). [SNIP] Thanks! That's a lot more understandable than Wikipedia. Some brain-food for the winter. ;-) From sundstromen at gmail.com Sat Oct 15 16:13:19 2011 From: sundstromen at gmail.com (=?ISO-8859-1?Q?Jan_Sundstr=F6m?=) Date: Sat, 15 Oct 2011 13:13:19 -0700 (PDT) Subject: How do I get curses to work in Python 3.2 on win-64? Message-ID: <3bc2636a-85b5-47bd-9a47-7c9ee16b2a75@w5g2000yqw.googlegroups.com> How do I get curses to work in Python 3.2 on win-64? I'm new to Python and when exploring Python in console I want to use some simple functions for console programming that don't emulate a typewriter terminal but rather a text screen terminal. I want to be able to clear the screen, position the cursor and do unbuffered reading from the keyboard. Also setting different colors for the text and background. That could in Windows be accomplished by the handy WConio (http:// newcenturycomputers.net/projects/wconio.html) which contains just about everything that is needed for a console application to become useful. However I want to accomplish it in Python 3.2 because I lack the experience to build it myself. Now an alternative would be to use some flavor of curses. Although having a plethora of unnecessary functions it has the advantage of existing for different platforms. I'm currently running Python 3.2.2 on win-64 When Python is installed there is a Python32/Lib/curses library. As I understand it this is only a some sort of wrapper for a curses module to be downloaded and installed later?? So I downloaded and installed a curses module I that found and which seemed appropriate: curses-2.2.win-amd64-py3.2.exe from http://www.lfd.uci.edu/~gohlke/pythonlibs/ It installed some stuff directly in Python32/lib/sitepackages. Now when I try in a program to do things like: import curses stdscr = curses.initscr Python complains it can't find curses. However if I do import _curses stdscr = _curses.initscr etc., everything works fine. I shouldn't have to write the underscores though?? How can I fix that? Should I try to find some other version of curses? It seems I haven't yet grasped how to install a Python module? /John From dihedral88888 at googlemail.com Sat Oct 15 16:38:54 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sat, 15 Oct 2011 13:38:54 -0700 (PDT) Subject: Loop through a dict changing keys In-Reply-To: References: Message-ID: <17691715.1416.1318711141838.JavaMail.geo-discussion-forums@prmr13> Is there an FAQ available here? Please check the PYTHON official site and the active state PYTHON examples first, also check the PLEAC comparisons of a lot programming languages first! ----------------------------------------------------------------------------- Nothing is more thrilling to obtain black magics in text books! From dihedral88888 at googlemail.com Sat Oct 15 16:38:54 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sat, 15 Oct 2011 13:38:54 -0700 (PDT) Subject: Loop through a dict changing keys In-Reply-To: References: Message-ID: <17691715.1416.1318711141838.JavaMail.geo-discussion-forums@prmr13> Is there an FAQ available here? Please check the PYTHON official site and the active state PYTHON examples first, also check the PLEAC comparisons of a lot programming languages first! ----------------------------------------------------------------------------- Nothing is more thrilling to obtain black magics in text books! From devplayer at gmail.com Sat Oct 15 17:00:20 2011 From: devplayer at gmail.com (DevPlayer) Date: Sat, 15 Oct 2011 14:00:20 -0700 (PDT) Subject: Can I search a list for a range of values? References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> Message-ID: <073a2e4d-0fd9-4680-9fcb-447b264d19e9@w5g2000yqw.googlegroups.com> On Oct 14, 7:46?pm, Ian Kelly wrote: > On Fri, Oct 14, 2011 at 5:36 PM, Troy S wrote: > (Python 3) > date_range = {d:v for d, v in source_dict.items() if '20110809' <= d > <= '20110911'} > Ian- Hide quoted text - > - Show quoted text - (Python 2.7) supports dictionary comprehensions. I prehaps as early as 2.5. From rurpy at yahoo.com Sat Oct 15 17:22:41 2011 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Sat, 15 Oct 2011 14:22:41 -0700 (PDT) Subject: How to generate error when argument are not supplied and there is no explicit defults (in optparse)? References: Message-ID: On 10/14/2011 03:29 PM, Peng Yu wrote: > Hi, > > The following code doesn't give me error, even I don't specify the > value of filename from the command line arguments. filename gets > 'None'. I checked the manual, but I don't see a way to let > OptionParser fail if an argument's value (which has no default > explicitly specified) is not specified. I may miss some thing in the > manual. Could any expert let me know if there is a way to do so? > Thanks! > > #!/usr/bin/env python > > from optparse import OptionParser > > usage = 'usage: %prog [options] arg1 arg2' > parser = OptionParser(usage=usage) > parser.set_defaults(verbose=True) > parser.add_option('-f', '--filename') > > #(options, args) = parser.parse_args(['-f', 'file.txt']) > (options, args) = parser.parse_args() > > print options.filename You can check it yourself. I find I use a pretty standard pattern with optparse: def main (args, opts): ... def parse_cmdline (): p = OptionParser() p.add_option('-f', '--filename') options, args = parser.parse_args() if not options.filename: p.error ("-f option required") if len (args) != 2: p.error ("Expected exactly 2 arguments") # Other checks can obviously be done here too. return args, options if __name__ == '__main__': args, opts = parse_cmdline() main (args, opts) While one can probably subclass OptionParser or use callbacks to achieve the same end, I find the above approach simple and easy to follow. I also presume you know that you have can optparse produce a usage message by adding 'help' arguments to the add_option() calls? And as was mentioned in another post, argparse in Python 2.7 (or in earlier Pythons by downloading/installing it yourself) can do the checking you want. From devplayer at gmail.com Sat Oct 15 17:31:20 2011 From: devplayer at gmail.com (DevPlayer) Date: Sat, 15 Oct 2011 14:31:20 -0700 (PDT) Subject: I am a newbie for python and try to understand class Inheritance. References: Message-ID: On Oct 15, 2:20?am, aaabb... at hotmail.com wrote: > Test.py > ----------- > #!/usr/bin/python > > from my_lib import my_function > > class MyClass(my_function): # usually class names start capital > > """We know you're not forgetting to document.""" > > ? ? def __init__(self, name): > super(MyClass, self).__init__(name) > ? ? ? ? # self.name = name automatically added from base class > > ? ? def test(self): > ? ? ? ? print "this is a test", self.name > > def __call__(self, name): > > # if you are subclassing something named my_function > # then other Python coders -might- expect the subclass > # to behave like a function. > > print "Now this class acts like a function %s" % name > print "because it has a def __call__(self,...)." > return True # not needed but because functions do stuff > > If __name__ == '__main__': > ? ? myclass_instance = MyClass('David') # confusing isn't it to subclass something called my_function > ================================================ > my_lib.py > --------- > class my_function(object): > > """This class acts like a function.""" > > def __init__(self, name): > self.name = SpamSpamAndEggs(name) > > def __call__(self): > # do stuff > return self.name.upper() > ... > > -david I editted your code to something closer to what is expected. Not a law but just a recommendation. Also defining a class my_function(..): --might-- be confusing to others as in Python there are things called functions that look like this: def my_function(name): print "Hi %s" % name note the use of "def" and not "class" Of course if you are making classes that represent custom application "functions" verse Python "functions" then yeah, calling your class: class MyFunction(object): ... makes sense I included the __doc__ "You are documenting" stuff because you seem so new. Otherwise when posting here they're not expected to be in these posts. From devplayer at gmail.com Sat Oct 15 18:04:24 2011 From: devplayer at gmail.com (DevPlayer) Date: Sat, 15 Oct 2011 15:04:24 -0700 (PDT) Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> Message-ID: <4acd4e59-cf83-47f5-ac6c-ee0cbec8aa34@u13g2000vbx.googlegroups.com> On Oct 8, 8:41?am, Alain Ketterlin wrote: > candide writes: > > Python provides > > > ? ? -- the not operator, meaning logical negation > > ? ? -- the in operator, meaning membership > > > On the other hand, Python provides the not in operator meaning > > non-membership. However, it seems we can reformulate any "not in" > > expression using only "not" and "in" operation. > > Sure, but note that you can also reformulate != using not and ==, < > using not and >=, etc. Operators like "not in" and "is not" should > really be considered single tokens, even though they seem to use "not". > And I think they are really convenient. > > -- Alain. 1. I thought "x not in y" was later added as syntax sugar for "not x in y" meaning they used the same set of tokens. (Too lazy to check the actual tokens) 2. "x not in y" ==>> (True if y.__call__(x) else False) class Y(object): def __contains__(self, x): for item in y: if x == y: return True return False And if you wanted "x not in y" to be a different token you'd have to ADD class Y(object): def __not_contained__(self, x): for item in self: if x == y: return False return True AND with __not_contained__() you'd always have to iterate the entire sequence to make sure even the last item doesn't match. SO with one token "x not in y" you DON'T have to itterate through the entire sequence thus it is more effiecient. From gshanemiller at verizon.net Sat Oct 15 19:00:17 2011 From: gshanemiller at verizon.net (Shane) Date: Sat, 15 Oct 2011 16:00:17 -0700 (PDT) Subject: type(), modules: clarification please Message-ID: <598dc382-bbc0-49e1-ad30-ff6b61b977f6@w5g2000yqw.googlegroups.com> Hi, When one writes, > className='Employee' > baseClasses = ... > dictionary = { ... } > newClass = type( className, , dictionary) in what module does newClass belong? If it's the current module what code do I run to print out the name of that module in a.b.c... form? Related: If I want to make `newClass' into a module called, say, a.b.c.d.e how do I do that? This doesn't work: > className='a.b.c.d.e.Employee' > newClass = type( className, , dictionary) As far as I know the correct procedure involves three steps: > import a.b.c.d.e as targetModule > newClass = type( className, , dictionary) > setattr( targetModule, 'newClassInTarget', newClass ) > obj = targetModule.newClassInTarget() I am not sure if newClass remains a valid type in whatever module it was created in. Final question. If, as an academic exercise I wanted to recursively dump all the classes in a module (and its sub-modules) would I do this? [I use some pseudo code]: def dump( namespace ): for i in dir(namespace): if i is a class: print i elif i is a module: dump(i) dump( ) Thank you From clp2 at rebertia.com Sat Oct 15 19:18:46 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 15 Oct 2011 16:18:46 -0700 Subject: type(), modules: clarification please In-Reply-To: <598dc382-bbc0-49e1-ad30-ff6b61b977f6@w5g2000yqw.googlegroups.com> References: <598dc382-bbc0-49e1-ad30-ff6b61b977f6@w5g2000yqw.googlegroups.com> Message-ID: On Sat, Oct 15, 2011 at 4:00 PM, Shane wrote: > Hi, > > When one writes, > >> className='Employee' >> baseClasses = ... >> dictionary = { ... } >> newClass = type( className, , dictionary) > > in what module does newClass belong? If it's the current module That does seem to be the case. > what code > do I run to print out the name of that module in a.b.c... form? newClass.__module__ is a string containing the (apparently) qualified name of the module wherein newClass was defined. > Final question. If, as an academic exercise I wanted to recursively > dump > all the classes in a module (and its sub-modules) would I do this? [I > use > some pseudo code]: > > def dump( namespace ): > ? ? ? for i in dir(namespace): > ? ? ? ? ? ? ?if i is a class: > ? ? ? ? ? ? ? ? ? print i > ? ? ? ? ? ? ?elif i is a module: > ? ? ? ? ? ? ? ? ? dump(i) > > dump( ) Pretty much, though `i` is just a string, so you'll need to use getattr() to get the actual value of the corresponding variable. You may also need to watch out for circular references so that your function doesn't get stuck in an infinite loop. FYI, `inspect` module had functions to test for class-ness and module-ness. http://docs.python.org/library/inspect.html Cheers, Chris -- http://rebertia.com From pod at internode.on.net Sat Oct 15 19:53:32 2011 From: pod at internode.on.net (PoD) Date: 15 Oct 2011 23:53:32 GMT Subject: Loop through a dict changing keys References: Message-ID: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Oct 2011 11:00:17 -0700, Gnarlodious wrote: > What is the best way (Python 3) to loop through dict keys, examine the > string, change them if needed, and save the changes to the same dict? > > So for input like this: > {'Mobile': 'string', 'context': '', 'order': '7', > 'time': 'True'} > > I want to booleanize 'True', turn '7' into an integer, escape > '', and ignore 'string'. > > Any elegant Python way to do this? > > -- Gnarlie How about data = { 'Mobile': 'string', 'context': '', 'order': '7', 'time': 'True'} types={'Mobile':str,'context':str,'order':int,'time':bool} for k,v in data.items(): data[k] = types[k](v) From tdsimpson at gmail.com Sat Oct 15 21:48:57 2011 From: tdsimpson at gmail.com (Troy S) Date: Sat, 15 Oct 2011 21:48:57 -0400 Subject: Reading a file into a data structure.... In-Reply-To: References: <763d6391-fc4d-4b47-b0c3-d3ad16e0fc38@gy7g2000vbb.googlegroups.com> Message-ID: Chris, Thanks for the help. I am using the powerball numbers from this text file downloaded from the site. http://www.powerball.com/powerball/winnums-text.txt The first row is the header/fieldnames and the file starts off like this: Draw Date WB1 WB2 WB3 WB4 WB5 PB PP 10/12/2011 43 10 12 23 47 18 3 10/08/2011 35 03 37 27 45 31 5 10/05/2011 46 07 43 54 20 17 4 10/01/2011 27 43 12 23 01 31 3 09/28/2011 41 51 30 50 53 08 2 09/24/2011 27 12 03 04 44 26 5 09/21/2011 47 52 55 48 12 13 4 The testing of a digit was used to skip the first row only. I'm stil dissecting your Python code to better understand the use of collection, namedtuples, etc. I have not found many examples/descriptions yet about collections, namedtuples, etc. I don't quite understand them that much. Do you know of a reference that can break this stuff down better for me? The couple of books that I have on Python do not go into collection, namedtuples, etc that much. Thanks, On Sat, Oct 15, 2011 at 12:47 AM, Chris Rebert wrote: > On Fri, Oct 14, 2011 at 7:59 PM, MrPink wrote: >> This is what I have been able to accomplish: >> >> def isInt(s): >> ? ?try: >> ? ? ? ?i = int(s) >> ? ? ? ?return True >> ? ?except ValueError: >> ? ? ? ?return False >> >> f = open("powerball.txt", "r") >> lines = f.readlines() >> f.close() >> >> dDrawings = {} >> for line in lines: >> ? ?if isInt(line[0]): >> ? ? ? ?t = line.split() >> ? ? ? ?d = t[0] >> ? ? ? ?month,day,year = t[0].split("/") >> ? ? ? ?i = int(year + month + day) >> ? ? ? ?wb = t[1:6] >> ? ? ? ?wb.sort() >> ? ? ? ?pb = t[6] >> ? ? ? ?r = {'d':d,'wb':wb,'pb':pb} >> ? ? ? ?dDrawings[i] = r >> >> The dictionary dDrawings contains records like this: >> dDrawings[19971101] >> {'pb': '20', 'd': '11/01/1997', 'wb': ['22', '25', '28', '33', '37']} >> >> I am now able to search for ticket in a date range. >> keys = dDrawings.keys() >> b = [key for key in keys if 20110909 <= key <= 20111212] >> >> How would I search for matching wb (White Balls) in the drawings? >> >> Is there a better way to organize the data so that it will be flexible >> enough for different types of searches? >> Search by date range, search by pb, search by wb matches, etc. >> >> I hope this all makes sense. > > from datetime import datetime > from collections import namedtuple, defaultdict > # for efficient searching by date: import bisect > > DATE_FORMAT = "%m/%d/%Y" > Ticket = namedtuple('Ticket', "white_balls powerball date".split()) > > powerball2ticket = defaultdict(set) > whiteball2ticket = defaultdict(set) > tickets_by_date = [] > > with open("powerball.txt", "r") as f: > ? ?for line in f: > ? ? ? ?if not line[0].isdigit(): > ? ? ? ? ? ?# what are these other lines anyway? > ? ? ? ? ? ?continue # skip such lines > > ? ? ? ?fields = line.split() > > ? ? ? ?date = datetime.strptime(fields[0], DATE_FORMAT).date() > ? ? ? ?white_balls = frozenset(int(num_str) for num_str in fields[1:6]) > ? ? ? ?powerball = int(fields[6]) > ? ? ? ?ticket = Ticket(white_balls, powerball, date) > > ? ? ? ?powerball2ticket[powerball].add(ticket) > ? ? ? ?for ball in white_balls: > ? ? ? ? ? ?whiteball2ticket[ball].add(ticket) > ? ? ? ?tickets_by_date.append(ticket) > > tickets_by_date.sort(key=lambda ticket: ticket.date) > > print(powerball2ticket[7]) # all tickets with a 7 powerball > print(whiteball2ticket[3]) # all tickets with a non-power 3 ball > > > Cheers, > Chris > -- > http://rebertia.com > -- Troy S From tdsimpson at gmail.com Sat Oct 15 22:18:18 2011 From: tdsimpson at gmail.com (MrPink) Date: Sat, 15 Oct 2011 19:18:18 -0700 (PDT) Subject: Reading a file into a data structure.... References: <763d6391-fc4d-4b47-b0c3-d3ad16e0fc38@gy7g2000vbb.googlegroups.com> Message-ID: I did not understand what a tuple was. So it was very hard for me to understand what a namedtuple was and follow the code. Then I looked up the word at dictionary.com and got this: http://dictionary.reference.com/browse/tuple tuple: computing a row of values in a relational database Now I understand a little better what a tuple is and can follow the code better. A namedtuple seems like a dictionary type. I'll need to read up on the difference between the two. Thanks again. On Oct 15, 12:47?am, Chris Rebert wrote: > On Fri, Oct 14, 2011 at 7:59 PM,MrPink wrote: > > This is what I have been able to accomplish: > > > def isInt(s): > > ? ?try: > > ? ? ? ?i = int(s) > > ? ? ? ?return True > > ? ?except ValueError: > > ? ? ? ?return False > > > f = open("powerball.txt", "r") > > lines = f.readlines() > > f.close() > > > dDrawings = {} > > for line in lines: > > ? ?if isInt(line[0]): > > ? ? ? ?t = line.split() > > ? ? ? ?d = t[0] > > ? ? ? ?month,day,year = t[0].split("/") > > ? ? ? ?i = int(year + month + day) > > ? ? ? ?wb = t[1:6] > > ? ? ? ?wb.sort() > > ? ? ? ?pb = t[6] > > ? ? ? ?r = {'d':d,'wb':wb,'pb':pb} > > ? ? ? ?dDrawings[i] = r > > > The dictionary dDrawings contains records like this: > > dDrawings[19971101] > > {'pb': '20', 'd': '11/01/1997', 'wb': ['22', '25', '28', '33', '37']} > > > I am now able to search for ticket in a date range. > > keys = dDrawings.keys() > > b = [key for key in keys if 20110909 <= key <= 20111212] > > > How would I search for matching wb (White Balls) in the drawings? > > > Is there a better way to organize the data so that it will be flexible > > enough for different types of searches? > > Search by date range, search by pb, search by wb matches, etc. > > > I hope this all makes sense. > > from datetime import datetime > from collections import namedtuple, defaultdict > # for efficient searching by date: import bisect > > DATE_FORMAT = "%m/%d/%Y" > Ticket = namedtuple('Ticket', "white_balls powerball date".split()) > > powerball2ticket = defaultdict(set) > whiteball2ticket = defaultdict(set) > tickets_by_date = [] > > with open("powerball.txt", "r") as f: > ? ? for line in f: > ? ? ? ? if not line[0].isdigit(): > ? ? ? ? ? ? # what are these other lines anyway? > ? ? ? ? ? ? continue # skip such lines > > ? ? ? ? fields = line.split() > > ? ? ? ? date = datetime.strptime(fields[0], DATE_FORMAT).date() > ? ? ? ? white_balls = frozenset(int(num_str) for num_str in fields[1:6]) > ? ? ? ? powerball = int(fields[6]) > ? ? ? ? ticket = Ticket(white_balls, powerball, date) > > ? ? ? ? powerball2ticket[powerball].add(ticket) > ? ? ? ? for ball in white_balls: > ? ? ? ? ? ? whiteball2ticket[ball].add(ticket) > ? ? ? ? tickets_by_date.append(ticket) > > tickets_by_date.sort(key=lambda ticket: ticket.date) > > print(powerball2ticket[7]) # all tickets with a 7 powerball > print(whiteball2ticket[3]) # all tickets with a non-power 3 ball > > Cheers, > Chris > --http://rebertia.com From pavlovevidence at gmail.com Sat Oct 15 23:29:40 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 15 Oct 2011 20:29:40 -0700 (PDT) Subject: argparse zero-length switch In-Reply-To: References: <17016857.666.1318572326692.JavaMail.geo-discussion-forums@prmi2> Message-ID: <7643428.719.1318735780945.JavaMail.geo-discussion-forums@prgv7> On Friday, October 14, 2011 12:41:26 AM UTC-7, Peter Otten wrote: > Carl Banks wrote: > > > Is it possible to specify a zero-length switch? Here's what I mean. > > > > I have a use case where some users would have to enter a section name on > > the command line almost every time, whereas other users (the ones using > > only one section) will never have to enter the section name. I don't want > > to burden users with only one "section" to always enter the section name > > as a required argument, but I also want to make it as convenient as > > possible to enter the section name for those who need to. > > > > My thought, on the thinking that practicality beats purity, was to create > > a zero-length switch using a different prefix character (say, @) to > > indicate the section name. So instead of typing this: > > > > sp subcommand -s abc foo bar > > > > they could type this: > > > > sp subcommand @abc foo bar > > > > Admittedly a small benefit. I tried the following but argparse doesn't > > seem to do what I'd hoped: > > > > p = argparse.ArgumentParser(prefix_chars='-@') > > p.add_argument('@',type=str,dest='section') > > ar = p.parse_args(['@abc']) > > > > This throws an exception claiming unrecognized arguments. > > > > Is there a way (that's not a hack) to do this? Since the current behavior > > of the above code seems to do nothing useful, it could be added to > > argparse with very low risk of backwards incompatibility. > > If the number of positional arguments is otherwise fixed you could make > section a positional argument with nargs="?" The positional arguments aren't fixed, otherwise I would have done it that way. I ended up deciding to prescan the command line for arguments starting with @, and that actually has some benefits over doing it with argparse. (One little surprise is if you pass it something like "-x @abc foo", where foo is the argument of -x.) I don't really care for or agree with Steven and Ben Finney's foolish consistency. I already weighed it against the benefits of consistency, and decided that this parameter was easily important enough to warrant special treatment. It's actually a good thing for this parameter to look different from other switches; it marks it as specially important. Carl Banks From pavlovevidence at gmail.com Sat Oct 15 23:32:18 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 15 Oct 2011 20:32:18 -0700 (PDT) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: <7c0baafc-70df-46ec-8482-8bbf267c8231@t38g2000prg.googlegroups.com> References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> <7c0baafc-70df-46ec-8482-8bbf267c8231@t38g2000prg.googlegroups.com> Message-ID: <6575958.1562.1318735938474.JavaMail.geo-discussion-forums@prmr13> On Friday, October 14, 2011 6:23:15 PM UTC-7, alex23 wrote: > On Oct 14, 4:56?pm, Carl Banks > wrote: > > But you can see that, fully realized, syntax like that can do much more > > than can be done with library code. > > Well sure, but imaginary syntax can do _anything_. That doesn't mean > it's possible within CPython. Hey, thanks for backing me up on that sentiment. :) Carl Banks From rosuav at gmail.com Sat Oct 15 23:45:33 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Oct 2011 14:45:33 +1100 Subject: argparse zero-length switch In-Reply-To: <7643428.719.1318735780945.JavaMail.geo-discussion-forums@prgv7> References: <17016857.666.1318572326692.JavaMail.geo-discussion-forums@prmi2> <7643428.719.1318735780945.JavaMail.geo-discussion-forums@prgv7> Message-ID: On Sun, Oct 16, 2011 at 2:29 PM, Carl Banks wrote: > I don't really care for or agree with Steven and Ben Finney's foolish consistency. ?I already weighed it against the benefits of consistency, and decided that this parameter was easily important enough to warrant special treatment. ?It's actually a good thing for this parameter to look different from other switches; it marks it as specially important. I'll weigh in then - in favour of the "foolish" consistency. It's a far more valuable feature than you might imagine. Think how much time your users (even yourself) are going to spend using your program; now think how much time those same people will spend using other programs. You can't fight something that's orders of magnitude bigger than you, so what you'll be doing is creating a special-case that has to be kept in the user's mind. You'll also run into trouble if anyone has a file name that begins @; this situation already exists, but I think most people know not to create a file called "-rf" (and even then, most Unix programs accept "--" to mean "end of options, the next thing is a filename"). Do what everyone else does. You'll thank yourself for it in a year or so. ChrisA From cjgohlke at gmail.com Sun Oct 16 00:59:04 2011 From: cjgohlke at gmail.com (Christoph Gohlke) Date: Sat, 15 Oct 2011 21:59:04 -0700 (PDT) Subject: How do I get curses to work in Python 3.2 on win-64? References: <3bc2636a-85b5-47bd-9a47-7c9ee16b2a75@w5g2000yqw.googlegroups.com> Message-ID: <57034ebb-5278-4a48-9e12-4e068eda820c@v8g2000pro.googlegroups.com> On Oct 15, 1:13?pm, Jan Sundstr?m wrote: > How do I get curses to work in Python 3.2 on win-64? > > I'm new to Python and when exploring Python in console I want to use > some > simple functions for console programming that don't emulate a > typewriter > terminal but rather a text screen terminal. I want to be able to clear > the screen, position the cursor > and do unbuffered reading from the keyboard. Also setting different > colors for the text and background. > > That could in Windows be accomplished by the handy WConio (http:// > newcenturycomputers.net/projects/wconio.html) > which contains just about everything that is needed for a console > application to become useful. > > However I want to accomplish it in Python 3.2 because I lack the > experience to build it myself. Now an alternative would > be to use some flavor of curses. Although having a plethora of > unnecessary functions it has the advantage of > existing for different platforms. > > I'm currently running Python 3.2.2 on win-64 > When Python is installed there is a Python32/Lib/curses library. As I > understand it this is only a some sort of > wrapper for a curses module to be downloaded and installed later?? > > So I downloaded and installed a curses module I that found and which > seemed appropriate: > > curses-2.2.win-amd64-py3.2.exe > > from > > http://www.lfd.uci.edu/~gohlke/pythonlibs/ > > It installed some stuff directly in Python32/lib/sitepackages. > > Now when I try in a program to do things like: > > import curses > stdscr = curses.initscr > > Python complains it can't find curses. However if I do > > import _curses > stdscr = _curses.initscr > > etc., everything works fine. I shouldn't have to write the underscores > though?? > How can I fix that? > Should I try to find some other version of curses? > > It seems I haven't yet grasped how to install a Python module? > > /John `import curses` should work. What exactly is the error message? Does `import curses` work outside your program/program directory? The curses package is part of the standard library and usually installed in Python32\Lib\curses. On Windows the _curses.pyd files is missing in the standard distribution. curses-2.2.win-amd64-py3.2.exe installs the missing _curses.pyd file into Lib/site-packages. From cjgohlke at gmail.com Sun Oct 16 01:05:17 2011 From: cjgohlke at gmail.com (Christoph Gohlke) Date: Sat, 15 Oct 2011 22:05:17 -0700 (PDT) Subject: SciPy/NumPy: read, write images using Python3 References: <9ca46882-acb1-4a23-8b6b-69539ff37d08@n15g2000vbn.googlegroups.com> Message-ID: On Oct 9, 8:43?am, thegripper wrote: > In SciPy / NumPy, the primary way to read and write images is PIL. But > PIL does not yet support Python3. Is there some good way to read, > write, and resize images in a NumPy and Python3 environment? Try Scikits.image . It uses a plugin system to read/write images to/from numpy arrays via FreeImage, PyQt, FITS, GDAL, etc. Other options: Unofficial PIL ports, e.g. or PythonMagick GDAL for raster geospatial data formats PyGame 1.9.2pre , uses SDL_image PyQt 4 From steve+comp.lang.python at pearwood.info Sun Oct 16 01:05:25 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Oct 2011 05:05:25 GMT Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4acd4e59-cf83-47f5-ac6c-ee0cbec8aa34@u13g2000vbx.googlegroups.com> Message-ID: <4e9a6614$0$29971$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Oct 2011 15:04:24 -0700, DevPlayer wrote: > 1. I thought "x not in y" was later added as syntax sugar for "not x in > y" > meaning they used the same set of tokens. (Too lazy to check the actual > tokens) Whether the compiler has a special token for "not in" is irrelevant. Perhaps it uses one token, or two, or none at all because a pre-processor changes "x not in y" to "not x in y". That's an implementation detail. What's important is whether it is valid syntax or not, and how it is implemented. As it turns out, the Python compiler does not distinguish the two forms: >>> from dis import dis >>> dis(compile('x not in y', '', 'single')) 1 0 LOAD_NAME 0 (x) 3 LOAD_NAME 1 (y) 6 COMPARE_OP 7 (not in) 9 PRINT_EXPR 10 LOAD_CONST 0 (None) 13 RETURN_VALUE >>> dis(compile('not x in y', '', 'single')) 1 0 LOAD_NAME 0 (x) 3 LOAD_NAME 1 (y) 6 COMPARE_OP 7 (not in) 9 PRINT_EXPR 10 LOAD_CONST 0 (None) 13 RETURN_VALUE Also for what it is worth, "x not in y" goes back to at least Python 1.5, and possibly even older. (I don't have any older versions available to test.) > 2. "x not in y" ==>> (True if y.__call__(x) else False) y.__call__ is irrelevant. But for what it's worth: (1) Instead of writing "y.__call__(x)", write "y(x)" (2) Instead of writing "True if blah else False", write "bool(blah)". > class Y(object): > def __contains__(self, x): > for item in y: > if x == y: > return True > return False You don't have to define a __contains__ method if you just want to test each item sequentially. All you need is to obey the sequence protocol and define a __getitem__ that works in the conventional way: >>> class Test: ... def __init__(self, args): ... self._data = list(args) ... def __getitem__(self, i): ... return self._data[i] ... >>> t = Test("abcde") >>> "c" in t True >>> "x" in t False Defining a specialist __contains__ method is only necessary for non- sequences, or if you have some fast method for testing whether an item is in the object quickly. If all you do is test each element one at a time, in numeric order, don't bother writing __contains__. > And if you wanted "x not in y" to be a different token you'd have to ADD Tokens are irrelevant. "x not in y" is defined to be the same as "not x in y" no matter what. You can't define "not in" to do something completely different. > class Y(object): > def __not_contained__(self, x): > for item in self: > if x == y: > return False > return True > > AND with __not_contained__() you'd always have to iterate the entire > sequence to make sure even the last item doesn't match. > > SO with one token "x not in y" you DON'T have to itterate through the > entire sequence thus it is more effiecient. That's not correct. -- Steven From steve+comp.lang.python at pearwood.info Sun Oct 16 01:14:45 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Oct 2011 05:14:45 GMT Subject: argparse zero-length switch References: <17016857.666.1318572326692.JavaMail.geo-discussion-forums@prmi2> <7643428.719.1318735780945.JavaMail.geo-discussion-forums@prgv7> Message-ID: <4e9a6845$0$29971$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Oct 2011 20:29:40 -0700, Carl Banks wrote: > I don't really care for or agree with Steven and Ben Finney's foolish > consistency. I already weighed it against the benefits of consistency, > and decided that this parameter was easily important enough to warrant > special treatment. It's actually a good thing for this parameter to > look different from other switches; it marks it as specially important. It seems to me that a parameter hardly deserves to be called "specially important" if it is optional and the user can leave it out. "Specially unimportant" is probably a better description. At the end of the day, your claimed motivation for inventing this anti- mnemonic was, and I quote, "to make it as convenient as possible to enter the section name". If you honestly think that typing shift-2 is more convenient than typing -s then go right ahead and do what you like. No skin off my nose. -- Steven From greg.ewing at canterbury.ac.nz Sun Oct 16 01:27:01 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 16 Oct 2011 18:27:01 +1300 Subject: argparse zero-length switch In-Reply-To: <4e997487$0$29979$c3e8da3$5496439d@news.astraweb.com> References: <17016857.666.1318572326692.JavaMail.geo-discussion-forums@prmi2> <4e997487$0$29979$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9fv895F3meU1@mid.individual.net> Steven D'Aprano wrote: > And it isn't like you gain any extra clarity or expressiveness, or even a > major saving of typing! "-s" vs "@". You don't even save a key stroke: "@" > requires two keystrokes, just as "-s" does. Also keep in mind that not all keystrokes are equal. Someone who uses all their fingers probably finds "-s" faster and easier to type than "@". I certainly do. -- Greg From joncle at googlemail.com Sun Oct 16 03:18:40 2011 From: joncle at googlemail.com (Jon Clements) Date: Sun, 16 Oct 2011 00:18:40 -0700 (PDT) Subject: Loop through a dict changing keys References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> Message-ID: <3b79994f-8891-4ab8-bd23-f6fb4e063155@e4g2000vbw.googlegroups.com> On Oct 16, 12:53?am, PoD wrote: > On Sat, 15 Oct 2011 11:00:17 -0700, Gnarlodious wrote: > > What is the best way (Python 3) to loop through dict keys, examine the > > string, change them if needed, and save the changes to the same dict? > > > So for input like this: > > {'Mobile': 'string', 'context': '', 'order': '7', > > 'time': 'True'} > > > I want to booleanize 'True', turn '7' into an integer, escape > > '', and ignore 'string'. > > > Any elegant Python way to do this? > > > -- Gnarlie > > How about > > data = { > ? ? 'Mobile': 'string', > ? ? 'context': '', > ? ? 'order': '7', > ? ? 'time': 'True'} > types={'Mobile':str,'context':str,'order':int,'time':bool} > > for k,v in data.items(): > ? ? data[k] = types[k](v) Bit of nit-picking, but: >>> bool('True') True >>> bool('False') True >>> bool('') False From masood.524 at gmail.com Sun Oct 16 04:03:51 2011 From: masood.524 at gmail.com (masood shaik) Date: Sun, 16 Oct 2011 01:03:51 -0700 (PDT) Subject: callling python function in c Message-ID: <8ca2fc3e-a3be-49c4-8107-a47385bc0911@w26g2000pro.googlegroups.com> Hi I am trying to call python function from c code.The following program i got from the web source while i am trying to run this program it throws an segmentation fault.I am working on Ubuntu 10.10 version.Can anyone guide me please The following program call_function.c // call_function.c - A sample of calling python functions from C code // #include #include int main(int argc, char *argv[]) { int i; PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue; if (argc < 3) { printf("Usage: exe_name python_source function_name\n"); return 1; } // Initialize the Python Interpreter Py_Initialize(); // Build the name object pName = PyString_FromString(argv[1]); // Load the module object pModule = PyImport_Import(pName); // pDict is a borrowed reference pDict = PyModule_GetDict(pModule); // pFunc is also a borrowed reference pFunc = PyDict_GetItemString(pDict, argv[2]); if (PyCallable_Check(pFunc)) { // Prepare the argument list for the call if( argc > 3 ) { pArgs = PyTuple_New(argc - 3); for (i = 0; i < argc - 3; i++) { pValue = PyInt_FromLong(atoi(argv[i + 3])); if (!pValue) { PyErr_Print(); return 1; } PyTuple_SetItem(pArgs, i, pValue); } pValue = PyObject_CallObject(pFunc, pArgs); if (pArgs != NULL) { Py_DECREF(pArgs); } } else { pValue = PyObject_CallObject(pFunc, NULL); } if (pValue != NULL) { printf("Return of call : %ld\n", PyInt_AsLong(pValue)); Py_DECREF(pValue); } else { PyErr_Print(); } } else { PyErr_Print(); } // Clean up Py_DECREF(pModule); Py_DECREF(pName); // Finish the Python Interpreter Py_Finalize(); return 0; } py_function.py '''py_function.py - Python source designed to demonstrate the use of python embedding''' def multiply(): c = 12345*6789 print 'The result of 12345 x 6789 :', c return c def multiply1(a,b): c = a*b print 'The result of', a, 'x', b, ':', c return c Regards Masood From ian.g.kelly at gmail.com Sun Oct 16 06:15:17 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 16 Oct 2011 04:15:17 -0600 Subject: Reading a file into a data structure.... In-Reply-To: References: <763d6391-fc4d-4b47-b0c3-d3ad16e0fc38@gy7g2000vbb.googlegroups.com> Message-ID: On Sat, Oct 15, 2011 at 8:18 PM, MrPink wrote: > I did not understand what a tuple was. > So it was very hard for me to understand what a namedtuple was and > follow the code. > Then I looked up the word at dictionary.com and got this: > http://dictionary.reference.com/browse/tuple > > tuple: ?computing ?a row of values in a relational database > > Now I understand a little better what a tuple is and can follow the > code better. Python tuples do not have anything to do with relational databases. You would get a better introduction from Wikipedia: http://en.wikipedia.org/wiki/Tuple In Python, tuples are nothing more than immutable sequences, as opposed to lists, which are mutable sequences. Another way of characterizing the difference between lists and tuples is in how they are typically used. A list is typically used for a homogeneous (meaning all elements are treated in the same way) sequence containing an arbitrary number of unrelated objects. A tuple is typically used for a heterogeneous sequence of a certain length. For example, a tuple might be expected to contain exactly two strings and an int that are related in some fashion. > A namedtuple seems like a dictionary type. ?I'll need to read up on > the difference between the two. A namedtuple is a tuple subclass where each of the elements the tuple is expected to contain has been given a specific name for ease of reference. The names are essentially aliases for numerical indices. It differs from a dictionary in that it is ordered and only contains elements with specific names (and always contains those elements), whereas a dictionary contains arbitrary key-value pairs. From pod at internode.on.net Sun Oct 16 07:12:31 2011 From: pod at internode.on.net (PoD) Date: 16 Oct 2011 11:12:31 GMT Subject: Loop through a dict changing keys References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <3b79994f-8891-4ab8-bd23-f6fb4e063155@e4g2000vbw.googlegroups.com> Message-ID: <4e9abc1f$0$14058$c3e8da3$76491128@news.astraweb.com> On Sun, 16 Oct 2011 00:18:40 -0700, Jon Clements wrote: > On Oct 16, 12:53?am, PoD wrote: >> On Sat, 15 Oct 2011 11:00:17 -0700, Gnarlodious wrote: >> > What is the best way (Python 3) to loop through dict keys, examine >> > the string, change them if needed, and save the changes to the same >> > dict? >> >> > So for input like this: >> > {'Mobile': 'string', 'context': '', 'order': '7', >> > 'time': 'True'} >> >> > I want to booleanize 'True', turn '7' into an integer, escape >> > '', and ignore 'string'. >> >> > Any elegant Python way to do this? >> >> > -- Gnarlie >> >> How about >> >> data = { >> ? ? 'Mobile': 'string', >> ? ? 'context': '', >> ? ? 'order': '7', >> ? ? 'time': 'True'} >> types={'Mobile':str,'context':str,'order':int,'time':bool} >> >> for k,v in data.items(): >> ? ? data[k] = types[k](v) > > Bit of nit-picking, but: > >>>> bool('True') > True >>>> bool('False') > True >>>> bool('') > False Oops :) Brain fade. From patlnorr at aim.com Sun Oct 16 10:00:16 2011 From: patlnorr at aim.com (54321) Date: Sun, 16 Oct 2011 07:00:16 -0700 (PDT) Subject: INSTANT PLAY (FLASH) CASINO GAMES Message-ID: <7b1cd41f-9474-4ebf-87d6-97643b391035@g16g2000yqi.googlegroups.com> INSTANT PLAY (FLASH) CASINO GAMES Bettwo.com offers the most prominent casino games including Blackjack, Baccarat, Poker, Craps, Video Poker, Roulette, Slots and many more. Our team of developers strives to introduce exciting new games every month to ensure our customers are playing the most advanced online casino games in the world. Bettwo.com's software was developed and is maintained by RealTime Gaming, one of the leading online gaming software companies in the world. RealTime Gaming's Random Number Generator (RNG) has been tested and certified by Technical Systems Testing, guaranteeing you absolute fairness in every game. Bettwo.com provides the internet's best instant play online casino action. Play our exciting casino games directly in your browser with no download needed! The Flash-based suite of casino games includes a wide selection to choose from, all featuring remarkable graphics combined with smooth, exciting gameplay. Downloading the software to your PC, as opposed to web-based play in your browser, makes the games much quicker and more stable, since all the casino graphics and multimedia effects are already installed on your computer, and US players are welcome - BetTwo.com. http://www.bettwo.com/ Company name: BetTwo.com From nvidhya01 at gmail.com Sun Oct 16 10:04:52 2011 From: nvidhya01 at gmail.com (n v) Date: Sun, 16 Oct 2011 07:04:52 -0700 (PDT) Subject: anagonda sucks ))))))))))))))) Message-ID: http://123maza.com/48/silver424/ From emile at fenx.com Sun Oct 16 12:09:50 2011 From: emile at fenx.com (Emile van Sebille) Date: Sun, 16 Oct 2011 09:09:50 -0700 Subject: Help with beginner form using lpthw.web In-Reply-To: <19577343.847.1318691001313.JavaMail.geo-discussion-forums@vbzc27> References: <19577343.847.1318691001313.JavaMail.geo-discussion-forums@vbzc27> Message-ID: On 10/15/2011 8:03 AM pngrv said... > > > Please Use This Form To Request Resources > > >
> Name:
> Project:
> # of Locations:
> # of Engines: >

> Where do you close this tag? >

>
> $def with (request_string) > $if request_string: > I just wanted to say$request_string. > $else: > Hello, world! > > > > And seeing this error: > at /rs_request > invalid syntax Template traceback: File 'templates/rs_request.html', line 30 (rs_request.html, line 30) Emile From sundstromen at gmail.com Sun Oct 16 12:16:44 2011 From: sundstromen at gmail.com (=?ISO-8859-1?Q?Jan_Sundstr=F6m?=) Date: Sun, 16 Oct 2011 09:16:44 -0700 (PDT) Subject: How do I get curses to work in Python 3.2 on win-64? References: <3bc2636a-85b5-47bd-9a47-7c9ee16b2a75@w5g2000yqw.googlegroups.com> <57034ebb-5278-4a48-9e12-4e068eda820c@v8g2000pro.googlegroups.com> Message-ID: On 16 Okt, 06:59, Christoph Gohlke wrote: > On Oct 15, 1:13?pm, Jan Sundstr?m wrote: > > > > `import curses` should work. What exactly is the error message? Does > `import curses` work outside your program/program directory? > > The curses package is part of the standard library and usually > installed in Python32\Lib\curses. On Windows the ?_curses.pyd files is > missing in the standard distribution. curses-2.2.win-amd64-py3.2.exe > installs the missing _curses.pyd file into Lib/site-packages. Thanks for the tip to check in what library it works, that set me on track tofind a silly mistake that I had done. Now everything works fine. But, how come that the Windows distribution for Python doesn't include the _curses.pyd file? From ramapraba2653 at gmail.com Sun Oct 16 12:21:07 2011 From: ramapraba2653 at gmail.com (SUPREME) Date: Sun, 16 Oct 2011 09:21:07 -0700 (PDT) Subject: SEXY HOT PHOTOS & VIDEOS Message-ID: FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html From gnarlodious at gmail.com Sun Oct 16 14:20:49 2011 From: gnarlodious at gmail.com (Gnarlodious) Date: Sun, 16 Oct 2011 11:20:49 -0700 (PDT) Subject: Loop through a dict changing keys References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> Message-ID: <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> On Oct 15, 5:53?pm, PoD wrote: > data = { > ? ? 'Mobile': 'string', > ? ? 'context': '', > ? ? 'order': '7', > ? ? 'time': 'True'} > types={'Mobile':str,'context':str,'order':int,'time':bool} > > for k,v in data.items(): > ? ? data[k] = types[k](v) Thanks for the tip, I didn't know you could do that. I ended up filtering the values the bulky way, but it gives me total control over what internet users feed my program. -- Gnarlie From hobson42 at gmail.com Sun Oct 16 17:35:14 2011 From: hobson42 at gmail.com (Ian) Date: Sun, 16 Oct 2011 22:35:14 +0100 Subject: python.org appears to be down Message-ID: <4E9B4E12.1040209@gmail.com> Hopefully someone who can do something about it will read this. From rosuav at gmail.com Sun Oct 16 17:44:22 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 17 Oct 2011 08:44:22 +1100 Subject: python.org appears to be down In-Reply-To: <4E9B4E12.1040209@gmail.com> References: <4E9B4E12.1040209@gmail.com> Message-ID: On Mon, Oct 17, 2011 at 8:35 AM, Ian wrote: > Hopefully someone who can do something about it will read this. Working for me. What are you seeing as down? ChrisA From gshanemiller at verizon.net Sun Oct 16 19:11:18 2011 From: gshanemiller at verizon.net (Shane) Date: Sun, 16 Oct 2011 16:11:18 -0700 (PDT) Subject: type vs. module (part2) Message-ID: <242f9fff-a607-4435-a317-200282e84377@o19g2000vbk.googlegroups.com> In the following t,t1 are the result of built-in call type() -- the form that takes three arguments. Therefore they are classes. Consider the following output: print type(t) > print id(t) >1234567 print t.__module__ >a.b.t.d print type(t1) > print id(t1) >1234568 print t1.__module__ >a.b.t.d I now have two questions: How does Python allow two classes of the same type as evidenced by identical ``print type()' output and different id outputs? Also, which module is t,t1 actually in? Is it "a.b.f"? Or is it "a.b.t.d". I am totally confused. From steve+comp.lang.python at pearwood.info Sun Oct 16 19:25:48 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Oct 2011 23:25:48 GMT Subject: Loop through a dict changing keys References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> Message-ID: <4e9b67fb$0$29967$c3e8da3$5496439d@news.astraweb.com> On Sun, 16 Oct 2011 11:20:49 -0700, Gnarlodious wrote: > On Oct 15, 5:53?pm, PoD wrote: > >> data = { >> ? ? 'Mobile': 'string', >> ? ? 'context': '', >> ? ? 'order': '7', >> ? ? 'time': 'True'} >> types={'Mobile':str,'context':str,'order':int,'time':bool} >> >> for k,v in data.items(): >> ? ? data[k] = types[k](v) > > Thanks for the tip, I didn't know you could do that. I ended up > filtering the values the bulky way, What is "the bulky way"? > but it gives me total control over > what internet users feed my program. Why does this not fill me with confidence? As Jon Clements has already spotted a major bug in the above: using bool as shown is not correct. Furthermore, converting '' into a string does nothing, since it is already a string. Gnarlodious, it is good that you are concerned about code injection attacks, but defending against them is not simple or easy. I don't intend to sound condescending, but when your response to being shown a simple filter that maps keys to types is to say "I didn't know you could do that", that's a good warning that your Python experience may not be quite up to the job of out-guessing the sort of obscure tricks hostile attackers may use. If you think that defending against malicious code is simple, you should read this blob post: http://tav.espians.com/a-challenge-to-break-python-security.html and the thread which inspired it: http://mail.python.org/pipermail/python-dev/2009-February/086401.html How do you sanitize user input? -- Steven From ganesh at cs.utah.edu Sun Oct 16 19:52:03 2011 From: ganesh at cs.utah.edu (Ganesh Gopalakrishnan) Date: Sun, 16 Oct 2011 17:52:03 -0600 Subject: Equal sets with unequal print and str() representations Message-ID: <4E9B6E23.9050106@cs.utah.edu> This probably is known, but a potential pitfall (was, for me) nevertheless. I suspect it is due to hash collisions between 's3' and 's13' in this case? It happens only rarely, depending on the contents of the set. >>> S1 = {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'} S1 = {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'} >>> S2 = {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'} S2 = {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'} >>> S1 S1 {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'} >>> S2 S2 {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'} >>> S1==S2 S1==S2 True >>> str(S1) str(S1) "{'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'}" >>> str(S2) str(S2) "{'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'}" >>> str(S1) == str(S2) False -- Ganesh From gnarlodious at gmail.com Sun Oct 16 20:41:55 2011 From: gnarlodious at gmail.com (Gnarlodious) Date: Sun, 16 Oct 2011 17:41:55 -0700 (PDT) Subject: Loop through a dict changing keys References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> <4e9b67fb$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: <66deee18-6595-474e-876d-84e1de21baa2@31g2000prt.googlegroups.com> On Oct 16, 5:25?pm, Steven D'Aprano wrote: > How do you sanitize user input? Thanks for your concern. This is what I now have, which merely expands each value into its usable type (unquotes them): # filter each value try: var=int(var) except ValueError: if var in ('False', 'True'): var=eval(var) # extract booleans else: var=cgi.escape(var) This is really no filtering at all, since all CGI variables are written to a dictionary without checking. However, if there is no receiver for the value I should be safe, right? I am also trapping some input at mod_wsgi, like php query strings. And that IP address gets quarantined. If you can suggest what attack words to block I'll thank you for it. I also have a system to reject variables that are not in a list, but waiting to see what the logfiles show before deploying it. -- Gnarlie http://Gnarlodious.com From ian.g.kelly at gmail.com Sun Oct 16 21:17:57 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 16 Oct 2011 19:17:57 -0600 Subject: Equal sets with unequal print and str() representations In-Reply-To: <4E9B6E23.9050106@cs.utah.edu> References: <4E9B6E23.9050106@cs.utah.edu> Message-ID: On Sun, Oct 16, 2011 at 5:52 PM, Ganesh Gopalakrishnan wrote: > This probably is known, but a potential pitfall (was, for me) nevertheless. > I suspect it is due to hash collisions between 's3' and 's13' in this case? > It happens only rarely, depending on the contents of the set. I'm not sure exactly which keys are colliding here, but in general the iteration order of a set (or dict) depends not just on the contents, but also on the order of insertion. And of course the repr depends on the iteration order -- anything consistent would require sorting, which would be O(n log n) and is not even necessarily well-defined. From ben+python at benfinney.id.au Sun Oct 16 22:23:47 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 17 Oct 2011 13:23:47 +1100 Subject: Equal sets with unequal print and str() representations References: Message-ID: <878vokuzik.fsf@benfinney.id.au> Ganesh Gopalakrishnan writes: > This probably is known, but a potential pitfall (was, for me) nevertheless. > I suspect it is due to hash collisions between 's3' and 's13' in this > case? What is the actual problem? What behaviour is occurring that doesn't match your expectation? > >>> S1==S2 > S1==S2 > True > >>> str(S1) > str(S1) > "{'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'}" > >>> str(S2) > str(S2) > "{'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'}" > >>> str(S1) == str(S2) > False Right, that's all correct (though I don't know why some of your expressions are being shown twice). A deliberate property of a set is that its items are unordered. Since sets are unordered, the string representation may show the items in an arbitrary and unpredictable sequence. Don't write any code that depends on a predictable sequence of retrieval from an unordered collection. So what did you expect instead, and what supports that expectation? -- \ ?When we pray to God we must be seeking nothing ? nothing.? | `\ ?Saint Francis of Assisi | _o__) | Ben Finney From gshanemiller at verizon.net Sun Oct 16 22:43:20 2011 From: gshanemiller at verizon.net (Shane) Date: Sun, 16 Oct 2011 19:43:20 -0700 (PDT) Subject: define module in non-standard location? Message-ID: <74a49f0a-a1db-491b-8a66-c6fdcb9a924d@v15g2000vbm.googlegroups.com> Normally if one has a code set under a directory "top_level" like this: top_level: __main__.py a __init__.py b __init__.py then this directory structure is naturally satisfies this line in __main__.py: >import a.b But support, for some stupid reason --- say a.b is user defined code --- that I want to locate modules a and a.b somewhere else under another directory "other_top_level". What would the line "import a.b" in __main__,py be replaced by? Thank you From tjreedy at udel.edu Sun Oct 16 22:47:09 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 16 Oct 2011 22:47:09 -0400 Subject: Equal sets with unequal print and str() representations In-Reply-To: References: <4E9B6E23.9050106@cs.utah.edu> Message-ID: On 10/16/2011 9:17 PM, Ian Kelly wrote: > On Sun, Oct 16, 2011 at 5:52 PM, Ganesh Gopalakrishnan > wrote: >> This probably is known, but a potential pitfall (was, for me) nevertheless. >> I suspect it is due to hash collisions between 's3' and 's13' in this case? >> It happens only rarely, depending on the contents of the set. > > I'm not sure exactly which keys are colliding here, but in general the > iteration order of a set (or dict) depends not just on the contents, > but also on the order of insertion. And of course the repr depends on > the iteration order -- anything consistent would require sorting, > which would be O(n log n) and is not even necessarily well-defined. To put it another way, any dependence on the arbitrary ordering of unordered collections in iteration or displays is a programming error. -- Terry Jan Reedy From steve+comp.lang.python at pearwood.info Sun Oct 16 23:31:44 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Oct 2011 03:31:44 GMT Subject: Loop through a dict changing keys References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> <4e9b67fb$0$29967$c3e8da3$5496439d@news.astraweb.com> <66deee18-6595-474e-876d-84e1de21baa2@31g2000prt.googlegroups.com> Message-ID: <4e9ba19f$0$29992$c3e8da3$5496439d@news.astraweb.com> On Sun, 16 Oct 2011 17:41:55 -0700, Gnarlodious wrote: > On Oct 16, 5:25?pm, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: > >> How do you sanitize user input? > Thanks for your concern. This is what I now have, which merely expands > each value into its usable type (unquotes them): > > # filter each value > try: > var=int(var) Should be safe, although I suppose if an attacker passed (say) five hundred thousand "9" digits, it might take int() a while to generate the long int. Instant DOS attack. A blunt object fix for that is to limit the user input to (say) 500 characters, which should be long enough for any legitimate input string. But that will depend on your application. > except ValueError: > if var in ('False', 'True'): > var=eval(var) # extract booleans Well, that's safe, but slow, and it might encourage some future maintainer to use eval in less safe ways. I'd prefer: try: {'True': True, 'False': False}[var] except KeyError: pass # try something else (To be a little more user-friendly, use var.strip().title() instead of just var.) > else: > var=cgi.escape(var) > > This is really no filtering at all, since all CGI variables are written > to a dictionary without checking. However, if there is no receiver for > the value I should be safe, right? What do you mean "no receiver"? If you mean that you don't pass the values to eval, exec, use them in SQL queries, call external shell scripts, etc., then that seems safe to me. But I'm hardly an expert on security, so don't take my word on it. And it depends on what you end up doing in the CGI script. > I am also trapping some input at mod_wsgi, like php query strings. And > that IP address gets quarantined. If you can suggest what attack words > to block I'll thank you for it. That's the wrong approach. Don't block words in a blacklist. Block everything that doesn't appear in a whitelist. Otherwise you're vulnerable to a blackhat coming up with an attack word that you never thought of. There's one of you and twenty million of them. Guess who has the advantage? -- Steven From wuwei23 at gmail.com Sun Oct 16 23:37:21 2011 From: wuwei23 at gmail.com (alex23) Date: Sun, 16 Oct 2011 20:37:21 -0700 (PDT) Subject: type vs. module (part2) References: <242f9fff-a607-4435-a317-200282e84377@o19g2000vbk.googlegroups.com> Message-ID: <1ac0f1eb-4ee6-4a1a-8306-85085021ca6e@y35g2000pre.googlegroups.com> On Oct 17, 9:11?am, Shane wrote: > I now have two questions: How does Python allow two classes of the > same > type as evidenced by identical ``print type()' output and > different id > outputs? You are looking at the id of two _instances_ of the class, not of the class itself. >>> class Example(object): ... pass ... >>> e1, e2 = Example(), Example() >>> type(e1), type(e2) (, ) >>> id(type(e1)), id(type(e2)) (20882000, 20882000) >>> id(e1), id(e2) (25931760, 25968816) > Also, which module is t,t1 actually in? Is it "a.b.f"? Or is it > "a.b.t.d". Which module did you declare them in? What makes you think they're defined somewhere other than what .__module__ is telling you? My guess is your class is in a.b.f, your instances are created in a.b.t.d, and you've demonstrated very powerfully the value of meaningful names in code. > I am totally confused. And you have the source code. Imagine how we feel. From steve+comp.lang.python at pearwood.info Sun Oct 16 23:55:29 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Oct 2011 03:55:29 GMT Subject: define module in non-standard location? References: <74a49f0a-a1db-491b-8a66-c6fdcb9a924d@v15g2000vbm.googlegroups.com> Message-ID: <4e9ba731$0$29992$c3e8da3$5496439d@news.astraweb.com> On Sun, 16 Oct 2011 19:43:20 -0700, Shane wrote: > Normally if one has a code set under a directory "top_level" like this: > > top_level: > __main__.py > a > __init__.py > b > __init__.py > > then this directory structure is naturally satisfies this line in > __main__.py: > >>import a.b > > But support, for some stupid reason --- say a.b is user defined code --- > that I want > to locate modules a and a.b somewhere else under another directory > "other_top_level". You mean like this? top_level/ __main__.py other_top_level/ a/ __init__.py b/ __init__.py > What would the line "import a.b" in __main__,py be replaced by? Make sure other_top_level is in your PYTHONPATH, and then just use "import a.b" as before. Either use your shell to do something like this: export PYTHONPATH=other_top_level:$PYTHONPATH (that's using bash syntax, other shells may need something different), or in __main__.py do this: import sys sys.path.append(other_top_level) -- Steven From gshanemiller at verizon.net Mon Oct 17 00:38:11 2011 From: gshanemiller at verizon.net (Shane) Date: Sun, 16 Oct 2011 21:38:11 -0700 (PDT) Subject: define module in non-standard location? References: <74a49f0a-a1db-491b-8a66-c6fdcb9a924d@v15g2000vbm.googlegroups.com> <4e9ba731$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Oct 16, 11:55?pm, Steven D'Aprano wrote: > On Sun, 16 Oct 2011 19:43:20 -0700, Shane wrote: > > Normally if one has a code set under a directory "top_level" like this: > > > top_level: > > ? ?__main__.py > > ? ?a > > ? ? ? __init__.py > > ? ? ? b > > ? ? ? ? ?__init__.py > > > then this directory structure is naturally satisfies this line in > > __main__.py: > > >>import a.b > > > But support, for some stupid reason --- say a.b is user defined code --- > > that I want > > to locate modules a and a.b somewhere else under another directory > > "other_top_level". > > You mean like this? > > top_level/ > ? ? __main__.py > other_top_level/ > ? ? a/ > ? ? ? ? __init__.py > ? ? ? ? b/ > ? ? ? ? ? ? __init__.py > > > What would the line "import a.b" in __main__,py be replaced by? > > Make sure other_top_level is in your PYTHONPATH, and then just use > "import a.b" as before. > > Either use your shell to do something like this: > > export PYTHONPATH=other_top_level:$PYTHONPATH > > (that's using bash syntax, other shells may need something different), or > in __main__.py do this: > > import sys > sys.path.append(other_top_level) > > -- > Steven Cheers. Thanks From steve+comp.lang.python at pearwood.info Mon Oct 17 02:32:00 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Oct 2011 06:32:00 GMT Subject: type vs. module (part2) References: <242f9fff-a607-4435-a317-200282e84377@o19g2000vbk.googlegroups.com> Message-ID: <4e9bcbe0$0$29992$c3e8da3$5496439d@news.astraweb.com> On Sun, 16 Oct 2011 16:11:18 -0700, Shane wrote: > In the following t,t1 are the result of built-in call type() -- the form > that takes three arguments. Are you sure about that? Because my explanation below will depend entirely on this alleged fact: that t and t1 themselves are classes, not instances. To be sure (well, *nearly* sure), please print t and t1 and see whether you get something like: print t => or print t => > Therefore they are classes. Consider the following output: > > print type(t) >> > print id(t) >>1234567 > print t.__module__ >>a.b.t.d > > print type(t1) >> > print id(t1) >>1234568 > print t1.__module__ >>a.b.t.d > > I now have two questions: How does Python allow two classes of the same > type as evidenced by identical ``print type()' output and > different id outputs? When you use the class statement, you end up with one class with one name, but that's not a hard rule about classes. It's just a convention. You can have multiple identical classes so long as you assign them to different names. For example: >>> class Spam: # bind a class "Spam" to the global name "Spam" ... pass ... >>> Ham = Spam # bind the class object to another global name >>> >>> class Spam: # and re-use the old name for a new class ... x = 1 ... >>> print Ham, Spam __main__.Spam __main__.Spam What's going on here? The secret is that classes (and functions!) generally have *two* names. The first name is their internal name, the name they report when you print them. The second is the name of the variable (or variables!) they are bound to. Nobody says that they MUST match, although they often do. When you use the class statement, Python's interpreter ensures that you start off with the two names matching, but as you can see from above, they don't necessarily stay matching. But the type() function doesn't enforce that: >>> brie = type('cheese', (), {}) >>> cheddar = type('cheese', (), {}) >>> brie is cheddar False >>> print brie, cheddar Both brie and cheddar know their own name as "cheese", but the names you use to refer to them are different. So, bringing this back to your examples... Both t and t1 are classes, both know their internal name as "F", but they are different classes, as seen by the fact that their IDs are different. > Also, which module is t,t1 actually in? Is it "a.b.f"? Or is it > "a.b.t.d". Since they are two independent classes, it could easily be "both, one for each". -- Steven From steve+comp.lang.python at pearwood.info Mon Oct 17 02:35:19 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Oct 2011 06:35:19 GMT Subject: type vs. module (part2) References: <242f9fff-a607-4435-a317-200282e84377@o19g2000vbk.googlegroups.com> <4e9bcbe0$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e9bcca7$0$29992$c3e8da3$5496439d@news.astraweb.com> On Mon, 17 Oct 2011 06:32:00 +0000, Steven D'Aprano wrote: > So, bringing this back to your examples... > > Both t and t1 are classes, both know their internal name as "F", but > they are different classes, as seen by the fact that their IDs are > different. Oops, no, sorry, a mistake... assuming you are correct that both t and t1 are classes, we don't have enough information to know what they believe they are called. (Printing t and t1 should tell you.) What we know is that their *metaclass* (the class of a class) knows itself as "F". -- Steven From ladasky at my-deja.com Mon Oct 17 02:52:30 2011 From: ladasky at my-deja.com (John Ladasky) Date: Sun, 16 Oct 2011 23:52:30 -0700 (PDT) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: <4c79d47c-c6ce-49b5-931e-c1bf5e94af75@c14g2000pro.googlegroups.com> Message-ID: <15a00455-eee9-4806-b940-5d40073f7fe4@v8g2000pro.googlegroups.com> On Oct 14, 7:32?pm, alex23 wrote: > You can do this right now with Python 3.2+ and concurrent.futures: > > from concurrent.futures import ThreadPoolExecutor You may have finally sold me on struggling through the upgrade from Python 2.6! I've been doing reasonably well with the Multiprocessing module, but it looks like the syntax of ThreadPoolExecutor offers some significant improvements. Here's hoping that numpy, scipy, and matplotlib are all Python 3.x- compatible by now... From ulrich.eckhardt at dominolaser.com Mon Oct 17 03:22:59 2011 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Mon, 17 Oct 2011 09:22:59 +0200 Subject: callling python function in c In-Reply-To: <8ca2fc3e-a3be-49c4-8107-a47385bc0911@w26g2000pro.googlegroups.com> References: <8ca2fc3e-a3be-49c4-8107-a47385bc0911@w26g2000pro.googlegroups.com> Message-ID: Am 16.10.2011 10:03, schrieb masood shaik: > I am trying to call python function from c code.The following > program i got from the web source while i am trying to run this > program it throws an segmentation fault. Try checking what functions returns instead of blindly using it. Use a debugger to find out where exactly it segfaults. Uli From lanyjie at yahoo.com Mon Oct 17 04:42:04 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Mon, 17 Oct 2011 01:42:04 -0700 (PDT) Subject: strange comparison result with 'is' Message-ID: <1318840924.74377.YahooMailNeo@web121512.mail.ne1.yahoo.com> Hi all,? This is quite strange when I used the Python shell with IDLE: >>> x = [] >>> id(getattr(x, 'pop')) == id(x.pop) True >>> getattr(x, 'pop') is x.pop False >>>? I suppose since the two things have the same id, the 'is'-test? should give a True value, but I get a False value.? Any particular reason for breaking this test? I am quite?confused as I show this before a large? audience only to find the result denies my prediction. The python version is 3.2.2; I am not sure about other versions. Regards, Yingjie -------------- next part -------------- An HTML attachment was scrubbed... URL: From noreply at python.org Mon Oct 17 05:13:39 2011 From: noreply at python.org (Automatic Email Delivery Software) Date: Mon, 17 Oct 2011 12:13:39 +0300 Subject: Message could not be delivered Message-ID: The original message was received at Mon, 17 Oct 2011 12:13:39 +0300 from python.org [153.233.80.188] ----- The following addresses had permanent fatal errors ----- ----- Transcript of session follows ----- while talking to python.org.: >>> MAIL From:"Automatic Email Delivery Software" <<< 501 "Automatic Email Delivery Software" ... Refused -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: RemovedAttachments518.txt URL: From __peter__ at web.de Mon Oct 17 05:19:35 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Oct 2011 11:19:35 +0200 Subject: strange comparison result with 'is' References: <1318840924.74377.YahooMailNeo@web121512.mail.ne1.yahoo.com> Message-ID: Yingjie Lan wrote: > This is quite strange when I used the Python shell with IDLE: > >>>> x = [] >>>> id(getattr(x, 'pop')) == id(x.pop) > > True >>>> getattr(x, 'pop') is x.pop > False >>>> > > I suppose since the two things have the same id, the 'is'-test > should give a True value, but I get a False value. > > Any particular reason for breaking this test? > I am quite confused as I show this before a large > audience only to find the result denies my prediction. > > The python version is 3.2.2; I am not sure about other versions. The getattr() call is just a distraction. Every x.pop attribute access creates a new method object. In the case of >>> x.pop is x.pop False they have to reside in memory simultaneously while in the expression >>> id(x.pop) == id(x.pop) True a list.pop method object is created, its id() is taken (which is actually its address) and then the method object is released so that its memory address can be reused for the second x.pop. So in the latter case the two method objects can (and do) share the same address because they don't need to exist at the same time. From tjreedy at udel.edu Mon Oct 17 05:33:00 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 Oct 2011 05:33:00 -0400 Subject: strange comparison result with 'is' In-Reply-To: <1318840924.74377.YahooMailNeo@web121512.mail.ne1.yahoo.com> References: <1318840924.74377.YahooMailNeo@web121512.mail.ne1.yahoo.com> Message-ID: On 10/17/2011 4:42 AM, Yingjie Lan wrote: > Hi all, > > This is quite strange when I used the Python shell with IDLE: Nothing to do with IDLE > >>> x = [] >> >> id(getattr(x, 'pop')) == id(x.pop) > True > >>> getattr(x, 'pop') is x.pop > False > I suppose since the two things have the same id, the 'is'-test > should give a True value, but I get a False value. id and is are notorious for confusing beginners. You actually created 4 bound method objects -- but not all at the same time. IDs only only unique among simultaneously existing objects. It is an accident of the CPython implementation that two of them have the same id, even though they are different objects. The second line is the correct one. > Any particular reason for breaking this test? > I am quite confused as I show this before a large > audience only to find the result denies my prediction. Don't show this sort of thing. Name your objects so they do not get garbage collected in the middle of any demonstration. -- Terry Jan Reedy From faucheuses at gmail.com Mon Oct 17 06:32:51 2011 From: faucheuses at gmail.com (faucheuse) Date: Mon, 17 Oct 2011 03:32:51 -0700 (PDT) Subject: Problem with a wx notebook Message-ID: Hi there, I've created a wx NoteBook in wich I set multiples panels in wich I set one or more sizers. But nothing displays in the notebook, everything is outside. I've been searching an answer for 2 days ><. Can you help me plz ? Here is my code(with only one panel, to sum up the code) : class StreamingActivationDialog(wx.Dialog): def __init__(self, *args, **kwds): # begin wxGlade: StreamingActivationDialog.__init__ kwds["style"] = wx.DEFAULT_DIALOG_STYLE wx.Dialog.__init__(self, *args, **kwds) self.bitmap_1_copy = wx.StaticBitmap(self, -1, wx.Bitmap("img\ \logo.png", wx.BITMAP_TYPE_ANY)) self.labelDnD = wx.StaticText(self, -1, "Si vous avez d?j? un fichier d'activation, faite le glisser dans cette fenetre") self.keyBitmap = wx.StaticBitmap(self, -1, wx.Bitmap("img\ \key.bmp", wx.BITMAP_TYPE_ANY)) self.conclude = wx.StaticText(self, -1, _("test"), style=wx.ALIGN_CENTRE) ### Panel ### self.intro3_label = wx.StaticText(self, -1, "Envoyez un mail ? \nactivation at monmail.com\ncontenant le code :",style=wx.ALIGN_CENTRE) self.activationCode_label= wx.StaticText(self, -1, "123456789", style=wx.TE_READONLY) self.copy2_Button = wx.Button(self, -1, "Copier dans le presse- papier") self.copy2_Button.Bind(wx.EVT_BUTTON, PanelMail.onCopy) ############## self.note = wx.Notebook(self, wx.ID_ANY, style=wx.BK_LEFT, size=wx.Size(100, 341)) self.page3 = wx.Panel(self.note) imagelist = wx.ImageList(94, 94) bitmap1 = wx.Bitmap("img\\a.bmp", wx.BITMAP_TYPE_BMP ) imagelist.Add(bitmap1) self.note.AssignImageList(imagelist) self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: StreamingActivationDialog.__set_properties self.SetTitle(_("Activation de FlashProcess")) self.SetBackgroundColour(wx.Colour(255, 255, 255)) #self.linkProblem.SetForegroundColour(wx.Colour(0, 0, 0)) # end wxGlade def __do_layout(self): # begin wxGlade: StreamingActivationDialog.__do_layout self.grid_sizer_1 = wx.FlexGridSizer(6, 1, 0, 0) self.grid_sizer_2 = wx.FlexGridSizer(1, 2, 0, 30) self.grid_sizer_1.Add(self.bitmap_1_copy, 0, wx.TOP|wx.BOTTOM| wx.EXPAND, 10) ### Page 3 ### sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.intro3_label, 0, wx.BOTTOM|wx.ALIGN_CENTER, 5) sizer.Add(self.activationCode_label, 0, wx.BOTTOM| wx.ALIGN_CENTER, 20) sizer.Add(self.copy2_Button, 0, wx.ALIGN_CENTER, 20) self.page3.SetSizer(sizer) sizer.Fit(self.page3) ############## self.note.AddPage(self.page3, "", False, 0) self.Bind(wx.EVT_TOOLBOOK_PAGE_CHANGED, self.OnPageChanged) self.Bind(wx.EVT_TOOLBOOK_PAGE_CHANGING, self.OnPageChanging) self.grid_sizer_1.Add(self.note, 0, wx.EXPAND, 20) self.grid_sizer_1.Add(self.labelDnD, 0, wx.TOP| wx.ALIGN_CENTER_HORIZONTAL, 20) self.grid_sizer_2.Add(self.keyBitmap, 0, wx.LEFT, 10) self.grid_sizer_2.Add(self.labelDnD, 0, wx.LEFT, 20) self.grid_sizer_1.Add(self.grid_sizer_2, 0, wx.EXPAND, 20) self.grid_sizer_1.Add(self.conclude, 0, wx.TOP| wx.ALIGN_CENTER_HORIZONTAL, 20) self.SetSizer(self.grid_sizer_1) self.grid_sizer_1.Fit(self) self.Layout() # end wxGlade def OnPageChanged(self, event): event.Skip() def OnPageChanging(self, event): event.Skip() From rosuav at gmail.com Mon Oct 17 06:43:31 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 17 Oct 2011 21:43:31 +1100 Subject: Loop through a dict changing keys In-Reply-To: <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> Message-ID: On Mon, Oct 17, 2011 at 5:20 AM, Gnarlodious wrote: > On Oct 15, 5:53?pm, PoD wrote: > >> types={'Mobile':str,'context':str,'order':int,'time':bool} >> >> for k,v in data.items(): >> ? ? data[k] = types[k](v) > > Thanks for the tip, I didn't know you could do that. I ended up > filtering the values the bulky way, but it gives me total control over > what internet users feed my program. It should be noted that this will not in any way sanitize data['context']. It calls the str() function on it, thus ensuring that it's a string, but that's all. If you're needing to deal with (potentially) malicious input, you'll want to swap in a function that escapes it in some way (if it's going into a database, your database engine will usually provide a 'quote' or 'escape' function; if it's to go into a web page, I think cgi.escape is what you want). ChrisA From devplayer at gmail.com Mon Oct 17 08:59:04 2011 From: devplayer at gmail.com (DevPlayer) Date: Mon, 17 Oct 2011 05:59:04 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> Message-ID: > DevPlayer ?wrote: > >I still assert that contradiction is caused by narrow perspective. > >By that I mean: just because an objects scope may not see a certain > >condition, doesn't mean that condition is non-existant. > Groetjes Albert wrote: > This is a far cry from the bible stating that someone is his > own grand father. Or going to great length to prove that Jezus > (through Jozef) is a descendant of David. Then declaring it > a dogma that Jozef has nothing to do with it. Do you not see? For ... One man's garbage is another man's treasure. One man's delusion is another man's epiphany. One man's untruth is another man's belief. One man's thing to attack is another mans thing to shield and defend. One man's logical undenighable truth is another man's small part of a bigger picture. As has been said for example does 1+1 = 2. Only in one small persepective. Whaa? what wack job says stuff like that? 1+1 = 10. In the bigger picture there is more then one numberic base besides decimal, such as binary. Or then one might say there are only 10 integer numbers from 0 to 9 or from 1 to 10 if you like. Again in the limited view, true, but in the larger view no. The Elucid numbering scale is not the only numbering scale ever invented, or needed for that matter. http://en.wikipedia.org/wiki/Euclidean_geometry "Euclid's axioms seemed so intuitively obvious that any theorem proved from them was deemed true in an absolute, often metaphysical, sense. Today, however, many other self-consistent non-Euclidean geometries are known, the first ones having been discovered in the early 19th century. An implication of Einstein's theory of general relativity is that Euclidean space is a good approximation to the properties of physical space ..." > Groetjes Albert wrote: > (It being ... well ... you know ...) Um... Huh? sorry didn't know what you meant. You got me on that one. Ellipses just put my brain into recursive mode. > Groetjes Albert wrote: > (I have this book, it is called "the amusing bible" with all > flippant and contradictory stuff pointed out by a French > 1930 communist. Cartoons too. ) I likely would find it very funny. > Economic growth -- being exponential -- ultimately falters. How true indeed. From nvidhya01 at gmail.com Mon Oct 17 09:23:38 2011 From: nvidhya01 at gmail.com (n v) Date: Mon, 17 Oct 2011 06:23:38 -0700 (PDT) Subject: @@@@@@@@@@@@@@@@@@@ Message-ID: <6adf527d-69f7-4ed9-a8b2-f2d3029c8508@y35g2000pre.googlegroups.com> http://123maza.com/48/silver424/ From steve+comp.lang.python at pearwood.info Mon Oct 17 10:34:34 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Oct 2011 14:34:34 GMT Subject: [OT] Re: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> Message-ID: <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> On Mon, 17 Oct 2011 05:59:04 -0700, DevPlayer wrote: > As has been said for example does 1+1 = 2. Only in one small > persepective. Whaa? what wack job says stuff like that? 1+1 = 10. In the > bigger picture there is more then one numberic base besides decimal, > such as binary. That is no more deep and meaningful than the fact that while some people say "one plus one equals two", others say "eins und eins gleich zwei", some say "un et un fait deux" and some say "???? ? ???? ???? ???". Regardless of whether you write two, zwei, ???, ???, 2 (in decimal), 10 (in binary), II (in Roman numerals) or even {0,1} using set theory notation, the number remains the same, only the symbol we use to label it is different. Do not confuse the map for the territory. -- Steven From brian.curtin at gmail.com Mon Oct 17 10:42:40 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Mon, 17 Oct 2011 09:42:40 -0500 Subject: How do I get curses to work in Python 3.2 on win-64? In-Reply-To: References: <3bc2636a-85b5-47bd-9a47-7c9ee16b2a75@w5g2000yqw.googlegroups.com> <57034ebb-5278-4a48-9e12-4e068eda820c@v8g2000pro.googlegroups.com> Message-ID: On Sun, Oct 16, 2011 at 11:16, Jan Sundstr?m wrote: > On 16 Okt, 06:59, Christoph Gohlke wrote: >> On Oct 15, 1:13?pm, Jan Sundstr?m wrote: >> >> >> >> `import curses` should work. What exactly is the error message? Does >> `import curses` work outside your program/program directory? >> >> The curses package is part of the standard library and usually >> installed in Python32\Lib\curses. On Windows the ?_curses.pyd files is >> missing in the standard distribution. curses-2.2.win-amd64-py3.2.exe >> installs the missing _curses.pyd file into Lib/site-packages. > > Thanks for the tip to check in what library it works, that set me on > track tofind a silly mistake that I had done. Now everything works > fine. > > But, how come that the Windows distribution for Python doesn't include > the _curses.pyd file? It's not a standard library module on Windows. The curses Christoph mentioned is built on the PDCurses library, which is an external project. From dihedral88888 at googlemail.com Mon Oct 17 12:21:35 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Mon, 17 Oct 2011 09:21:35 -0700 (PDT) Subject: Loop through a dict changing keys In-Reply-To: References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> Message-ID: <31199636.1883.1318868495227.JavaMail.geo-discussion-forums@prfp13> Uh, sounds reasonable, if one loops over an index variable that could be altered during the loop execution then the loop may not end as expected. From dihedral88888 at googlemail.com Mon Oct 17 12:21:35 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Mon, 17 Oct 2011 09:21:35 -0700 (PDT) Subject: Loop through a dict changing keys In-Reply-To: References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> Message-ID: <31199636.1883.1318868495227.JavaMail.geo-discussion-forums@prfp13> Uh, sounds reasonable, if one loops over an index variable that could be altered during the loop execution then the loop may not end as expected. From anikom15 at gmail.com Mon Oct 17 12:29:39 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Mon, 17 Oct 2011 09:29:39 -0700 Subject: Equal sets with unequal print and str() representations In-Reply-To: <4E9B6E23.9050106@cs.utah.edu> References: <4E9B6E23.9050106@cs.utah.edu> Message-ID: <20111017162939.GA23669@Smoke> On Sun, Oct 16, 2011 at 05:52:03PM -0600, Ganesh Gopalakrishnan wrote: > This probably is known, but a potential pitfall (was, for me) > nevertheless. I suspect it is due to hash collisions between 's3' > and 's13' in this case? It happens only rarely, depending on the > contents of the set. > > >>> S1 = {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'} > S1 = {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'} > >>> S2 = {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'} > S2 = {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'} > >>> S1 > S1 > {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'} > >>> S2 > S2 > {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'} > >>> S1==S2 > S1==S2 > True > >>> str(S1) > str(S1) > "{'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'}" > >>> str(S2) > str(S2) > "{'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'}" > >>> str(S1) == str(S2) > False This is because sets do not preserve order. From tjreedy at udel.edu Mon Oct 17 13:53:13 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 Oct 2011 13:53:13 -0400 Subject: strange comparison result with 'is' In-Reply-To: References: <1318840924.74377.YahooMailNeo@web121512.mail.ne1.yahoo.com> Message-ID: On 10/17/2011 5:19 AM, Peter Otten wrote: > The getattr() call is just a distraction. Every x.pop attribute access > creates a new method object. In the case of > >>>> x.pop is x.pop > False > > they have to reside in memory simultaneously while in the expression > >>>> id(x.pop) == id(x.pop) > True > > a list.pop method object is created, its id() is taken (which is actually > its address) and then the method object is released so that its memory > address can be reused for the second x.pop. > > So in the latter case the two method objects can (and do) share the same > address because they don't need to exist at the same time. This has come up enough that I opened http://bugs.python.org/issue13203 ============================================================== Newbies too often do something like (3.2.2, ) >>> id(getattr(x, 'pop')) == id(x.pop) True and get confused by the (invalid) result, whereas >>> a,b=getattr(x, 'pop'),x.pop >>> id(a)==id(b) False works properly. I think we should add a sentence or two or three to the id() doc, such as Since a newly created argument object is either destroyed or becomes inaccessible before the function returns, *id(obj)* is only useful and valid if *obj* exists prior to the call and therefore after its return. The value of an expression such as *id(666)== id(667)* is arbitrary and meaningless. The id of the first int object might or might not be reused for the second one. ==================================================================== With something like this added, we could just say 'read the id() doc'. -- Terry Jan Reedy From ian.g.kelly at gmail.com Mon Oct 17 14:12:27 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 17 Oct 2011 12:12:27 -0600 Subject: Loop through a dict changing keys In-Reply-To: <31199636.1883.1318868495227.JavaMail.geo-discussion-forums@prfp13> References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> <31199636.1883.1318868495227.JavaMail.geo-discussion-forums@prfp13> Message-ID: On Mon, Oct 17, 2011 at 10:21 AM, 88888 dihedral wrote: > Uh, sounds reasonable, if one loops over an index variable ?that could be altered during the loop execution then the loop may not end as expected. >From the docs: "Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries." Changing the values of existing entries while iterating is considered to be safe, though. From miki.tebeka at gmail.com Mon Oct 17 14:38:08 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 17 Oct 2011 11:38:08 -0700 (PDT) Subject: python.org appears to be down In-Reply-To: References: Message-ID: <12197444.1847.1318876688689.JavaMail.geo-discussion-forums@prmr25> http://www.isup.me/python.org ;) From miki.tebeka at gmail.com Mon Oct 17 14:38:08 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 17 Oct 2011 11:38:08 -0700 (PDT) Subject: python.org appears to be down In-Reply-To: References: Message-ID: <12197444.1847.1318876688689.JavaMail.geo-discussion-forums@prmr25> http://www.isup.me/python.org ;) From devplayer at gmail.com Mon Oct 17 14:44:27 2011 From: devplayer at gmail.com (DevPlayer) Date: Mon, 17 Oct 2011 11:44:27 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Oct 17, 10:34?am, Steven D'Aprano wrote: > On Mon, 17 Oct 2011 05:59:04 -0700, DevPlayer wrote: > > As has been said for example does 1+1 = 2. Only in one small > > persepective. Whaa? what wack job says stuff like that? 1+1 = 10. In the > > bigger picture there is more then one numberic base besides decimal, > > such as binary. > > That is no more deep and meaningful than the fact that while some people > say "one plus one equals two", others say "eins und eins gleich zwei", > some say "un et un fait deux" and some say "???? ? ???? ???? ???". > Regardless of whether you write two, zwei, ???, ???, 2 (in decimal), 10 > (in binary), II (in Roman numerals) or even {0,1} using set theory > notation, the number remains the same, only the symbol we use to label it > is different. > > Do not confuse the map for the territory. > Steven Good point. But I disagree: The symbol is not only used to label it. The symbol is used to put it in context in reference to something else. "2" is a quantity in decimal, but in binary, "2" is not a quantity nor is 01+01==10 equal to "2" from withIN the binary perspective. Those symantics are symbolic of concepts which are being equated to quantities OUTSIDE of the binary perspective. True binary states, True + True does not equal two True, correct? Programmers use binary "math" to -represent- quantity. Here you are arranging syntax to change meaning -out of scope-. The original machine language notation inventors could have said in binary there is no 1+1 they could have said "1 Jumps 1 means "A"", or "On repowers On equals 5th gate in nand circuit". To reitterate, I agree with you that it doesn't matter what symbology you use if that symobology represents "same-stateness" -FROM a broader perspective (i.e. scope). BUT in binary, in the narrow scope of binary logic there is no "2". The available states are restrained to the scope you place them, when WITHIN that scope. (using caps to try to be clear and I don't intend to say you are wrong and I am right but to say, I disagree because of this logic. Said differently I intend to explain, not to demoralize or offend). "1+1=10" is being viewed as 2 because of a larger world view is being used, a broader perspective. Using broader concepts of numbers and math which is a superset of a strictly binary system and is also a superset of a decimal only view. Remember a computer does not function with concepts of "2" or "a" or "15". Computers function in ons and offs and "indeterminate" states. The binary representation of "10" to a computer does not mean "2". That quantity representation is something the human applies to that state. Perhaps a differant analogy made by someone else. Many years ago, I've studied the "The Fourth Dimension" a book based mostly on math by Rudy Rucker. There are a few books with that name but this one is algra based. It attempts to teach the reader to be able to view 4 dimensional objects using 3 dimensional and even 2 dimensional translations of "mapped" objects - with a 4 dimensional view. There are two popular schools of thought on this attempt. 1. It's impossible or us to concieve of a 4 dimentional space objects within our 3 dimentional senses and perceptions. and 2. We can conceive with our mind-s eye 4 dimensional objects much like we concieve of 2 dimentional objects (the plane) and even harder one dimensional objects. The author attempts to teach by first using an analogy. First he clarifies that for his purposes of 4 dimensional space, that no dimension axis in his math singularly represents time or anything ephemeral like the supernatural or energy or such. Each fo the 4 dimensions represent an axis in a physical vector. He then creates a 3 dimensional man who lives in a 3 dimensional world. This 3d man sees up, down, north, south, east, west. And he can see a plane or even a line. But the 3d man does not see the 4th axis because he is not made of that vector and does not therefore have sensory to perceive that axis. The author then goes on to show a 2d man does not see the 3rd axis and then better explains how the 1d man can only "see" in left or right directions. Following that story further, keeping to certain assumptions about 1d space, puts the man in a binary world view, where there is no "2", much like a computer. there is not "2" there is only 10, which TO YOU is a 2. but to the 1d man and the computer is a 10. Of course when you try to limit someone's view to make a point about a limited view it sounds rediculas. Supposition is often that way after all. > That is no more deep and meaningful than the fact that while some people > say "one plus one equals two", others say "eins und eins gleich zwei", > some say "un et un fait deux" and some say "???? ? ???? ???? ???". > Regardless of whether you write two, zwei, ???, ???, 2 (in decimal), 10 > (in binary), II (in Roman numerals) or even {0,1} using set theory > notation, the number remains the same, only the symbol we use to label it > is different. Also here you are talking about syntax as if it were symantics or mnuemonics. Symbology is a superset of those three terms and they are not entirely equivelent although -closely- knitted in function and purpose. Context (=limited perspective) is revelent if not entirely revelent when using symantics coupled with symbols. For example: One man's war is a another man's liberation. Here the word symbol "war" has different meanings for each man. The two smantics is to apply the notion of war (fighting/killing) to the purpose of war (rebellion to what is "good" (man1) to removal from what is "bad" (man2)). Along with my notion of the "Duality of Nature", also puts around the idea-almost-belief that "Everything is symantics". These two goofy notions are tightly linked (at least in my musings). Ever hear/read the term: "It's all good."? A reference to Karma and how things will work out for the better in the end inspite of what you see now... A great example of "Everything is Symantics". Apart of that notion btw is that: No symbol completely and entirely represents a thing, a person, a place, an idea completely and accurately, only partially. And symbology is very tied into "Relativity" (of perspective) (another term I apply to "Duality of Nature" where in DoN there exists at least two extreme but opposite states, in "Relativity" has something LIKE extremes but they are vectors of state and not limited sets of state with a infinite range. for example the infinite range of numbers between 0 and 1 or 1 and 2. or for example where 0 and 1 are numeric synbols of off state and on state - two opposite and partially contradictory states. (Some say "None" is the opposite of a bool state). btw for those in electronics fields know that on and off states are mearly arbitary, chosen to be some function like 2 *square of power for on. In electronics on off states there are infinite levels of "on-ness" but only two points in that range are chosen to be revelent (was that 75% power I forget). And another weird notion to put forward. "2" as a numberic quantity by itself is utterly meaningless. Two what? It's the "what" that is revelent. I was going to go on to make some connection to "2" being a representive of "instantation" of objects and the place and usage of instances is meaningful but that chain of thought is just as windy as all the hot air I just gushed. Well. Hope you enjoyed my crazy. Later. From gnarlodious at gmail.com Mon Oct 17 14:50:41 2011 From: gnarlodious at gmail.com (Gnarlodious) Date: Mon, 17 Oct 2011 11:50:41 -0700 (PDT) Subject: Loop through a dict changing keys References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> <4e9b67fb$0$29967$c3e8da3$5496439d@news.astraweb.com> <66deee18-6595-474e-876d-84e1de21baa2@31g2000prt.googlegroups.com> <4e9ba19f$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: <07ebfa36-d0d7-4abb-86c0-ae5ab19e0729@p35g2000prp.googlegroups.com> Steven: Thanks for those tips, I've implemented all of them. Also only allowing whitelisted variable names. Feeling much more confident. -- Gnarlie From eswint at vt.edu Mon Oct 17 15:55:58 2011 From: eswint at vt.edu (Ethan Swint) Date: Mon, 17 Oct 2011 15:55:58 -0400 Subject: Python hangs: Problem with wxPython, threading, pySerial, or events? In-Reply-To: <4E99A3FD.1010708@vt.edu> References: <4E99A3FD.1010708@vt.edu> Message-ID: <4E9C884E.2050507@vt.edu> I just wanted to bump this back onto the list since I posted over the weekend. Thanks, Ethan On 10/15/2011 11:17 AM, Ethan Swint wrote: > Hi- > > I'm experiencing crashes in my Win32 Python 2.7 application which > appear to be linked to pyzmq. At the moment, I can't even kill the > "python.exe *32" process in the Windows Task Manager. I'm running the > script using Ipython by calling > > C:\Python27\pythonw.exe > "/python27/scripts/ipython-qtconsole-script.pyw" -pylab > > but I also experience similar behavior when running within Eclipse. > I've included an error message at the end which appears in the Windows > 'cmd' window, but the message is not reflected in the pylab window. > > My attached device is transmitting <160><1><2><3><4><80> and is > received correctly when I run the sample pyserial script > 'wxTerminal.py'. In my application, however, the message appears to > get characters out of order or drop bytes. > > If there's a better place to post or if you'd like more info, let me > know. > > Thanks, > Ethan > > ------------------Serial Port Listening > Thread---------------------------------------- > def MotorRxThread(self): > """Thread that handles the incoming traffic. Does buffer input and > generates an SerialRxEvent""" > while self.alive.isSet(): #loop while alive event is > true > text = self.serMotor.read(1) #read one, with timeout > if text: #check if not timeout > n = self.serMotor.inWaiting() #look if there is more to read > if n: > text = text + self.serMotor.read(n) #get it > #log to terminal > printstring = "MotorRxThread: " > for b in text: > printstring += str(ord(b)) + " " > print printstring > #pdb.set_trace() > if self.motorRx0.proc_string(text): > print "Message: cmd: " + str(self.motorRx0.cmd) + " data: " > + str(self.motorRx0.data) > event = SerialRxSpeedEvent(self.GetId(), text) > self.GetEventHandler().AddPendingEvent(event) > -----------------\Serial Port Listening > Thread---------------------------------------- > > ----------------Thread > Start&Stop------------------------------------------------------ > def StartMotorThread(self): > """Start the receiver thread""" > self.motorThread = threading.Thread(target=self.MotorRxThread) > self.motorThread.setDaemon(1) > self.alive.set() > self.motorThread.start() > > def StopMotorThread(self): > """Stop the receiver thread, wait until it's finished.""" > if self.motorThread is not None: > self.alive.clear() #clear alive event for thread > self.motorThread.join() #wait until thread has finished > self.motorThread = None > self.serMotor.close() #close the serial port connection > ----------------\Thread > Start&Stop------------------------------------------------------ > > -------------------Error message > -------------------------------------------------------- > ValueError: '' is not in list > ([], ['', '', '', > '{"date":"2011-10-15T10:24:27.231000","username":"kernel","session":"82906c8a-1235-44d0-b65d- > 0882955305c1","msg_id":"7cfcd155-bc05-4f47-9c39-094252223dab","msg_type":"stream"}', > '{"date":"2011-10-15T10:24:27.23100 > 0","username":"kernel","session":"82906c8a-1235-44d0-b65d-0882955305c1","msg_id":"f4b88228-b353-4cfb-9bbe-ae524ee1ac38", > > "msg_type":"stream"}', > '{"date":"2011-10-15T10:24:00.774000","username":"username","session":"9f393860-c2ab-44e9-820d-8f > 08ae35044e","msg_id":"13a46e93-8da2-487b-ab12-6cae47b1ac34","msg_type":"execute_request"}', > '{"date":"2011-10-15T10:24:0 > 0.774000","username":"username","session":"9f393860-c2ab-44e9-820d-8f08ae35044e","msg_id":"13a46e93-8da2-487b-ab12-6cae4 > > 7b1ac34","msg_type":"execute_request"}', '{"data":"\\nMotorRxThread: 0 > MotorRxThread: 4 ","name":"stdout"}']) > ERROR:root:Exception in I/O handler for fd object at 0x03ADFCC0> > Traceback (most recent call last): > File > "C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\ioloop.py", > line 291, in start > self._handlers[fd](fd, events) > File > "C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\stack_context.py", > line 133, in wrapped > callback(*args, **kwargs) > File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", > line 448, in _handle_events > self._handle_recv() > File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", > line 458, in _handle_recv > ident,msg = self.session.recv(self.socket) > File "C:\Python27\lib\site-packages\IPython\zmq\session.py", line > 585, in recv > raise e > ValueError: No JSON object could be decoded > ERROR:root:Exception in I/O handler for fd object at 0x03ADFCC0> > Traceback (most recent call last): > File > "C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\ioloop.py", > line 291, in start > self._handlers[fd](fd, events) > File > "C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\stack_context.py", > line 133, in wrapped > callback(*args, **kwargs) > File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", > line 448, in _handle_events > self._handle_recv() > File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", > line 458, in _handle_recv > ident,msg = self.session.recv(self.socket) > File "C:\Python27\lib\site-packages\IPython\zmq\session.py", line > 579, in recv > idents, msg_list = self.feed_identities(msg_list, copy) > File "C:\Python27\lib\site-packages\IPython\zmq\session.py", line > 609, in feed_identities > idx = msg_list.index(DELIM) > ValueError: '' is not in list > --------------------------------------------------------------------------- > > ZMQError Traceback (most recent call > last) > C:\Users\Ethan\ in () > > C:\Python27\lib\site-packages\IPython\zmq\ipkernel.pyc in main() > 671 """Run an IPKernel as an application""" > 672 app = IPKernelApp.instance() > --> 673 app.initialize() > 674 app.start() > 675 > > C:\Python27\lib\site-packages\IPython\zmq\ipkernel.pyc in > initialize(self=, arg > v=None) > 604 ) > 605 def initialize(self, argv=None): > --> 606 super(IPKernelApp, self).initialize(argv) > 607 self.init_shell() > 608 self.init_extensions() > > C:\Python27\lib\site-packages\IPython\zmq\kernelapp.pyc in > initialize(self=, ar > gv=None) > 213 self.init_session() > 214 self.init_poller() > --> 215 self.init_sockets() > 216 self.init_io() > 217 self.init_kernel() > > C:\Python27\lib\site-packages\IPython\zmq\kernelapp.pyc in > init_sockets(self=) > 148 > 149 self.shell_socket = context.socket(zmq.XREP) > --> 150 self.shell_port = self._bind_socket(self.shell_socket, > self.shell_port) > 151 self.log.debug("shell XREP Channel on port: > %i"%self.shell_port) > 152 > > C:\Python27\lib\site-packages\IPython\zmq\kernelapp.pyc in > _bind_socket(self=, > s=, port=50104) > 137 port = s.bind_to_random_port(iface) > 138 else: > --> 139 s.bind(iface + ':%i'%port) > 140 return port > 141 > > C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\core\socket.pyd > in zmq.core.socket.Socket.bind (zmq\core\s > ocket.c:4527)() > > ZMQError: Address in use > ---------\ERROR MESSAGE-------------------------------------------------- > From mathias.lafeldt at googlemail.com Mon Oct 17 16:02:03 2011 From: mathias.lafeldt at googlemail.com (Mathias Lafeldt) Date: Mon, 17 Oct 2011 22:02:03 +0200 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: On Sat, Oct 15, 2011 at 1:44 AM, MrPink wrote: > > Is there a function in Python that can be used to test if the value in > a string is an integer? ?I had to make one up for myself and it looks > like this: > > def isInt(s): > ? ?try: > ? ? ? ?i = int(s) > ? ? ? ?return True > ? ?except ValueError: > ? ? ? ?return False According to [1], there're more Exceptions to test for: try: int(s) return True except (TypeError, ValueError, OverflowError): # int conversion failed return False [1] http://jaynes.colorado.edu/PythonIdioms.html, idiom "Catch errors rather than avoiding them to avoid cluttering your code with special cases" -Mathias From ganesh at cs.utah.edu Mon Oct 17 16:25:12 2011 From: ganesh at cs.utah.edu (Ganesh Gopalakrishnan) Date: Mon, 17 Oct 2011 14:25:12 -0600 Subject: Equal sets with unequal print and str() representations In-Reply-To: <878vokuzik.fsf@benfinney.id.au> References: <878vokuzik.fsf@benfinney.id.au> Message-ID: <4E9C8F28.3000605@cs.utah.edu> Thanks to all who replied - also to Ben. I had foolishly assumed that the same set exhibits the same rep on at least one platform. Like any bug, the falsity of my assumption took months to expose - till then, things had worked fine. Needless to say I'm new to Python. (The double printing is because I tend to work within an Emacs inferior shell.) Cheers, Ganesh On 10/16/11 8:23 PM, Ben Finney wrote: > Ganesh Gopalakrishnan writes: > >> This probably is known, but a potential pitfall (was, for me) nevertheless. >> I suspect it is due to hash collisions between 's3' and 's13' in this >> case? > What is the actual problem? What behaviour is occurring that doesn't > match your expectation? > >>>>> S1==S2 >> S1==S2 >> True >>>>> str(S1) >> str(S1) >> "{'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'}" >>>>> str(S2) >> str(S2) >> "{'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'}" >>>>> str(S1) == str(S2) >> False > Right, that's all correct (though I don't know why some of your > expressions are being shown twice). A deliberate property of a set is > that its items are unordered. > > > Since sets are unordered, the string representation may show the items > in an arbitrary and unpredictable sequence. Don't write any code that > depends on a predictable sequence of retrieval from an unordered > collection. > > So what did you expect instead, and what supports that expectation? > From enalicho at gmail.com Mon Oct 17 16:44:51 2011 From: enalicho at gmail.com (Noah Hall) Date: Mon, 17 Oct 2011 21:44:51 +0100 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: On Sat, Oct 15, 2011 at 12:44 AM, MrPink wrote: > > Is there a function in Python that can be used to test if the value in > a string is an integer? ?I had to make one up for myself and it looks > like this: > > def isInt(s): > ? ?try: > ? ? ? ?i = int(s) > ? ? ? ?return True > ? ?except ValueError: > ? ? ? ?return False There's the isdigit method, for example - >>> str = "1324325" >>> str.isdigit() True >>> str = "1232.34" >>> str.isdigit() False >>> str = "I am a string, not an int!" >>> str.isdigit() False From ben+python at benfinney.id.au Mon Oct 17 16:52:48 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Oct 2011 07:52:48 +1100 Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> Message-ID: <87vcrntk67.fsf@benfinney.id.au> DevPlayer writes: > Do you not see? For ... > One man's delusion is another man's epiphany. > One man's untruth is another man's belief. > One man's logical undenighable truth is another man's small part of a > bigger picture. Those are just not true. A belief that doesn't match reality is a delusion. That doesn't change when someone thinks it's an epiphany: it's still a delusion. If a claim about reality doesn't actually match reality, it's untrue. That doesn't change when someone believes it: it's still untrue, or claims it's ?part of a bigger picture?. If you make claims about reality, then you'd better be ready for them to be subjected to the tests of reality, or be ready for ridicule if you can't back them up with such tests. If, on the other hand, you claim a ?bigger picture?, then that's just another scope within reality and you haven't escaped any part of your burden to demonstrate that reality. If, on the gripping hand, you want to make claims that are *not* about reality, then be very clear about that at the beginning and don't try to shift the goalposts later. > http://en.wikipedia.org/wiki/Euclidean_geometry > "Euclid's axioms seemed so intuitively obvious that any theorem proved > from them was deemed true in an absolute, often metaphysical, sense. > Today, however, many other self-consistent non-Euclidean geometries > are known, the first ones having been discovered in the early 19th > century. An implication of Einstein's theory of general relativity is > that Euclidean space is a good approximation to the properties of > physical space ..." Yes. Anyone who claimed that Euclids axioms hold in real spacetime was *wrong*. If they believed it, they were *deluded*. There was no shame in that before the discovery that Euclid's axioms don't hold in real spacetime. But, once its falseness has been demonstrated, to handwave about ?one man's truth? and ?bigger picture? is an attempt to avoid the admission that the claim was false. It is uncomfortable ? sometimes painful ? to admit that one's belief does not match reality; and hence natural and common for us to seek to avoid that admission when the evidence is against our belief. But that doesn't lessen the delusion. -- \ ?Human reason is snatching everything to itself, leaving | `\ nothing for faith.? ?Bernard of Clairvaux, 1090?1153 CE | _o__) | Ben Finney From ben+python at benfinney.id.au Mon Oct 17 17:04:08 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Oct 2011 08:04:08 +1100 Subject: Equal sets with unequal print and str() representations References: <878vokuzik.fsf@benfinney.id.au> Message-ID: <87r52btjnb.fsf@benfinney.id.au> Ganesh Gopalakrishnan writes: > Thanks to all who replied - also to Ben. You're welcome. (Please don't top-post your replies.) > Needless to say I'm new to Python. Welcome to this forum, then! You would be wise to get a solid grounding in Python by working through the Python tutorial from beginning to end . Perform each exercise, experiment with it until you understand, and only then move on to the next. Repeat until done :-) -- \ ?Know what I hate most? Rhetorical questions.? ?Henry N. Camp | `\ | _o__) | Ben Finney From ian.g.kelly at gmail.com Mon Oct 17 17:49:08 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 17 Oct 2011 15:49:08 -0600 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: On Mon, Oct 17, 2011 at 2:44 PM, Noah Hall wrote: > There's the isdigit method, for example - > >>>> str = "1324325" >>>> str.isdigit() > True >>>> str = "1232.34" >>>> str.isdigit() > False >>>> str = "I am a string, not an int!" >>>> str.isdigit() > False That works for non-negative base-10 integers. But: >>> "-1234".isdigit() False Cheers, Ian From roy at panix.com Mon Oct 17 20:33:08 2011 From: roy at panix.com (Roy Smith) Date: Mon, 17 Oct 2011 20:33:08 -0400 Subject: How to test if object is an integer? References: Message-ID: In article , Mathias Lafeldt wrote: > According to [1], there're more Exceptions to test for: > > try: > int(s) > return True > except (TypeError, ValueError, OverflowError): # int conversion failed > return False I don't think I would catch TypeError here. It kind of depends on how isInt() is defined. Is it: def isInt(s): "Return True if s is a string representing an integer" or is it: def isInt(s): "Return True if s (which must be a string) represents an integer" If the latter, then passing a non-string violates the contract, and the function should raise TypeError. If the former, then you could make some argument for catching the TypeError and returning False, but I think the second version is what most people have in mind for isInt(). Can you even get an OverflowError any more in a modern Python? >>> int('99999999999999999999999999999999999999999999999999999999999999999') 99999999999999999999999999999999999999999999999999999999999999999L From ckaynor at zindagigames.com Mon Oct 17 20:40:00 2011 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Mon, 17 Oct 2011 17:40:00 -0700 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: Python 2.6 running on Windows 7: >>> 99.0**99**99 OverflowError: (34, 'Result too large') Traceback (most recent call last): ? File "", line 1, in OverflowError: (34, 'Result too large') However, from the documentation: "Because of the lack of standardization of floating point exception handling in C, most floating point operations also aren?t checked." (http://docs.python.org/library/exceptions.html#exceptions.OverflowError) Chris On Mon, Oct 17, 2011 at 5:33 PM, Roy Smith wrote: > > In article , > ?Mathias Lafeldt wrote: > > > According to [1], there're more Exceptions to test for: > > > > try: > > ? ? int(s) > > ? ? return True > > except (TypeError, ValueError, OverflowError): # int conversion failed > > ? ? return False > > > I don't think I would catch TypeError here. ?It kind of depends on how > isInt() is defined. ?Is it: > > def isInt(s): > ?"Return True if s is a string representing an integer" > > or is it: > > def isInt(s): > ?"Return True if s (which must be a string) represents an integer" > > If the latter, then passing a non-string violates the contract, and the > function should raise TypeError. ?If the former, then you could make > some argument for catching the TypeError and returning False, but I > think the second version is what most people have in mind for isInt(). > > Can you even get an OverflowError any more in a modern Python? > > >>> > int('99999999999999999999999999999999999999999999999999999999999999999') > 99999999999999999999999999999999999999999999999999999999999999999L > -- > http://mail.python.org/mailman/listinfo/python-list From ian.g.kelly at gmail.com Mon Oct 17 20:59:44 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 17 Oct 2011 18:59:44 -0600 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: On Mon, Oct 17, 2011 at 6:40 PM, Chris Kaynor wrote: > Python 2.6 running on Windows 7: >>>> 99.0**99**99 > OverflowError: (34, 'Result too large') > Traceback (most recent call last): > ? File "", line 1, in > OverflowError: (34, 'Result too large') > > However, from the documentation: > "Because of the lack of standardization of floating point exception > handling in C, most floating point operations also aren?t checked." > (http://docs.python.org/library/exceptions.html#exceptions.OverflowError) I think what Roy meant was "can you even get an OverflowError from calling int() any more", to which I think the answer is no, since in modern Pythons int() will auto-promote to a long, and in Python 3 they're even the same thing. From lanyjie at yahoo.com Mon Oct 17 22:50:27 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Mon, 17 Oct 2011 19:50:27 -0700 (PDT) Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: <1318906227.86720.YahooMailNeo@web121510.mail.ne1.yahoo.com> ----- Original Message ----- > From: Noah Hall > To: MrPink > Cc: python-list at python.org > Sent: Tuesday, October 18, 2011 4:44 AM > Subject: Re: How to test if object is an integer? > There's the isdigit method, for example - > >>>> str = "1324325" >>>> str.isdigit() > True >>>> str = "1232.34" >>>> str.isdigit() > False >>>> str = "I am a string, not an int!" >>>> str.isdigit() > False > There are some corner cases to be considered with this approach: 1. negative integers: '-3' 2. strings starting with '0': '03' 3. strings starting with one '+': '+3' From steve+comp.lang.python at pearwood.info Mon Oct 17 23:56:57 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 18 Oct 2011 03:56:57 GMT Subject: How to test if object is an integer? References: Message-ID: <4e9cf909$0$29992$c3e8da3$5496439d@news.astraweb.com> On Mon, 17 Oct 2011 18:59:44 -0600, Ian Kelly wrote: > On Mon, Oct 17, 2011 at 6:40 PM, Chris Kaynor > wrote: >> Python 2.6 running on Windows 7: >>>>> 99.0**99**99 >> OverflowError: (34, 'Result too large') Traceback (most recent call >> last): >> ? File "", line 1, in >> OverflowError: (34, 'Result too large') >> >> However, from the documentation: >> "Because of the lack of standardization of floating point exception >> handling in C, most floating point operations also aren?t checked." >> (http://docs.python.org/library/ exceptions.html#exceptions.OverflowError) > > I think what Roy meant was "can you even get an OverflowError from > calling int() any more", to which I think the answer is no, since in > modern Pythons int() will auto-promote to a long, and in Python 3 > they're even the same thing. You can still get an OverflowError: >>> inf = float('inf') >>> int(inf) Traceback (most recent call last): File "", line 1, in OverflowError: cannot convert float infinity to integer and similarly for Decimal('inf') as well. -- Steven From shilparani9030 at gmail.com Tue Oct 18 01:25:52 2011 From: shilparani9030 at gmail.com (SHILPA) Date: Mon, 17 Oct 2011 22:25:52 -0700 (PDT) Subject: SOUTH INDIAN HOT ACTRESS Message-ID: <0ccc957e-e05c-426a-aeb6-9fd4a04f1ff9@31g2000prt.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html From peter.marczis at nsn.com Tue Oct 18 01:43:41 2011 From: peter.marczis at nsn.com (Peter G. Marczis) Date: Tue, 18 Oct 2011 08:43:41 +0300 Subject: Fwd: os.statvfs bug or my incompetence ? In-Reply-To: References: <4E97DB66.50302@nsn.com> <4E97F093.4000203@nsn.com> Message-ID: <4E9D120D.2060302@nsn.com> Hi, not yet, I will check it today, thanks for the idea ! We may have some deeper problem... Br, Peter. On 10/15/2011 05:46 PM, ext Kev Dwyer wrote: > Peter G. Marczis wrote: > > > > Hello Peter, > > Welcome to the list. > > Have you tried calling statvfs from a C program? What happens if you do? > > Best regards, > > Kev > > > > From as at sci.fi Tue Oct 18 07:32:15 2011 From: as at sci.fi (Anssi Saari) Date: Tue, 18 Oct 2011 14:32:15 +0300 Subject: callling python function in c References: <8ca2fc3e-a3be-49c4-8107-a47385bc0911@w26g2000pro.googlegroups.com> Message-ID: masood shaik writes: > Hi > > I am trying to call python function from c code.The following > program i got from the web source while i am trying to run this > program it throws an segmentation fault. Yes, the call to PyImport_Import fails and returns a NULL. You could use the more complete example at http://docs.python.org/extending/embedding.html which includes some error handling... Anyways, apparently PyImport_Import can't import from the current working directory but with parameters like math sqrt 2 it returns the square root of 2. Setting PYTHONPATH to point to the working directory works for me, but I don't know if there's a more correct solution. From curty at free.fr Tue Oct 18 10:23:49 2011 From: curty at free.fr (Curt) Date: 18 Oct 2011 14:23:49 GMT Subject: [OT] Re: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2011-10-17, Steven D'Aprano wrote: > > That is no more deep and meaningful than the fact that while some people > say "one plus one equals two", others say "eins und eins gleich zwei", > some say "un et un fait deux" and some say "???? ? ???? ???? ???". **** Most of us say "un et un _font_ deux," in fact, because we know how to conjugate as well as perform simple arithmetic. :-) From ramit.prasad at jpmorgan.com Tue Oct 18 14:23:18 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 18 Oct 2011 14:23:18 -0400 Subject: Re-raise different exception with original stack trace In-Reply-To: <4E98BC91.3010207@mrabarnett.plus.com> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F217865A4@EMARC112VS01.exchad.jpmchase.net> <4E98BC91.3010207@mrabarnett.plus.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2186310B@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- From: python-list-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of MRAB Sent: Friday, October 14, 2011 5:50 PM To: python-list at python.org Subject: Re: Re-raise different exception with original stack trace On 14/10/2011 22:30, Prasad, Ramit wrote: > Hi all, > Hopefully you guys can help me with my problem. > > Basically I have a UI program that can "save" information. The UI passes the save to the controller and the controller saves a file and does some post processing. If saving the file fails, I want to handle the error differently than if the error was in post processing. In both cases the possible exceptions are varied and unknown so I cannot pick and choose certain exception. The problem with the sample program below is that the stack trace is replaced by the re-raise. What would be the best way(s) to get the original stack trace in save_from_UI if the exception occurs in post_process? Using Python 2.6 and Windows(XP and 7) / Linux. > > Def save_from_model(): > save() # do not catch exception (could be any exception) > try: > post_process() > except Exception as e: > #do something > raise CustomException() # "wrap" exception so bar knows to handle it differently > > def save_from_UI(): > try: > foo() > except CustomException() as e: > # How do I get the original stacktrace instead of the reraise? > except Exception as e: > # do something else with this exception > You could save a reference to the exception in the custom exception: class CustomException(Exception): def __init__(self, e): Exception.__init__(self) self.exc = e def save_from_model(): save() # do not catch exception (could be any exception) try: post_process() except Exception as e: #do something raise CustomException(e) def save_from_UI(): try: foo() except CustomException as e: # Original exception is e.exc except Exception as e: # do something else with this exception ======================================================================= Yes, but raising the CustomException replaces the last traceback and even with the saved exception, how would you get the original stacktrace? The only thing I can think is get the stacktrace and store it in the exception. That does not seem very Pythonic to me. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ian.g.kelly at gmail.com Tue Oct 18 15:45:26 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 18 Oct 2011 13:45:26 -0600 Subject: Re-raise different exception with original stack trace In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2186310B@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F217865A4@EMARC112VS01.exchad.jpmchase.net> <4E98BC91.3010207@mrabarnett.plus.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2186310B@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Tue, Oct 18, 2011 at 12:23 PM, Prasad, Ramit wrote: > Yes, but raising the CustomException replaces the last traceback and even with the saved exception, how would you get the original stacktrace? The only thing I can think is get the stacktrace and store it in the exception. That does not seem very Pythonic to me. In Python 3 you could chain the exceptions with: except Exception as e: raise CustomException() from e There is no such syntax in Python 2, but you could manually store and retrieve the __cause__ and __traceback__ attributes similarly to the way Python 3 does it. See PEP 3134 for full details. HTH, Ian From devplayer at gmail.com Tue Oct 18 18:14:29 2011 From: devplayer at gmail.com (DevPlayer) Date: Tue, 18 Oct 2011 15:14:29 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <87vcrntk67.fsf@benfinney.id.au> Message-ID: <7f0318ad-d9de-4651-8e70-0e1258125c2c@b10g2000vbc.googlegroups.com> "3rd Base" From kwebb at teradactyl.com Tue Oct 18 21:37:00 2011 From: kwebb at teradactyl.com (Kristen J. Webb) Date: Tue, 18 Oct 2011 19:37:00 -0600 Subject: ssl module with C Message-ID: <4E9E29BC.8080307@teradactyl.com> Hi All, I'm hoping that the answer to this question will shed light on the Python/C interface and make me a much better python programer. I have a test TLS connection program in python (very breif) import socket, ssl news=socket.socket() news.connect() new_ssl=ssl.wrap_socket() new_ssl.read()/new_ssl.write() I'd like to pass my new_ssl to a C .so library so that I can SSL_read()/SSL_write. Why? Using the python/ssl interface gets me around so many issues with varies Linux distros as libssl.so is so unstandard. My idea is that using the installed python helps me to separte my own work-horse C code from the native openssl library. Can this be done? If not, the why should make me a better python programer! Many thanks in advance! Kris -- Mr. Kristen J. Webb Teradactyl LLC. PHONE: 1-505-242-1091 EMAIL: kwebb at teradactyl.com VISIT: http://www.teradactyl.com Home of the True incremental Backup System From steve+comp.lang.python at pearwood.info Tue Oct 18 23:05:28 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 19 Oct 2011 03:05:28 GMT Subject: [OT] Re: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> On Tue, 18 Oct 2011 14:23:49 +0000, Curt wrote: > On 2011-10-17, Steven D'Aprano > wrote: >> >> That is no more deep and meaningful than the fact that while some >> people say "one plus one equals two", others say "eins und eins gleich >> zwei", some say "un et un fait deux" and some say "???? ? ???? ???? >> ???". > **** > > Most of us say "un et un _font_ deux," in fact, because we know how to > conjugate as well as perform simple arithmetic. > > :-) I blame Google Translate. -- Steven From wuwei23 at gmail.com Tue Oct 18 23:58:05 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 18 Oct 2011 20:58:05 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: <3cbd7630-2dd0-4b36-9a76-a024364c2b0f@42g2000prp.googlegroups.com> DevPlayer wrote: > Ever hear/read the term: "It's all good."? A reference to Karma and > how things will work out for the better in the end inspite of what you > see now... A great example of "Everything is Symantics". "Semantics". Also: nonsense. You're conflating an ethical system with a _completely_ indepdent symbolic one via overloaded terminology. That's pretty true of most of your rants, actually. > And another weird notion to put forward. "2" as a numberic quantity by > itself is utterly meaningless. Two what? More nonsense. The whole field of number theory would like to dispute this point. So would Python: i = 2. What exactly does i hold? Two integers? From wuwei23 at gmail.com Wed Oct 19 00:03:22 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 18 Oct 2011 21:03:22 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <87vcrntk67.fsf@benfinney.id.au> Message-ID: On Oct 18, 6:52?am, Ben Finney wrote: > A belief that doesn't match reality is a delusion. That doesn't change > when someone thinks it's an epiphany: it's still a delusion. Apparently there was some talk about removing delusional as a classification from the DSM due to its definition being, in part, that it was an _unshared_ belief (which seems to be a loophole for not locking up the religious). With the advent of the internet, it's almost impossible to _not_ find someone who agrees with you, no matter how batshit crazy you might be :) From wuwei23 at gmail.com Wed Oct 19 00:05:42 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 18 Oct 2011 21:05:42 -0700 (PDT) Subject: strange comparison result with 'is' References: <1318840924.74377.YahooMailNeo@web121512.mail.ne1.yahoo.com> Message-ID: <95885d32-ecfd-4e70-9f35-4bcaad57e96f@u10g2000prl.googlegroups.com> On Oct 18, 3:53?am, Terry Reedy wrote: > This has come up enough that I opened http://bugs.python.org/issue13203 I really don't get the new Python user obsession with id(). I don't think I've ever used it, in production code or otherwise. From rustompmody at gmail.com Wed Oct 19 03:03:01 2011 From: rustompmody at gmail.com (rusi) Date: Wed, 19 Oct 2011 00:03:01 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Oct 17, 7:34?pm, Steven D'Aprano wrote: > That is no more deep and meaningful than the fact that while some people > say "one plus one equals two", others say "eins und eins gleich zwei", > some say "un et un fait deux" and some say "???? ? ???? ???? ???". > Regardless of whether you write two, zwei, ???, ???, 2 (in decimal), 10 > (in binary), II (in Roman numerals) or even {0,1} using set theory > notation, the number remains the same, only the symbol we use to label it > is different. And Ben said: > A belief that doesn't match reality is a delusion. That doesn't change > when someone thinks it's an epiphany: it's still a delusion. > If a claim about reality doesn't actually match reality, it's untrue. > That doesn't change when someone believes it: it's still untrue, or > claims it's ?part of a bigger picture?. These are classical platonist claims: In short objective reality exists aside from the subjective perception of it. Here is an extract from Gurevich's http://research.microsoft.com/en-us/um/people/gurevich/opera/123.pdf ------------------------------------------ Q: Still, most mathematicians are Platonists, is that right? A: I think so. Q: Somehow we independently grow to become Platonists. A: I do not think it is always independent. To an extent, we learn the attitude. I remember, in a geometry class, my teacher wanted to prove the congruence of two triangles. Let?s take a third triangle, she said, and I asked where do triangles come from. I worried that there may be no more triangles there. Those were hard times in Russia, and we were accustomed to shortages. Q: What did she say? A: She looked at me for a while and then said: ?Shut up?. But eventually I got the idea that you don?t have to build a triangle when you need one; all possible triangles exist ahead of time. -------------------------- Quantum physics would not exist if all physicists were as cock-sure of objective reality. Nor would computer science. Heres a capsule history: Kronecker and Cantor disagree on whether sets exist. K: Only numbers exist. C: All manner of infinite sets exist A generation later and continuing Hilbert and Brouwer disagree on what constitutes a proof A generation later Godel sets out to demolish Hilbert's formalist agenda. Turing tries to demolish Godel. He does not succeed (Simple questions turn out to be undecidable/non-computable. However a side-effect of his attempts is... the computer Python version: The integers that exist in builtin type int exist somehow differently from the integers in function nats def nats(): ... n = -1 ... while True: ... n +=1 ... yield n which once again exist differently from the integers in range(10). In short: To be a computer scientist (as against classical scientist) is to know that "to exist" "to be true" "to be valid" are more real valued than boolean predicates From aspineux at gmail.com Wed Oct 19 04:06:53 2011 From: aspineux at gmail.com (aspineux) Date: Wed, 19 Oct 2011 01:06:53 -0700 (PDT) Subject: fromutc: dt.tzinfo is not self: pytz.timezone('UTC').fromutc(datetime.utcnow()) Message-ID: hi >>> import pytz >>> from datetime import datetime >>> pytz.timezone('GMT0').fromutc(datetime.utcnow()) datetime.datetime(2011, 10, 19, 7, 54, 45, 579125, tzinfo=) >>> pytz.timezone('UTC').fromutc(datetime.utcnow()) Traceback (most recent call last): File "", line 1, in ValueError: fromutc: dt.tzinfo is not self >>> pytz.timezone('Europe/Brussels').fromutc(datetime.utcnow()) datetime.datetime(2011, 10, 19, 9, 55, 47, 787937, tzinfo=) Why does UTC fail ? Bug or feature ? From clp2 at rebertia.com Wed Oct 19 04:32:58 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 19 Oct 2011 01:32:58 -0700 Subject: fromutc: dt.tzinfo is not self: pytz.timezone('UTC').fromutc(datetime.utcnow()) In-Reply-To: References: Message-ID: On Wed, Oct 19, 2011 at 1:06 AM, aspineux wrote: > hi > >>>> import pytz >>>> from datetime import datetime >>>> pytz.timezone('GMT0').fromutc(datetime.utcnow()) > datetime.datetime(2011, 10, 19, 7, 54, 45, 579125, > tzinfo=) >>>> ?pytz.timezone('UTC').fromutc(datetime.utcnow()) > Traceback (most recent call last): > ?File "", line 1, in > ValueError: fromutc: dt.tzinfo is not self >>>> pytz.timezone('Europe/Brussels').fromutc(datetime.utcnow()) > datetime.datetime(2011, 10, 19, 9, 55, 47, 787937, tzinfo= 'Europe/Brussels' CEST+2:00:00 DST>) > > Why does UTC fail ? > Bug or feature ? Dunno, but it might be worth noting that the examples in the pytz docs don't use .fromutc(). Have you tried using .localize() instead? Or specifically in the case of UTC, datetime.utcnow().replace(tzinfo=pytz.utc) ? Cheers, Chris From ben+python at benfinney.id.au Wed Oct 19 07:06:40 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Oct 2011 22:06:40 +1100 Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <87vcrntk67.fsf@benfinney.id.au> Message-ID: <87fwips0jj.fsf@benfinney.id.au> alex23 writes: > On Oct 18, 6:52?am, Ben Finney wrote: > > A belief that doesn't match reality is a delusion. That doesn't change > > when someone thinks it's an epiphany: it's still a delusion. > > Apparently there was some talk about removing delusional as a > classification from the DSM due to its definition being, in part, that > it was an _unshared_ belief (which seems to be a loophole for not > locking up the religious). Does the DSM define delusion dependent on who shares the belief? I thought that was, rather, part of the definition of delusional disorder. In other words, some delusions don't count as disorders because plenty of people share them, but are still delusions. Just as most people's vision has some imperfection, but visual disorders would be diagnosed in some smaller subset of those people. I don't have access to the DSM, though, so can only speculate based on indirect sources . -- \ ?For myself, I am an optimist ? it does not seem to be much use | `\ being anything else.? ?Winston Churchill, 1954-11-09 | _o__) | Ben Finney From rustompmody at gmail.com Wed Oct 19 07:17:41 2011 From: rustompmody at gmail.com (rusi) Date: Wed, 19 Oct 2011 04:17:41 -0700 (PDT) Subject: Equal sets with unequal print and str() representations References: <4E9B6E23.9050106@cs.utah.edu> Message-ID: On Oct 17, 7:47?am, Terry Reedy wrote: > On 10/16/2011 9:17 PM, Ian Kelly wrote: > > > On Sun, Oct 16, 2011 at 5:52 PM, Ganesh Gopalakrishnan > > ?wrote: > >> This probably is known, but a potential pitfall (was, for me) nevertheless. > >> I suspect it is due to hash collisions between 's3' and 's13' in this case? > >> It happens only rarely, depending on the contents of the set. > > > I'm not sure exactly which keys are colliding here, but in general the > > iteration order of a set (or dict) depends not just on the contents, > > but also on the order of insertion. ?And of course the repr depends on > > the iteration order -- anything consistent would require sorting, > > which would be O(n log n) and is not even necessarily well-defined. > > To put it another way, any dependence on the arbitrary ordering of > unordered collections in iteration or displays is a programming error. Given that this is becoming a FAQ, I wonder if something like the above statement should go into the docs? From ben+python at benfinney.id.au Wed Oct 19 07:30:42 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Oct 2011 22:30:42 +1100 Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87botdrzfh.fsf@benfinney.id.au> rusi writes: > These are classical platonist claims: In short objective reality > exists aside from the subjective perception of it. Yes, that's the simplest explanation for the comparability of our observations: there's one reality and we all inhabit it. > Quantum physics would not exist if all physicists were as cock-sure of > objective reality. Not at all. It's because those physicists *are* sure that there is an objective reality that they are able to form testable hypotheses about it and come up with objective tests and make objectively-comparable observations of objective reality to see which hypotheses are objectively false. As a result, quantum physics is responsible for astoundingly accurate correspondence between its predictions of objective reality and what is actually observed. That's not grounds to be cock-sure of any particular explanation; the whole enterprise of scientific inquiry is based on trying to demonstrate that people's explanations are false. But it's certainly grounds to be confident that reality exists and is the same for everyone. People's subjective perception of reality can of course be wrong to varying degrees; and that's what science is designed to discover. But it is pointless to try to find out more about objective reality unless one takes objective reality as an axiom. > Heres a capsule history: [mathematicians disagree about reality and > much progress results] Yes, exactly. Much progress is made in testing prejudices and assumptions and hypotheses about objective reality to see which ones are objectively false, and not by abandoning objective reality for some ?my subjective perception is just as god as yours? miasma. That's just wrong-headed: subjective perception is commonly an inaccurate representation of what's real, and we delude ourselves if we think that doesn't apply to us. -- \ ?Don't be misled by the enormous flow of money into bad defacto | `\ standards for unsophisticated buyers using poor adaptations of | _o__) incomplete ideas.? ?Alan Kay | Ben Finney From rustompmody at gmail.com Wed Oct 19 08:17:37 2011 From: rustompmody at gmail.com (rusi) Date: Wed, 19 Oct 2011 05:17:37 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <87botdrzfh.fsf@benfinney.id.au> Message-ID: On Oct 19, 4:30?pm, Ben Finney wrote: > rusi writes: > > These are classical platonist claims: ?In short objective reality > > exists aside from the subjective perception of it. > > Yes, that's the simplest explanation for the comparability of our > observations: there's one reality and we all inhabit it. > > > Quantum physics would not exist if all physicists were as cock-sure of > > objective reality. > > Not at all. It's because those physicists *are* sure that there is an > objective reality that they are able to form testable hypotheses about > it and come up with objective tests and make objectively-comparable > observations of objective reality to see which hypotheses are > objectively false. It may be better to let the quantum physicists speak for themselves? [From http://www.marxists.org/reference/subject/philosophy/works/ge/heisenb3.htm] In classical physics science started from the belief - or should one say from the illusion? - that we could describe the world or at least parts of the world without any reference to ourselves. This division (into object and rest of the world) is arbitrary and historically a direct consequence of our scientific method; the use of the classical concepts is finally a consequence of the general human way of thinking. But this is already a reference to ourselves and in so far our description is not completely objective. Objectivity has become the first criterion for the value of any scientific result... (and the Copenhagen interpretation of) quantum theory corresponds to this ideal as far as possible. From curty at free.fr Wed Oct 19 09:15:54 2011 From: curty at free.fr (Curt) Date: 19 Oct 2011 13:15:54 GMT Subject: [OT] Re: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2011-10-19, Steven D'Aprano wrote: > On Tue, 18 Oct 2011 14:23:49 +0000, Curt wrote: > >> Most of us say "un et un _font_ deux," in fact, because we know how to >> conjugate as well as perform simple arithmetic. >> >> :-) > > > I blame Google Translate. > I thought you were trying to shine as a polyglot(math). From hg at schaathun.net Wed Oct 19 09:30:26 2011 From: hg at schaathun.net (Hans Georg Schaathun) Date: Wed, 19 Oct 2011 14:30:26 +0100 Subject: tiff/pbm in pyplot (ubuntu) Message-ID: Does anyone know how to get support for tiff/pbm in pyplot on Ubuntu (11.04)? This used to work for me, on some system, but when I attempt to regenerate my TIFF files on a new system, it all crashes. The error message is clear; TIFF and PBM are not supported, and the exception occurs in a call to imsave(). I know that someone will suggest to use PNG instead, converting with ImageMagick. Trouble is, when I load a grayscale PNG in python I get a 3D array with three colour channels. I need a 2D array, and I'd rather avoid the hassle of modifying all the occurrences to accept a 3D array and check that the colour channels are equal. I'll be grateful for any pointers, TIA -- :-- Hans Georg From ramit.prasad at jpmorgan.com Wed Oct 19 11:50:09 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 19 Oct 2011 11:50:09 -0400 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F217865FA@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F218F794A@EMARC112VS01.exchad.jpmchase.net> Redirecting to his question to the list. >I need of a matrix, not of an array. >But is this error due to a numpy bug? I am not an expert on NumPy/SciPy, but I do not believe matrixes are allowed to be 3 dimensional. Google only produced results of 3 dimensional arrays. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From admin at mbnoimi.net Wed Oct 19 13:14:49 2011 From: admin at mbnoimi.net (Muhammad Bashir Al-Noimi) Date: Wed, 19 Oct 2011 20:14:49 +0300 Subject: Python based silent installer, how to? Message-ID: <4E9F0589.9020005@mbnoimi.net> An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: admin.vcf Type: text/x-vcard Size: 332 bytes Desc: not available URL: From markus.mj at gmail.com Wed Oct 19 16:14:21 2011 From: markus.mj at gmail.com (markus.mj at gmail.com) Date: Wed, 19 Oct 2011 13:14:21 -0700 (PDT) Subject: Threading: Method trigger after thred finished Message-ID: <13676309.461.1319055261456.JavaMail.geo-discussion-forums@yqnv12> Hi, I am looking for help with following problem. I scripted threaded database query, with session open per thread, and queries delivered through queue. Every open DB session must be closed with "abort" or "commit", however on which event should I trigger the DB disconnect? Ideally it would close the DB as the thread class gets deconstructed, but "__del__" does never fire. How would you solve the problem? Here an non working example (bended from IBM developerWorks tutorial) that explains the situation: multi_query = ["query1","query2","query3","query4","query5","query6"] queue = Queue.Queue() class ThreadSql(threading.Thread): def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue #Open database connection instance self.session = DbConnect() def run(self): while True: #grabs query from queue query = self.queue.get() #Fire query and print result print self.session.SQL(query) #Queue job is done self.queue.task_done() # THIS PART IS NOT WORKING def __del__(self): #Disconnect Database session and commit or abort transactions self.session.Disconnect() print "The End" #--------------------------------- for i in range(5): t = ThreadUrl(queue) t.setDaemon(True) t.start() #Fill the queue for single_query in multi_query: queue.put(single_query) #Wait until query is empty and finish queue.join() Thank you for any idea! Markus From steve+comp.lang.python at pearwood.info Wed Oct 19 17:00:23 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 19 Oct 2011 21:00:23 GMT Subject: Python based silent installer, how to? References: Message-ID: <4e9f3a67$0$29974$c3e8da3$5496439d@news.astraweb.com> On Wed, 19 Oct 2011 20:14:49 +0300, Muhammad Bashir Al-Noimi wrote: > > > > > > > bidimailui-detected-decoding-type="UTF-8" bgcolor="#FFFFFF" > text="#000000"> >

Hi All,

>


>

Please don't send raw HTML (so-called "rich text") to mailing lists. It makes it very difficult for some people to read. If you must use HTML, please ensure your email client or news reader also sends a plain text version of the message as well. >

I'm using many python based packages (ex. href="http://launchpad.net/bzr/2.4/2.4.1/+download/bzr-2.4.1-1.win32- py2.6.exe">bzr-2.4.1-1.win32-py2.6.exe) > inside my installer.
>
> How can I install them silently in Windows?

That will depend on what your installer is, and whether it has an option for silent installation. Your question is unclear. What is the connection between Python and the installer? "I am installing Python on Windows." "Python is already installed, and I'm installing extra Python packages, using many different installers." "I'm installing applications using an installer written in Python." "I'm writing my own installer, using Python." or something else? If you want a better answer, you will need to explain what you are doing in more detail. -- Steven From steve+comp.lang.python at pearwood.info Wed Oct 19 17:01:39 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 19 Oct 2011 21:01:39 GMT Subject: [OT] Re: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> On Wed, 19 Oct 2011 13:15:54 +0000, Curt wrote: > On 2011-10-19, Steven D'Aprano > wrote: >> On Tue, 18 Oct 2011 14:23:49 +0000, Curt wrote: >> >>> Most of us say "un et un _font_ deux," in fact, because we know how to >>> conjugate as well as perform simple arithmetic. >>> >>> :-) >> >> >> I blame Google Translate. >> >> > I thought you were trying to shine as a polyglot(math). I am a poly-illiterate. I can't read or write hundreds of languages. -- Steven From steve+comp.lang.python at pearwood.info Wed Oct 19 17:03:21 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 19 Oct 2011 21:03:21 GMT Subject: fromutc: dt.tzinfo is not self: pytz.timezone('UTC').fromutc(datetime.utcnow()) References: Message-ID: <4e9f3b19$0$29974$c3e8da3$5496439d@news.astraweb.com> On Wed, 19 Oct 2011 01:06:53 -0700, aspineux wrote: > hi > >>>> import pytz >>>> from datetime import datetime >>>> pytz.timezone('GMT0').fromutc(datetime.utcnow()) > datetime.datetime(2011, 10, 19, 7, 54, 45, 579125, tzinfo= 'GMT0'>) >>>> pytz.timezone('UTC').fromutc(datetime.utcnow()) > Traceback (most recent call last): > File "", line 1, in > ValueError: fromutc: dt.tzinfo is not self >>>> pytz.timezone('Europe/Brussels').fromutc(datetime.utcnow()) > datetime.datetime(2011, 10, 19, 9, 55, 47, 787937, tzinfo= 'Europe/Brussels' CEST+2:00:00 DST>) > > Why does UTC fail ? > Bug or feature ? Looks like a bug to me. But I'm not an expert on pytz. Perhaps you should report it back to the package author. -- Steven From anikom15 at gmail.com Wed Oct 19 17:49:26 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 19 Oct 2011 14:49:26 -0700 Subject: [OT] Re: Benefit and belief In-Reply-To: <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20111019214926.GA31343@Smoke> On Wed, Oct 19, 2011 at 09:01:39PM +0000, Steven D'Aprano wrote: > On Wed, 19 Oct 2011 13:15:54 +0000, Curt wrote: > > > On 2011-10-19, Steven D'Aprano > > wrote: > >> On Tue, 18 Oct 2011 14:23:49 +0000, Curt wrote: > >> > >>> Most of us say "un et un _font_ deux," in fact, because we know how to > >>> conjugate as well as perform simple arithmetic. > >>> > >>> :-) > >> > >> > >> I blame Google Translate. > >> > >> > > I thought you were trying to shine as a polyglot(math). > > I am a poly-illiterate. I can't read or write hundreds of languages. I think you need to speak German fluently to be a good programmer. From ben+python at benfinney.id.au Wed Oct 19 18:12:54 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 20 Oct 2011 09:12:54 +1100 Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <87botdrzfh.fsf@benfinney.id.au> Message-ID: <8739eosk9l.fsf@benfinney.id.au> rusi writes: > This division (into object and rest of the world) is arbitrary and > historically a direct consequence of our scientific method; the use of > the classical concepts is finally a consequence of the general human > way of thinking. But this is already a reference to ourselves and in > so far our description is not completely objective. Yes, it's natural for humans to think in dualistic terms ? thinking that the self is separate from the external world ? and that thinking is unsupported by evidence so is probably wrong. That doesn't argue against the position I've been elaborating, and it doesn't say anything against objective reality. We humans are part of that objective reality, and descriptions of reality need to incorporate that fact. -- \ ?I got food poisoning today. I don't know when I'll use it.? | `\ ?Steven Wright | _o__) | Ben Finney From alec.taylor6 at gmail.com Wed Oct 19 18:35:45 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Thu, 20 Oct 2011 09:35:45 +1100 Subject: Python based silent installer, how to? In-Reply-To: <4E9F0589.9020005@mbnoimi.net> References: <4E9F0589.9020005@mbnoimi.net> Message-ID: Just download the msi (script is available to regenerate yourself) and run it with the silent swtich, something like: msiexec /x nameofmsi.msi On 10/20/11, Muhammad Bashir Al-Noimi wrote: > Hi All, > > > I'm using many python based packages (ex. bzr-2.4.1-1.win32-py2.6.exe) > inside my installer. > > How can I install them silently in Windows? > > PS > > Most installers has arguments for silent installation ex. NSIS based > installers has /S argument but I didn't find any reference for python based > installers > > -- > Best Regards > Muhammad Bashir Al-Noimi > My Blog: http://mbnoimi.net From steve+comp.lang.python at pearwood.info Wed Oct 19 23:55:44 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 20 Oct 2011 03:55:44 GMT Subject: Threading: Method trigger after thred finished References: <13676309.461.1319055261456.JavaMail.geo-discussion-forums@yqnv12> Message-ID: <4e9f9bc0$0$29974$c3e8da3$5496439d@news.astraweb.com> On Wed, 19 Oct 2011 13:14:21 -0700, markus.mj wrote: > Hi, > > I am looking for help with following problem. I scripted threaded > database query, with session open per thread, and queries delivered > through queue. Every open DB session must be closed with "abort" or > "commit", however on which event should I trigger the DB disconnect? > Ideally it would close the DB as the thread class gets deconstructed, > but "__del__" does never fire. The __del__ destructor method is not guaranteed to be called in a timely fashion, if at all. My *guess* is that the main Python environment is shutting down when the daemon threads get killed, and the __del__ method never gets a chance to run. To be honest, I'm not sure why you are using daemon threads. It seems to me that blocking until the queue is empty makes the use of daemon threads pointless, but I'm not experienced enough with threads to be sure. The usual advice is to explicitly call destructors rather than rely on automatic __del__ methods. Given that, this works for me: import threading import Queue import time # Fill the queue. queue = Queue.Queue() queries = ["query"+str(i) for i in range(10)] for query in queries: queue.put(query) # Make consumer threads. class ThreadSql(threading.Thread): def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue # Open database connection instance self.session = "+++connection+++" # DbConnect() self._open = True def run(self): while self._open: # Grab a query from queue. query = self.queue.get() # And process it. print self, query time.sleep(1) # Mark the queue job as done. self.queue.task_done() def close(self): print "Closing", self # self.session.Disconnect() self._open = False threads = [ThreadSql(queue) for _ in range(4)] for t in threads: t.setDaemon(True) t.start() # Wait until the queue is empty, then close the threads. queue.join() for t in threads: t.close() -- Steven From markus.mj at gmail.com Thu Oct 20 03:05:27 2011 From: markus.mj at gmail.com (Markus) Date: Thu, 20 Oct 2011 00:05:27 -0700 (PDT) Subject: Threading: Method trigger after thred finished References: <13676309.461.1319055261456.JavaMail.geo-discussion-forums@yqnv12> <4e9f9bc0$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: <7bb60119-a84a-4660-83ff-f9c50191a667@g25g2000yqh.googlegroups.com> On Oct 20, 5:55?am, Steven D'Aprano wrote: > On Wed, 19 Oct 2011 13:14:21 -0700, markus.mj wrote: > > Hi, > > > I am looking for help with following problem. I scripted threaded > > database query, with session open per thread, and queries delivered > > through queue. Every open DB session must be closed with "abort" or > > "commit", however on which event should I trigger the DB disconnect? > > Ideally it would close the DB as the thread class gets deconstructed, > > but "__del__" does never fire. > > The __del__ destructor method is not guaranteed to be called in a timely > fashion, if at all. My *guess* is that the main Python environment is > shutting down when the daemon threads get killed, and the __del__ method > never gets a chance to run. > > To be honest, I'm not sure why you are using daemon threads. It seems to > me that blocking until the queue is empty makes the use of daemon threads > pointless, but I'm not experienced enough with threads to be sure. > > The usual advice is to explicitly call destructors rather than rely on > automatic __del__ methods. Given that, this works for me: > > import threading > import Queue > import time > > # Fill the queue. > queue = Queue.Queue() > queries = ["query"+str(i) for i in range(10)] > for query in queries: > ? ? queue.put(query) > > # Make consumer threads. > class ThreadSql(threading.Thread): > ? ? def __init__(self, queue): > ? ? ? ? threading.Thread.__init__(self) > ? ? ? ? self.queue = queue > ? ? ? ? # Open database connection instance > ? ? ? ? self.session = "+++connection+++" ?# DbConnect() > ? ? ? ? self._open = True > > ? ? def run(self): > ? ? ? ? while self._open: > ? ? ? ? ? ? # Grab a query from queue. > ? ? ? ? ? ? query = self.queue.get() > ? ? ? ? ? ? # And process it. > ? ? ? ? ? ? print self, query > ? ? ? ? ? ? time.sleep(1) > ? ? ? ? ? ? # Mark the queue job as done. > ? ? ? ? ? ? self.queue.task_done() > > ? ? def close(self): > ? ? ? ? print "Closing", self > ? ? ? ? # self.session.Disconnect() > ? ? ? ? self._open = False > > threads = [ThreadSql(queue) for _ in range(4)] > for t in threads: > ? ? t.setDaemon(True) > ? ? t.start() > > # Wait until the queue is empty, then close the threads. > queue.join() > for t in threads: > ? ? t.close() > > -- > Steven Hi Steven, great point with the explicit call of destructor. I did a quick test and it is behaving exactly like I need. Thank you very much! Markus From steve+comp.lang.python at pearwood.info Thu Oct 20 04:04:16 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 20 Oct 2011 08:04:16 GMT Subject: Are range iterators thread safe? Message-ID: <4e9fd600$0$29974$c3e8da3$5496439d@news.astraweb.com> Using Python 3, are range_iterator objects thread-safe? I have tried this, and it seems to be safe: >>> from threading import Thread >>> x = iter(range(4)) >>> def doit(x): ... print("result =", next(x)) ... >>> threads = [Thread(target=doit, args=(x,)) for i in range(4)] >>> for t in threads: ... t.start() ... result = 0 result = 1 result = 2 result = 3 >>> -- Steven From oh at no.no Thu Oct 20 04:06:21 2011 From: oh at no.no (Uffe Kousgaard) Date: Thu, 20 Oct 2011 10:06:21 +0200 Subject: COM / .NET Message-ID: <4e9fd67f$0$281$14726298@news.sunsite.dk> Is python able to access COM libraries or .NET assemblies? If both, which is the easist or most popular? From mail at timgolden.me.uk Thu Oct 20 04:42:11 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 20 Oct 2011 09:42:11 +0100 Subject: COM / .NET In-Reply-To: <4e9fd67f$0$281$14726298@news.sunsite.dk> References: <4e9fd67f$0$281$14726298@news.sunsite.dk> Message-ID: <4E9FDEE3.7010401@timgolden.me.uk> On 20/10/2011 09:06, Uffe Kousgaard wrote: > Is python able to access COM libraries or .NET assemblies? If both, which is > the easist or most popular? You have a few choices in this regard: * CPython can access COM objects either via the pywin32 extensions[1] or via comtypes[2]. The former is maintained and is quite mature and stable (and has recently had a small fix made to allow more flexibility when dealing with COM VARIANTS). comtypes, I think, unmaintained, although perfectly usable and somewhat more flexible than pywin32 in certain respects. * Python.NET [3] is a project which was dormant for a while but which is now maintained once more. This is a sort of bridge between CPython and the .NET assemblies. * IronPython [4] is a project, originally run inside Microsoft, now spun off as an Open Source project, which re-implements Python as a 1st-class .NET language running on the DLR. From that you have full access to the .NET Framework and its facilities. [1] http://sourceforge.net/projects/pywin32/ [2] http://pypi.python.org/pypi/comtypes [3] http://pythonnet.sourceforge.net/ (not sure if that's the canonical URL for that project or not) [4] http://ironpython.net/ TJG From admin at mbnoimi.net Thu Oct 20 04:45:51 2011 From: admin at mbnoimi.net (Muhammad Bashir Al-Noimi) Date: Thu, 20 Oct 2011 11:45:51 +0300 Subject: Python based silent installer, how to? In-Reply-To: References: <4E9F0589.9020005@mbnoimi.net> Message-ID: <4E9FDFBF.2020801@mbnoimi.net> On 20/10/2011 01:35 ?, Alec Taylor wrote: > Just download the msi (script is available to regenerate yourself) and > run it with the silent swtich, something like: > > msiexec /x nameofmsi.msi Sorry I didn't explain what I'm looking for exactly. I've packages built by bdist_wininst, Is there any way for install them silently? Or is there any way for convert them to another format (ex. msi) in that way I can install them silently. -- Best Regards Muhammad Bashir Al-Noimi My Blog: http://mbnoimi.net -------------- next part -------------- A non-text attachment was scrubbed... Name: admin.vcf Type: text/x-vcard Size: 332 bytes Desc: not available URL: From admin at mbnoimi.net Thu Oct 20 05:05:24 2011 From: admin at mbnoimi.net (Muhammad Bashir Al-Noimi) Date: Thu, 20 Oct 2011 12:05:24 +0300 Subject: Python based silent installer, how to? In-Reply-To: <4e9f3a67$0$29974$c3e8da3$5496439d@news.astraweb.com> References: <4e9f3a67$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E9FE454.7090106@mbnoimi.net> On 20/10/2011 12:00 ?, Steven D'Aprano wrote: > Please don't send raw HTML (so-called "rich text") to mailing lists. It > makes it very difficult for some people to read. If you must use HTML, > please ensure your email client or news reader also sends a plain text > version of the message as well. Sorry I forgot to configure my Thunderbird. > That will depend on what your installer is, and whether it has an option > for silent installation. > > Your question is unclear. What is the connection between Python and the > installer? > > "I am installing Python on Windows." > > "Python is already installed, and I'm installing extra Python packages, > using many different installers." > > "I'm installing applications using an installer written in Python." > > "I'm writing my own installer, using Python." > > or something else? > > > If you want a better answer, you will need to explain what you are doing > in more detail. I've packages built by bdist_wininst, Is there any way for install them silently? Or is there any way for convert them to another format (ex. msi) in that way I can install them silently. PS I tried to unzip that packages (I thought I may re-package un-zipped packages by NSIS or something else) and I discovered that the structure of directories of bdist_wininst packages so different! for example: ---xlwt-0.7.2.win32.exe--- PURELIB | |-- xlwt-0.7.2-py2.5.egg-info |-+ xlwt |-+ doc |-+ examples |-- __init__.py |-- antlr.py . . ---bzr-2.3.4-1.win32-py2.6.exe--- DATA |-- Doc PLATLIB | |-- bzr-2.3.4-py2.6.egg-info |-+ bzrlib |-+ bundle |-+ doc |-- __init__.py |-- _annotator_py.py . . SCRIPTS | |-- bzr |-- bzr-win32-bdist-postinstall.py -- Best Regards Muhammad Bashir Al-Noimi My Blog: http://mbnoimi.net -------------- next part -------------- A non-text attachment was scrubbed... Name: admin.vcf Type: text/x-vcard Size: 332 bytes Desc: not available URL: From oh at no.no Thu Oct 20 05:12:10 2011 From: oh at no.no (Uffe Kousgaard) Date: Thu, 20 Oct 2011 11:12:10 +0200 Subject: COM / .NET References: <4e9fd67f$0$281$14726298@news.sunsite.dk> Message-ID: <4e9fe5ec$0$290$14726298@news.sunsite.dk> "Tim Golden" wrote in message news:mailman.2075.1319100141.27778.python-list at python.org... > > You have a few choices in this regard: Thanks for a detailed reply. We'll start looking at [1] and [3]. From mail at timgolden.me.uk Thu Oct 20 05:12:45 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 20 Oct 2011 10:12:45 +0100 Subject: Python based silent installer, how to? In-Reply-To: <4E9FDFBF.2020801@mbnoimi.net> References: <4E9F0589.9020005@mbnoimi.net> <4E9FDFBF.2020801@mbnoimi.net> Message-ID: <4E9FE60D.8020009@timgolden.me.uk> On 20/10/2011 09:45, Muhammad Bashir Al-Noimi wrote: > On 20/10/2011 01:35 ?, Alec Taylor wrote: >> Just download the msi (script is available to regenerate yourself) and >> run it with the silent swtich, something like: >> >> msiexec /x nameofmsi.msi > Sorry I didn't explain what I'm looking for exactly. > > I've packages built by bdist_wininst, Is there any way for install them > silently? > Or is there any way for convert them to another format (ex. msi) in that > way I can install them silently. If you can get the source (specifically including the setup.py which I don't think is included in the wininst .zip) then you can use that to build an msi: python setup.py bdist_msi which you can then manage via the usual msiexec switches. It's often available from the same source as the wininst .exe and/or from the project's code repository. If not, you're down to reverse-engineering a suitable setup.py. For many projects this is pretty simple. TJG From stefan_ml at behnel.de Thu Oct 20 05:22:18 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 20 Oct 2011 11:22:18 +0200 Subject: Are range iterators thread safe? In-Reply-To: <4e9fd600$0$29974$c3e8da3$5496439d@news.astraweb.com> References: <4e9fd600$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano, 20.10.2011 10:04: > Using Python 3, are range_iterator objects thread-safe? > > I have tried this, and it seems to be safe: > > >>> from threading import Thread > >>> x = iter(range(4)) > >>> def doit(x): > ... print("result =", next(x)) > ... > >>> threads = [Thread(target=doit, args=(x,)) for i in range(4)] > >>> for t in threads: > ... t.start() > ... > result = 0 > result = 1 > result = 2 > result = 3 The GIL ensures it's thread safe. Stefan From admin at mbnoimi.net Thu Oct 20 07:14:04 2011 From: admin at mbnoimi.net (Muhammad Bashir Al-Noimi) Date: Thu, 20 Oct 2011 14:14:04 +0300 Subject: Python based silent installer, how to? In-Reply-To: <4E9FE60D.8020009@timgolden.me.uk> References: <4E9F0589.9020005@mbnoimi.net> <4E9FDFBF.2020801@mbnoimi.net> <4E9FE60D.8020009@timgolden.me.uk> Message-ID: <4EA0027C.1010001@mbnoimi.net> On 20/10/2011 12:12 ?, Tim Golden wrote: > If you can get the source (specifically including the setup.py > which I don't think is included in the wininst .zip) then you > can use that to build an msi: > > python setup.py bdist_msi > > which you can then manage via the usual msiexec switches. > > It's often available from the same source as the wininst .exe > and/or from the project's code repository. In case I got .egg file (ex. http://pypi.python.org/pypi/setuptools/0.6c11) from some website, can I use it as alternative to bdist_wininst package? In case 'yes' where I've to put .egg file? -- Best Regards Muhammad Bashir Al-Noimi My Blog: http://mbnoimi.net -------------- next part -------------- A non-text attachment was scrubbed... Name: admin.vcf Type: text/x-vcard Size: 332 bytes Desc: not available URL: From ben+python at benfinney.id.au Thu Oct 20 07:23:42 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 20 Oct 2011 22:23:42 +1100 Subject: Are range iterators thread safe? References: <4e9fd600$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87obxbrjnl.fsf@benfinney.id.au> Stefan Behnel writes: > Steven D'Aprano, 20.10.2011 10:04: > > Using Python 3, are range_iterator objects thread-safe? > The GIL ensures it's thread safe. The GIL applies only to CPython. What is the answer for other Python implementations which don't have a GIL? -- \ Eccles: ?I just saw the Earth through the clouds!? Lew: ?Did | `\ it look round?? Eccles: ?Yes, but I don't think it saw me.? | _o__) ?The Goon Show, _Wings Over Dagenham_ | Ben Finney From lists at cheimes.de Thu Oct 20 07:27:01 2011 From: lists at cheimes.de (Christian Heimes) Date: Thu, 20 Oct 2011 13:27:01 +0200 Subject: Threading: Method trigger after thred finished In-Reply-To: <4e9f9bc0$0$29974$c3e8da3$5496439d@news.astraweb.com> References: <13676309.461.1319055261456.JavaMail.geo-discussion-forums@yqnv12> <4e9f9bc0$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 20.10.2011 05:55, schrieb Steven D'Aprano: > # Make consumer threads. > class ThreadSql(threading.Thread): > def __init__(self, queue): > threading.Thread.__init__(self) > self.queue = queue > # Open database connection instance > self.session = "+++connection+++" # DbConnect() > self._open = True > > def run(self): > while self._open: > # Grab a query from queue. > query = self.queue.get() > # And process it. > print self, query > time.sleep(1) > # Mark the queue job as done. > self.queue.task_done() > > def close(self): > print "Closing", self > # self.session.Disconnect() > self._open = False The code may contain a subtle and nasty bug but this really depends on your database connection. Most db connections are neither thread safe nor reentrant and must not be shared between threads. However this code shares the connection across two threads. The __init__() method is run inside the thread that *creates* the new thread, not the new thread. Just the run() is executed in the new thread. I suggest that you acquire and close the connection inside the run() method protected by an try/finally or with block. Christian From 4k3nd0 at googlemail.com Thu Oct 20 08:34:14 2011 From: 4k3nd0 at googlemail.com (4k3nd0) Date: Thu, 20 Oct 2011 14:34:14 +0200 Subject: Insert Data with pymongo Message-ID: <4EA01546.3080609@gmail.com> Hi guys, i want to insert a JSON formated String into a mongoDB. But get some problem with the insert to the database. Traceback (most recent call last): File "obp_import_pb.py", line 102, in do_import() File "obp_import_pb.py", line 97, in do_import collection = db.pb_mp.insert(obp_transaction_json) File "/usr/lib64/python2.7/site-packages/pymongo/collection.py", line 274, in insert docs = [self.__database._fix_incoming(doc, self) for doc in docs] File "/usr/lib64/python2.7/site-packages/pymongo/database.py", line 249, in _fix_incoming son = manipulator.transform_incoming(son, collection) File "/usr/lib64/python2.7/site-packages/pymongo/son_manipulator.py", line 73, in transform_incoming son["_id"] = ObjectId() TypeError: 'str' object does not support item assignment I'm using json.dumps to format a json string obp_transaction_json = json.dumps(......) I took a look about the pymongo Doc, which didn't help me a bit. I using Python 2.7, on a Gentoo(Linux-3.0.5) AMD64 Greeting's from Germany, Akendo From stefan_ml at behnel.de Thu Oct 20 08:43:49 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 20 Oct 2011 14:43:49 +0200 Subject: Are range iterators thread safe? In-Reply-To: <87obxbrjnl.fsf@benfinney.id.au> References: <4e9fd600$0$29974$c3e8da3$5496439d@news.astraweb.com> <87obxbrjnl.fsf@benfinney.id.au> Message-ID: Ben Finney, 20.10.2011 13:23: > Stefan Behnel writes: > >> Steven D'Aprano, 20.10.2011 10:04: >>> Using Python 3, are range_iterator objects thread-safe? >> The GIL ensures it's thread safe. > > The GIL applies only to CPython. and PyPy. > What is the answer for other Python > implementations which don't have a GIL? That would basically be Jython and IronPython. Note that none of the three alternative implementations currently supports Python language version 3. So, the current answer for all existing Python 3 implementations is: the GIL ensures that it's thread safe. Stefan From roy at panix.com Thu Oct 20 08:54:13 2011 From: roy at panix.com (Roy Smith) Date: Thu, 20 Oct 2011 08:54:13 -0400 Subject: Insert Data with pymongo References: Message-ID: In article , 4k3nd0 <4k3nd0 at googlemail.com> wrote: > Hi guys, > > i want to insert a JSON formated String into a mongoDB. But get some > problem with the insert to the database. > > Traceback (most recent call last): > File "obp_import_pb.py", line 102, in > do_import() > File "obp_import_pb.py", line 97, in do_import > collection = db.pb_mp.insert(obp_transaction_json) > File "/usr/lib64/python2.7/site-packages/pymongo/collection.py", line > 274, in insert > docs = [self.__database._fix_incoming(doc, self) for doc in docs] > File "/usr/lib64/python2.7/site-packages/pymongo/database.py", line > 249, in _fix_incoming > son = manipulator.transform_incoming(son, collection) > File "/usr/lib64/python2.7/site-packages/pymongo/son_manipulator.py", > line 73, in transform_incoming > son["_id"] = ObjectId() > TypeError: 'str' object does not support item assignment > > > I'm using json.dumps to format a json string > > obp_transaction_json = json.dumps(......) > > I took a look about the pymongo Doc, which didn't help me a bit. > I using Python 2.7, on a Gentoo(Linux-3.0.5) AMD64 You haven't given enough information to even guess at the problem. Does the exception get thrown as part of the assignment, or evaluating the "....." you pass to json.dumps()? I would start by breaking things down into smaller pieces and seeing which piece raises the exception. Also, post more of your code so we can see what's going on. From lanyjie at yahoo.com Thu Oct 20 09:19:40 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Thu, 20 Oct 2011 06:19:40 -0700 (PDT) Subject: compare range objects Message-ID: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> Hi,? Is it possible to test if two range objects contain the same sequence of integers by the following algorithm in Python 3.2? 1. standardize the ending bound by letting it be the first excluded integer for the given step size. 2. compare the standardized starting bound, ending bound and step size: two ranges equal if and only if this triplet is the same. If that's correct, it would be good to have equality comparison on two ranges.? Further, it might also be good to have sub-sequence test on ranges without enumerating it. Cheers, Yingjie From lanyjie at yahoo.com Thu Oct 20 09:23:50 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Thu, 20 Oct 2011 06:23:50 -0700 (PDT) Subject: revive a generator Message-ID: <1319117030.48985.YahooMailNeo@web121516.mail.ne1.yahoo.com> Hi, it seems a generator expression can be used only once: >>> g = (x*x for x in range(3)) >>> for x in g: print x 0 1 4 >>> for x in g: print x #nothing printed >>> Is there any way to revive g here? Yingjie From rosuav at gmail.com Thu Oct 20 09:52:13 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Oct 2011 00:52:13 +1100 Subject: revive a generator In-Reply-To: <1319117030.48985.YahooMailNeo@web121516.mail.ne1.yahoo.com> References: <1319117030.48985.YahooMailNeo@web121516.mail.ne1.yahoo.com> Message-ID: On Fri, Oct 21, 2011 at 12:23 AM, Yingjie Lan wrote: > Hi, > > it seems a generator expression can be used only once: > >>>> g = (x*x for x in range(3)) >>>> for x in g: print x > 0 > 1 > 4 >>>> for x in g: print x #nothing printed >>>> > > Is there any way to revive g here? If you're not generating very much, just use a list comprehension instead; you can iterate over the list as many times as you like: >>> g = [x*x for x in range(3)] >>> for x in g: print(x) 0 1 4 >>> for x in g: print(x) 0 1 4 Of course, since this is Python 3, you need the parens on print, but I assume you had something else you were doing with x. ChrisA From paul.nospam at rudin.co.uk Thu Oct 20 10:28:53 2011 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Thu, 20 Oct 2011 15:28:53 +0100 Subject: revive a generator References: Message-ID: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> Yingjie Lan writes: > Hi, > > it seems a generator expression can be used only once: > >>>> g = (x*x for x in range(3)) >>>> for x in g: print x > 0 > 1 > 4 >>>> for x in g: print x #nothing printed >>>> > > Is there any way to revive g here? > Generators are like that - you consume them until they run out of values. You could have done [x*x for x in range(3)] and then iterated over that list as many times as you wanted. A generator doesn't have to remember all the values it generates so it can be more memory efficient that a list. Also it can, for example, generate an infinite sequence. From ian.g.kelly at gmail.com Thu Oct 20 12:00:57 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 20 Oct 2011 10:00:57 -0600 Subject: Are range iterators thread safe? In-Reply-To: References: <4e9fd600$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Oct 20, 2011 at 3:22 AM, Stefan Behnel wrote: > Steven D'Aprano, 20.10.2011 10:04: >> >> Using Python 3, are range_iterator objects thread-safe? >> >> I have tried this, and it seems to be safe: >> >> >>> from threading import Thread >> >>> x = iter(range(4)) >> >>> def doit(x): >> ... ? ? print("result =", next(x)) >> ... >> >>> threads = [Thread(target=doit, args=(x,)) for i in range(4)] >> >>> for t in threads: >> ... ? ? t.start() >> ... >> result = 0 >> result = 1 >> result = 2 >> result = 3 > > The GIL ensures it's thread safe. Because range_iterator objects are implemented in C and so calling the __next__ method is only a single bytecode instruction, correct? If they were implemented in Python the GIL would make no such assurance. From anikom15 at gmail.com Thu Oct 20 12:22:04 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 20 Oct 2011 09:22:04 -0700 Subject: compare range objects In-Reply-To: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> Message-ID: <20111020162204.GA26505@Smoke> On Thu, Oct 20, 2011 at 06:19:40AM -0700, Yingjie Lan wrote: > Hi,? > > Is it possible to test if two range objects contain the same sequence of integers by the following algorithm in Python 3.2? > > 1. standardize the ending bound by letting it be the first excluded integer for the given step size. > 2. compare the standardized starting bound, ending bound and step size: two ranges equal if and only if this triplet is the same. > > If that's correct, it would be good to have equality comparison on two ranges.? > > Further, it might also be good to have sub-sequence test on ranges without enumerating it. > There's already a discussion about this on python-ideas. But somebody please tell me, why would you ever need to compare ranges? From bulg at ngs.ru Thu Oct 20 13:28:11 2011 From: bulg at ngs.ru (Yosifov Pavel) Date: Thu, 20 Oct 2011 10:28:11 -0700 (PDT) Subject: Py3K: file inheritance Message-ID: In the Python 2.x was simple to create own file object: class MyFile(file): pass for example to reimplement write() or something else. How to do it in Python 3.x? From ian.g.kelly at gmail.com Thu Oct 20 13:42:13 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 20 Oct 2011 11:42:13 -0600 Subject: Py3K: file inheritance In-Reply-To: References: Message-ID: On Thu, Oct 20, 2011 at 11:28 AM, Yosifov Pavel wrote: > In the Python 2.x was simple to create own file object: > > class MyFile(file): > ?pass > > for example to reimplement write() or something else. How to do it in > Python 3.x? See the docs for the io module. Depending on what you want to do, you probably need to subclass either io.FileIO or io.TextIOWrapper. From gordon at panix.com Thu Oct 20 13:46:31 2011 From: gordon at panix.com (John Gordon) Date: Thu, 20 Oct 2011 17:46:31 +0000 (UTC) Subject: Benefits of xml.dom.minidom? Message-ID: I recently inherited some code that uses xml.dom.minidom to build a large XML document, and I noticed that it is quite slow and uses a ton of memory. I converted the same code to use lxml.etree and it is much faster and uses not nearly so much memory. Why is minidom so hungry for resources? What is it doing with all that memory and CPU? -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From hansmu at xs4all.nl Thu Oct 20 14:00:57 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Thu, 20 Oct 2011 20:00:57 +0200 Subject: compare range objects In-Reply-To: References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> Message-ID: <4ea061da$0$6941$e4fe514c@news2.news.xs4all.nl> On 20/10/11 18:22:04, Westley Mart?nez wrote: > On Thu, Oct 20, 2011 at 06:19:40AM -0700, Yingjie Lan wrote: >> Hi, >> >> Is it possible to test if two range objects contain the same sequence of integers by the following algorithm in Python 3.2? >> >> 1. standardize the ending bound by letting it be the first excluded integer for the given step size. >> 2. compare the standardized starting bound, ending bound and step size: two ranges equal if and only if this triplet is the same. >> >> If that's correct, it would be good to have equality comparison on two ranges. >> >> Further, it might also be good to have sub-sequence test on ranges without enumerating it. >> > > There's already a discussion about this on python-ideas. But somebody > please tell me, why would you ever need to compare ranges? It could be useful if you're unit-testing a function that returns a range. -- HansM From ian.g.kelly at gmail.com Thu Oct 20 14:14:56 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 20 Oct 2011 12:14:56 -0600 Subject: compare range objects In-Reply-To: <4ea061da$0$6941$e4fe514c@news2.news.xs4all.nl> References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <4ea061da$0$6941$e4fe514c@news2.news.xs4all.nl> Message-ID: On Thu, Oct 20, 2011 at 12:00 PM, Hans Mulder wrote: >> There's already a discussion about this on python-ideas. ?But somebody >> please tell me, why would you ever need to compare ranges? > > It could be useful if you're unit-testing a function that returns a range. Easy: list(range1) == list(range2) From ethan at stoneleaf.us Thu Oct 20 14:24:53 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 20 Oct 2011 11:24:53 -0700 Subject: compare range objects In-Reply-To: References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <4ea061da$0$6941$e4fe514c@news2.news.xs4all.nl> Message-ID: <4EA06775.4060003@stoneleaf.us> Ian Kelly wrote: > On Thu, Oct 20, 2011 at 12:00 PM, Hans Mulder wrote: >>> There's already a discussion about this on python-ideas. But somebody >>> please tell me, why would you ever need to compare ranges? >> It could be useful if you're unit-testing a function that returns a range. > > Easy: > > list(range1) == list(range2) The biggest reason in my mind for implementing range equality is that currently two ranges compare equal iff they are the same range. In other words: --> range(10) == range(10) False ~Ethan~ From driley at mantaro.com Thu Oct 20 14:25:47 2011 From: driley at mantaro.com (David Riley) Date: Thu, 20 Oct 2011 14:25:47 -0400 Subject: sysconfig on OS X 10.7 (Lion) and XCode 4.2 Message-ID: <5ED3F418-A03D-4BE6-91A5-51C0DF899FC5@mantaro.com> Hello all, I've struggled mightily to get Numpy and pyopencl installed on my brand-new Lion machine running XCode 4.2 (not recommended, I know, but I'm a sucker for punishment). I did finally succeed, anyway. I found that the greatest problem I had (after installing gfortran from a precompiled package) was getting setup.py and subsidiaries to use the right GCC. The python.org official builds of Python (I'm specifically using 3.2.2, though I'm sure this applies to 2.7 as well) have some trouble with building extensions because CC is specified as "gcc-4.2", which no longer exists in XCode 4.2 (one could chalk that up to being Apple's problem, but hey). The root of this problem is in the sysconfig module, which I assume has hardcoded names for the compiler, etc. Most insidious was fixing LDSHARED, which was gcc-4.2 with a bunch of flags appended to it including the system framework (for 10.6, I should point out, which is also what sysconfig returned for sysconfig.platform()). Is there any way to permanently override these values in sysconfig short of building my own Python and installing it? I'm having to override the environment variables whenever I build a C/C++ module, and it's getting to be a pain. For anyone looking for the answer to a similar problem (usually gcc-4.2 not being found when running setup.py), export the following environment variables to build things under XCode 4.2: CC=gcc CXX=g++ LDSHARED="gcc -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.7.sdk -isysroot /Developer/SDKs/MacOSX10.7.sdk -g" (obviously, replace 10.7 with 10.6 if you're building under 10.6) For example: sudo CC=gcc CXX=g++ LDSHARED="gcc -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.7.sdk -isysroot /Developer/SDKs/MacOSX10.7.sdk -g" pip install pyopencl This will override the default values taken from the sysconfig module. - Dave From dihedral88888 at googlemail.com Thu Oct 20 14:34:54 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Thu, 20 Oct 2011 11:34:54 -0700 (PDT) Subject: compare range objects In-Reply-To: <4ea061da$0$6941$e4fe514c@news2.news.xs4all.nl> References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <4ea061da$0$6941$e4fe514c@news2.news.xs4all.nl> Message-ID: <29301560.436.1319135694405.JavaMail.geo-discussion-forums@prms22> The range() in python is an iterable generator that returns an object ref/id. The xrange() is different. From chris at 3fdev.com Thu Oct 20 14:39:45 2011 From: chris at 3fdev.com (Christopher Saunders) Date: Thu, 20 Oct 2011 11:39:45 -0700 (PDT) Subject: google maps api help Message-ID: <7d3df23f-fc24-41f5-a4d3-87b2f4d44c77@13g2000prp.googlegroups.com> I have an excel sheet with a bunch of info regarding the stops a delivery truck makes throughout the day. I can successfully extract the information I need with xlrd. This is the code I am using: book = xlrd.open_workbook(r'c:\xytest.xls') sheet= book.sheet_by_index(0) odList = [] for i in range(1,6125): cID = sheet.row(i)[0].value #Company ID tID = sheet.row(i)[1].value #Truck ID xyCoord = sheet.row_values(i,start_colx = 8,end_colx = 10 ) #long and lat xyCoord.reverse() #reversed, so that lat,long is in correct format odList.append([cID,tID,xyCoord]) Printing odList give me this output where fields are [CompanyID,TruckID, Lat,Long] : [[5000020.0, 1.0, [35.779999, -78.115784]], [5000020.0, 1.0, [36.075812, -78.256766]], [5000020.0, 1.0, [35.779999, -78.115784]], [5000020.0, 2.0, [35.79528, -78.137549]], [5000020.0, 3.0, [35.79528, -78.137549]] I used list indices to grab the coordinates and query gmaps with: result = gmaps.directions(odList[0][2],odList[1][2]) time = result['Directions']['Duration']['seconds'] dist = result['Directions']['Distance']['meters'] Unfortunately, gmaps does not understand [35.779999, -78.115784], [36.075812, -78.256766], gmaps does understand (35.779999, -78.115784), (36.075812, -78.256766). Any ideas on how to get the query to send () instead of [] ? From hidura at gmail.com Thu Oct 20 14:55:38 2011 From: hidura at gmail.com (Hidura) Date: Thu, 20 Oct 2011 14:55:38 -0400 Subject: Benefits of xml.dom.minidom? In-Reply-To: References: Message-ID: I use minidom all the time and i don' t have that problem could you describe more of the process ? El oct 20, 2011 5:53 p.m., "John Gordon" escribi?: > > I recently inherited some code that uses xml.dom.minidom to build a large > XML document, and I noticed that it is quite slow and uses a ton of memory. > > I converted the same code to use lxml.etree and it is much faster and > uses not nearly so much memory. > > Why is minidom so hungry for resources? What is it doing with all that > memory and CPU? > > -- > John Gordon A is for Amy, who fell down the stairs > gordon at panix.com B is for Basil, assaulted by bears > -- Edward Gorey, "The Gashlycrumb Tinies" > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Thu Oct 20 14:57:38 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 20 Oct 2011 20:57:38 +0200 Subject: Benefits of xml.dom.minidom? In-Reply-To: References: Message-ID: John Gordon, 20.10.2011 19:46: > I recently inherited some code that uses xml.dom.minidom to build a large > XML document, and I noticed that it is quite slow and uses a ton of memory. > > I converted the same code to use lxml.etree and it is much faster and > uses not nearly so much memory. > > Why is minidom so hungry for resources? What is it doing with all that > memory and CPU? Not much. It's memory hungry because it builds a tree from rather heavy XML objects and is neither optimised for speed nor for a low memory footprint. Its main purpose is to be (mostly) W3C DOM compatible. It's also been in the standard library for quite a bit longer than ElementTree, and predates lxml by years. That's the most likely reason why your original script was written using minidom. In a way, it's unfair to compare minidom with lxml.etree (or cElementTree, for that purpose), as the latter two were specifically designed for high performance and a much simpler API. Stefan From python at mrabarnett.plus.com Thu Oct 20 15:02:50 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 20 Oct 2011 20:02:50 +0100 Subject: google maps api help In-Reply-To: <7d3df23f-fc24-41f5-a4d3-87b2f4d44c77@13g2000prp.googlegroups.com> References: <7d3df23f-fc24-41f5-a4d3-87b2f4d44c77@13g2000prp.googlegroups.com> Message-ID: <4EA0705A.8020602@mrabarnett.plus.com> On 20/10/2011 19:39, Christopher Saunders wrote: > I have an excel sheet with a bunch of info regarding the stops a > delivery truck makes throughout the day. I can successfully extract > the information I need with xlrd. This is the code I am using: > > book = xlrd.open_workbook(r'c:\xytest.xls') > sheet= book.sheet_by_index(0) > odList = [] > > for i in range(1,6125): > cID = sheet.row(i)[0].value #Company ID > tID = sheet.row(i)[1].value #Truck ID > xyCoord = sheet.row_values(i,start_colx = 8,end_colx = 10 ) #long > and lat > xyCoord.reverse() #reversed, so that lat,long is in correct format > odList.append([cID,tID,xyCoord]) > > > Printing odList give me this output where fields are > [CompanyID,TruckID, Lat,Long] : [[5000020.0, 1.0, [35.779999, > -78.115784]], [5000020.0, 1.0, [36.075812, -78.256766]], [5000020.0, > 1.0, [35.779999, -78.115784]], [5000020.0, 2.0, [35.79528, > -78.137549]], [5000020.0, 3.0, [35.79528, -78.137549]] > > I used list indices to grab the coordinates and query gmaps with: > > result = gmaps.directions(odList[0][2],odList[1][2]) > time = result['Directions']['Duration']['seconds'] > dist = result['Directions']['Distance']['meters'] > > Unfortunately, gmaps does not understand [35.779999, -78.115784], > [36.075812, -78.256766], gmaps does understand (35.779999, -78.115784), > (36.075812, -78.256766). Any ideas on how to get the query to send () > instead of [] ? Try turning the lists into tuples: result = gmaps.directions(tuple(odList[0][2]), tuple(odList[1][2])) From chris at 3fdev.com Thu Oct 20 15:28:44 2011 From: chris at 3fdev.com (Christopher Saunders) Date: Thu, 20 Oct 2011 12:28:44 -0700 (PDT) Subject: google maps api help References: <7d3df23f-fc24-41f5-a4d3-87b2f4d44c77@13g2000prp.googlegroups.com> Message-ID: On Oct 20, 1:02?pm, MRAB wrote: > On 20/10/2011 19:39, Christopher Saunders wrote: > > > > > > > > > > > I have an excel sheet with a bunch of info regarding the stops a > > delivery truck makes throughout the day. ?I can successfully extract > > the information I need with xlrd. ?This is the code I am using: > > > book = xlrd.open_workbook(r'c:\xytest.xls') > > sheet= book.sheet_by_index(0) > > odList = [] > > > for i in range(1,6125): > > ? ? ?cID = sheet.row(i)[0].value #Company ID > > ? ? ?tID = sheet.row(i)[1].value #Truck ID > > ? ? ?xyCoord = sheet.row_values(i,start_colx = 8,end_colx = 10 ) #long > > and lat > > ? ? ?xyCoord.reverse() #reversed, so that lat,long is in correct format > > ? ? ?odList.append([cID,tID,xyCoord]) > > > Printing odList give me this output where fields are > > [CompanyID,TruckID, Lat,Long] : [[5000020.0, 1.0, [35.779999, > > -78.115784]], [5000020.0, 1.0, [36.075812, -78.256766]], [5000020.0, > > 1.0, [35.779999, -78.115784]], [5000020.0, 2.0, [35.79528, > > -78.137549]], [5000020.0, 3.0, [35.79528, -78.137549]] > > > I used list indices to grab the coordinates and query gmaps with: > > > result = gmaps.directions(odList[0][2],odList[1][2]) > > time = result['Directions']['Duration']['seconds'] > > dist = result['Directions']['Distance']['meters'] > > > Unfortunately, gmaps does not understand [35.779999, -78.115784], > > [36.075812, -78.256766], gmaps does understand (35.779999, -78.115784), > > (36.075812, -78.256766). ?Any ideas on how to get the query to send () > > instead of [] ? > > Try turning the lists into tuples: > > result = gmaps.directions(tuple(odList[0][2]), tuple(odList[1][2])) Awesome, that worked! From tjreedy at udel.edu Thu Oct 20 15:56:30 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 20 Oct 2011 15:56:30 -0400 Subject: revive a generator In-Reply-To: <1319117030.48985.YahooMailNeo@web121516.mail.ne1.yahoo.com> References: <1319117030.48985.YahooMailNeo@web121516.mail.ne1.yahoo.com> Message-ID: On 10/20/2011 9:23 AM, Yingjie Lan wrote: > it seems a generator expression can be used only once: Generators are iterators. Once iterators raise StopIteration, they are supposed to continue doing so. A generator expression defines a temporary anonymous generator function that is called once to produce a generator and then deleted. It, like all comprehensions, is purely a convenient abbreviation. >>>> g = (x*x for x in range(3)) for x in g: print x > 0 1 4 >>>> for x in g: print x #nothing printed Define a named generator function (and add a parameter to make it more flexible and useful and reuse it. def g(n): for i in range(n): yield i*i Then, "for x in g(3)", "for x in g(8)", "for x in g(y*x)", etc, as many times as you want. You might call it 'square' or even 'r_square' instead of 'g'. -- Terry Jan Reedy From nad at acm.org Thu Oct 20 16:20:50 2011 From: nad at acm.org (Ned Deily) Date: Thu, 20 Oct 2011 13:20:50 -0700 Subject: sysconfig on OS X 10.7 (Lion) and XCode 4.2 References: <5ED3F418-A03D-4BE6-91A5-51C0DF899FC5@mantaro.com> Message-ID: In article <5ED3F418-A03D-4BE6-91A5-51C0DF899FC5 at mantaro.com>, David Riley wrote: > I've struggled mightily to get Numpy and pyopencl installed on my brand-new > Lion machine running XCode 4.2 (not recommended, I know, but I'm a sucker for > punishment). I did finally succeed, anyway. > > I found that the greatest problem I had (after installing gfortran from a > precompiled package) was getting setup.py and subsidiaries to use the right > GCC. The python.org official builds of Python (I'm specifically using 3.2.2, > though I'm sure this applies to 2.7 as well) have some trouble with building > extensions because CC is specified as "gcc-4.2", which no longer exists in > XCode 4.2 (one could chalk that up to being Apple's problem, but hey). > > The root of this problem is in the sysconfig module, which I assume has > hardcoded names for the compiler, etc. Most insidious was fixing LDSHARED, > which was gcc-4.2 with a bunch of flags appended to it including the system > framework (for 10.6, I should point out, which is also what sysconfig > returned for sysconfig.platform()). > > Is there any way to permanently override these values in sysconfig short of > building my own Python and installing it? I'm having to override the > environment variables whenever I build a C/C++ module, and it's getting to be > a pain. > > > > For anyone looking for the answer to a similar problem (usually gcc-4.2 not > being found when running setup.py), export the following environment > variables to build things under XCode 4.2: > > CC=gcc > CXX=g++ > LDSHARED="gcc -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 > -isysroot /Developer/SDKs/MacOSX10.7.sdk -isysroot > /Developer/SDKs/MacOSX10.7.sdk -g" > > (obviously, replace 10.7 with 10.6 if you're building under 10.6) > > For example: > > sudo CC=gcc CXX=g++ LDSHARED="gcc -bundle -undefined dynamic_lookup -arch > i386 -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.7.sdk -isysroot > /Developer/SDKs/MacOSX10.7.sdk -g" pip install pyopencl > > > This will override the default values taken from the sysconfig module. On OS X, Python's Distutils goes to some trouble to ensure that C extension modules are built with the same compiler and compatible settings as the Python interpreter itself was built. The current python.org 64-bit/32-bit installers (which I assume you are using) for 3.2.x and 2.7.x were built on 10.6 using the gcc-4.2 available in Xcode 3. Now that Xcode 4.2 has been released and has deleted gcc-4.2, that's a problem. A thorough building and testing cycle using the various compiler options (llvm-gcc and clang) is needed for Lion; there have been problems already reported and corrected for clang with Xcode 4.1. I'm starting to do that. It would be helpful if you could open an issue on the Python bug tracker (http://bugs.python.org) and summarize what you've found there. -- Ned Deily, nad at acm.org From greg.ewing at canterbury.ac.nz Thu Oct 20 17:05:46 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Fri, 21 Oct 2011 10:05:46 +1300 Subject: COM / .NET In-Reply-To: References: <4e9fd67f$0$281$14726298@news.sunsite.dk> Message-ID: <9gbgpaFvh6U1@mid.individual.net> Tim Golden wrote: > You have a few choices in this regard: Also it's reportedly possible to register a .NET assembly as a COM library and use it that way. -- Greg From ramit.prasad at jpmorgan.com Thu Oct 20 17:26:37 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 20 Oct 2011 17:26:37 -0400 Subject: Problem with a wx notebook In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21A39706@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- From: python-list-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of faucheuse Sent: Monday, October 17, 2011 5:33 AM To: python-list at python.org Subject: Problem with a wx notebook Hi there, I've created a wx NoteBook in wich I set multiples panels in wich I set one or more sizers. But nothing displays in the notebook, everything is outside. I've been searching an answer for 2 days ><. Can you help me plz ? Here is my code(with only one panel, to sum up the code) : class StreamingActivationDialog(wx.Dialog): def __init__(self, *args, **kwds): # begin wxGlade: StreamingActivationDialog.__init__ kwds["style"] = wx.DEFAULT_DIALOG_STYLE wx.Dialog.__init__(self, *args, **kwds) self.bitmap_1_copy = wx.StaticBitmap(self, -1, wx.Bitmap("img\ \logo.png", wx.BITMAP_TYPE_ANY)) self.labelDnD = wx.StaticText(self, -1, "Si vous avez d?j? un fichier d'activation, faite le glisser dans cette fenetre") self.keyBitmap = wx.StaticBitmap(self, -1, wx.Bitmap("img\ \key.bmp", wx.BITMAP_TYPE_ANY)) self.conclude = wx.StaticText(self, -1, _("test"), style=wx.ALIGN_CENTRE) ### Panel ### self.intro3_label = wx.StaticText(self, -1, "Envoyez un mail ? \nactivation at monmail.com\ncontenant le code :",style=wx.ALIGN_CENTRE) self.activationCode_label= wx.StaticText(self, -1, "123456789", style=wx.TE_READONLY) self.copy2_Button = wx.Button(self, -1, "Copier dans le presse- papier") self.copy2_Button.Bind(wx.EVT_BUTTON, PanelMail.onCopy) ############## self.note = wx.Notebook(self, wx.ID_ANY, style=wx.BK_LEFT, size=wx.Size(100, 341)) self.page3 = wx.Panel(self.note) imagelist = wx.ImageList(94, 94) bitmap1 = wx.Bitmap("img\\a.bmp", wx.BITMAP_TYPE_BMP ) imagelist.Add(bitmap1) self.note.AssignImageList(imagelist) self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: StreamingActivationDialog.__set_properties self.SetTitle(_("Activation de FlashProcess")) self.SetBackgroundColour(wx.Colour(255, 255, 255)) #self.linkProblem.SetForegroundColour(wx.Colour(0, 0, 0)) # end wxGlade def __do_layout(self): # begin wxGlade: StreamingActivationDialog.__do_layout self.grid_sizer_1 = wx.FlexGridSizer(6, 1, 0, 0) self.grid_sizer_2 = wx.FlexGridSizer(1, 2, 0, 30) self.grid_sizer_1.Add(self.bitmap_1_copy, 0, wx.TOP|wx.BOTTOM| wx.EXPAND, 10) ### Page 3 ### sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.intro3_label, 0, wx.BOTTOM|wx.ALIGN_CENTER, 5) sizer.Add(self.activationCode_label, 0, wx.BOTTOM| wx.ALIGN_CENTER, 20) sizer.Add(self.copy2_Button, 0, wx.ALIGN_CENTER, 20) self.page3.SetSizer(sizer) sizer.Fit(self.page3) ############## self.note.AddPage(self.page3, "", False, 0) self.Bind(wx.EVT_TOOLBOOK_PAGE_CHANGED, self.OnPageChanged) self.Bind(wx.EVT_TOOLBOOK_PAGE_CHANGING, self.OnPageChanging) self.grid_sizer_1.Add(self.note, 0, wx.EXPAND, 20) self.grid_sizer_1.Add(self.labelDnD, 0, wx.TOP| wx.ALIGN_CENTER_HORIZONTAL, 20) self.grid_sizer_2.Add(self.keyBitmap, 0, wx.LEFT, 10) self.grid_sizer_2.Add(self.labelDnD, 0, wx.LEFT, 20) self.grid_sizer_1.Add(self.grid_sizer_2, 0, wx.EXPAND, 20) self.grid_sizer_1.Add(self.conclude, 0, wx.TOP| wx.ALIGN_CENTER_HORIZONTAL, 20) self.SetSizer(self.grid_sizer_1) self.grid_sizer_1.Fit(self) self.Layout() # end wxGlade def OnPageChanged(self, event): event.Skip() def OnPageChanging(self, event): event.Skip() ========================================= Is this still a problem? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From mwilson at the-wire.com Thu Oct 20 17:49:24 2011 From: mwilson at the-wire.com (Mel) Date: Thu, 20 Oct 2011 17:49:24 -0400 Subject: Problem with a wx notebook References: Message-ID: Prasad, Ramit wrote: > I've created a wx NoteBook in wich I set multiples panels in wich I > set one or more sizers. But nothing displays in the notebook, > everything is outside. I've been searching an answer for 2 days ><. > Can you help me plz ? Here is my code(with only one panel, to sum up > the code) : > > class StreamingActivationDialog(wx.Dialog): > def __init__(self, *args, **kwds): > # begin wxGlade: StreamingActivationDialog.__init__ > kwds["style"] = wx.DEFAULT_DIALOG_STYLE > wx.Dialog.__init__(self, *args, **kwds) > self.bitmap_1_copy = wx.StaticBitmap(self, -1, wx.Bitmap("img\ > \logo.png", wx.BITMAP_TYPE_ANY)) > self.labelDnD = wx.StaticText(self, -1, "Si vous avez d?j? un > fichier d'activation, faite le glisser dans cette fenetre") > self.keyBitmap = wx.StaticBitmap(self, -1, wx.Bitmap("img\ > \key.bmp", wx.BITMAP_TYPE_ANY)) > self.conclude = wx.StaticText(self, -1, _("test"), > style=wx.ALIGN_CENTRE) > > ### Panel ### > self.intro3_label = wx.StaticText(self, -1, "Envoyez un mail ? > \nactivation at monmail.com\ncontenant le code :",style=wx.ALIGN_CENTRE) > self.activationCode_label= wx.StaticText(self, -1, > "123456789", style=wx.TE_READONLY) > self.copy2_Button = wx.Button(self, -1, "Copier dans le presse- > papier") > self.copy2_Button.Bind(wx.EVT_BUTTON, PanelMail.onCopy) > ############## > > self.note = wx.Notebook(self, wx.ID_ANY, style=wx.BK_LEFT, > size=wx.Size(100, 341)) > self.page3 = wx.Panel(self.note) > > imagelist = wx.ImageList(94, 94) > bitmap1 = wx.Bitmap("img\\a.bmp", wx.BITMAP_TYPE_BMP ) > imagelist.Add(bitmap1) > self.note.AssignImageList(imagelist) > > self.__set_properties() > self.__do_layout() > # end wxGlade > > def __set_properties(self): > # begin wxGlade: StreamingActivationDialog.__set_properties > self.SetTitle(_("Activation de FlashProcess")) > self.SetBackgroundColour(wx.Colour(255, 255, 255)) > #self.linkProblem.SetForegroundColour(wx.Colour(0, 0, 0)) > # end wxGlade > > def __do_layout(self): > # begin wxGlade: StreamingActivationDialog.__do_layout > self.grid_sizer_1 = wx.FlexGridSizer(6, 1, 0, 0) > self.grid_sizer_2 = wx.FlexGridSizer(1, 2, 0, 30) > self.grid_sizer_1.Add(self.bitmap_1_copy, 0, wx.TOP|wx.BOTTOM| > wx.EXPAND, 10) > > > ### Page 3 ### > sizer = wx.BoxSizer(wx.VERTICAL) > sizer.Add(self.intro3_label, 0, wx.BOTTOM|wx.ALIGN_CENTER, 5) > sizer.Add(self.activationCode_label, 0, wx.BOTTOM| > wx.ALIGN_CENTER, 20) > sizer.Add(self.copy2_Button, 0, wx.ALIGN_CENTER, 20) > > self.page3.SetSizer(sizer) > sizer.Fit(self.page3) > ############## > > self.note.AddPage(self.page3, "", False, 0) [ ... ] It looks a though all the controls that are meant for page3 have been created with the top-level dialog as their parent. AFAIK this cannot be. self.page3 is (correctly) a child window of self.note, but the controls to be shown inside have to be children of self.page3 . Putting things into the sizers is not enough. In my own code, I usually define a separate class descended from wx.Panel to create a page3 instance with its own sizers, then create one of those with a a wx.Notebook instance as a parent, and add it to the notebook: def _new_capture_page (self): new_trace = TraceWindow (self.tracebook) self.tracebook.AddPage (new_trace, 'Capture %d' % (self.capture_serial,), select=True) return new_trace Hope this helps, Mel. From ramit.prasad at jpmorgan.com Thu Oct 20 18:05:00 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 20 Oct 2011 18:05:00 -0400 Subject: [OT] Re: Benefit and belief In-Reply-To: <20111019214926.GA31343@Smoke> References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> <20111019214926.GA31343@Smoke> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21A3979F@EMARC112VS01.exchad.jpmchase.net> >I think you need to speak German fluently to be a good programmer. Why? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From redcat at catfolks.net Thu Oct 20 18:14:41 2011 From: redcat at catfolks.net (Redcat) Date: 20 Oct 2011 22:14:41 GMT Subject: [OT] Re: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9gbkqhFo5dU3@mid.individual.net> On Wed, 19 Oct 2011 14:49:26 -0700, Westley Mart?nez wrote: >> I am a poly-illiterate. I can't read or write hundreds of languages. > > I think you need to speak German fluently to be a good programmer. No, just Dutch :) From anikom15 at gmail.com Thu Oct 20 18:55:57 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 20 Oct 2011 15:55:57 -0700 Subject: [OT] Re: Benefit and belief In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21A3979F@EMARC112VS01.exchad.jpmchase.net> References: <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> <20111019214926.GA31343@Smoke> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21A3979F@EMARC112VS01.exchad.jpmchase.net> Message-ID: <20111020225557.GA28340@Smoke> On Thu, Oct 20, 2011 at 06:05:00PM -0400, Prasad, Ramit wrote: > >I think you need to speak German fluently to be a good programmer. > Why? > I won't reveal my secrets to JP Morgan Chase! I am loyal to the mighty Bank of America. From rosuav at gmail.com Thu Oct 20 20:31:09 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Oct 2011 11:31:09 +1100 Subject: [OT] Re: Benefit and belief In-Reply-To: <9gbkqhFo5dU3@mid.individual.net> References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> <9gbkqhFo5dU3@mid.individual.net> Message-ID: On Fri, Oct 21, 2011 at 9:14 AM, Redcat wrote: > On Wed, 19 Oct 2011 14:49:26 -0700, Westley Mart?nez wrote: >> >> I think you need to speak German fluently to be a good programmer. > > No, just Dutch :) Whatever language it be, you do need to be competent in a human language to be a good programmer. I speak only English of all human languages (can comprehend a smattering of phrases in a few other languages, but no fluency), and there are plenty of programmers who speak only X for some other X, but you do need the skill of coalescing thoughts into words. If nothing else, it makes everyone's lives easier when you ask for help :) ChrisA From installman at 189.cn Thu Oct 20 21:08:54 2011 From: installman at 189.cn (installman at 189.cn) Date: Thu, 20 Oct 2011 18:08:54 -0700 (PDT) Subject: how to change the order of a button, static text or other components Message-ID: <9655f270-15a1-4d59-b5b0-4d2320e27440@h39g2000prh.googlegroups.com> what i want to do is,when i press a button, i change the order of selected components,how to do this? From clp2 at rebertia.com Thu Oct 20 21:26:07 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 20 Oct 2011 18:26:07 -0700 Subject: how to change the order of a button, static text or other components In-Reply-To: <9655f270-15a1-4d59-b5b0-4d2320e27440@h39g2000prh.googlegroups.com> References: <9655f270-15a1-4d59-b5b0-4d2320e27440@h39g2000prh.googlegroups.com> Message-ID: On Thu, Oct 20, 2011 at 6:08 PM, installman at 189.cn wrote: > what i want to do is,when i press a button, i change the order of > selected components,how to do this? Which GUI toolkit are you using? Cheers, Chris From lanyjie at yahoo.com Thu Oct 20 21:46:30 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Thu, 20 Oct 2011 18:46:30 -0700 (PDT) Subject: revive a generator In-Reply-To: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> ----- Original Message ----- > From: Paul Rudin > To: python-list at python.org > Cc: > Sent: Thursday, October 20, 2011 10:28 PM > Subject: Re: revive a generator > > Yingjie Lan writes: > >> Hi, >> >> it seems a generator expression can be used only once: >> >>>>> g = (x*x for x in range(3)) >>>>> for x in g: print x >> 0 >> 1 >> 4 >>>>> for x in g: print x #nothing printed >>>>> >> >> Is there any way to revive g here? >> > > Generators are like that - you consume them until they run out of > values. You could have done [x*x for x in range(3)] and then iterated > over that list as many times as you wanted. > > A generator doesn't have to remember all the values it generates so it > can be more memory efficient that a list. Also it can, for example, > generate an infinite sequence. > > Thanks a lot to all who answered my question.? I am still not sure why should we enforce that? a generator can not be reused after an explicit? request to revive it? From rosuav at gmail.com Thu Oct 20 21:51:38 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Oct 2011 12:51:38 +1100 Subject: revive a generator In-Reply-To: <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> Message-ID: On Fri, Oct 21, 2011 at 12:46 PM, Yingjie Lan wrote: > > Thanks a lot to all who answered my question. > I am still not sure why should we enforce that > a generator can not be reused after an explicit > request to revive it? Here's an example of an explicit request to revive the generator: >>> g = (x*x for x in range(3)) >>> for x in g: print x 0 1 4 >>> g = (x*x for x in range(3)) # revive the generator >>> for x in g: print x #now this will work 0 1 4 ChrisA From lanyjie at yahoo.com Thu Oct 20 21:55:00 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Thu, 20 Oct 2011 18:55:00 -0700 (PDT) Subject: compare range objects In-Reply-To: <20111020162204.GA26505@Smoke> References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> Message-ID: <1319162100.73735.YahooMailNeo@web121502.mail.ne1.yahoo.com> ----- Original Message ----- > From: Westley Mart?nez > To: python-list at python.org > Cc: > Sent: Friday, October 21, 2011 12:22 AM > Subject: Re: compare range objects > > There's already a discussion about this on python-ideas.? But somebody > please tell me, why would you ever need to compare ranges? In simulation, one can use range objects to denote a discrete domain, and domain comparison could be very useful. Not just equality, but also things like if one domain is contained in another. From lanyjie at yahoo.com Thu Oct 20 22:09:42 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Thu, 20 Oct 2011 19:09:42 -0700 (PDT) Subject: revive a generator In-Reply-To: References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> Message-ID: <1319162982.85636.YahooMailNeo@web121513.mail.ne1.yahoo.com> > Here's an example of an explicit request to revive the generator: > >>>> g = (x*x for x in range(3)) >>>> for x in g: print x > 0 > 1 > 4 >>>> g = (x*x for x in range(3)) # revive the generator >>>> for x in g: print x #now this will work > 0 > 1 > 4 > > ChrisA What if the generator is passed in as an argument? when you are writing a function? That is, the expression is not available?? Secondly, it would be nice to automatically revive it. For example, when another for-statement or other equivalent is applied to it. Yingjie From rosuav at gmail.com Thu Oct 20 22:16:30 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Oct 2011 13:16:30 +1100 Subject: compare range objects In-Reply-To: <1319162100.73735.YahooMailNeo@web121502.mail.ne1.yahoo.com> References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> <1319162100.73735.YahooMailNeo@web121502.mail.ne1.yahoo.com> Message-ID: On Fri, Oct 21, 2011 at 12:55 PM, Yingjie Lan wrote: > In simulation, one can use range objects to denote a discrete domain, > and domain comparison could be very useful. Not just equality, but also > things like if one domain is contained in another. > Hmm. I wonder would slice objects be appropriate? They're comparable: >>> a=slice(1,10) >>> b=slice(1,10) >>> a==b True They're not iterable though - not directly (but you could slice range(maxint) down to size). You could possibly use itertools.islice objects for a similar job, but they're not comparable. ChrisA From rustompmody at gmail.com Thu Oct 20 22:34:50 2011 From: rustompmody at gmail.com (rusi) Date: Thu, 20 Oct 2011 19:34:50 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> <9gbkqhFo5dU3@mid.individual.net> Message-ID: <6036ba50-cdf4-4eef-bc3a-dda4dc862b3a@h23g2000pra.googlegroups.com> On Oct 21, 5:31?am, Chris Angelico wrote: > On Fri, Oct 21, 2011 at 9:14 AM, Redcat wrote: > > On Wed, 19 Oct 2011 14:49:26 -0700, Westley Mart?nez wrote: > > >> I think you need to speak German fluently to be a good programmer. > > > No, just Dutch :) > > Whatever language it be, you do need to be competent in a human > language to be a good programmer. I speak only English of all human > languages (can comprehend a smattering of phrases in a few other > languages, but no fluency), and there are plenty of programmers who > speak only X for some other X, but you do need the skill of coalescing > thoughts into words. If nothing else, it makes everyone's lives easier > when you ask for help :) > > ChrisA The American programmer would profit more from learning Latin than from learning yet another programming language. Edsger Dijkstra in "On the fact that the Atlantic Ocean has two sides" http://www.cs.utexas.edu/users/EWD/transcriptions/EWD06xx/EWD611.html From installman at 189.cn Thu Oct 20 23:00:45 2011 From: installman at 189.cn (installman at 189.cn) Date: Thu, 20 Oct 2011 20:00:45 -0700 (PDT) Subject: how to change the order of a button, static text or other components References: <9655f270-15a1-4d59-b5b0-4d2320e27440@h39g2000prh.googlegroups.com> Message-ID: On 10?21?, ??9?26?, Chris Rebert wrote: > On Thu, Oct 20, 2011 at 6:08 PM, install... at 189.cn wrote: > > what i want to do is,when i press a button, i change the order of > > selected components,how to do this? > > Which GUI toolkit are you using? > > Cheers, > Chris wxpython. thx so much. From wuwei23 at gmail.com Thu Oct 20 23:04:54 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 20 Oct 2011 20:04:54 -0700 (PDT) Subject: compare range objects References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> <1319162100.73735.YahooMailNeo@web121502.mail.ne1.yahoo.com> Message-ID: On Oct 21, 12:16?pm, Chris Angelico wrote: > Hmm. I wonder would slice objects be appropriate? > They're not iterable though They're not hashable either, which kind of surprised me. From bulg at ngs.ru Fri Oct 21 00:17:41 2011 From: bulg at ngs.ru (Yosifov Pavel) Date: Thu, 20 Oct 2011 21:17:41 -0700 (PDT) Subject: Py3K: file inheritance References: Message-ID: <36acfea8-1649-4ee9-9959-2c611bdd4da2@f5g2000vbz.googlegroups.com> On 21 ???, 00:42, Ian Kelly wrote: > On Thu, Oct 20, 2011 at 11:28 AM, Yosifov Pavel wrote: > > In the Python 2.x was simple to create own file object: > > > class MyFile(file): > > ?pass > > > for example to reimplement write() or something else. How to do it in > > Python 3.x? > > See the docs for the io module. ?Depending on what you want to do, you > probably need to subclass either io.FileIO or io.TextIOWrapper. Little silly example: class MyFile(file): def __init__(self, *a, **ka): super(MyFile, self).__init__(*a, **ka) self.commented = 0 def write(self, s): if s.startswith("#"): self.commented += 1 super(MyFile, self).write(s) When I tried in Python 3.x to inherit FileIO or TextIOWrapper and then to use MyFile (ex., open(name, mode, encoding), write(s)...) I get errors like 'unsupported write' or AttributeError 'readable'... Can you show me similar simple example like above but in Python 3.x? From rosuav at gmail.com Fri Oct 21 01:20:55 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Oct 2011 16:20:55 +1100 Subject: Benefit and belief In-Reply-To: <6036ba50-cdf4-4eef-bc3a-dda4dc862b3a@h23g2000pra.googlegroups.com> References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> <9gbkqhFo5dU3@mid.individual.net> <6036ba50-cdf4-4eef-bc3a-dda4dc862b3a@h23g2000pra.googlegroups.com> Message-ID: On Fri, Oct 21, 2011 at 1:34 PM, rusi wrote: > The American programmer would profit more from learning Latin than > from learning yet another programming language. > > Edsger Dijkstra in "On the fact that the Atlantic Ocean has two > sides" > Expanding that quote: --- A thorough study of one or more foreign languages makes one much more conscious about one's own; because an excellent mastery of his native tongue is one of the computing scientist's most vital assets, I often feel that the American programmer would profit more from learning, say, Latin than from learning yet another programming language. --- The reason he recommends learning Latin is because it helps you master English. One of the benefits (if you like, a blessing in a REALLY good disguise) of being Australian is that we're forced to work internationally in a way that Americans aren't. You can write a program, even sell it and make your living off it, that never goes outside the boundaries of the US of A. Here in Australia, that's not really a viable option, which means our minds have to be able to 'skip to Honolulu and back in two seconds' as a regular thing. Yes, we can still restrict ourselves to English-speaking countries quite easily, but there's the encouragement to support Europe, and extending from there to the whole world. Of course, not everyone takes advantage of the opportunity thus afforded. There are still plenty of people who are ignorant of the difference between a character and a byte, who assume or mandate one date format, or who parse mailing addresses too strictly. But at least we have a bit of impetus. Which means it's more of a crime for an Aussie (or a European, for that matter) to muck up like that than it is for an American. Blessing or curse? Now I'm not even sure myself. :) ChrisA From ben+python at benfinney.id.au Fri Oct 21 02:36:48 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Oct 2011 17:36:48 +1100 Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> <9gbkqhFo5dU3@mid.individual.net> <6036ba50-cdf4-4eef-bc3a-dda4dc862b3a@h23g2000pra.googlegroups.com> Message-ID: <877h3yq29r.fsf@benfinney.id.au> rusi writes: > The American programmer would profit more from learning Latin than > from learning yet another programming language. > > Edsger Dijkstra in "On the fact that the Atlantic Ocean has two > sides" > > http://www.cs.utexas.edu/users/EWD/transcriptions/EWD06xx/EWD611.html It's ambiguous whether Dijkstra is saying anything positive about Latin there. He could be saying ?learning Latin would be a useful thing for average US programmers?. Or he could be saying ?learning any second natural human language ? even one as useless as Latin ? will benefit the average US programmer more than learning another programming language?. I prefer to think someone as wise as Dijkstra would not be deluded as to the value of Latin, and lean more toward the latter meaning. -- \ ?Everyone is entitled to their own opinions, but they are not | `\ entitled to their own facts.? ?US Senator Pat Moynihan | _o__) | Ben Finney From ian.g.kelly at gmail.com Fri Oct 21 02:50:35 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 21 Oct 2011 00:50:35 -0600 Subject: Py3K: file inheritance In-Reply-To: <36acfea8-1649-4ee9-9959-2c611bdd4da2@f5g2000vbz.googlegroups.com> References: <36acfea8-1649-4ee9-9959-2c611bdd4da2@f5g2000vbz.googlegroups.com> Message-ID: On Thu, Oct 20, 2011 at 10:17 PM, Yosifov Pavel wrote: > Little silly example: > > class MyFile(file): > ?def __init__(self, *a, **ka): > ? ?super(MyFile, self).__init__(*a, **ka) > ? ?self.commented = 0 > ?def write(self, s): > ? ?if s.startswith("#"): > ? ? ?self.commented += 1 > ? ? ?super(MyFile, self).write(s) > > When I tried in Python 3.x to inherit FileIO or TextIOWrapper and then > to use MyFile (ex., open(name, mode, encoding), write(s)...) I get > errors like 'unsupported write' or AttributeError 'readable'... Can > you show me similar simple example like above but in Python 3.x? class MyTextIO(io.TextIOWrapper): def __init__(self, *args, **kw): super().__init__(*args, **kw) self.commented = 0 def write(self, s): if s.startswith('#'): self.commented += 1 super().write(s) buffered = open(name, 'wb') textio = MyTextIO(buffered, encoding='utf-8') textio.write('line 1') textio.write('# line 2') textio.close() print(textio.commented) HTH, Ian From ian.g.kelly at gmail.com Fri Oct 21 02:54:45 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 21 Oct 2011 00:54:45 -0600 Subject: compare range objects In-Reply-To: References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> <1319162100.73735.YahooMailNeo@web121502.mail.ne1.yahoo.com> Message-ID: On Thu, Oct 20, 2011 at 8:16 PM, Chris Angelico wrote: > Hmm. I wonder would slice objects be appropriate? They're comparable: > >>>> a=slice(1,10) >>>> b=slice(1,10) >>>> a==b > True > > They're not iterable though - not directly (but you could slice > range(maxint) down to size). You could possibly use itertools.islice > objects for a similar job, but they're not comparable. They have completely different semantics for negative numbers. range(-7, 10) and range(maxint)[slice(-7, 10)] are two completely different things. Still, though, if slice objects are directly comparable, I can't see any reason why range objects shouldn't be. Cheers, Ian From pankaj.anand.26 at gmail.com Fri Oct 21 03:10:45 2011 From: pankaj.anand.26 at gmail.com (Pankaj) Date: Fri, 21 Oct 2011 00:10:45 -0700 (PDT) Subject: SMS api for python Message-ID: <07a0a94e-2b96-4149-a18c-2cf2836351d8@f3g2000pri.googlegroups.com> I want to make an api that would recieve the SMS text from the user and process it then send the result back to the use. Is there any api that I can use to do this?? From paul.nospam at rudin.co.uk Fri Oct 21 03:27:54 2011 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Fri, 21 Oct 2011 08:27:54 +0100 Subject: revive a generator References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> Yingjie Lan writes: > ----- Original Message ----- >> From: Paul Rudin >> Generators are like that - you consume them until they run out of >> values. You could have done [x*x for x in range(3)] and then iterated >> over that list as many times as you wanted. >> >> A generator doesn't have to remember all the values it generates so it >> can be more memory efficient that a list. Also it can, for example, >> generate an infinite sequence. >> >> > Thanks a lot to all who answered my question.? > I am still not sure why should we enforce that? > a generator can not be reused after an explicit? > request to revive it? The language has no explicit notion of a request to "revive" a generator. You could use the same syntax to make a new generator that yeilds the same values as the one you started with if that's what you want. As we've already discussed if you want to iterate several times over the same values then it probably makes sense to compute them and store them in e.g. a list (although there are always trade-offs between storage use and the cost of computing things again). From lanyjie at yahoo.com Fri Oct 21 03:59:04 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Fri, 21 Oct 2011 00:59:04 -0700 (PDT) Subject: revive a generator In-Reply-To: <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <1319183944.58926.YahooMailNeo@web121516.mail.ne1.yahoo.com> ----- Original Message ----- > From: Paul Rudin > To: python-list at python.org > Cc: > Sent: Friday, October 21, 2011 3:27 PM > Subject: Re: revive a generator > > > The language has no explicit notion of a request to "revive" a > generator. You could use the same syntax to make a new generator that > yeilds the same values as the one you started with if that's what you > want. > > As we've already discussed if you want to iterate several times over the > same values then it probably makes sense to compute them and store them > in e.g. a list (although there are always trade-offs between storage use > and the cost of computing things again). > > What if the generator involves a variable from another scope, and before re-generating, the variable changed its value. Also, the generator could be passed in as an argument, so that we don't know its exact expression. >>> vo = 34 >>>?g = (vo*x for x in range(3)) >>> def myfun(g): for i in g: print(i) vo ?+= 3 revive(g) #best if revived automatically for i in g: print(i) myfun(g) Yingjie From lanyjie at yahoo.com Fri Oct 21 04:02:53 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Fri, 21 Oct 2011 01:02:53 -0700 (PDT) Subject: revive a generator In-Reply-To: <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <1319184173.21862.YahooMailNeo@web121506.mail.ne1.yahoo.com> ----- Original Message ----- > From: Paul Rudin > The language has no explicit notion of a request to "revive" a > generator. You could use the same syntax to make a new generator that > yeilds the same values as the one you started with if that's what you > want. > > As we've already discussed if you want to iterate several times over the > same values then it probably makes sense to compute them and store them > in e.g. a list (although there are always trade-offs between storage use > and the cost of computing things again). > Oops, my former reply has the code indentation messed up? by the mail system. Here is a reformatted one: What if the generator involves a variable from another scope, and before re-generating, the variable changed its value. Also, the generator could be passed in as an argument, so that we don't know its exact expression. >>> vo = 34 >>>?g = (vo*x for x in range(3)) >>> def myfun(g): ? ? ? ? ? ? for i in g: print(i) ? ? ? ? ? ??vo ?+= 3 ? ? ? ? ? ??revive(g) #best if revived automatically ? ? ? ? ? ??for i in g: print(i) >>> myfun(g) Yingjie From sverreodegard at gmail.com Fri Oct 21 04:07:09 2011 From: sverreodegard at gmail.com (Sverre) Date: Fri, 21 Oct 2011 01:07:09 -0700 (PDT) Subject: Problem with inheritance Message-ID: I have to classes a and b class a(object): def __init__(self,x): self.x = x self.build() def build(self): return class b(a): def __init__(self,x): a.__init__(self,x) self.y = 0 # ??? def build(self): # do something self.y += 2*self.x t = b(1) The line marked with "???" will no be executed and I don't know the reason. This example is working as intended, but not not the code I'm working on. I'm using Eclipse. I don't know how to debug this problem. From sverreodegard at gmail.com Fri Oct 21 04:16:58 2011 From: sverreodegard at gmail.com (Sverre) Date: Fri, 21 Oct 2011 01:16:58 -0700 (PDT) Subject: Problem with inheritance References: Message-ID: On Oct 21, 10:07?am, Sverre wrote: > I have to classes a ?and b > > class a(object): > ? ? def __init__(self,x): > ? ? ? ? self.x = x > ? ? ? ? self.build() > > ? ? def build(self): > ? ? ? ? return > > class b(a): > ? ? def __init__(self,x): > ? ? ? ? a.__init__(self,x) > ? ? ? ? self.y = 0 ?# ??? > > ? ? def build(self): > ? ? ? ? # do something > ? ? ? ? self.y += 2*self.x > > ?t = b(1) > > The line marked with "???" will no be executed and I don't know the > reason. This example is working as intended, but not not the code I'm > working on. I'm using Eclipse. I don't know how to debug this > problem. I found the solution. I caused an exception in b.build that wasn't reported by Eclipse properly. From paul.nospam at rudin.co.uk Fri Oct 21 04:17:48 2011 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Fri, 21 Oct 2011 09:17:48 +0100 Subject: revive a generator References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <8739emlpw2.fsf@no-fixed-abode.cable.virginmedia.net> Yingjie Lan writes: > > > What if the generator involves a variable from another scope, > and before re-generating, the variable changed its value. > Also, the generator could be passed in as an argument, > so that we don't know its exact expression. > >>>> vo = 34 >>>>?g = (vo*x for x in range(3)) >>>> def myfun(g): > ? ? ? ? ? ? for i in g: print(i) > ? ? ? ? ? ??vo ?+= 3 > ? ? ? ? ? ??revive(g) #best if revived automatically > ? ? ? ? ? ??for i in g: print(i) >>>> myfun(g) > > I'm not really sure whether you intend g to yield the original values after your "revive" or new values based on the new value of vo. But still you can make a class that supports the iterator protocol and does whatever you want (but you can't use the generator expression syntax). If you want something along these lines you should probably read up on the .send() part of the generator protocol. As an aside you shouldn't really write code that uses a global in that way.. it'll end up biting you eventually. Anyway... we can speculate endlessly about non-existent language constructs, but I think we've probably done this one to death. From rosuav at gmail.com Fri Oct 21 04:27:40 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Oct 2011 19:27:40 +1100 Subject: revive a generator In-Reply-To: <1319184173.21862.YahooMailNeo@web121506.mail.ne1.yahoo.com> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> <1319184173.21862.YahooMailNeo@web121506.mail.ne1.yahoo.com> Message-ID: On Fri, Oct 21, 2011 at 7:02 PM, Yingjie Lan wrote: > What if the generator involves a variable from another scope, > and before re-generating, the variable changed its value. > Also, the generator could be passed in as an argument, > so that we don't know its exact expression. > There's actually no way to know that the generator's even deterministic. Try this, for instance: >>> g=(input("Enter value %d or blank to stop: "%n) for n in range(1,11)) >>> for s in g: if not s: break print("Processing input: "+s) It may not be particularly useful, but it's certainly legal. And this generator cannot viably be restarted. The only way is to cast it to list first, but that doesn't work when you have to stop reading expressions from the generator part way. What you could perhaps do is wrap the generator in something that saves its values: >>> class restartable(object): def __init__(self,gen): self.gen=gen self.yielded=[] self.iter=iter(self.yielded) def restart(self): self.iter=iter(self.yielded) def __iter__(self): return self def __next__(self): # Remove the underscores for Python 2 try: return self.iter.__next__() except StopIteration: pass ret=self.gen.__next__() self.yielded.append(ret) return ret >>> h=restartable(g) >>> for i in h: if not i: break print("Using: ",i) >>> h.restart() >>> for i in h: if not i: break print("Using: ",i) Complicated, but what this does is returns a value from its saved list if there is one, otherwise returns a value from the original generator. It can be restarted as many times as necessary, and any time you read "past the end" of where you've read so far, the original generator will be called upon. Actually, this model might be useful for a repeatable random-number generator. But those are more efficiently restarted by means of reseeding the PRNG. ChrisA From rosuav at gmail.com Fri Oct 21 04:34:56 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Oct 2011 19:34:56 +1100 Subject: Problem with inheritance In-Reply-To: References: Message-ID: On Fri, Oct 21, 2011 at 7:07 PM, Sverre wrote: > The line marked with "???" will no be executed and I don't know the > reason. This example is working as intended, but not not the code I'm > working on. I'm using Eclipse. I don't know how to debug this > problem. > Did you notice the error you got when you tried? Copying and pasting your example into IDLE shows this (Python 3): >>> t=b(1) Traceback (most recent call last): File "", line 1, in t=b(1) File "", line 3, in __init__ a.__init__(self,x) File "", line 4, in __init__ self.build() File "", line 8, in build self.y += 2*self.x AttributeError: 'b' object has no attribute 'y' When a calls self.build(), it calls b's build() function. That tries to modify self.y, which then fails. If you put the self.y = 0 line above the chaining call to a.__init__, all is well. Incidentally, you may wish to replace the a.__init__ call with this: super().__init__(x) That way, you're not repeating the name 'a', and if you change the inheritance tree, you don't need to change your code. ChrisA From lanyjie at yahoo.com Fri Oct 21 04:40:54 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Fri, 21 Oct 2011 01:40:54 -0700 (PDT) Subject: revive a generator In-Reply-To: <8739emlpw2.fsf@no-fixed-abode.cable.virginmedia.net> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> <8739emlpw2.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <1319186454.92385.YahooMailNeo@web121502.mail.ne1.yahoo.com> ----- Original Message ----- > From: Paul Rudin > > I'm not really sure whether you intend g to yield the original values > after your "revive" or new values based on the new value of vo.? But > still you can make a class that supports the iterator protocol and does > whatever you want (but you can't use the generator expression syntax). > > If you want something along these lines you should probably read up on > the .send() part of the generator protocol. > > As an aside you shouldn't really write code that uses a global in that > way.. it'll end up biting you eventually. > > Anyway... we can speculate endlessly about non-existent language > constructs, but I think we've probably done this one to death. > -- Maybe no new language construct is needed: just define that x.send() revives a generator. Yingjie From clp2 at rebertia.com Fri Oct 21 04:41:07 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 21 Oct 2011 01:41:07 -0700 Subject: SMS api for python In-Reply-To: <07a0a94e-2b96-4149-a18c-2cf2836351d8@f3g2000pri.googlegroups.com> References: <07a0a94e-2b96-4149-a18c-2cf2836351d8@f3g2000pri.googlegroups.com> Message-ID: On Fri, Oct 21, 2011 at 12:10 AM, Pankaj wrote: > I want to make an api that would recieve the SMS text from the user > and process it then send the result back to the use. Is there any api > that I can use to do this?? There would seem to be several options: http://pypi.python.org/pypi?%3Aaction=search&term=sms&submit=search Cheers, Chris From lanyjie at yahoo.com Fri Oct 21 04:49:59 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Fri, 21 Oct 2011 01:49:59 -0700 (PDT) Subject: revive a generator In-Reply-To: References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> <1319184173.21862.YahooMailNeo@web121506.mail.ne1.yahoo.com> Message-ID: <1319186999.52359.YahooMailNeo@web121506.mail.ne1.yahoo.com> ----- Original Message ----- > From: Chris Angelico > To: python-list at python.org > Cc: > Sent: Friday, October 21, 2011 4:27 PM > Subject: Re: revive a generator > > On Fri, Oct 21, 2011 at 7:02 PM, Yingjie Lan wrote: >> What if the generator involves a variable from another scope, >> and before re-generating, the variable changed its value. >> Also, the generator could be passed in as an argument, >> so that we don't know its exact expression. >> > > There's actually no way to know that the generator's even > deterministic. Try this, for instance: > >>>> g=(input("Enter value %d or blank to stop: "%n) for n in > range(1,11)) >>>> for s in g: > ??? if not s: break > ??? print("Processing input: "+s) > > It may not be particularly useful, but it's certainly legal. And this > generator cannot viably be restarted.? Depends on what you want. If you want ten more inputs from user, reviving this generator is certainly a good thing to do. > The only way is to cast it to > list first, but that doesn't work when you have to stop reading > expressions from the generator part way. > > What you could perhaps do is wrap the generator in something that > saves its values: > >>>> class restartable(object): > ??? def __init__(self,gen): > ??? ??? self.gen=gen > ??? ??? self.yielded=[] > ??? ??? self.iter=iter(self.yielded) > ??? def restart(self): > ??? ??? self.iter=iter(self.yielded) > ??? def __iter__(self): > ??? ??? return self > ??? def __next__(self): # Remove the underscores for Python 2 > ??? ??? try: > ??? ??? ??? return self.iter.__next__() > ??? ??? except StopIteration: > ??? ??? ??? pass > ??? ??? ret=self.gen.__next__() > ??? ??? self.yielded.append(ret) > ??? ??? return ret > >>>> h=restartable(g) >>>> for i in h: > ??? if not i: break > ??? print("Using: ",i) >>>> h.restart() >>>> for i in h: > ??? if not i: break > ??? print("Using: ",i) > > Complicated, but what this does is returns a value from its saved list > if there is one, otherwise returns a value from the original > generator. It can be restarted as many times as necessary, and any > time you read "past the end" of where you've read so far, the > original > generator will be called upon. > > Actually, this model might be useful for a repeatable random-number > generator. But those are more efficiently restarted by means of > reseeding the PRNG. > Sure. Or you would like to have the next few random numbers with? the same PRNG.? These two cases seem to be strong use cases for reviving a generator. Yingjie From durumdara at gmail.com Fri Oct 21 04:51:05 2011 From: durumdara at gmail.com (durumdara) Date: Fri, 21 Oct 2011 01:51:05 -0700 (PDT) Subject: No module named Pwd - under Apache 2.2 Message-ID: <5299bc04-e18d-487a-8774-ba0b2943d32e@a9g2000yqo.googlegroups.com> Hi! Win7/x64, Python 3.2, PyPGSQL f 3.2 and Apahce 2.2. I created a script that working in CGI mode, it is read some table, and returns with an XML. It was working with normal mode, under Pyscripter, and under command line. But! When I trying to use it from Apache 2.2 as cgi, I got the subjected error: "No module named Pwd" I checked the code. Everything is fine for the lines import postgresql # this is working con = postgresql.open(....) # this failed Traceback (most recent call last): File "C:/web/Apache2.2/cgi-bin/testpg.py", line 20, in Session Function() File "C:/web/Apache2.2/cgi-bin/testpg.py", line 38, in WebFunction db = postgresql.open("pq://postgres:m at localhost/webdbdb") File "C:\python32\lib\site-packages\postgresql\__init__.py", line 76, in open std_params = _pg_param.collect(prompt_title = None) File "C:\python32\lib\site-packages\postgresql\clientparameters.py", line 620, in collect cpd = normalize(extrapolate(chain(*d_parameters))) File "C:\python32\lib\site-packages\postgresql\clientparameters.py", line 563, in normalize for (k, v) in iter: File "C:\python32\lib\site-packages\postgresql\clientparameters.py", line 524, in extrapolate for item in iter: File "C:\python32\lib\site-packages\postgresql\clientparameters.py", line 130, in defaults user = getuser() or 'postgres' File "C:\python32\lib\getpass.py", line 156, in getuser import pwd ImportError: No module named pwd The Apache is running under my account (normal user). The sys.path is ok: ['C:\\web\\Apache2.2\\cgi-bin', 'C:\\Windows\\system32\\python32.zip', 'C:\\python32\\DLLs', 'C:\\python32\\lib', 'C:\\python32', 'C:\ \python32\\lib\\site-packages'] So we (me, and the postgresql's author) don't understand, why it happens. Any idea? Thanks for your help: dd From __peter__ at web.de Fri Oct 21 05:33:06 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Oct 2011 11:33:06 +0200 Subject: No module named Pwd - under Apache 2.2 References: <5299bc04-e18d-487a-8774-ba0b2943d32e@a9g2000yqo.googlegroups.com> Message-ID: durumdara wrote: > Hi! > > Win7/x64, Python 3.2, PyPGSQL f 3.2 and Apahce 2.2. > > I created a script that working in CGI mode, it is read some table, > and returns with an XML. > > It was working with normal mode, under Pyscripter, and under command > line. > > But! > > When I trying to use it from Apache 2.2 as cgi, I got the subjected > error: > > "No module named Pwd" Remember that case matters in Python. Fortunately you included the traceback. > I checked the code. > Everything is fine for the lines > import postgresql # this is working > con = postgresql.open(....) # this failed > > Traceback (most recent call last): > File "C:/web/Apache2.2/cgi-bin/testpg.py", line 20, in Session > Function() > File "C:/web/Apache2.2/cgi-bin/testpg.py", line 38, in WebFunction db > = postgresql.open("pq://postgres:m at localhost/webdbdb") > File "C:\python32\lib\site-packages\postgresql\__init__.py", line 76, > in open std_params = _pg_param.collect(prompt_title = None) > File "C:\python32\lib\site-packages\postgresql\clientparameters.py", > line 620, in collect cpd = > normalize(extrapolate(chain(*d_parameters))) > File "C:\python32\lib\site-packages\postgresql\clientparameters.py", > line 563, in normalize for (k, v) in iter: > File "C:\python32\lib\site-packages\postgresql\clientparameters.py", > line 524, in extrapolate for item in iter: > File "C:\python32\lib\site-packages\postgresql\clientparameters.py", > line 130, in defaults user = getuser() or 'postgres' > File "C:\python32\lib\getpass.py", line 156, in getuser import pwd > ImportError: No module named pwd The direct cause is that pwd is not available on Windows: http://docs.python.org/dev/py3k/library/pwd.html """ 33.2. pwd ? The password database Platforms: Unix This module provides access to the Unix user account and password database. It is available on all Unix versions. """ The source of the failing function... ''' def getuser(): """Get the username from the environment or password database. First try various environment variables, then the password database. This works on Windows as long as USERNAME is set. """ import os for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'): user = os.environ.get(name) if user: return user # If this fails, the exception will "explain" why import pwd return pwd.getpwuid(os.getuid())[0] ''' ...suggests that you can make it work on Windows by setting the USERNAME environment variable (or any of the alternatives checked in the for-loop). Does postgresql use the os user as a fallback for the database user? If so you might consider providing the database user explicitly. From jeanmichel at sequans.com Fri Oct 21 05:49:49 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 21 Oct 2011 11:49:49 +0200 Subject: Problem with inheritance In-Reply-To: References: Message-ID: <4EA1403D.9000706@sequans.com> Sverre wrote: > I have to classes a and b > > > class a(object): > def __init__(self,x): > self.x = x > self.build() > > def build(self): > return > > class b(a): > def __init__(self,x): > a.__init__(self,x) > self.y = 0 # ??? > > def build(self): > # do something > self.y += 2*self.x > > t = b(1) > > The line marked with "???" will no be executed and I don't know the > reason. This example is working as intended, but not not the code I'm > working on. I'm using Eclipse. I don't know how to debug this > problem. > > By the way, you're executing self.y += 2*self.x before initializing it to 0. class b(a): def __init__(self,x): self.y = 0 a.__init__(self,x) Note that having the constructor of 'a' calling an overriden method by 'b' (build) is kinda funny. I would advise not to do so unless required. JM From rustompmody at gmail.com Fri Oct 21 05:56:09 2011 From: rustompmody at gmail.com (rusi) Date: Fri, 21 Oct 2011 02:56:09 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> <9gbkqhFo5dU3@mid.individual.net> <6036ba50-cdf4-4eef-bc3a-dda4dc862b3a@h23g2000pra.googlegroups.com> <877h3yq29r.fsf@benfinney.id.au> Message-ID: On Oct 21, 11:36?am, Ben Finney wrote: > rusi writes: > > The American programmer would profit more from learning Latin than > > from learning yet another programming language. > > > Edsger Dijkstra in "On the fact that the Atlantic Ocean has two > > sides" > > >http://www.cs.utexas.edu/users/EWD/transcriptions/EWD06xx/EWD611.html > > It's ambiguous whether Dijkstra is saying anything positive about Latin > ?there. > > He could be saying ?learning Latin would be a useful thing for average > US programmers?. > > Or he could be saying ?learning any second natural human language ? even > one as useless as Latin ? will benefit the average US programmer more > than learning another programming language?. > > I prefer to think someone as wise as Dijkstra would not be deluded as to > the value of Latin, and lean more toward the latter meaning. Well if you see the additional lines Chris has added or other personal correspondences of EWD eg http://digitalundivide.blogspot.com/2005/12/ewd-personal-reflection.html Dijkstra clearly has a specific choice of latin. It is easier to discount your view -- Dijkstra is wise -- than to deny that Dijkstra was a devoted classicist -- music, languages and ultimately programming. And much bigger CSists than you and I -- eg Egon Borger, R W Hamming etc -- have called Dijkstra a nut. It seems to me that Dijkstra's quote would become a bit more meaningful if one went up, so to speak, the class hierarchy. He is talking of 3 languages -- English, Latin and ones native tongue. Generalizing (with slight inaccuracy) one could list 3 categories: a communication language b sacred/classical language c mother tongue Today a is singleton -- {English} b is roughly {sanskrit, hebrew, arabic, latin, greek} Each of these categories has a very different function just as Bach and beatles have different functions. From d at davea.name Fri Oct 21 07:11:49 2011 From: d at davea.name (Dave Angel) Date: Fri, 21 Oct 2011 07:11:49 -0400 Subject: revive a generator In-Reply-To: <1319162982.85636.YahooMailNeo@web121513.mail.ne1.yahoo.com> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> <1319162982.85636.YahooMailNeo@web121513.mail.ne1.yahoo.com> Message-ID: <4EA15375.9050004@davea.name> On 10/20/2011 10:09 PM, Yingjie Lan wrote: > > > What if the generator is passed in as an argument > when you are writing a function? That is, the expression > is not available? > > Secondly, it would be nice to automatically revive it. > For example, when another for-statement or other > equivalent is applied to it. > > Yingjie That last point would definitely be incompatible. It's quite useful to be able to peel some values off a generator, then use a for loop to get the remainder. Simplest example I can think of would be to read a file where the first line(s) represent header information, and the body is obtainable with a simple loop. I wouldn't be surprised if the csv module does that. Not arguing whether an explicit revival is useful or not. Although as others have pointed out, not all generators could accomplish it, and in some cases not unambiguously. -- DaveA From bulg at ngs.ru Fri Oct 21 08:36:28 2011 From: bulg at ngs.ru (Yosifov Pavel) Date: Fri, 21 Oct 2011 05:36:28 -0700 (PDT) Subject: Py3K: file inheritance References: mailman.2109.1319179873.27778.python-list@python.org Message-ID: <21ed0bdb-0907-4f51-a667-79fb9ea5ebbe@y8g2000yqf.googlegroups.com> On 21 ???, 13:50, Ian Kelly wrote: > On Thu, Oct 20, 2011 at 10:17 PM, Yosifov Pavel wrote: > > Little silly example: > > > class MyFile(file): > > ?def __init__(self, *a, **ka): > > ? ?super(MyFile, self).__init__(*a, **ka) > > ? ?self.commented = 0 > > ?def write(self, s): > > ? ?if s.startswith("#"): > > ? ? ?self.commented += 1 > > ? ? ?super(MyFile, self).write(s) > > > When I tried in Python 3.x to inherit FileIO or TextIOWrapper and then > > to use MyFile (ex., open(name, mode, encoding), write(s)...) I get > > errors like 'unsupported write' or AttributeError 'readable'... Can > > you show me similar simple example like above but in Python 3.x? > > class MyTextIO(io.TextIOWrapper): > ? ? def __init__(self, *args, **kw): > ? ? ? ? super().__init__(*args, **kw) > ? ? ? ? self.commented = 0 > ? ? def write(self, s): > ? ? ? ? if s.startswith('#'): > ? ? ? ? ? ? self.commented += 1 > ? ? ? ? ? ? super().write(s) > > buffered = open(name, 'wb') > textio = MyTextIO(buffered, encoding='utf-8') > textio.write('line 1') > textio.write('# line 2') > textio.close() > print(textio.commented) > > HTH, > Ian Thank you very much! From msarro at gmail.com Fri Oct 21 09:39:35 2011 From: msarro at gmail.com (Matty Sarro) Date: Fri, 21 Oct 2011 09:39:35 -0400 Subject: Automated form submissions Message-ID: Hey everyone. First, I apologize because I know this question has probably gotten asked a lot. I am looking to automate filling out web forms, and no, its not for spamming purposes. I have looked at mechanize so far, but I'm not sure it quite fits what I'm looking for. I know it can act as a browser and do some basic work with forms, but I couldn't find anything in their documentation about interacting with things like drop down boxes, etc. Is selenium a better choice for this? -Matt From steve+comp.lang.python at pearwood.info Fri Oct 21 09:48:43 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Oct 2011 13:48:43 GMT Subject: revive a generator References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> Message-ID: <4ea1783a$0$29968$c3e8da3$5496439d@news.astraweb.com> On Thu, 20 Oct 2011 19:09:42 -0700, Yingjie Lan wrote: >> Here's an example of an explicit request to revive the generator: > > >>>>> g = (x*x for x in range(3)) >>>>> for x in g: print x >> 0 >> 1 >> 4 >>>>> g = (x*x for x in range(3)) # revive the generator for x in g: >>>>> print x #now this will work >> 0 >> 1 >> 4 >> >> ChrisA > > > What if the generator is passed in as an argument when you are writing a > function? That is, the expression is not available? If the expression is not available, how do you expect to revive it? The expression is gone, it no longer exists. As you said in another post: "What if the generator involves a variable from another scope, and before re-generating, the variable changed its value." Exactly. In general, you *can't* revive general iterators. It simply isn't possible. The variables that defined it might be gone. They might be non-deterministic: random numbers, data from the Internet or a file system that has changed, or user input. Trying to enforce the rule "iterators must support restarting" is foolish: it can't be done. You use an iterator when you want to iterate over something *once*, that is why they exist. If you want to iterate over it twice, don't use an iterator, use a sequence. Forcing all iterators to save their data, on the off-chance that maybe somebody might want to iterate over it twice, defeats the purpose of an iterator. > Secondly, it would be nice to automatically revive it. For example, when > another for-statement or other equivalent is applied to it. Nice? No, it would be horrible. It goes against the basic concept of an iterator: iterators should be memory efficient, generating values lazily. If you want an iterable sequence that you can iterate over multiple times, then use a list, or a custom iterable class. If you want a socket wrench, use a socket wrench. Don't insist that hammers have to have a socket wrench attachment. -- Steven From k.sahithi2862 at gmail.com Fri Oct 21 09:57:28 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Fri, 21 Oct 2011 06:57:28 -0700 (PDT) Subject: NEW UPDATS Message-ID: FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ SAKUNI MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/sakuni-movie-stills.html 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html From gshanemiller at verizon.net Fri Oct 21 10:05:32 2011 From: gshanemiller at verizon.net (Shane) Date: Fri, 21 Oct 2011 07:05:32 -0700 (PDT) Subject: non-standard module location (again) Message-ID: Need to refine a question I asked earlier. If I have a module, |-- foo |-------| |-------|---bar |-------|-------| |-------|-------|---__init__.py then I can say import foo.bar But suppose I want to import foo.bar.stuff and stuff isn't located on under `bar' because it's user supplied code: |- stuff <- I want this to be logically under foo.bar |-------|---__init__.py <- even though it's not under bar in the computer's file system Now what: how to arrange to do command: import foo.bar.stuff From ian.g.kelly at gmail.com Fri Oct 21 10:25:22 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 21 Oct 2011 08:25:22 -0600 Subject: revive a generator In-Reply-To: <1319184173.21862.YahooMailNeo@web121506.mail.ne1.yahoo.com> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> <1319184173.21862.YahooMailNeo@web121506.mail.ne1.yahoo.com> Message-ID: On Fri, Oct 21, 2011 at 2:02 AM, Yingjie Lan wrote: > Oops, my former reply has the code indentation messed up > by the mail system. Here is a reformatted one: > > > What if the generator involves a variable from another scope, > and before re-generating, the variable changed its value. > Also, the generator could be passed in as an argument, > so that we don't know its exact expression. In the former case, use a named generator function and call it twice to create two generators. In the latter case, don't pass in the generator as an argument. Pass in a callable that constructs the iterator instead. Modifying your example: vo = 34 def mygen(): for x in range(3): yield vo * x def myfun(g): global vo for i in g(): print(i) vo += 3 for i in g(): print(i) myfun(mygen) Cheers, Ian From invalid at invalid.invalid Fri Oct 21 10:32:36 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 21 Oct 2011 14:32:36 +0000 (UTC) Subject: Automated form submissions References: Message-ID: On 2011-10-21, Matty Sarro wrote: > First, I apologize because I know this question has probably gotten > asked a lot. I am looking to automate filling out web forms, and no, > its not for spamming purposes. I use ClientForm for that, and I'm happy with it. -- Grant Edwards grant.b.edwards Yow! MERYL STREEP is my at obstetrician! gmail.com From c.fangeux at gmail.com Fri Oct 21 10:33:32 2011 From: c.fangeux at gmail.com (c.fangeux at gmail.com) Date: Fri, 21 Oct 2011 07:33:32 -0700 (PDT) Subject: IDLE lost from Windows menu ! In-Reply-To: References: <264d1536-864b-4cd5-9930-b4f5e69e8d46@h38g2000yqn.googlegroups.com> Message-ID: <8750605.542.1319207612892.JavaMail.geo-discussion-forums@yqja14> Thanks Alec. For me it works with the following Default key : "C:\Python32\pythonw.exe" "C:\Python32\Lib\idlelib\idle.pyw" -e "%1" Otherwise IDLE does not open, only python was executed. From c.fangeux at gmail.com Fri Oct 21 10:33:32 2011 From: c.fangeux at gmail.com (c.fangeux at gmail.com) Date: Fri, 21 Oct 2011 07:33:32 -0700 (PDT) Subject: IDLE lost from Windows menu ! In-Reply-To: References: <264d1536-864b-4cd5-9930-b4f5e69e8d46@h38g2000yqn.googlegroups.com> Message-ID: <8750605.542.1319207612892.JavaMail.geo-discussion-forums@yqja14> Thanks Alec. For me it works with the following Default key : "C:\Python32\pythonw.exe" "C:\Python32\Lib\idlelib\idle.pyw" -e "%1" Otherwise IDLE does not open, only python was executed. From dihedral88888 at googlemail.com Fri Oct 21 11:07:12 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Fri, 21 Oct 2011 08:07:12 -0700 (PDT) Subject: non-standard module location (again) In-Reply-To: References: Message-ID: <5099513.170.1319209633099.JavaMail.geo-discussion-forums@pref15> 1. Define a new class with an instance of the foo class included so that one can use all foo's properties and add new attributes. 2. Derive a new class from foo that extends its properties with the properties in foo accessible. From ian.g.kelly at gmail.com Fri Oct 21 11:48:21 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 21 Oct 2011 09:48:21 -0600 Subject: non-standard module location (again) In-Reply-To: References: Message-ID: On Fri, Oct 21, 2011 at 8:05 AM, Shane wrote: > Need to refine a question I asked earlier. If I have a module, > > |-- ?foo > |-------| > |-------|---bar > |-------|-------| > |-------|-------|---__init__.py > > then I can say import foo.bar > > But suppose I want to import foo.bar.stuff and stuff isn't located on > under `bar' because it's user > supplied code: > > |- stuff ? ? ? ? ? ? ? ? ? ? ? ? ? ? <- I want this to be logically > under foo.bar > |-------|---__init__.py ? ? ? ? ? <- even though it's not under bar in > the computer's file system > > Now what: how to arrange to do command: import foo.bar.stuff I've never tried this myself, but I think that pkgutil.extend_path is what you're looking for. http://docs.python.org/library/pkgutil.html Cheers, Ian From aspineux at gmail.com Fri Oct 21 12:06:07 2011 From: aspineux at gmail.com (aspineux) Date: Fri, 21 Oct 2011 09:06:07 -0700 (PDT) Subject: fromutc: dt.tzinfo is not self: pytz.timezone('UTC').fromutc(datetime.utcnow()) References: <4e9f3b19$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: <66d73f14-7ad1-458c-8b3a-5794ed9de8f4@x20g2000vbl.googlegroups.com> On Oct 19, 11:03?pm, Steven D'Aprano wrote: > On Wed, 19 Oct 2011 01:06:53 -0700, aspineux wrote: > > hi > > >>>> import pytz > >>>> from datetime import datetime > >>>> pytz.timezone('GMT0').fromutc(datetime.utcnow()) > > datetime.datetime(2011, 10, 19, 7, 54, 45, 579125, tzinfo= > 'GMT0'>) > >>>> ?pytz.timezone('UTC').fromutc(datetime.utcnow()) > > Traceback (most recent call last): > > ? File "", line 1, in > > ValueError: fromutc: dt.tzinfo is not self > >>>> pytz.timezone('Europe/Brussels').fromutc(datetime.utcnow()) > > datetime.datetime(2011, 10, 19, 9, 55, 47, 787937, tzinfo= > 'Europe/Brussels' CEST+2:00:00 DST>) > > > Why does UTC fail ? > > Bug or feature ? > > Looks like a bug to me. But I'm not an expert on pytz. Perhaps you should > report it back to the package author. Done https://bugs.launchpad.net/pytz/+bug/879480 > > -- > Steven From ironfroggy at gmail.com Fri Oct 21 12:41:52 2011 From: ironfroggy at gmail.com (Calvin Spealman) Date: Fri, 21 Oct 2011 12:41:52 -0400 Subject: non-standard module location (again) In-Reply-To: References: Message-ID: I am biased, but you could use a plugin loader like straight.plugin at https://github.com/ironfroggy/straight.plugin On Fri, Oct 21, 2011 at 10:05 AM, Shane wrote: > Need to refine a question I asked earlier. If I have a module, > > |-- ?foo > |-------| > |-------|---bar > |-------|-------| > |-------|-------|---__init__.py > > then I can say import foo.bar > > But suppose I want to import foo.bar.stuff and stuff isn't located on > under `bar' because it's user > supplied code: > > |- stuff ? ? ? ? ? ? ? ? ? ? ? ? ? ? <- I want this to be logically > under foo.bar > |-------|---__init__.py ? ? ? ? ? <- even though it's not under bar in > the computer's file system > > Now what: how to arrange to do command: import foo.bar.stuff > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy From steve+comp.lang.python at pearwood.info Fri Oct 21 13:29:48 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Oct 2011 17:29:48 GMT Subject: non-standard module location (again) References: Message-ID: <4ea1ac0c$0$29968$c3e8da3$5496439d@news.astraweb.com> On Fri, 21 Oct 2011 07:05:32 -0700, Shane wrote: > Need to refine a question I asked earlier. If I have a module, > > |-- foo > |-------| > |-------|---bar > |-------|-------| > |-------|-------|---__init__.py > > then I can say import foo.bar No you can't, not the way you have listed it. As shown, foo is just a directory, so "import foo" will fail. However, "import bar" may work, provided foo/bar is in the module search path. Perhaps you mean you have a package, with a sub-package: foo/ +-- __init__.py +-- bar/ ... +-- __init__.py Now you have TWO modules, foo and foo.bar, and you can "import foo.bar" successfully. > But suppose I want to import foo.bar.stuff and stuff isn't located on > under `bar' because it's user > supplied code: > > |- stuff <- I want this to be logically > under foo.bar > |-------|---__init__.py <- even though it's not under bar in > the computer's file system This is not clear what you are trying to do. Please explain more clearly what your module layout is. foo/ +-- __init__.py +-- stuff.py +-- bar/ ... +-- __init__.py Or: stuff.py foo/ +-- __init__.py +-- bar/ ... +-- __init__.py But since stuff is supposed to be a plugin, the most obvious, sensible way to lay out the modules would be: foo/ +-- __init__.py +-- plugins/ ... +-- __init__.py ... +-- stuff.py +-- bar/ ... +-- __init__.py and then "import foo.plugins.stuff". Clear, simple and obvious. > Now what: how to arrange to do command: import foo.bar.stuff Why do you want to call it foo.bar.stuff when it isn't actually foo.bar.stuff? Anyone trying to debug this will hate you, when they try to find a module foo/bar/stuff.py and can't find it because it doesn't exist. If you must play games with module locations, put this inside the foo/bar/__init__.py module: import foo.plugins.stuff as stuff and now you can say "import foo.bar.stuff". But why bother? Of course, plugin discovery is still a problem, but that's still a problem no matter what you do. Best to use a well-tested plugin library instead of trying to invent your own. -- Steven From ian.g.kelly at gmail.com Fri Oct 21 13:39:58 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 21 Oct 2011 11:39:58 -0600 Subject: how to change the order of a button, static text or other components In-Reply-To: References: <9655f270-15a1-4d59-b5b0-4d2320e27440@h39g2000prh.googlegroups.com> Message-ID: I assume you're arranging the components with a sizer. Remove them from the sizer, reinsert them in the order you want, and then call sizer.Layout(). Cheers, Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Oct 21 16:25:47 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 Oct 2011 16:25:47 -0400 Subject: revive a generator In-Reply-To: <1319162982.85636.YahooMailNeo@web121513.mail.ne1.yahoo.com> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> <1319162982.85636.YahooMailNeo@web121513.mail.ne1.yahoo.com> Message-ID: Here is a class that creates a re-iterable from any callable, such as a generator function, that returns an iterator when called, + captured arguments to be given to the function. class reiterable(): def __init__(self, itercall, *args, **kwds): self.f = itercall # callable that returns an iterator self.args = args self.kwds = kwds def __iter__(self): return self.f(*self.args, **self.kwds) def squares(n): for i in range(n): yield i*i sq3 = reiterable(squares, 3) for i in sq3: print(i) for i in sq3: print(i) >>> 0 1 4 0 1 4 -- Terry Jan Reedy From ramit.prasad at jpmorgan.com Fri Oct 21 18:20:49 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 21 Oct 2011 18:20:49 -0400 Subject: how to change the order of a button, static text or other components In-Reply-To: <9655f270-15a1-4d59-b5b0-4d2320e27440@h39g2000prh.googlegroups.com> References: <9655f270-15a1-4d59-b5b0-4d2320e27440@h39g2000prh.googlegroups.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21AB4727@EMARC112VS01.exchad.jpmchase.net> >what i want to do is,when i press a button, i change the order of >selected components,how to do this? This is so vague, I am tempted to think it is spam....but on the chance it is not, I need a lot more information than you are providing to even attempt to give you any guidance. 1. By "button" do you mean keyboard/mouse or GUI; if you mean GUI button then what toolkit (Tk, wx, etc) are you referring to? 2. Define "selected components". How are they selected? What is a component? 3. Define "order" in regards to "components". Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From esj at harvee.org Fri Oct 21 19:30:32 2011 From: esj at harvee.org (Eric S. Johansson) Date: Fri, 21 Oct 2011 19:30:32 -0400 Subject: need python+windows edit control help Message-ID: <4EA20098.8040308@harvee.org> I'm back with yet another attempt at adding accessibility features using Python and NaturallySpeaking. I've simplified the concepts again and I really need some help from someone who knows Microsoft Windows and Python. My goal is developing a template for what I'm trying to do, then I can take over and generate some useful accessibility tools. The core idea is an accessibility adjunct program receiving focus at start-of-utterance and returns focus to the original application at end-of-utterance. The window associated with the program contains a grid. Within the grid is an active cell which can accept input. Any cell could be made active depending on the state of the program but only one cell accepts input at any one time. How would this be used? For example, the Skype IM window is atrocious for its disabled users. If one associated at two cell window accessibility adjunct program with Skype, the user could dictate, edit, retrain, etc. within the adjunct program and on command, return the data to Skype. One could also contain a small history so that like Skype, you could go back and edit a previously sent message. a second use case is found on my blog http://blog.esjworks.com which is the tool to create mangled codenames from speech. I think the grid model works better than individual text fields that I originally wrote because it allows me to make better use of a cache of previously generated symbols. Anyway, if anybody can help, I would really appreciate some assistance. --- eric From sigmundv at gmail.com Fri Oct 21 19:42:16 2011 From: sigmundv at gmail.com (SigmundV) Date: Fri, 21 Oct 2011 16:42:16 -0700 (PDT) Subject: compare range objects References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> Message-ID: <453d196e-4516-47f3-9d33-caea70d33a8f@l12g2000vby.googlegroups.com> On Oct 21, 2:55?am, Yingjie Lan wrote: > > In simulation, one can use range objects to denote a discrete domain, > and domain comparison could be very useful. Not just equality, but also > things like if one domain is contained in another. Can't sets [help(set)] be used for this? From skippy.hammond at gmail.com Fri Oct 21 22:03:04 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Sat, 22 Oct 2011 13:03:04 +1100 Subject: need python+windows edit control help In-Reply-To: <4EA20098.8040308@harvee.org> References: <4EA20098.8040308@harvee.org> Message-ID: <4EA22458.9080305@gmail.com> On 22/10/2011 10:30 AM, Eric S. Johansson wrote: > I'm back with yet another attempt at adding accessibility features using > Python and NaturallySpeaking. I've simplified the concepts again and I > really need some help from someone who knows Microsoft Windows and > Python. My goal is developing a template for what I'm trying to do, then > I can take over and generate some useful accessibility tools. The python-win32 at python.org mailing list might be the best place to look for help - although you will probably need to provide much more information before anyone can help. MSDN documents most of what you can do with edit control (look for windows messages starting with "EM_"), but without checking, I expect you will find programs like Skype don't use a Windows edit control at all. Mark From peter at engcorp.com Fri Oct 21 22:10:22 2011 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Oct 2011 19:10:22 -0700 (PDT) Subject: Python on BlackBerry PlayBook Message-ID: <5b3f6a95-3296-4a62-8e0c-38461dd540a8@n18g2000vbv.googlegroups.com> I'm slightly surprised to search and not see any recent mention of Python running on the BlackBerry PlayBook. Since the PlayBook simulators (for developers) were first available late last year, they've contained Python 2.7. Some time before release, the permissions were changed so the binaries weren't accessible to developers or to apps. There's now a developer beta of the upcoming 2.0 release of the PlayBook's OS (built on QNX, previously named Tablet OS and now rebranded as BBX). Though this beta has almost none of the "user- facing" improvements included, much of what's below the covers is intact and probably fairly representative of how the final release will look. In this beta 2.0 release, I see a full installation of Python 3.2.1 (qnx6 build). (The 2.7 install is still present, and likely will remain for a long time, as it underpins some important features in the OS.) There are other clear signs that RIM/QNX have a significant chunk of Python related work done already, including a video with some TAT user interface demos ( http://www.youtube.com/watch?feature=player_embedded&v=Mia10Rekd0c ) where you can see (in 720P mode, around 3:30) files such as Accelerometer.py and Horizon.py along with a "PyCascadesSDK". Currently RIM has no public plans to make a Python SDK available to developers for use in building PlayBook/BBX apps (which would include the next generation of their phones). I believe if there were enough interest shown, this situation could change. So, I'm curious to what degree it would influence people's interest in developing apps for the PlayBook if they were to provide a full Python SDK, or even part of one which the community could flesh out, as one of the development platforms available for the PlayBook. For those not watching this area, the current set of platforms includes native C/C++, WebWorks (HTML5/JavaScript and other web standards), Java in the form of the now-beta Android player, and Adobe AIR (Flash/ActionScript3). I think Python would round that out very nicely. ;-) From dhoese at gmail.com Fri Oct 21 23:13:06 2011 From: dhoese at gmail.com (David Hoese) Date: Fri, 21 Oct 2011 22:13:06 -0500 Subject: shutil _isindir Message-ID: <4EA234C2.8020709@gmail.com> Hi, I wasn't really sure where to post this since the python-dev list seems way too official. I'm wondering/questioning the behavior of shutil.move. It currently does a check for if the dst is inside the src directory with a _destinsrc function. This function uses os.path.abspath to convert the arguments, but I think it should convert using os.path.realpath. A recent problem I had with this I ended up asking on stackoverflow: http://stackoverflow.com/questions/7854608/python-shutil-move-odd-softlinking So I was wondering if this sounds like a change that should happen in the shutil code or should programmers(me) just be more careful. I feel like it should be in the shutil code since its getting around a checked case (destination inside source) and it can end up deleting information when a move was intended. But then again this has been in the standard lib for a while now, so I'm guessing there are reasons for it...plus it was a dumb mistake by me. So I guess what I'm asking is what are the reasons that _destinsrc uses abspath instead of realpath? And is there a better place to ask this? FYI, I was provided this link to the shutil.py source on SO: http://hg.python.org/cpython/file/d30482d51c25/Lib/shutil.py#l262 -Dave From esj at harvee.org Fri Oct 21 23:45:58 2011 From: esj at harvee.org (Eric S. Johansson) Date: Fri, 21 Oct 2011 23:45:58 -0400 Subject: need python+windows edit control help In-Reply-To: <4EA22458.9080305@gmail.com> References: <4EA20098.8040308@harvee.org> <4EA22458.9080305@gmail.com> Message-ID: <4EA23C76.7010602@harvee.org> On 10/21/2011 10:03 PM, Mark Hammond wrote: > On 22/10/2011 10:30 AM, Eric S. Johansson wrote: >> I'm back with yet another attempt at adding accessibility features using >> Python and NaturallySpeaking. I've simplified the concepts again and I >> really need some help from someone who knows Microsoft Windows and >> Python. My goal is developing a template for what I'm trying to do, then >> I can take over and generate some useful accessibility tools. > > The python-win32 at python.org mailing list might be the best place to look for > help - although you will probably need to provide much more information before > anyone can help. MSDN documents most of what you can do with edit control > (look for windows messages starting with "EM_"), but without checking, I > expect you will find programs like Skype don't use a Windows edit control at all. > > Mark thanks for the pointer. When I talk about speech user interfaces in general and accessibility specifically, I find it's better to give a short overview (yes, this was short) before going into the details. I'll be clearer about what kind of help I need. --- eric From steve+comp.lang.python at pearwood.info Sat Oct 22 01:32:44 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Oct 2011 05:32:44 GMT Subject: compare range objects References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> <453d196e-4516-47f3-9d33-caea70d33a8f@l12g2000vby.googlegroups.com> Message-ID: <4ea2557c$0$29968$c3e8da3$5496439d@news.astraweb.com> On Fri, 21 Oct 2011 16:42:16 -0700, SigmundV wrote: > On Oct 21, 2:55?am, Yingjie Lan wrote: >> >> In simulation, one can use range objects to denote a discrete domain, >> and domain comparison could be very useful. Not just equality, but also >> things like if one domain is contained in another. > > Can't sets [help(set)] be used for this? Sure. But the downside of sets is that, like lists, they are not lazy, they actually store every value in them rather than calculate them as needed, so they are only suitable for relatively small domains. Compare: >>> sys.getsizeof(range(9999)) 20 >>> sys.getsizeof(set(range(9999))) 262256 Now consider: >>> sys.getsizeof(range(-999999999, 999999999)) 20 Converted to a set, the memory requirements will be quite large, and the processing time to do anything useful with it likewise inflated. If you need a data type to store large numeric domains, whether discrete or continuous, a tree of intervals storing the lower and upper bounds is probably the right solution. -- Steven From steve+comp.lang.python at pearwood.info Sat Oct 22 01:39:59 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Oct 2011 05:39:59 GMT Subject: revive a generator References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> <1319162982.85636.YahooMailNeo@web121513.mail.ne1.yahoo.com> Message-ID: <4ea2572e$0$29968$c3e8da3$5496439d@news.astraweb.com> On Fri, 21 Oct 2011 16:25:47 -0400, Terry Reedy wrote: > Here is a class that creates a re-iterable from any callable, such as a > generator function, that returns an iterator when called, + captured > arguments to be given to the function. > > class reiterable(): > def __init__(self, itercall, *args, **kwds): > self.f = itercall # callable that returns an iterator > self.args = args > self.kwds = kwds > def __iter__(self): > return self.f(*self.args, **self.kwds) > > def squares(n): > for i in range(n): > yield i*i > > sq3 = reiterable(squares, 3) We can do that even more simply, using a slightly different interface. >>> from functools import partial >>> sq3 = partial(squares, 3) sq3 is now an iterator factory. You can't iterate over it directly, but it's easy to restart: just call it to return a fresh iterator. >>> list(sq3()) [0, 1, 4] >>> list(sq3()) [0, 1, 4] -- Steven From __peter__ at web.de Sat Oct 22 03:58:10 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 Oct 2011 09:58:10 +0200 Subject: shutil _isindir References: <4EA234C2.8020709@gmail.com> Message-ID: David Hoese wrote: > I wasn't really sure where to post this since the python-dev list seems > way too official. I'm wondering/questioning the behavior of > shutil.move. It currently does a check for if the dst is inside the src > directory with a _destinsrc function. This function uses > os.path.abspath to convert the arguments, but I think it should convert > using os.path.realpath. A recent problem I had with this I ended up > asking on stackoverflow: > http://stackoverflow.com/questions/7854608/python-shutil-move-odd- softlinking > > So I was wondering if this sounds like a change that should happen in > the shutil code or should programmers(me) just be more careful. I feel > like it should be in the shutil code since its getting around a checked > case (destination inside source) and it can end up deleting information > when a move was intended. But then again this has been in the standard > lib for a while now, so I'm guessing there are reasons for it...plus it > was a dumb mistake by me. > > So I guess what I'm asking is what are the reasons that _destinsrc uses > abspath instead of realpath? And is there a better place to ask this? > > FYI, I was provided this link to the shutil.py source on SO: > http://hg.python.org/cpython/file/d30482d51c25/Lib/shutil.py#l262 Your suggestion makes sense to me and I don't see any disadvantages. I encourage you to file a bug report on bugs.python.org, preferably with a patch. If there are any problems with the proposed change they can be discussed there. From steve+comp.lang.python at pearwood.info Sat Oct 22 05:03:10 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Oct 2011 09:03:10 GMT Subject: shutil _isindir References: Message-ID: <4ea286ce$0$29968$c3e8da3$5496439d@news.astraweb.com> On Fri, 21 Oct 2011 22:13:06 -0500, David Hoese wrote: > So I guess what I'm asking is what are the reasons that _destinsrc uses > abspath instead of realpath? And is there a better place to ask this? Probably because abspath goes back to Python 1.5, while realpath is comparatively recent only going back to 2.2, and nobody has thought to change the code in shutil. I recommend you raise a bug/feature request on the bug tracker, preferably with a fix and a test demonstrating the problem. http://bugs.python.org/ -- Steven From pavlovevidence at gmail.com Sat Oct 22 05:38:57 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 22 Oct 2011 02:38:57 -0700 (PDT) Subject: revive a generator In-Reply-To: References: Message-ID: <29012412.474.1319276337983.JavaMail.geo-discussion-forums@pref15> On Thursday, October 20, 2011 6:23:50 AM UTC-7, Yingjie Lan wrote: > Hi, > > it seems a generator expression can be used only once: > > >>> g = (x*x for x in range(3)) > >>> for x in g: print x > 0 > 1 > 4 > >>> for x in g: print x #nothing printed > >>> > > Is there any way to revive g here? Revive is the wrong word for what you want. Once an iterator (be it a generator or some other kind of iterator) is done, it's done. What you are asking for is, given a generator, to create a new generator from the same expression/function that created the original generator. This is not reviving, but recreating. I have two objections to this: a major ideological one and a minor practical one. The practical drawback to allowing generators to be recreated is that it forces all generators to carry around a reference to the code object that created it. if random.random() > 5: g = (x*x for x in xrange(3)) else: g = (x+x for x in xrange(3)) for y in g: print x revive(g) # which generator expression was it? # need to carry around a reference to be able to tell for y in g: print x Carrying a reference to a code object in turn carries around any closures used in the generator expression or function, so it can potentially keep a large amount of data alive. Given that the vast majority of generators would never be recreated, this is quite wasteful. My ideological objection is that it forces the programmer to be wary of the effects of recreation. Right now, if someone writes a generator expression, they can rely on the fact that it can only be iterated through once (per time the generator expression is evaluated). But if you allow a downstream user to recreate the generator at will, then the writer will always have to be wary of adverse side-effects if the generator is iterated through twice. So, although I can see it being occasionally useful, I'm going to opine that it is more trouble than it's worth. Carl Banks From vinay_sajip at yahoo.co.uk Sat Oct 22 08:09:14 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Sat, 22 Oct 2011 12:09:14 +0000 (UTC) Subject: logging: warn() methods and function to be deprecated. Message-ID: In response to an issue (#13235) raised on the Python bug tracker, I'm going to deprecate the warn() methods in the Logger and LoggerAdapter classes in the stdlib logging package, as well the module-level warn() function. The warn() variants were synonyms for the warning() methods and function, and a holdover from before the time that logging was added to Python.They were not documented; it's probably time to retire them, so I've added a DeprecationWarning to appear in 3.3, and they'll be completely removed in 3.4 (along with the WARN synonym for WARNING). With this change, all the logging levels are adjectives which apply to the logged message: DEBUG, INFO, WARNING, ERROR and CRITICAL. I don't believe the WARN/warn variants were used much, if at all - but this is just a heads up for anyone who might have used them. Regards, Vinay Sajip From dhoese at gmail.com Sat Oct 22 08:49:52 2011 From: dhoese at gmail.com (David Hoese) Date: Sat, 22 Oct 2011 07:49:52 -0500 Subject: shutil _isindir In-Reply-To: References: Message-ID: <4EA2BBF0.4050602@gmail.com> I was about to submit a bug report, but while testing I have figured out that my specific problem has been solved in Python 2.7 (server that I was using had 2.6 on it). You can see the differences here: 2.6: http://hg.python.org/cpython/file/b9a95ce2692c/Lib/shutil.py 2.7: http://hg.python.org/cpython/file/d30482d51c25/Lib/shutil.py You'll notice that in move(), there is now a check for the same file, which if they're not the same file you don't get unexpected deleted files. If you still think I should submit a bug report let me know and provide me with the test case...or just submit the bug yourself. -Dave P.S. Sorry for the original poor subject line, was a place holder that I forgot to change. On 10/22/2011 5:00 AM, python-list-request at python.org wrote: > Subject: > Re: shutil _isindir > From: > Steven D'Aprano > Date: > 10/22/2011 4:03 AM > > To: > python-list at python.org > > > On Fri, 21 Oct 2011 22:13:06 -0500, David Hoese wrote: > >> > So I guess what I'm asking is what are the reasons that _destinsrc uses >> > abspath instead of realpath? And is there a better place to ask this? > Probably because abspath goes back to Python 1.5, while realpath is > comparatively recent only going back to 2.2, and nobody has thought to > change the code in shutil. > > I recommend you raise a bug/feature request on the bug tracker, > preferably with a fix and a test demonstrating the problem. > > http://bugs.python.org/ From steve+comp.lang.python at pearwood.info Sat Oct 22 08:51:32 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Oct 2011 12:51:32 GMT Subject: compare range objects References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> <453d196e-4516-47f3-9d33-caea70d33a8f@l12g2000vby.googlegroups.com> <4ea2557c$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4ea2bc54$0$29968$c3e8da3$5496439d@news.astraweb.com> On Sat, 22 Oct 2011 05:32:44 +0000, Steven D'Aprano wrote: > On Fri, 21 Oct 2011 16:42:16 -0700, SigmundV wrote: > >> On Oct 21, 2:55?am, Yingjie Lan wrote: >>> >>> In simulation, one can use range objects to denote a discrete domain, >>> and domain comparison could be very useful. Not just equality, but >>> also things like if one domain is contained in another. [...] > If you need a data type to store large numeric domains, whether discrete > or continuous, a tree of intervals storing the lower and upper bounds is > probably the right solution. And purely by coincidence, I came across this today: http://docs.pylandro.com/pylandro-collections-range/0.1/tutorial.html I haven't used the library yet, but it looks impressive. -- Steven From mcepl at redhat.com Sat Oct 22 09:16:47 2011 From: mcepl at redhat.com (Matej Cepl) Date: Sat, 22 Oct 2011 15:16:47 +0200 Subject: help In-Reply-To: References: <9f8pa1Fsh8U3@mid.individual.net> Message-ID: On Oct 8, 2:51 pm, X1 wrote: > > easy_install does not exist on Fedora. That's a pure lie. mitmanek:~ $ sudo repoquery -qf /usr/bin/easy_install python-setuptools-0:0.6.10-3.el6.noarch mitmanek:~ $ Mat?j From ramapraba2653 at gmail.com Sat Oct 22 09:38:01 2011 From: ramapraba2653 at gmail.com (SUPREME) Date: Sat, 22 Oct 2011 06:38:01 -0700 (PDT) Subject: LATEST MOVIE HOT PHOTO STILLS` Message-ID: <362c2e06-e9dd-4be7-a473-02e36c01252d@h23g2000pra.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ SAKUNI MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/sakuni-movie-stills.html 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html SNEHA ULLAL HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/sneha-ullal-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html From steve+comp.lang.python at pearwood.info Sat Oct 22 11:02:47 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Oct 2011 15:02:47 GMT Subject: help References: <9f8pa1Fsh8U3@mid.individual.net> Message-ID: <4ea2db17$0$29968$c3e8da3$5496439d@news.astraweb.com> On Sat, 22 Oct 2011 15:16:47 +0200, Matej Cepl wrote: > On Oct 8, 2:51 pm, X1 wrote: >> >> easy_install does not exist on Fedora. > > That's a pure lie. Rather than assume malice, we should give X1 the benefit of the doubt and assume he genuinely believed what he wrote but was merely mistaken. -- Steven From sigmundv at gmail.com Sat Oct 22 13:51:07 2011 From: sigmundv at gmail.com (SigmundV) Date: Sat, 22 Oct 2011 10:51:07 -0700 (PDT) Subject: compare range objects References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> <453d196e-4516-47f3-9d33-caea70d33a8f@l12g2000vby.googlegroups.com> <4ea2557c$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <57fe18d1-b66c-4b8c-bb83-a8994498d2cf@u13g2000vbx.googlegroups.com> On Oct 22, 6:32?am, Steven D'Aprano wrote: > > Sure. But the downside of sets is that, like lists, they are not lazy, Thank you for pointing this out. I agree that it's not a viable alternative for large domains. Storing the bounds and the resolution should be enough. /Sigmund From jonathan at jloescher.com Sat Oct 22 18:18:17 2011 From: jonathan at jloescher.com (Jonathan Loescher) Date: Sat, 22 Oct 2011 15:18:17 -0700 (PDT) Subject: Books to lean Python 3 Web Programming? Message-ID: Can anyone recommend a good book to learn the web programming aspects of Python 3? From gnarlodious at gmail.com Sat Oct 22 20:26:22 2011 From: gnarlodious at gmail.com (Gnarlodious) Date: Sat, 22 Oct 2011 17:26:22 -0700 (PDT) Subject: How to isolate a constant? Message-ID: Say this: class tester(): _someList = [0, 1] def __call__(self): someList = self._someList someList += "X" return someList test = tester() But guess what, every call adds to the variable that I am trying to copy each time: test() > [0, 1, 'X'] test() > [0, 1, 'X', 'X'] Can someone explain this behavior? And how to prevent a classwide constant from ever getting changed? -- Gnarlie From clp2 at rebertia.com Sat Oct 22 20:41:23 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 22 Oct 2011 17:41:23 -0700 Subject: How to isolate a constant? In-Reply-To: References: Message-ID: On Sat, Oct 22, 2011 at 5:26 PM, Gnarlodious wrote: > Say this: > > class tester(): Style note: either have it explicitly subclass `object`, or don't include the parens at all. Empty parens for the superclasses is just weird. > ? ? ? ?_someList = [0, 1] > ? ? ? ?def __call__(self): > ? ? ? ? ? ? ? ?someList = self._someList > ? ? ? ? ? ? ? ?someList += "X" > ? ? ? ? ? ? ? ?return someList > > test = tester() > > But guess what, every call adds to the variable that I am trying to > copy each time: > test() >> [0, 1, 'X'] > test() >> [0, 1, 'X', 'X'] > > > Can someone explain this behavior? The line `someList = self._someList` does NOT copy the list. It make `someList` point to the same existing list object. Hence, modifications to that object from either variable will affect the other. Similarly, `someList += "X"` modifies someList *in-place*; it does not produce a new list object. The upshot is that you're just modifying and returning references to *the same list* repeatedly, never producing a new list object. > And how to prevent a classwide > constant from ever getting changed? Python doesn't have any language-enforced notion of constants. So, short of writing/using a library to try and enforce such a notion, you're out of luck. You could use an immutable datatype (e.g. a tuple) instead of a mutable one (e.g. a list) as some level of safeguard though. Cheers, Chris -- http://rebertia.com From python at mrabarnett.plus.com Sat Oct 22 20:46:55 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 23 Oct 2011 01:46:55 +0100 Subject: How to isolate a constant? In-Reply-To: References: Message-ID: <4EA363FF.4070803@mrabarnett.plus.com> On 23/10/2011 01:26, Gnarlodious wrote: > Say this: > > class tester(): > _someList = [0, 1] > def __call__(self): > someList = self._someList > someList += "X" > return someList > > test = tester() > > But guess what, every call adds to the variable that I am trying to > copy each time: > test() >> [0, 1, 'X'] > test() >> [0, 1, 'X', 'X'] > > > Can someone explain this behavior? And how to prevent a classwide > constant from ever getting changed? > '_someList' is part of the class itself. This: someList = self._someList just creates a new _reference to the list and this: someList += "X" appends the items of the sequence "X" to the list. Note that a string is also a sequence of characters, so: >>> x = [] >>> x += "XY" >>> x ['X', 'Y'] Python will copy something only when you tell it to copy. A simple way of copying a list is to slice it: someList = self._someList[:] From gnarlodious at gmail.com Sat Oct 22 21:01:52 2011 From: gnarlodious at gmail.com (Gnarlodious) Date: Sat, 22 Oct 2011 18:01:52 -0700 (PDT) Subject: How to isolate a constant? References: Message-ID: <7840d89c-3648-45fe-ae6f-d3bb2ca2abdb@z28g2000pro.googlegroups.com> On Oct 22, 6:41?pm, Chris Rebert wrote: > The line `someList = self._someList` does NOT copy the list. It make > `someList` point to the same existing list object. Thanks for all those explanations, I've already fixed it with a tuple. Which is more reliable anyway. -- Gnarlie From lchaplin13 at gmail.com Sun Oct 23 00:09:04 2011 From: lchaplin13 at gmail.com (Lee) Date: Sat, 22 Oct 2011 21:09:04 -0700 (PDT) Subject: Exception Handling (C - extending python) Message-ID: Hi all, Where does PyExc_TypeError (and alike) points to? I can see its declaration - PyAPI_DATA(PyObject *) PyExc_TypeError; - in pyerrors.h but I cannot figure out what it is its value, where it is initialized. Any help is greatly appreciated. Lee From rustompmody at gmail.com Sun Oct 23 01:08:31 2011 From: rustompmody at gmail.com (rusi) Date: Sat, 22 Oct 2011 22:08:31 -0700 (PDT) Subject: compare range objects References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> <453d196e-4516-47f3-9d33-caea70d33a8f@l12g2000vby.googlegroups.com> <4ea2557c$0$29968$c3e8da3$5496439d@news.astraweb.com> <57fe18d1-b66c-4b8c-bb83-a8994498d2cf@u13g2000vbx.googlegroups.com> Message-ID: <019dd721-055c-4aa3-aa03-6c355c2b3e18@k13g2000prg.googlegroups.com> On Oct 22, 10:51?pm, SigmundV wrote: > On Oct 22, 6:32?am, Steven D'Aprano > +comp.lang.pyt... at pearwood.info> wrote: > > > Sure. But the downside of sets is that, like lists, they are not lazy, > > Thank you for pointing this out. I agree that it's not a viable > alternative for large domains. Storing the bounds and the resolution > should be enough. > > /Sigmund This kind of question is a nontrivial research issue -- dealt with for example in the polyhedral language alpha: http://www.irisa.fr/cosi/Rajopadhye/dag-talk.ps From dihedral88888 at googlemail.com Sun Oct 23 01:12:16 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Sat, 22 Oct 2011 22:12:16 -0700 (PDT) Subject: How to isolate a constant? In-Reply-To: <7840d89c-3648-45fe-ae6f-d3bb2ca2abdb@z28g2000pro.googlegroups.com> References: <7840d89c-3648-45fe-ae6f-d3bb2ca2abdb@z28g2000pro.googlegroups.com> Message-ID: <12317784.900.1319346736804.JavaMail.geo-discussion-forums@prfk19> Thank you for the good trick for a static class owned property. Someone might object this but this is really useful. From steve+comp.lang.python at pearwood.info Sun Oct 23 01:32:56 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Oct 2011 05:32:56 GMT Subject: How to isolate a constant? References: <7840d89c-3648-45fe-ae6f-d3bb2ca2abdb@z28g2000pro.googlegroups.com> Message-ID: <4ea3a707$0$29968$c3e8da3$5496439d@news.astraweb.com> On Sat, 22 Oct 2011 18:01:52 -0700, Gnarlodious wrote: > On Oct 22, 6:41?pm, Chris Rebert wrote: > >> The line `someList = self._someList` does NOT copy the list. It make >> `someList` point to the same existing list object. > Thanks for all those explanations, I've already fixed it with a tuple. > Which is more reliable anyway. No, tuples are not "more reliable" than lists. Don't make the mistake of confusing your inexperience and lack of understanding about Python's object model for "lists are unreliable". They are completely reliable. You just have to learn how they work, and not make invalid assumptions about how they work. You wouldn't say "Nails are more reliable than screws, because I hammered a screw into a plaster wall and it just fell out." Of course it fell out: you used it incorrectly for what you needed. -- Steven From stefan_ml at behnel.de Sun Oct 23 05:06:54 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 23 Oct 2011 11:06:54 +0200 Subject: Exception Handling (C - extending python) In-Reply-To: References: Message-ID: Lee, 23.10.2011 06:09: > Where does PyExc_TypeError (and alike) points to? I can see its > declaration - PyAPI_DATA(PyObject *) PyExc_TypeError; - in pyerrors.h > but I cannot figure out what it is its value, where it is > initialized. It gets initialised inside of the interpreter core and then points to a Python object. > Any help is greatly appreciated. The question is: why do you ask? What exactly do you want to do? If you ask a more targeted question, you will get an answer that will help you further. Stefan From apometron.listas.cinco at gmail.com Sun Oct 23 06:03:54 2011 From: apometron.listas.cinco at gmail.com (apometron) Date: Sun, 23 Oct 2011 08:03:54 -0200 Subject: What is wrong with my code? Message-ID: <4EA3E68A.5010301@gmail.com> import os nome = sys.argv[1] final = nome for i in nome: print i if nome[i] = "_": final[i] = " " os.rename(nome, final) From clp2 at rebertia.com Sun Oct 23 06:08:33 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Oct 2011 03:08:33 -0700 Subject: What is wrong with my code? In-Reply-To: <4EA3E68A.5010301@gmail.com> References: <4EA3E68A.5010301@gmail.com> Message-ID: On Sun, Oct 23, 2011 at 3:03 AM, apometron wrote: > import os > nome = sys.argv[1] You did not `import sys`, so you'll get a NameError there. > final = nome > for i in nome: > ? ?print i > ? ?if nome[i] = "_": > ? ? ? ?final[i] = " " Strings aren't mutable in Python; you can't assign to slices of them. So you'll get a TypeError on the previous line. Cheers, Chris From paul.nospam at rudin.co.uk Sun Oct 23 06:23:38 2011 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Sun, 23 Oct 2011 11:23:38 +0100 Subject: How to isolate a constant? References: <7840d89c-3648-45fe-ae6f-d3bb2ca2abdb@z28g2000pro.googlegroups.com> Message-ID: <87y5wcj9at.fsf@no-fixed-abode.cable.virginmedia.net> Gnarlodious writes: > Thanks for all those explanations, I've already fixed it with a tuple. > Which is more reliable anyway. neither of lists or tuples are "more reliable" than the other. They both have perfectly well defined behaviour (which can be gleaned from reading the documentation) and reliably behave as documented. You just have to choose which fits better for the computation you're trying to implement. From lchaplin13 at gmail.com Sun Oct 23 07:32:00 2011 From: lchaplin13 at gmail.com (Lee) Date: Sun, 23 Oct 2011 04:32:00 -0700 (PDT) Subject: Exception Handling (C - extending python) References: Message-ID: <75930aea-ed09-44f8-b7ca-0fa9f72e6b12@g27g2000pro.googlegroups.com> Thanks Stefan, I am just interested to understand the mechanism inside python. If it points to an object that means I can defered it (through ob_type). >From there, how a function like PyErr_SetString knows what exception is? Where its value is kept? Lee On Oct 23, 10:06?pm, Stefan Behnel wrote: > Lee, 23.10.2011 06:09: > > > Where does PyExc_TypeError (and alike) points to? I can see its > > declaration - PyAPI_DATA(PyObject *) PyExc_TypeError; - in pyerrors.h > > but I cannot figure out what it is its value, where it is > > initialized. > > It gets initialised inside of the interpreter core and then points to a > Python object. > > > Any help is greatly appreciated. > > The question is: why do you ask? What exactly do you want to do? > > If you ask a more targeted question, you will get an answer that will help > you further. > > Stefan From darragh.ssa at gmail.com Sun Oct 23 07:38:54 2011 From: darragh.ssa at gmail.com (Kruptein) Date: Sun, 23 Oct 2011 04:38:54 -0700 (PDT) Subject: Deditor 0.3.1 Message-ID: <8d82dee9-7aa8-4e07-84e3-c81019bd4eeb@f36g2000vbm.googlegroups.com> Hey, I'm happy to announce a new release of Deditor version 0.3.1. What is Deditor? Deditor is a pythonic text-editor, written 100% in python and with the primary goal to ease python development. There is a python shell, codecompletion, code analyzing, instant code running and error checking and lots more. (Other languages are ofcourse also supported for syntax highlighting but don't have the other features) Deditor uses a very good plugin system DPlug which makes it easy to use a combination of plugins like a projects plugin to manage files, a network plugin to up-download stuff,... What's new in this version? The Projects plugin has been totally rewritten and is now a very usefull plugin which makes developing much easier if you have to work at multiple projects in short periods. Note that the network plugin is going to be totally rewritten for next release and is thus not that good atm, nevertheless enjoy! Download .deb/.tar.gz http://launchpad.net/deditor Download ppa: ppa:darragh-ssa/deditor and sudo apt-get install deditor Note: ppa is still in building proces but should be finished this afternoon pictures/videos of the new version are still in progress of creation but here is a short snapshot https://lh6.googleusercontent.com/-oopTygoo6o4/TqCwLY4EoRI/AAAAAAAAAbw/19J1jDq4yIU/deditor_project_0.3.1.png From lists at cheimes.de Sun Oct 23 08:12:18 2011 From: lists at cheimes.de (Christian Heimes) Date: Sun, 23 Oct 2011 14:12:18 +0200 Subject: Exception Handling (C - extending python) In-Reply-To: References: Message-ID: Am 23.10.2011 06:09, schrieb Lee: > Hi all, > > Where does PyExc_TypeError (and alike) points to? I can see its > declaration - PyAPI_DATA(PyObject *) PyExc_TypeError; - in pyerrors.h > but I cannot figure out what it is its value, where it is > initialized. It's initialized in Objects/exceptions.c SimpleExtendsException(PyExc_StandardError, TypeError, "Inappropriate argument type."); SimpleExtendsException() is a macro that defines a PyTypeObject and stores a cast to PyObject in PyExc_TypeError. Christian From stefan_ml at behnel.de Sun Oct 23 08:41:05 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 23 Oct 2011 14:41:05 +0200 Subject: Exception Handling (C - extending python) In-Reply-To: <75930aea-ed09-44f8-b7ca-0fa9f72e6b12@g27g2000pro.googlegroups.com> References: <75930aea-ed09-44f8-b7ca-0fa9f72e6b12@g27g2000pro.googlegroups.com> Message-ID: Hi, note that I reformatted your posting to get the replies back into order. Lee, 23.10.2011 13:32: > On Oct 23, 10:06 pm, Stefan Behnel wrote: >> Lee, 23.10.2011 06:09: >>> Where does PyExc_TypeError (and alike) points to? I can see its >>> declaration - PyAPI_DATA(PyObject *) PyExc_TypeError; - in pyerrors.h >>> but I cannot figure out what it is its value, where it is >>> initialized. >> >> It gets initialised inside of the interpreter core and then points to a >> Python object. > > If it points to an object that means I can defered it (through > ob_type). That will give you the "type" object, because PyExc_TypeError points to the type "TypeError". Note that types are also objects in Python. > From there, how a function like PyErr_SetString knows what exception > is? The type object that you pass in must inherit from the BaseException type. You can read the code in Python/errors.c, function PyErr_SetObject(). >>> Any help is greatly appreciated. >> >> The question is: why do you ask? What exactly do you want to do? >> >> If you ask a more targeted question, you will get an answer that will help >> you further. > > I am just interested to understand the mechanism inside python. That's just fine. If you are interested in the inner mechanics of the CPython runtime, reading the source is a very good way to start getting involved with the project. However, many extension module authors don't care about these inner mechanics and just use Cython instead. That keeps them from having to learn the C-API of CPython, and from tying their code too deeply into the CPython runtime itself. Stefan From 1248283536 at qq.com Sun Oct 23 09:15:08 2011 From: 1248283536 at qq.com (=?gbk?B?y66+ssH3ye4=?=) Date: Sun, 23 Oct 2011 21:15:08 +0800 Subject: python32 to write file Message-ID: code 1 can run in python2.6 #coding:utf-8 import urllib import lxml.html down='http://frux.wikispaces.com/' root=urllib.urlopen(down).read() root=lxml.html.fromstring(root) file=root.xpath('//a') for i in file: str1=i.text_content() if str1.find('pdf') >-1 : str2='http://frux.wikispaces.com/file/view/'+str1 myfile=urllib.urlopen(str2).read() book=open('/tmp/'+str1,'w') book.write(myfile) book.close() i usr command : 2to3-3.2 ~/xml.py -w to get code2 #coding:utf-8 import urllib.request, urllib.parse, urllib.error import lxml.html down='http://frux.wikispaces.com/' root=urllib.request.urlopen(down).read() root=lxml.html.fromstring(root) file=root.xpath('//a') for i in file: str1=i.text_content() if str1.find('pdf') >-1 : str2='http://frux.wikispaces.com/file/view/'+str1 myfile=urllib.request.urlopen(str2).read() book=open('c:\'+str1,'w') # i change it book.write(myfile) book.close() when i run it in python32,the output is : book=open('c:\'+str1,'w') invalid syntax,what is wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Oct 23 09:48:31 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Oct 2011 06:48:31 -0700 Subject: python32 to write file In-Reply-To: References: Message-ID: 2011/10/23 ???? <1248283536 at qq.com>: > ????? ? book=open('c:\'+str1,'w')? #? i? change it > when i run it? in? python32,the output is? : > book=open('c:\'+str1,'w') > invalid? syntax,what is wrong? Your problem is not at all Python 3-specific. Backslashes are used for escape sequences in string literals (e.g. "\n" is newline, "\t" is tab). For example, the string "c:\new\tally" contains both a newline and a tab, but not an N, nor a T, nor any backslashes (a literal backslash is written using the escape sequence "\\"; i.e. two backslashes). Similarly, "\'" is an escape sequence for apostrophe, and thus does not terminate the string literal, leading to a not entirely obvious SyntaxError. Use forward slashes (/) instead; Windows accepts them instead of backslashes as directory separators in path strings, and they have no such escaping issues. Cheers, Chris -- Damn you, CP/M! http://rebertia.com From 1248283536 at qq.com Sun Oct 23 09:59:19 2011 From: 1248283536 at qq.com (=?gbk?B?y66+ssH3ye4=?=) Date: Sun, 23 Oct 2011 21:59:19 +0800 Subject: =?gbk?B?u9i4tKO6IHB5dGhvbjMyIHRvIHdyaXRlIGZpbGU=?= Message-ID: i change my code into : import urllib.request, urllib.parse, urllib.error import lxml.html down='http://frux.wikispaces.com/' root=urllib.request.urlopen(down).read() root=lxml.html.fromstring(root) file=root.xpath('//a') for i in file: str1=i.text_content() if str1.find('pdf') >-1 : str2='http://frux.wikispaces.com/file/view/'+str1 myfile=urllib.request.urlopen(str2).read() book=open('c:/'+str1,'w') book.write(myfile) book.close() the new problem is : C:\Python32>python c:\xml.py Traceback (most recent call last): File "c:\xml.py", line 5, in root=lxml.html.fromstring(root) File "C:\Python32\lib\site-packages\lxml\html\__init__.py", line 630, in froms tring if start.startswith('; ????: 2011?10?23?(???) ??9:48 ???: "????"<1248283536 at qq.com>; ??: "python-list"; ??: Re: python32 to write file 2011/10/23 ???? <1248283536 at qq.com>: > book=open('c:\'+str1,'w') # i change it > when i run it in python32,the output is : > book=open('c:\'+str1,'w') > invalid syntax,what is wrong? Your problem is not at all Python 3-specific. Backslashes are used for escape sequences in string literals (e.g. "\n" is newline, "\t" is tab). For example, the string "c:\new\tally" contains both a newline and a tab, but not an N, nor a T, nor any backslashes (a literal backslash is written using the escape sequence "\\"; i.e. two backslashes). Similarly, "\'" is an escape sequence for apostrophe, and thus does not terminate the string literal, leading to a not entirely obvious SyntaxError. Use forward slashes (/) instead; Windows accepts them instead of backslashes as directory separators in path strings, and they have no such escaping issues. Cheers, Chris -- Damn you, CP/M! http://rebertia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolftracks at invalid.com Sun Oct 23 10:57:02 2011 From: wolftracks at invalid.com (W. eWatson) Date: Sun, 23 Oct 2011 07:57:02 -0700 Subject: File Association for Python on XP Message-ID: Last night I thought I'd install Python on a friend's XP PC. I noticed he had declined to show extensions on any file. I thought the Control Panel might be the way to do it. I couldn't find anything that would do all files, doc, txt, py, etc. I was able to do it, I think, from a right-click on a py file. However, when I then clicked on the file, it seemed like the IDE was not going to come up. Instead it looked like it was headed directly for interpreter. His computer is quite slow. We went on to something else. Python doesn't yet need that much attention. So what should I have done, and how do I undo what I did? From mdanakodi16 at yahoo.com Sun Oct 23 11:48:11 2011 From: mdanakodi16 at yahoo.com (mdanakodi16 at yahoo.com) Date: Sun, 23 Oct 2011 08:48:11 -0700 (PDT) Subject: See Hot Sexy Star *Angelina Jolie* Nude Bathing Videos In All Angles Message-ID: See Hot Sexy Star *Angelina Jolie* Nude Bathing Videos In All Angles At http://angelina-health.co.cc Due to high sex content, i have hidden the videos in an image. in that website on Right side below search box click on image and watch videos in all angles. From mdanakodi16 at yahoo.com Sun Oct 23 11:49:46 2011 From: mdanakodi16 at yahoo.com (mdanakodi16 at yahoo.com) Date: Sun, 23 Oct 2011 08:49:46 -0700 (PDT) Subject: See Hot Sexy Star *Angelina Jolie* Nude Bathing Videos In All Angles Message-ID: See Hot Sexy Star *Angelina Jolie* Nude Bathing Videos In All Angles At http://angelina-health.co.cc Due to high sex content, i have hidden the videos in an image. in that website on Right side below search box click on image and watch videos in all angles. From ivo at webcrowd.net Sun Oct 23 11:50:54 2011 From: ivo at webcrowd.net (webcrowd.net) Date: Sun, 23 Oct 2011 17:50:54 +0200 Subject: Job Offer: 3 Python Backend Developer and other Positions in Berlin Message-ID: Hi Folks, hope it is okay to post job offers here. If not sorry for the spam and please let me know! One of our clients is looking for new and talented people to join their international, seven people strong, developers team in the heart of Berlin. You will join an awesome, nice and humble startup and you can enjoy the coffee and smoothie flatrate whilst playing a quick round of foosball in between. The team is working with Scrum and TDD so everybody stays involved and English is the language of choice. Furthermore they go out for a beer now and then and the company can even provide you with housing for the first couple of weeks in Berlin. Excited? Here are the job details: // Python Backend Developer You speak Python whilst dreaming and you do have experience with Django or RoR? You are not afraid of Javascript, HTML, CSS nor unit or functional testing (cucumber, lettuce) and github is your source codes living room? // Java Backend Developer You?ve worked on a professional Java (J2EE, J2SE 5/6) application at least for two years and you liked Spring and Hibernate on Facebook? Even the following technologies: Lucenel Solr, Tomcat, JBoss and GIT don?t make you sweat? // Technical QA Manager You mainly discuss about object oriented programming concepts with your friends? xUnit, TDD, BDD in combination with Scrum and XP raise your heartbeat? You call Ubuntu, Nginx, PostgreSQL as well as Python, Django and GIT your daily bread? // Frontend Developer (Javascript) You are a talent with Javascript in general and particularly with jQuery, Require.js and Backbone.js? You do testing and object orientated coding by heart and the user experience always comes in the first place for you? If so, request more details and apply: Tweet @webcrowdnet or email at hello at webcrowd.net or just reply here for further information. From mcepl at redhat.com Sun Oct 23 12:05:30 2011 From: mcepl at redhat.com (Matej Cepl) Date: Sun, 23 Oct 2011 18:05:30 +0200 Subject: help In-Reply-To: <4ea2db17$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <9f8pa1Fsh8U3@mid.individual.net> <4ea2db17$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: Dne 22.10.2011 17:02, Steven D'Aprano napsal(a): > Rather than assume malice, we should give X1 the benefit of the doubt and > assume he genuinely believed what he wrote but was merely mistaken. Sure, I didn't want to assume malice (sorry, English is my second language and sometimes it shows; would "libel" or "slander" fit the bill better?). I just wanted to slip in the information about repoquery which is an awesome tool, but not many people know about it. Mat?j From fraveydank at gmail.com Sun Oct 23 12:34:50 2011 From: fraveydank at gmail.com (David Riley) Date: Sun, 23 Oct 2011 12:34:50 -0400 Subject: help In-Reply-To: References: <9f8pa1Fsh8U3@mid.individual.net> <4ea2db17$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5ED19ED7-D7DC-4094-A685-BB1FB42D09F1@gmail.com> "Libel" and "slander" also generally indicate malice. Perhaps just "That's incorrect" might have come off a little less harsh. :-) - Dave On Oct 23, 2011, at 12:05 PM, Matej Cepl wrote: > Dne 22.10.2011 17:02, Steven D'Aprano napsal(a): >> Rather than assume malice, we should give X1 the benefit of the doubt and >> assume he genuinely believed what he wrote but was merely mistaken. > > Sure, I didn't want to assume malice (sorry, English is my second language and sometimes it shows; would "libel" or "slander" fit the bill better?). I just wanted to slip in the information about repoquery which is an awesome tool, but not many people know about it. > > Mat?j > -- > http://mail.python.org/mailman/listinfo/python-list From python at mrabarnett.plus.com Sun Oct 23 12:41:39 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 23 Oct 2011 17:41:39 +0100 Subject: File Association for Python on XP In-Reply-To: References: Message-ID: <4EA443C3.7050308@mrabarnett.plus.com> On 23/10/2011 15:57, W. eWatson wrote: > Last night I thought I'd install Python on a friend's XP PC. I noticed > he had declined to show extensions on any file. I thought the Control > Panel might be the way to do it. I couldn't find anything that would do > all files, doc, txt, py, etc. > > I was able to do it, I think, from a right-click on a py file. However, > when I then clicked on the file, it seemed like the IDE was not going to > come up. Instead it looked like it was headed directly for interpreter. > His computer is quite slow. We went on to something else. Python doesn't > yet need that much attention. > > So what should I have done, and how do I undo what I did? To show the extensions, in an Explorer window go to Tools->Folder Options... and look in the View tab. You can also look at the file associations in the File Types tab. From gherron at islandtraining.com Sun Oct 23 13:04:45 2011 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 23 Oct 2011 10:04:45 -0700 Subject: What is wrong with my code? In-Reply-To: References: <4EA3E68A.5010301@gmail.com> Message-ID: <4EA4492D.5080405@islandtraining.com> On 10/23/2011 03:08 AM, Chris Rebert wrote: > On Sun, Oct 23, 2011 at 3:03 AM, apometron > wrote: >> import os >> nome = sys.argv[1] > You did not `import sys`, so you'll get a NameError there. > >> final = nome >> for i in nome: >> print i >> if nome[i] = "_": >> final[i] = " " > Strings aren't mutable in Python; you can't assign to slices of them. > So you'll get a TypeError on the previous line. > > Cheers, > Chris Also, the statement for i in nome: does not loop through indices, but rather it loops through the actual characters of the string. Gary Herron From wolftracks at invalid.com Sun Oct 23 13:24:44 2011 From: wolftracks at invalid.com (W. eWatson) Date: Sun, 23 Oct 2011 10:24:44 -0700 Subject: File Association for Python on XP In-Reply-To: References: Message-ID: On 10/23/2011 9:41 AM, MRAB wrote: > To show the extensions, in an Explorer window go to Tools->Folder > Options... and look in the View tab. You can also look at the file > associations in the File Types tab. Thanks. From roy at panix.com Sun Oct 23 13:37:40 2011 From: roy at panix.com (Roy Smith) Date: Sun, 23 Oct 2011 13:37:40 -0400 Subject: argparse.ArgumentParser("blah") Message-ID: As I read the docs (http://tinyurl.com/3ww9scr), the following two calls should result in the same object: parser = argparse.ArgumentParser(description="blah") parser = argparse.ArgumentParser("blah") In the first case, I'm explicitly setting description to "blah", in the second case, I'm passing "blah" as a positional parameter so it should be taken as first parameter to the function, which happens to be description. Either way should end up the same. I don't, however, get the same behavior when run with "-h". The first gives what I would expect: ------------------------------------------------ usage: arg.py [-h] blah optional arguments: -h, --help show this help message and exit ------------------------------------------------ and the second gives: ------------------------------------------------ usage: blah [-h] optional arguments: -h, --help show this help message and exit ------------------------------------------------ Is this a bug, or am I just not reading the docs right? From __peter__ at web.de Sun Oct 23 14:06:14 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 23 Oct 2011 20:06:14 +0200 Subject: argparse.ArgumentParser("blah") References: Message-ID: Roy Smith wrote: > As I read the docs (http://tinyurl.com/3ww9scr), the following two calls > should result in the same object: > > parser = argparse.ArgumentParser(description="blah") > parser = argparse.ArgumentParser("blah") > > In the first case, I'm explicitly setting description to "blah", in the > second case, I'm passing "blah" as a positional parameter so it should > be taken as first parameter to the function, which happens to be > description. Either way should end up the same. > > I don't, however, get the same behavior when run with "-h". The first > gives what I would expect: > > ------------------------------------------------ > usage: arg.py [-h] > > blah > > optional arguments: > -h, --help show this help message and exit > ------------------------------------------------ > > and the second gives: > > ------------------------------------------------ > usage: blah [-h] > > optional arguments: > -h, --help show this help message and exit > ------------------------------------------------ > > Is this a bug, or am I just not reading the docs right? A quick look into the source code reveals the the documentation is not consistent with the actual implementation: http://hg.python.org/cpython/file/eef1027ab2f0/Lib/argparse.py#l1581 """ class ArgumentParser(_AttributeHolder, _ActionsContainer): [...] def __init__(self, prog=None, usage=None, description=None, epilog=None, version=None, parents=[], formatter_class=HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True): """ I suggest that you file a bug report. PS: My guess is that you are supposed to use keyword parameters only, but that the implementation doesn't enforce that (yet?). From wm at localhost.localdomain Sun Oct 23 14:25:34 2011 From: wm at localhost.localdomain (Waldek M.) Date: Sun, 23 Oct 2011 20:25:34 +0200 Subject: Job Offer: 3 Python Backend Developer and other Positions in Berlin References: Message-ID: <1b9shmovw2l6m$.dlg@localhost.localdomain> On Sun, 23 Oct 2011 17:50:54 +0200, webcrowd.net wrote: > hope it is okay to post job offers here. If not sorry for the spam and > please let me know! Not really. It's a newsgroup on Python *language*, not on Python-everything. You might want to post here instead, though: http://www.python.org/community/jobs/ Best regards, Waldek From roy at panix.com Sun Oct 23 14:33:50 2011 From: roy at panix.com (Roy Smith) Date: Sun, 23 Oct 2011 14:33:50 -0400 Subject: argparse.ArgumentParser("blah") References: Message-ID: In article , Roy Smith wrote: > As I read the docs (http://tinyurl.com/3ww9scr), the following two calls > should result in the same object: > > parser = argparse.ArgumentParser(description="blah") > parser = argparse.ArgumentParser("blah") Sigh. I should have dug deeper before posting. The docs don't match the code (they list the arguments in different orders). I've opened http://bugs.python.org/issue13249 on this. From tjreedy at udel.edu Sun Oct 23 14:50:54 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 23 Oct 2011 14:50:54 -0400 Subject: argparse.ArgumentParser("blah") In-Reply-To: References: Message-ID: On 10/23/2011 2:06 PM, Peter Otten wrote: > Roy Smith wrote: > >> As I read the docs (http://tinyurl.com/3ww9scr), the following two calls >> should result in the same object: >> >> parser = argparse.ArgumentParser(description="blah") >> parser = argparse.ArgumentParser("blah") >> >> In the first case, I'm explicitly setting description to "blah", in the >> second case, I'm passing "blah" as a positional parameter so it should >> be taken as first parameter to the function, which happens to be >> description. Either way should end up the same. >> >> I don't, however, get the same behavior when run with "-h". The first >> gives what I would expect: >> >> ------------------------------------------------ >> usage: arg.py [-h] >> >> blah >> >> optional arguments: >> -h, --help show this help message and exit >> ------------------------------------------------ >> >> and the second gives: >> >> ------------------------------------------------ >> usage: blah [-h] >> >> optional arguments: >> -h, --help show this help message and exit >> ------------------------------------------------ >> >> Is this a bug, or am I just not reading the docs right? > > A quick look into the source code reveals the the documentation is not > consistent with the actual implementation: > > http://hg.python.org/cpython/file/eef1027ab2f0/Lib/argparse.py#l1581 > > """ > class ArgumentParser(_AttributeHolder, _ActionsContainer): > [...] > def __init__(self, > prog=None, > usage=None, > description=None, > epilog=None, > version=None, > parents=[], > formatter_class=HelpFormatter, > prefix_chars='-', > fromfile_prefix_chars=None, > argument_default=None, > conflict_handler='error', > add_help=True): > """ I would call this a doc bug. The explanation of the parameters is in a different order yet. That should be changed too. help(ArgumentParser) gives them in the actual order. > I suggest that you file a bug report. > > PS: My guess is that you are supposed to use keyword parameters only, Parameters are just names local to the function. They are matched to argument objects by position or keyword, unless positional matching is disabled with the '*,' syntax, or unless the function is 'builtin' and keyword matching is not enabled. > but that the implementation doesn't enforce that (yet?). This would be an easy change in that adding '*, ' after 'self, ' in the parameter list would do it. It would be difficult in that it could break code that uses positional matching correctly, as given in the help message, and there is no way I know of to give a deprecation message. But there might be very little code that does so, given the mis-documentation in the manual. -- Terry Jan Reedy From tjreedy at udel.edu Sun Oct 23 15:52:28 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 23 Oct 2011 15:52:28 -0400 Subject: =?UTF-8?B?5Zue5aSN77yaIHB5dGhvbjMyIHRvIHdyaXRlIGZpbGU=?= In-Reply-To: References: Message-ID: On 10/23/2011 9:59 AM, ???? wrote: > i change my code into : Calling your file xml.py (as indicated below) is a potentially bad idea since the Python stdlib has a package named 'xml'. If you write 'import xml.xxx' in another file in the same directory, Python will try to find 'xxx' in your xml.py file. > import urllib.request, urllib.parse, urllib.error > import lxml.html Are you sure you have a version of lxml that works with Python 3? > down='http://frux.wikispaces.com/' > root=urllib.request.urlopen(down).read() What type of object is returned and bound to root? (print(type(root)) if doc not clear.) > root=lxml.html.fromstring(root) What type of object is root required to be (from lxml docs)? [snip] > the new problem is : > > C:\Python32>python c:\xml.py > Traceback (most recent call last): > File "c:\xml.py", line 5, in > root=lxml.html.fromstring(root) > File "C:\Python32\lib\site-packages\lxml\html\__init__.py", line 630, in > fromstring > if start.startswith(' TypeError: startswith first arg must be bytes or a tuple of bytes, not str This implies that the name 'start' is bound to bytes when it should be (for 3.2) bound to unicode, which would most likely mean that 'root' is the wrong type. Or that the above is the 2.x version of lxml where ' <75930aea-ed09-44f8-b7ca-0fa9f72e6b12@g27g2000pro.googlegroups.com> Message-ID: <14d4f626-0791-4608-aee3-fe29016cd593@p20g2000prm.googlegroups.com> For a moment, back to the basics... I am using the example provided by docs at 2.1.2 "Providing finer control...". Using say: mynoddy = noddy2.Noddy() mynoddy.first = "a" mynoddy.last = 0 the last line causes an ugly crash (on python 2.6.5 on winxp). No way to catch the exception. As I understand from the docs, all PyErr_SetString does is to set an exception, what one has to do to raise this exception (in C)? If I replace "return -1" in the Noddy_setlast() function with "return NULL" (well, the compiler will complain...) the program passes by without raising an exception. Any explanations?... Lee From d at davea.name Sun Oct 23 18:56:34 2011 From: d at davea.name (Dave Angel) Date: Sun, 23 Oct 2011 18:56:34 -0400 Subject: What is wrong with my code? In-Reply-To: <4EA3E68A.5010301@gmail.com> References: <4EA3E68A.5010301@gmail.com> Message-ID: <4EA49BA2.6080309@davea.name> On 10/23/2011 06:03 AM, apometron wrote: > import os > nome = sys.argv[1] > final = nome > for i in nome: > print i > if nome[i] = "_": > final[i] = " " > os.rename(nome, final) > What do you want to be wrong with it? There are so many things, it'd be fun to try to see who could come up with the most. 1) it's not a valid Fortran program. 2) it's missing a shebang line if we assume it's for Windows, or that you run it with an explicit bash line 3) if we pretend it's a python program, a few more 3a) It has a syntax error calling the print() function. (Python 3.2) If we assume it's a python 2.x program 4) it uses sys, without importing it 5) it uses second argument without checking if the user typed such an argument 6) it tries to change a character within a string, which is a non-mutable type 7) It creates two more references to the same string sys.argv[1], then tries to modify one of them, not realizing the others would change to. 8) it tries to subscript a string using a character. 9) it calls rename with two references to the same object. So nothing will ever actually happen, even if the other problems were fixed. Generally, you'll get the best answers here if you specify more of your environment (python version, OS), show what you tried (pasted from the command line), and the results you got (such as stack traces). HTH DaveA -- DaveA From skippy.hammond at gmail.com Sun Oct 23 19:42:23 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Mon, 24 Oct 2011 10:42:23 +1100 Subject: logging: warn() methods and function to be deprecated. In-Reply-To: References: Message-ID: <4EA4A65F.2090205@gmail.com> On 22/10/2011 11:09 PM, Vinay Sajip wrote: > In response to an issue (#13235) raised on the Python bug tracker, I'm going to > deprecate the warn() methods in the Logger and LoggerAdapter classes in the > stdlib logging package, as well the module-level warn() function. > > The warn() variants were synonyms for the warning() methods and function, and a > holdover from before the time that logging was added to Python.They were not > documented; it's probably time to retire them, so I've added a > DeprecationWarning to appear in 3.3, and they'll be completely removed in 3.4 > (along with the WARN synonym for WARNING). With this change, all the logging > levels are adjectives which apply to the logged message: DEBUG, INFO, WARNING, > ERROR and CRITICAL. > > I don't believe the WARN/warn variants were used much, if at all - but this is > just a heads up for anyone who might have used them. I think that is a real shame - it seems to be gratuitous breakage for almost zero benefit. That issue shows that Trac makes heavy use of .warn, I've use .warn almost exclusively for many years, and code.google.com shows it is used extensively in the wild. Is there still a chance to reconsider? Mark From 1248283536 at qq.com Sun Oct 23 21:06:12 2011 From: 1248283536 at qq.com (=?gbk?B?y66+ssH3ye4=?=) Date: Mon, 24 Oct 2011 09:06:12 +0800 Subject: getroot() problem Message-ID: C:\Documents and Settings\peng>cd c:\python32 C:\Python32>python Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import lxml.html >>> sfile='http://finance.yahoo.com/q/op?s=A+Options' >>> root=lxml.html.parse(sfile).getroot() there is no problem to parse : http://finance.yahoo.com/q/op?s=A+Options' why i can not parse http://frux.wikispaces.com/ ?? >>> import lxml.html >>> sfile='http://frux.wikispaces.com/' >>> root=lxml.html.parse(sfile).getroot() Traceback (most recent call last): File "", line 1, in File "C:\Python32\lib\site-packages\lxml\html\__init__.py", line 692, in parse return etree.parse(filename_or_url, parser, base_url=base_url, **kw) File "lxml.etree.pyx", line 2942, in lxml.etree.parse (src/lxml/lxml.etree.c:5 4187) File "parser.pxi", line 1528, in lxml.etree._parseDocument (src/lxml/lxml.etre e.c:79485) File "parser.pxi", line 1557, in lxml.etree._parseDocumentFromURL (src/lxml/lx ml.etree.c:79768) File "parser.pxi", line 1457, in lxml.etree._parseDocFromFile (src/lxml/lxml.e tree.c:78843) File "parser.pxi", line 997, in lxml.etree._BaseParser._parseDocFromFile (src/ lxml/lxml.etree.c:75698) File "parser.pxi", line 564, in lxml.etree._ParserContext._handleParseResultDo c (src/lxml/lxml.etree.c:71739) File "parser.pxi", line 645, in lxml.etree._handleParseResult (src/lxml/lxml.e tree.c:72614) File "parser.pxi", line 583, in lxml.etree._raiseParseError (src/lxml/lxml.etr ee.c:71927) IOError: Error reading file 'b'http://frux.wikispaces.com/'': b'failed to load e xternal entity "http://frux.wikispaces.com/"' >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun Oct 23 21:22:32 2011 From: d at davea.name (Dave Angel) Date: Sun, 23 Oct 2011 21:22:32 -0400 Subject: getroot() problem In-Reply-To: References: Message-ID: <4EA4BDD8.2070509@davea.name> On 10/23/2011 09:06 PM, ???????? wrote: > C:\Documents and Settings\peng>cd c:\python32 > > > > C:\Python32>python > > Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win > > 32 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> import lxml.html > >>>> sfile='http://finance.yahoo.com/q/op?s=A+Options' > >>>> root=lxml.html.parse(sfile).getroot() > there is no problem to parse : > > > http://finance.yahoo.com/q/op?s=A+Options' > > > > > why i can not parse > > http://frux.wikispaces.com/ ?? > >>>> import lxml.html > >>>> sfile='http://frux.wikispaces.com/' > >>>> root=lxml.html.parse(sfile).getroot() > > Traceback (most recent call last): > > File "", line 1, in > > File "C:\Python32\lib\site-packages\lxml\html\__init__.py", line 692, in parse > > > > return etree.parse(filename_or_url, parser, base_url=base_url, **kw) > > File "lxml.etree.pyx", line 2942, in lxml.etree.parse (src/lxml/lxml.etree.c:5 > > 4187) > > File "parser.pxi", line 1528, in lxml.etree._parseDocument (src/lxml/lxml.etre > > e.c:79485) > > File "parser.pxi", line 1557, in lxml.etree._parseDocumentFromURL (src/lxml/lx > > ml.etree.c:79768) > > File "parser.pxi", line 1457, in lxml.etree._parseDocFromFile (src/lxml/lxml.e > > tree.c:78843) > > File "parser.pxi", line 997, in lxml.etree._BaseParser._parseDocFromFile (src/ > > lxml/lxml.etree.c:75698) > > File "parser.pxi", line 564, in lxml.etree._ParserContext._handleParseResultDo > > c (src/lxml/lxml.etree.c:71739) > > File "parser.pxi", line 645, in lxml.etree._handleParseResult (src/lxml/lxml.e > > tree.c:72614) > > File "parser.pxi", line 583, in lxml.etree._raiseParseError (src/lxml/lxml.etr > > ee.c:71927) > > IOError: Error reading file 'b'http://frux.wikispaces.com/'': b'failed to load e > > xternal entity "http://frux.wikispaces.com/"' > >>> > Double-spacing makes your message much harder to read. I can only comment in a general way, in any case. most html is mal-formed, and not legal html. Although I don't have any experience with parsing it, I do with xml which has similar problems. The first thing I'd do is to separate the loading of the byte string from the website, from the parsing of those bytes. Further, I'd make a local copy of those bytes, so you can do testing repeatably. For example, you could run wget utility to copy the bytes locally and create a file. -- DaveA From dihedral88888 at googlemail.com Sun Oct 23 22:10:45 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Sun, 23 Oct 2011 19:10:45 -0700 (PDT) Subject: compare range objects In-Reply-To: <019dd721-055c-4aa3-aa03-6c355c2b3e18@k13g2000prg.googlegroups.com> References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> <453d196e-4516-47f3-9d33-caea70d33a8f@l12g2000vby.googlegroups.com> <4ea2557c$0$29968$c3e8da3$5496439d@news.astraweb.com> <57fe18d1-b66c-4b8c-bb83-a8994498d2cf@u13g2000vbx.googlegroups.com> <019dd721-055c-4aa3-aa03-6c355c2b3e18@k13g2000prg.googlegroups.com> Message-ID: <4393301.246.1319422245832.JavaMail.geo-discussion-forums@prng5> To compare two instances of objects defined by others in the same class or in derived classes from the same base class is an old problem in OOP. From aaabbb16 at hotmail.com Sun Oct 23 22:44:42 2011 From: aaabbb16 at hotmail.com (aaabbb16 at hotmail.com) Date: Sun, 23 Oct 2011 19:44:42 -0700 (PDT) Subject: How to use shell return value like $? In python? Message-ID: <9a377efb-7e18-46b8-902b-8fc40ab4d24b@m5g2000prg.googlegroups.com> exp: os.system('ls -al'? #I like to catch return value after this command. 0 or 1,2,3.... does python support to get "$?"? then I can use something like: If $?==0: ........ ................ TIA david From aaabbb16 at hotmail.com Sun Oct 23 22:51:47 2011 From: aaabbb16 at hotmail.com (aaabbb16 at hotmail.com) Date: Sun, 23 Oct 2011 19:51:47 -0700 (PDT) Subject: How to use shell return value like $? In python? References: <9a377efb-7e18-46b8-902b-8fc40ab4d24b@m5g2000prg.googlegroups.com> Message-ID: On Oct 23, 7:44?pm, aaabb... at hotmail.com wrote: > exp: > os.system('ls -al'? > #I like to catch return value after this command. 0 or 1,2,3.... > does python support to get "$?"? > then I can use something like: > ?If $?==0: > ? ? ?........ > ................ > TIA > david So for what I do is: r_number =os.system('ls -al') if r_number == 0 ......... ......... any other way? From clp2 at rebertia.com Sun Oct 23 22:58:37 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Oct 2011 19:58:37 -0700 Subject: How to use shell return value like $? In python? In-Reply-To: References: <9a377efb-7e18-46b8-902b-8fc40ab4d24b@m5g2000prg.googlegroups.com> Message-ID: On Sun, Oct 23, 2011 at 7:51 PM, wrote: > On Oct 23, 7:44?pm, aaabb... at hotmail.com wrote: >> exp: >> os.system('ls -al'? >> #I like to catch return value after this command. 0 or 1,2,3.... >> does python support to get "$?"? >> then I can use something like: >> ?If $?==0: > So for what I do is: > r_number =os.system('ls -al') > ? ? if r_number == 0 > ? ? ?......... > ? ? ?......... > any other way? I would recommend using the `subprocess` module instead: http://docs.python.org/library/subprocess.html#convenience-functions Cheers, Chris From fraveydank at gmail.com Sun Oct 23 23:00:22 2011 From: fraveydank at gmail.com (David Riley) Date: Sun, 23 Oct 2011 23:00:22 -0400 Subject: How to use shell return value like $? In python? In-Reply-To: <9a377efb-7e18-46b8-902b-8fc40ab4d24b@m5g2000prg.googlegroups.com> References: <9a377efb-7e18-46b8-902b-8fc40ab4d24b@m5g2000prg.googlegroups.com> Message-ID: <3A924B42-7BB4-4934-805C-87C2615832F5@gmail.com> On Oct 23, 2011, at 10:44 PM, aaabbb16 at hotmail.com wrote: > exp: > os.system('ls -al'? > #I like to catch return value after this command. 0 or 1,2,3.... > does python support to get "$?"? > then I can use something like: > If $?==0: > ........ > ................ From the manual (http://docs.python.org/library/os.html#os.system): "On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent." From the linked wait() documentation, the data returned is in a 16-bit integer, with the high byte indicating the exit status (the low byte is the signal that killed the process). So: status = os.system("foo") retval, sig = ((status >> 8) & 0xFF), (status & 0xFF) In the above example, your return status will end up in "retval". Of course, you probably ought to be using subprocess to run your subprocesses anyway; it's a lot more powerful and a lot harder to enable things like shell injection attacks. See: http://docs.python.org/library/subprocess.html#subprocess-replacements (which, of course, shows a direct replacement for os.system which is just as vulnerable to shell injection) - Dave From apometron.listas.cinco at gmail.com Sun Oct 23 23:21:49 2011 From: apometron.listas.cinco at gmail.com (apometron) Date: Mon, 24 Oct 2011 01:21:49 -0200 Subject: What is wrong with my code? In-Reply-To: <4EA49BA2.6080309@davea.name> References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> Message-ID: <4EA4D9CD.7010101@gmail.com> Sorry to continue discussing my thread on this list, I already subbed on the Tutor list but I need to reply and if possible, some ideas of why it dont works. Now it is another thing, entirely. Rename1.py and Rename2.py works, but why Rename3.py dont works? http://pastebin.com/dExFtTkp Thanks by the gentle support. []s Apometron On 10/23/2011 8:56 PM, Dave Angel wrote: > On 10/23/2011 06:03 AM, apometron wrote: >> import os >> nome = sys.argv[1] >> final = nome >> for i in nome: >> print i >> if nome[i] = "_": >> final[i] = " " >> os.rename(nome, final) >> > What do you want to be wrong with it? There are so many things, it'd > be fun to try to see who could come up with the most. > > 1) it's not a valid Fortran program. > 2) it's missing a shebang line > if we assume it's for Windows, or that you run it with an explicit > bash line > 3) if we pretend it's a python program, a few more > 3a) It has a syntax error calling the print() function. (Python 3.2) > If we assume it's a python 2.x program > 4) it uses sys, without importing it > 5) it uses second argument without checking if the user typed such an > argument > 6) it tries to change a character within a string, which is a > non-mutable type > 7) It creates two more references to the same string sys.argv[1], then > tries to modify one of them, not realizing the others would change to. > 8) it tries to subscript a string using a character. > 9) it calls rename with two references to the same object. So nothing > will ever actually happen, even if the other problems were fixed. > > Generally, you'll get the best answers here if you specify more of > your environment (python version, OS), show what you tried (pasted > from the command line), and the results you got (such as stack traces). > > HTH > > DaveA > > From nicholas.dokos at hp.com Sun Oct 23 23:23:12 2011 From: nicholas.dokos at hp.com (Nick Dokos) Date: Sun, 23 Oct 2011 23:23:12 -0400 Subject: How to use shell return value like $? In python? In-Reply-To: Message from David Riley of "Sun\, 23 Oct 2011 23\:00\:22 EDT." <3A924B42-7BB4-4934-805C-87C2615832F5@gmail.com> References: <9a377efb-7e18-46b8-902b-8fc40ab4d24b@m5g2000prg.googlegroups.com> <3A924B42-7BB4-4934-805C-87C2615832F5@gmail.com> Message-ID: <8800.1319426592@alphaville.dokosmarshall.org> David Riley wrote: > On Oct 23, 2011, at 10:44 PM, aaabbb16 at hotmail.com wrote: > > > exp: > > os.system('ls -al'? > > #I like to catch return value after this command. 0 or 1,2,3.... > > does python support to get "$?"? > > then I can use something like: > > If $?==0: > > ........ > > ................ > > From the manual (http://docs.python.org/library/os.html#os.system): > > "On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent." > > From the linked wait() documentation, the data returned is in a 16-bit integer, with the high byte indicating the exit status (the low byte is the signal that killed the process). So: > > > > > status = os.system("foo") > > retval, sig = ((status >> 8) & 0xFF), (status & 0xFF) > ... or retval, sig = os.WEXITSTATUS(status), os.WTERMSIG(status) for some insulation from low-level details. Nick > > > > In the above example, your return status will end up in "retval". > > Of course, you probably ought to be using subprocess to run your subprocesses anyway; it's a lot more powerful and a lot harder to enable things like shell injection attacks. See: http://docs.python.org/library/subprocess.html#subprocess-replacements (which, of course, shows a direct replacement for os.system which is just as vulnerable to shell injection) > > > - Dave > > -- > http://mail.python.org/mailman/listinfo/python-list From clp2 at rebertia.com Sun Oct 23 23:27:38 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Oct 2011 20:27:38 -0700 Subject: What is wrong with my code? In-Reply-To: <4EA4D9CD.7010101@gmail.com> References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> <4EA4D9CD.7010101@gmail.com> Message-ID: On Sun, Oct 23, 2011 at 8:21 PM, apometron wrote: > Sorry to continue discussing my thread on this list, I already subbed on the > Tutor list > but I need to reply and if possible, some ideas of why it dont works. Now it > is another > thing, entirely. Rename1.py and Rename2.py works, but why Rename3.py dont > works? You haven't specified in what way it's not working. What error are you getting, or what undesired/unexpected behavior are you observing? - Chris From 1248283536 at qq.com Mon Oct 24 00:02:45 2011 From: 1248283536 at qq.com (=?gbk?B?y66+ssH3ye4=?=) Date: Mon, 24 Oct 2011 12:02:45 +0800 Subject: install lxml Message-ID: there are two python versions in my computer, python2.7 is the default,python3.2 is the second install. for python2.7 ~$python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import lxml >>> for python3.2 ~$python3.2 Python 3.2.2 (default, Oct 24 2011, 10:33:35) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import lxml Traceback (most recent call last): File "", line 1, in ImportError: No module named lxml i want to install lxml in python3.2. how can i do? -------------- next part -------------- An HTML attachment was scrubbed... URL: From apometron.listas.cinco at gmail.com Mon Oct 24 00:30:40 2011 From: apometron.listas.cinco at gmail.com (apometron) Date: Mon, 24 Oct 2011 02:30:40 -0200 Subject: What is wrong with my code? In-Reply-To: References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> <4EA4D9CD.7010101@gmail.com> Message-ID: <4EA4E9F0.4010600@gmail.com> The problem is that it is not reporting any error. The do something and quits silently. No rename action is done and no error. Running Python 2.7 on Windows Seven. I know that it is a bit tricky to help someone so, but I dont have any info to pass that be good to understand the situation. Thanks by the effort in help me. I appreciate every character of it. []s Apometron On 10/24/2011 1:27 AM, Chris Rebert wrote: > On Sun, Oct 23, 2011 at 8:21 PM, apometron > wrote: >> Sorry to continue discussing my thread on this list, I already subbed on the >> Tutor list >> but I need to reply and if possible, some ideas of why it dont works. Now it >> is another >> thing, entirely. Rename1.py and Rename2.py works, but why Rename3.py dont >> works? > You haven't specified in what way it's not working. What error are you > getting, or what undesired/unexpected behavior are you observing? > > - Chris From 1248283536 at qq.com Mon Oct 24 00:30:41 2011 From: 1248283536 at qq.com (=?gbk?B?y66+ssH3ye4=?=) Date: Mon, 24 Oct 2011 12:30:41 +0800 Subject: =?gbk?B?u9i4tKO6IGdldHJvb3QoKSAgIHByb2JsZW0=?= Message-ID: in my computer,there two os , 1.xp+python32 import lxml.html sfile='http://finance.yahoo.com/q/op?s=A+Options' root=lxml.html.parse(sfile).getroot() it is ok import lxml.html sfile='http://frux.wikispaces.com/' root=lxml.html.parse(sfile).getroot() there is problem Traceback (most recent call last): File "", line 1, in File "C:\Python32\lib\site-packages\lxml\html\__init__.py", line 692, in parse return etree.parse(filename_or_url, parser, base_url=base_url, **kw) File "lxml.etree.pyx", line 2942, in lxml.etree.parse (src/lxml/lxml.etree.c:5 4187) File "parser.pxi", line 1528, in lxml.etree._parseDocument (src/lxml/lxml.etre e.c:79485) File "parser.pxi", line 1557, in lxml.etree._parseDocumentFromURL (src/lxml/lx ml.etree.c:79768) File "parser.pxi", line 1457, in lxml.etree._parseDocFromFile (src/lxml/lxml.e tree.c:78843) File "parser.pxi", line 997, in lxml.etree._BaseParser._parseDocFromFile (src/ lxml/lxml.etree.c:75698) File "parser.pxi", line 564, in lxml.etree._ParserContext._handleParseResultDo c (src/lxml/lxml.etree.c:71739) File "parser.pxi", line 645, in lxml.etree._handleParseResult (src/lxml/lxml.e tree.c:72614) File "parser.pxi", line 583, in lxml.etree._raiseParseError (src/lxml/lxml.etr ee.c:71927) IOError: Error reading file 'b'http://frux.wikispaces.com/'': b'failed to load e xternal entity "http://frux.wikispaces.com/"' 2. ubuntu11.04+python2.6 import lxml.html sfile='http://frux.wikispaces.com/' root=lxml.html.parse(sfile).getroot() it is ok it is so strange thing for me to understand ------------------ ???? ------------------ ???: "Dave Angel"; ????: 2011?10?24?(???) ??9:22 ???: "1248283536"<1248283536 at qq.com>; ??: "lxml"; "python-list"; ??: Re: getroot() problem On 10/23/2011 09:06 PM, ???? wrote: > C:\Documents and Settings\peng>cd c:\python32 > > > > C:\Python32>python > > Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win > > 32 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> import lxml.html > >>>> sfile='http://finance.yahoo.com/q/op?s=A+Options' > >>>> root=lxml.html.parse(sfile).getroot() > there is no problem to parse : > > > http://finance.yahoo.com/q/op?s=A+Options' > > > > > why i can not parse > > http://frux.wikispaces.com/ ?? > >>>> import lxml.html > >>>> sfile='http://frux.wikispaces.com/' > >>>> root=lxml.html.parse(sfile).getroot() > > Traceback (most recent call last): > > File "", line 1, in > > File "C:\Python32\lib\site-packages\lxml\html\__init__.py", line 692, in parse > > > > return etree.parse(filename_or_url, parser, base_url=base_url, **kw) > > File "lxml.etree.pyx", line 2942, in lxml.etree.parse (src/lxml/lxml.etree.c:5 > > 4187) > > File "parser.pxi", line 1528, in lxml.etree._parseDocument (src/lxml/lxml.etre > > e.c:79485) > > File "parser.pxi", line 1557, in lxml.etree._parseDocumentFromURL (src/lxml/lx > > ml.etree.c:79768) > > File "parser.pxi", line 1457, in lxml.etree._parseDocFromFile (src/lxml/lxml.e > > tree.c:78843) > > File "parser.pxi", line 997, in lxml.etree._BaseParser._parseDocFromFile (src/ > > lxml/lxml.etree.c:75698) > > File "parser.pxi", line 564, in lxml.etree._ParserContext._handleParseResultDo > > c (src/lxml/lxml.etree.c:71739) > > File "parser.pxi", line 645, in lxml.etree._handleParseResult (src/lxml/lxml.e > > tree.c:72614) > > File "parser.pxi", line 583, in lxml.etree._raiseParseError (src/lxml/lxml.etr > > ee.c:71927) > > IOError: Error reading file 'b'http://frux.wikispaces.com/'': b'failed to load e > > xternal entity "http://frux.wikispaces.com/"' > >>> > Double-spacing makes your message much harder to read. I can only comment in a general way, in any case. most html is mal-formed, and not legal html. Although I don't have any experience with parsing it, I do with xml which has similar problems. The first thing I'd do is to separate the loading of the byte string from the website, from the parsing of those bytes. Further, I'd make a local copy of those bytes, so you can do testing repeatably. For example, you could run wget utility to copy the bytes locally and create a file. -- DaveA -------------- next part -------------- An HTML attachment was scrubbed... URL: From moijes12 at gmail.com Mon Oct 24 00:53:41 2011 From: moijes12 at gmail.com (moijes12) Date: Sun, 23 Oct 2011 21:53:41 -0700 (PDT) Subject: Books to lean Python 3 Web Programming? References: Message-ID: <2d15360d-ab41-49e6-be5a-38490e3f96c8@v8g2000pro.googlegroups.com> On Oct 23, 3:18?am, Jonathan Loescher wrote: > Can anyone recommend a good book to learn the web programming aspects > of Python 3? Hi You can check "Dive into Python 3" by Mark Pilgrim. It does cover some aspects of web programming. I haven't read it myself,but I've been reading "Dive into Python". I hope this helps. regards Alexander From tjreedy at udel.edu Mon Oct 24 00:58:24 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Oct 2011 00:58:24 -0400 Subject: install lxml In-Reply-To: References: Message-ID: On 10/24/2011 12:02 AM, ???? wrote: > there are two python versions in my computer, > python2.7 is the default,python3.2 is the second install. > for python2.7 > ~$python > Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import lxml > >>> > > for python3.2 > ~$python3.2 > Python 3.2.2 (default, Oct 24 2011, 10:33:35) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import lxml > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named lxml > > i want to install lxml in python3.2. > how can i do? Put a 3.2 version of lxml in the 3.2 Lib/site-packages directory. -- Terry Jan Reedy From moijes12 at gmail.com Mon Oct 24 01:09:44 2011 From: moijes12 at gmail.com (moijes12) Date: Sun, 23 Oct 2011 22:09:44 -0700 (PDT) Subject: Books to lean Python 3 Web Programming? References: Message-ID: On Oct 23, 3:18?am, Jonathan Loescher wrote: > Can anyone recommend a good book to learn the web programming aspects > of Python 3? Hi Try out "Dive into Python 3" for an introduction to HTTP services. regards Moses From jason.swails at gmail.com Mon Oct 24 01:18:46 2011 From: jason.swails at gmail.com (Jason Swails) Date: Mon, 24 Oct 2011 01:18:46 -0400 Subject: CSV writer question Message-ID: Hello, I have a question about a csv.writer instance. I have a utility that I want to write a full CSV file from lots of data, but due to performance (and memory) considerations, there's no way I can write the data sequentially. Therefore, I write the data in chunks to temporary files, then combine them all at the end. For convenience, I declare each writer instance via a statement like my_csv = csv.writer(open('temp.1.csv', 'wb')) so the open file object isn't bound to any explicit reference, and I don't know how to reference it inside the writer class (the documentation doesn't say, unless I've missed the obvious). Thus, the only way I can think of to make sure that all of the data is written before I start copying these files sequentially into the final file is to unbuffer them so the above command is changed to my_csv = csv.writer(open('temp.1.csv', 'wb', 0)) unless, of course, I add an explicit reference to track the open file object and manually close or flush it (but I'd like to avoid it if possible). My question is 2-fold. Is there a way to do that directly via the CSV API, or is the approach I'm taking the only way without binding the open file object to another reference? Secondly, if these files are potentially very large (anywhere from ~1KB to 20 GB depending on the amount of data present), what kind of performance hit will I be looking at by disabling buffering on these types of files? Tips, answers, comments, and/or suggestions are all welcome. Thanks a lot! Jason As an afterthought, I suppose I could always subclass the csv.writer class and add the reference I want to that, which I may do if there's no other convenient solution. -------------- next part -------------- An HTML attachment was scrubbed... URL: From 1248283536 at qq.com Mon Oct 24 01:31:19 2011 From: 1248283536 at qq.com (=?gbk?B?y66+ssH3ye4=?=) Date: Mon, 24 Oct 2011 13:31:19 +0800 Subject: =?gbk?B?u9i4tKO6IGluc3RhbGwgIGx4bWw=?= Message-ID: The latest version is lxml 2.3.1, released 2011-09-25, 1.download it 2.extract it ,put it in the /home/user/Python-3.2.2/libxml2-2.7.8 3.cd /home/user/Python-3.2.2/libxml2-2.7.8 4. ./configure 5.make 6.sudo make install when i finished ~$ python3.2 Python 3.2.2 (default, Oct 24 2011, 10:33:35) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import lxml Traceback (most recent call last): File "", line 1, in ImportError: No module named lxml there is still the problem!! ------------------ ???? ------------------ ???: "Terry Reedy"; ????: 2011?10?24?(???) ??12:58 ???: "python-list"; ??: "lxml"; ??: Re: install lxml On 10/24/2011 12:02 AM, ???? wrote: > there are two python versions in my computer, > python2.7 is the default,python3.2 is the second install. > for python2.7 > ~$python > Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import lxml > >>> > > for python3.2 > ~$python3.2 > Python 3.2.2 (default, Oct 24 2011, 10:33:35) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import lxml > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named lxml > > i want to install lxml in python3.2. > how can i do? Put a 3.2 version of lxml in the 3.2 Lib/site-packages directory. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Mon Oct 24 02:08:59 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Oct 2011 23:08:59 -0700 Subject: CSV writer question In-Reply-To: References: Message-ID: On Sun, Oct 23, 2011 at 10:18 PM, Jason Swails wrote: > Hello, > > I have a question about a csv.writer instance.? I have a utility that I want > to write a full CSV file from lots of data, but due to performance (and > memory) considerations, there's no way I can write the data sequentially. > Therefore, I write the data in chunks to temporary files, then combine them > all at the end.? For convenience, I declare each writer instance via a > statement like > > my_csv = csv.writer(open('temp.1.csv', 'wb')) > > so the open file object isn't bound to any explicit reference, and I don't > know how to reference it inside the writer class (the documentation doesn't > say, unless I've missed the obvious).? Thus, the only way I can think of to > make sure that all of the data is written before I start copying these files > sequentially into the final file is to unbuffer them so the above command is > changed to > > my_csv = csv.writer(open('temp.1.csv', 'wb', 0)) > > unless, of course, I add an explicit reference to track the open file object > and manually close or flush it > (but I'd like to avoid it if possible). Why? Especially when the performance cost is likely to be nontrivial... >?Is there a way to do that directly via the CSV API, Very doubtful; csv.writer (and reader for that matter) is implemented in C, doesn't expose a ._file or similar attribute, and has no .close() or .flush() methods. Cheers, Chris -- http://rebertia.com From rosuav at gmail.com Mon Oct 24 03:03:15 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 24 Oct 2011 18:03:15 +1100 Subject: CSV writer question In-Reply-To: References: Message-ID: On Mon, Oct 24, 2011 at 4:18 PM, Jason Swails wrote: > my_csv = csv.writer(open('temp.1.csv', 'wb')) > Have you confirmed, or can you confirm, whether or not the file gets closed automatically when the writer gets destructed? If so, all you need to do is: my_csv = something_else # or: del my_csv to unbind what I assume is the only reference to the csv.writer, upon which it should promptly clean itself up. ChrisA From stefan_ml at behnel.de Mon Oct 24 03:12:40 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Oct 2011 09:12:40 +0200 Subject: =?UTF-8?B?5Zue5aSN77yaIGluc3RhbGwgIGx4bWw=?= In-Reply-To: References: Message-ID: ????, 24.10.2011 07:31: > The latest version is lxml 2.3.1, released 2011-09-25, > 1.download it > 2.extract it ,put it in the /home/user/Python-3.2.2/libxml2-2.7.8 > 3.cd /home/user/Python-3.2.2/libxml2-2.7.8 > 4. ./configure > 5.make > 6.sudo make install Not libxml2. lxml. > when i finished > ~$ python3.2 > Python 3.2.2 (default, Oct 24 2011, 10:33:35) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import lxml > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named lxml > > there is still the problem!! You can get a binary build for Windows from PyPI: http://pypi.python.org/pypi/lxml/2.3 Oh, and please avoid cross-posting (and top-posting in replies). Stefan From __peter__ at web.de Mon Oct 24 03:28:11 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Oct 2011 09:28:11 +0200 Subject: shutil _isindir References: <4EA2BBF0.4050602@gmail.com> Message-ID: David Hoese wrote: > I was about to submit a bug report, but while testing I have figured out > that my specific problem has been solved in Python 2.7 (server that I > was using had 2.6 on it). You can see the differences here: > > 2.6: http://hg.python.org/cpython/file/b9a95ce2692c/Lib/shutil.py > 2.7: http://hg.python.org/cpython/file/d30482d51c25/Lib/shutil.py > > You'll notice that in move(), there is now a check for the same file, > which if they're not the same file you don't get unexpected deleted > files. If you still think I should submit a bug report let me know and > provide me with the test case...or just submit the bug yourself. Aren't there still problems that can be avoided with the change you propose? I think the bug report is worthwhile. From ivo at webcrowd.net Mon Oct 24 03:40:45 2011 From: ivo at webcrowd.net (webcrowd.net) Date: Mon, 24 Oct 2011 09:40:45 +0200 Subject: Job Offer: 3 Python Backend Developer and other Positions in Berlin In-Reply-To: <1b9shmovw2l6m$.dlg@localhost.localdomain> References: <1b9shmovw2l6m$.dlg@localhost.localdomain> Message-ID: Am 23.10.11 20:25, schrieb Waldek M.: > On Sun, 23 Oct 2011 17:50:54 +0200, webcrowd.net wrote: >> hope it is okay to post job offers here. If not sorry for the spam and >> please let me know! > > Not really. It's a newsgroup on Python *language*, not > on Python-everything. > > You might want to post here instead, though: > http://www.python.org/community/jobs/ > > Best regards, > Waldek Thanks Waldek, will do so in future! Best Regards, Ivo From vinay_sajip at yahoo.co.uk Mon Oct 24 04:28:28 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Mon, 24 Oct 2011 09:28:28 +0100 (BST) Subject: logging: warn() methods and function to be deprecated. In-Reply-To: <4EA4A65F.2090205@gmail.com> References: <4EA4A65F.2090205@gmail.com> Message-ID: <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> > I think that is a real shame - it seems to be gratuitous breakage for almost > zero benefit.? That issue shows that Trac makes heavy use of .warn, I've use > .warn almost exclusively for many years, and code.google.com shows it is used > extensively in the wild. Okay, but it's easy enough to change, and people are getting a reasonable amount of time to deal with it. > Is there still a chance to reconsider? I'm not dogmatic about things like this; warn() is just a hangover from a long time ago and bit of a nit, that's all. I suppose I should have removed it when 3.0 was released, but it went under my radar at that time. Hence my post here, to get feedback from logging users about this proposed change. Regards, Vinay Sajip From d at davea.name Mon Oct 24 08:18:28 2011 From: d at davea.name (Dave Angel) Date: Mon, 24 Oct 2011 08:18:28 -0400 Subject: What is wrong with my code? In-Reply-To: <4EA4E9F0.4010600@gmail.com> References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> <4EA4D9CD.7010101@gmail.com> <4EA4E9F0.4010600@gmail.com> Message-ID: <4EA55794.3050304@davea.name> (Don't top-post. Put your response after the part you're quoting from earlier messages. And include enough that somebody can help with minimal effort.) On 10/24/2011 12:30 AM, apometron wrote: > The problem is that it is not reporting any error. > > The do something and quits silently. > > No rename action is done and no error. > > Running Python 2.7 on Windows Seven. > Your link http://pastebin.com/dExFtTkp shows two copies of the code. I'm assuming they're identical, and using the second one. How do you know no rename action is done? Did you do a dir before and after running it? Were there any files that actually had underscores in them? Did you try adding a print to the innermost if statement to see if it ever ran? Did you try adding a print right after the os.rename that showed both nome and final? When I run it in CPython 2.7 on Linux, it successfully renamed the file (dumm_1.txt) I had supplied. davea at think:~/pytests$ ls dumm_1.txt itpone.itp~ lina.py~ pdbone.pdb~ prim.py~ itpone.itp lina.py pdbone.pdb prim.py whatswrong.py davea at think:~/pytests$ python whatswrong.py dumm_1.txt davea at think:~/pytests$ ls dumm 1.txt itpone.itp~ lina.py~ pdbone.pdb~ prim.py~ itpone.itp lina.py pdbone.pdb prim.py whatswrong.py davea at think:~/pytests$ (I had to delete the following part, since you put yours out of order) -- DaveA From npropadovic at googlemail.com Mon Oct 24 08:43:58 2011 From: npropadovic at googlemail.com (Propad) Date: Mon, 24 Oct 2011 05:43:58 -0700 (PDT) Subject: spawnl issues with Win 7 access rights Message-ID: Hello everybody, I have some trouble with a program I run both on a WinXP and on Win 7. It boils down to this several lines: import os vePath = r'C:\Programme\RA Consulting_Webservices\DiagRA-MCD \DiagRA_D.exe' #vePath = r'C:\Windows\notepad.exe' process_id = os.spawnl(os.P_NOWAIT, vePath) Under Win XP they open DiagRA just fine; under Win 7 I'm getting: OSError: [Errno 22] Invalid argument Needless to say, I checked the path under Win 7; it is correct. As you can see, I tried the same lines with notepad, just in case; same result. Works fine under XP, IOError under Win 7. So I'm pretty sure it's some kind of Win 7 access rights issue... Can anybody point me to a concise overview of the issues involved, and maybe even the known solutions? Again, it's os.spawnl in Python 2.2, under Win 7. Thank you very much in advance. Cheers, Nenad From mail at timgolden.me.uk Mon Oct 24 09:18:27 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 24 Oct 2011 14:18:27 +0100 Subject: spawnl issues with Win 7 access rights In-Reply-To: References: Message-ID: <4EA565A3.3030909@timgolden.me.uk> On 24/10/2011 13:43, Propad wrote: > Hello everybody, > I have some trouble with a program I run both on a WinXP and on Win 7. > It boils down to this several lines: > > import os > vePath = r'C:\Programme\RA Consulting_Webservices\DiagRA-MCD > \DiagRA_D.exe' > #vePath = r'C:\Windows\notepad.exe' > process_id = os.spawnl(os.P_NOWAIT, vePath) > > Under Win XP they open DiagRA just fine; under Win 7 I'm getting: > OSError: [Errno 22] Invalid argument > Needless to say, I checked the path under Win 7; it is correct. > > As you can see, I tried the same lines with notepad, just in case; > same result. Works fine under XP, IOError under Win 7. > > So I'm pretty sure it's some kind of Win 7 access rights issue... Can > anybody point me to a concise overview of the issues involved, and > maybe even the known solutions? Again, it's os.spawnl in Python 2.2, > under Win 7. That's impressive. I ran this (on Python 2.7 on Win7): import os os.spawnl (os.P_NOWAIT, r"c:\windows\notepad.exe") and Python crashed hard! Long time since I've seen that happen. This may or may not be related to what you're seeing but it's definitely a problem. I'll check the bugs database and/or file a bug. I *can* reproduce your problem running Python22 on Win7. Now, no-one's going to be applying patches to Python 2.2 at this stage: in the 2.x series, only 2.7 is getting anything other than urgent security fixes. And even 2.7's only getting clear bugfixes. Just so you know. Without checking the code, I'm going to assume that the 2.2 codebase is handing off to the MS C Runtime Library for posix-related calls such as the spawn* family. So it may not even be Python's code directly which is returning this error. TJG From alec.taylor6 at gmail.com Mon Oct 24 09:39:11 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 25 Oct 2011 00:39:11 +1100 Subject: Python as a replacement to PL/SQL Message-ID: Good morning, Is there a set of libraries for python which can be used as a complete replacement to PL/SQL? Alternatively, is there a python library for generating PL/SQL? (I am speaking from the context of Oracle DB, PL/Python only works with PostgreSQL) Thanks for all suggestions, Alec Taylor From npropadovic at googlemail.com Mon Oct 24 09:47:22 2011 From: npropadovic at googlemail.com (Propad) Date: Mon, 24 Oct 2011 06:47:22 -0700 (PDT) Subject: spawnl issues with Win 7 access rights References: Message-ID: Hello Tim, thanx for the fast answer. Sorry to hear there are such issues. I'm obviously not free to choose my version of Python, or I'would be using the latest'n'greatest. It's more like this: I'm obliged to use the version delivered with dSpace tools (which is HiL - ECU-testing software for the automotive and aerospace industries). I'just might be able to use 2.5, which dSpace delivered 2-3 years ago; but I'm not sure of that, and not sure it would help in any way. So some solution without tweaking the code or anything would be realy nice. I can't imagine anything of such importance was not tested at all during the beta phase - so it could be the tests were not run with such a tricky configuration of windows. Any hints are appreciated! Cheers, Nenad On 24 Okt., 15:18, Tim Golden wrote: > On 24/10/2011 13:43, Propad wrote: > > > > > > > Hello everybody, > > I have some trouble with a program I run both on a WinXP and on Win 7. > > It boils down to this several lines: > > > import os > > vePath = r'C:\Programme\RA Consulting_Webservices\DiagRA-MCD > > \DiagRA_D.exe' > > #vePath = r'C:\Windows\notepad.exe' > > process_id = os.spawnl(os.P_NOWAIT, vePath) > > > Under Win XP they ?open DiagRA just fine; under Win 7 I'm getting: > > OSError: [Errno 22] Invalid argument > > Needless to say, I checked the path under Win 7; it is correct. > > > As you can see, I tried the same lines with notepad, just in case; > > same result. Works fine under XP, IOError under Win 7. > > > So I'm pretty sure it's some kind of Win 7 access rights issue... Can > > anybody point me to a concise overview of the issues involved, and > > maybe even the known solutions? Again, it's os.spawnl in Python 2.2, > > under Win 7. > > That's impressive. I ran this (on Python 2.7 on Win7): > > > import os > > os.spawnl (os.P_NOWAIT, r"c:\windows\notepad.exe") > > > > and Python crashed hard! Long time since I've seen that happen. > > This may or may not be related to what you're seeing but it's > definitely a problem. I'll check the bugs database and/or > file a bug. > > I *can* reproduce your problem running Python22 on Win7. Now, > no-one's going to be applying patches to Python 2.2 at this > stage: in the 2.x series, only 2.7 is getting anything other > than urgent security fixes. And even 2.7's only getting clear > bugfixes. Just so you know. > > Without checking the code, I'm going to assume that the 2.2 codebase > is handing off to the MS C Runtime Library for posix-related calls > such as the spawn* family. So it may not even be Python's code directly > which is returning this error. > > TJG- Zitierten Text ausblenden - > > - Zitierten Text anzeigen - From mail at timgolden.me.uk Mon Oct 24 10:18:48 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 24 Oct 2011 15:18:48 +0100 Subject: spawnl issues with Win 7 access rights In-Reply-To: <4EA565A3.3030909@timgolden.me.uk> References: <4EA565A3.3030909@timgolden.me.uk> Message-ID: <4EA573C8.1080502@timgolden.me.uk> On 24/10/2011 14:18, Tim Golden wrote: I ran this (on Python 2.7 on Win7): > > > import os > > os.spawnl (os.P_NOWAIT, r"c:\windows\notepad.exe") > > > > and Python crashed hard! Long time since I've seen that happen. > > This may or may not be related to what you're seeing but it's > definitely a problem. I'll check the bugs database and/or > file a bug. > > I *can* reproduce your problem running Python22 on Win7. Now, > no-one's going to be applying patches to Python 2.2 at this > stage: in the 2.x series, only 2.7 is getting anything other > than urgent security fixes. And even 2.7's only getting clear > bugfixes. Just so you know. OK; the python 2.7 issues is http://bugs.python.org/issue8036 Let's see if I can get a fix in before the next release! Not quite sure whether the 2.2 issue is the same but it's looking like being a W7 / CRT-related issue. I'll keep looking TJG From jeanmichel at sequans.com Mon Oct 24 10:34:32 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 Oct 2011 16:34:32 +0200 Subject: logging: warn() methods and function to be deprecated. In-Reply-To: <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> References: <4EA4A65F.2090205@gmail.com> <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> Message-ID: <4EA57778.1030306@sequans.com> Vinay Sajip wrote: >> I think that is a real shame - it seems to be gratuitous breakage for almost >> > > >> zero benefit. That issue shows that Trac makes heavy use of .warn, I've use >> .warn almost exclusively for many years, and code.google.com shows it is used >> extensively in the wild. >> > > Okay, but it's easy enough to change, and people are getting a reasonable amount of time to deal with it. > > >> Is there still a chance to reconsider? >> > > I'm not dogmatic about things like this; warn() is just a hangover from a long time ago and bit of a nit, that's all. I suppose I should have removed it when 3.0 was released, but it went under my radar at that time. > > Hence my post here, to get feedback from logging users about this proposed change. > > Regards, > > Vinay Sajip > I'm not using python 3, I'm not sure my feedback matters, but I wouldn't mind refactoring warn into warning If I'd have to. It's better to use documented API anyway. JM PS : I also had an issue with my logging wrappers where I did not implement warn, quite confusing the first time I had this error. From mcfletch at vrplumber.com Mon Oct 24 10:38:55 2011 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Mon, 24 Oct 2011 10:38:55 -0400 Subject: logging: warn() methods and function to be deprecated. In-Reply-To: <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> References: <4EA4A65F.2090205@gmail.com> <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> Message-ID: <4EA5787F.1050906@vrplumber.com> On 11-10-24 04:28 AM, Vinay Sajip wrote: >> I think that is a real shame - it seems to be gratuitous breakage for almost >> zero benefit. That issue shows that Trac makes heavy use of .warn, I've use >> .warn almost exclusively for many years, and code.google.com shows it is used >> extensively in the wild. > Okay, but it's easy enough to change, and people are getting a reasonable amount of time to deal with it. I'd have to echo Mark's sentiment here. There is a *lot* of (fairly old) code around that uses .warn, and I'd wager even a lot of new code written by old programmers (such as myself) that uses it. Breaking it to avoid having an undocumented method seems wrong; suggest just adding documentation: "logger.warn(...) -- an alias to logger.warning provided for backward compatibility" >> Is there still a chance to reconsider? > I'm not dogmatic about things like this; warn() is just a hangover from a long time ago and bit of a nit, that's all. I suppose I should have removed it when 3.0 was released, but it went under my radar at that time. > > Hence my post here, to get feedback from logging users about this proposed change. I actually consider .warning() a nit :) . After all, it's 3 extra characters :) , and *who* actually reads documentation instead of just poking around and finding the shortest-named method in the instance? Anyway, I personally don't see this as worth the breakage. Just my $0.02, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From alain at dpt-info.u-strasbg.fr Mon Oct 24 10:45:08 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Mon, 24 Oct 2011 16:45:08 +0200 Subject: Python as a replacement to PL/SQL References: Message-ID: <87bot6sb2j.fsf@dpt-info.u-strasbg.fr> Alec Taylor writes: > Is there a set of libraries for python which can be used as a complete > replacement to PL/SQL? This doesn't make much sense: PL/SQL lets you write server-side code, i.e., executed by the DBMS. Oracle can't execute python code directly, so python can only be used on the client side (I meant "client of the DBMS"), i.e., not to write stored procedures. There is no "complete replacement" of PL/SQL besides Java. This page shows you how to _call_ PL/SQL procedures from a python script: http://www.oracle.com/technetwork/articles/dsl/python-091105.html > (I am speaking from the context of Oracle DB, PL/Python only works > with PostgreSQL) PL/Python is a different beast, it lets you write stored functions in python. There is no such thing, afaik, with Oracle. -- Alain. From alec.taylor6 at gmail.com Mon Oct 24 10:59:07 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 25 Oct 2011 01:59:07 +1100 Subject: Python as a replacement to PL/SQL In-Reply-To: <87bot6sb2j.fsf@dpt-info.u-strasbg.fr> References: <87bot6sb2j.fsf@dpt-info.u-strasbg.fr> Message-ID: Hmm... What else is there besides PL/Python (for any DB) in the context of writing stored procedures in function? Thanks for all suggestions, Alec Taylor On Tue, Oct 25, 2011 at 1:45 AM, Alain Ketterlin wrote: > Alec Taylor writes: > >> Is there a set of libraries for python which can be used as a complete >> replacement to PL/SQL? > > This doesn't make much sense: PL/SQL lets you write server-side code, > i.e., executed by the DBMS. Oracle can't execute python code directly, > so python can only be used on the client side (I meant "client of the > DBMS"), i.e., not to write stored procedures. There is no "complete > replacement" of PL/SQL besides Java. > > This page shows you how to _call_ PL/SQL procedures from a python script: > > http://www.oracle.com/technetwork/articles/dsl/python-091105.html > >> (I am speaking from the context of Oracle DB, PL/Python only works >> with PostgreSQL) > > PL/Python is a different beast, it lets you write stored functions in > python. There is no such thing, afaik, with Oracle. > > -- Alain. > -- > http://mail.python.org/mailman/listinfo/python-list > From k.sahithi2862 at gmail.com Mon Oct 24 12:19:15 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Mon, 24 Oct 2011 09:19:15 -0700 (PDT) Subject: HOT ACTRESSES Message-ID: <17e12435-5ed4-4402-9e26-7c2c2133aec0@d33g2000prb.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html SAKUNI MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/sakuni-movie-stills.html 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html SNEHA ULLAL HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/sneha-ullal-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html From alec.taylor6 at gmail.com Mon Oct 24 12:30:41 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 25 Oct 2011 03:30:41 +1100 Subject: Convert DDL to ORM Message-ID: Good morning, I'm often generating DDLs from EER->Logical diagrams using tools such as PowerDesigner and Oracle Data Modeller. I've recently come across an ORM library (SQLalchemy), and it seems like a quite useful abstraction. Is there a way to convert my DDL to ORM code? Thanks for all suggestions, Alec Taylor From M.Komon at SiliconHill.cz Mon Oct 24 12:37:24 2011 From: M.Komon at SiliconHill.cz (=?UTF-8?B?TWFydGluIEtvbW/FiA==?=) Date: Mon, 24 Oct 2011 18:37:24 +0200 Subject: Python as a replacement to PL/SQL In-Reply-To: References: <87bot6sb2j.fsf@dpt-info.u-strasbg.fr> Message-ID: <4EA59444.60407@SiliconHill.cz> PostgreSQL supports PL/SQL, PL/TCL, PL/Python, PL/Perl and I've also seen PL/Java add on module. Martin On 10/24/2011 4:59 PM, Alec Taylor wrote: > Hmm... > > What else is there besides PL/Python (for any DB) in the context of > writing stored procedures in function? > > Thanks for all suggestions, > > Alec Taylor > > On Tue, Oct 25, 2011 at 1:45 AM, Alain Ketterlin > wrote: >> Alec Taylor writes: >> >>> Is there a set of libraries for python which can be used as a complete >>> replacement to PL/SQL? >> >> This doesn't make much sense: PL/SQL lets you write server-side code, >> i.e., executed by the DBMS. Oracle can't execute python code directly, >> so python can only be used on the client side (I meant "client of the >> DBMS"), i.e., not to write stored procedures. There is no "complete >> replacement" of PL/SQL besides Java. >> >> This page shows you how to _call_ PL/SQL procedures from a python script: >> >> http://www.oracle.com/technetwork/articles/dsl/python-091105.html >> >>> (I am speaking from the context of Oracle DB, PL/Python only works >>> with PostgreSQL) >> >> PL/Python is a different beast, it lets you write stored functions in >> python. There is no such thing, afaik, with Oracle. >> >> -- Alain. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> From M.Komon at SiliconHill.cz Mon Oct 24 12:43:05 2011 From: M.Komon at SiliconHill.cz (=?UTF-8?B?TWFydGluIEtvbW/FiA==?=) Date: Mon, 24 Oct 2011 18:43:05 +0200 Subject: Convert DDL to ORM In-Reply-To: References: Message-ID: <4EA59599.2040806@SiliconHill.cz> Hi, for the project I'm working on right now I've written a simple "SQL create script to ORM generator". I use SQLalchemy as well and this generator takes all tables and prepares classes, maps them to tables, introspects them and creates explicit attribute definitions in the classes. Contact me off-list for more details. Martin On 10/24/2011 6:30 PM, Alec Taylor wrote: > Good morning, > > I'm often generating DDLs from EER->Logical diagrams using tools such > as PowerDesigner and Oracle Data Modeller. > > I've recently come across an ORM library (SQLalchemy), and it seems > like a quite useful abstraction. > > Is there a way to convert my DDL to ORM code? > > Thanks for all suggestions, > > Alec Taylor From dmitrey15 at gmail.com Mon Oct 24 14:24:48 2011 From: dmitrey15 at gmail.com (dmitrey) Date: Mon, 24 Oct 2011 11:24:48 -0700 (PDT) Subject: [ANN] New free multifactor analysis tool for experiment planning Message-ID: Hi all, you may be interested in new free multifactor analysis tool for experiment planning (in physics, chemistry, biology etc). It is based on numerical optimization solver BOBYQA, released in 2009 by Michael J.D. Powell, and has easy and convenient GUI frontend, written in Python + tkinter. Maybe other (alternative) engines will be available in future. See its webpage for details: http://openopt.org/MultiFactorAnalysis Regards, Dmitrey. From candide at free.invalid Mon Oct 24 15:26:59 2011 From: candide at free.invalid (candide) Date: Mon, 24 Oct 2011 21:26:59 +0200 Subject: randrange exceptional behavior Message-ID: <4ea5bc04$0$6448$426a74cc@news.free.fr> Where is documented the behaviour of the standard function randrange in the case of an empty list ? for instance randrange(42,33) ? May I rely on an ValueError type error? From jason.swails at gmail.com Mon Oct 24 15:41:31 2011 From: jason.swails at gmail.com (Jason Swails) Date: Mon, 24 Oct 2011 15:41:31 -0400 Subject: CSV writer question In-Reply-To: References: Message-ID: On Mon, Oct 24, 2011 at 2:08 AM, Chris Rebert wrote: > On Sun, Oct 23, 2011 at 10:18 PM, Jason Swails > wrote: > > > unless, of course, I add an explicit reference to track the open file > object > > and manually close or flush it > > (but I'd like to avoid it if possible). > > Why? Especially when the performance cost is likely to be nontrivial... > Because if the CSV API exposed the file object, I wouldn't have to create that extra reference, and the class that is handling this stuff already has enough attributes without having to add a separate one for each CSV writer it instantiates. It's not a serious objection to creating it, just one I'd rather not do (it's less elegant IMO, whatever that's worth). > > Is there a way to do that directly via the CSV API, > > Very doubtful; csv.writer (and reader for that matter) is implemented > in C, doesn't expose a ._file or similar attribute, and has no > .close() or .flush() methods. > The machinery implemented in C, but they are wrapped in Python, and it's a Python file object being passed to the writer, so I thought maybe there was a 'standard' method of exposing file objects in these types of cases that I just wasn't aware of, but it appears not. Thanks for the info! Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From blueeagle2 at gmail.com Mon Oct 24 15:47:56 2011 From: blueeagle2 at gmail.com (blueeagle2 at gmail.com) Date: Mon, 24 Oct 2011 12:47:56 -0700 Subject: Gui Builder for Python an wxPython Message-ID: I am just getting into gui building in python and I am trying to find a designer that is easy to use. I tried wxGlade and though it looks promising I could not get anywhere with it. It would not let me create a simple dialog application. If I were using MonoDevelop it would be a snap, but there does not seem to be any descent tutorials anywhere that I can find. One would think it would be rather intuitive, but it is not or at least not for me. I have looked at wxFormBuilder and QT4 with python and they both looked better. I was just wondering what anyone else would consider a good wxPython designer. I would even be willing to buy one if it was not too expensive and had descent tutorials and documentation. -------------- next part -------------- An HTML attachment was scrubbed... URL: From candide at free.invalid Mon Oct 24 15:51:53 2011 From: candide at free.invalid (candide) Date: Mon, 24 Oct 2011 21:51:53 +0200 Subject: Importing a module from a non-cwd Message-ID: <4ea5c1da$0$3708$426a74cc@news.free.fr> Hi, It's easy to open a file not located in the current working directory (cwd). But how about importing a module? For instance, suppose I have a file, say my_file.py, located in the cwd, say /home/candide/ and suppose the module to be imported, say my_module.py, is located in the /home/candide/foo/ directory. How my_file.py can import the my_module.py module ? Thanks From python at mrabarnett.plus.com Mon Oct 24 16:09:16 2011 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 24 Oct 2011 21:09:16 +0100 Subject: randrange exceptional behavior In-Reply-To: <4ea5bc04$0$6448$426a74cc@news.free.fr> References: <4ea5bc04$0$6448$426a74cc@news.free.fr> Message-ID: <4EA5C5EC.40606@mrabarnett.plus.com> On 24/10/2011 20:26, candide wrote: > Where is documented the behaviour of the standard function randrange in > the case of an empty list ? for instance randrange(42,33) ? May I rely > on an ValueError type error? It's the same back to at least Python 2.5, so you can probably rely on that behaviour. Interestingly, the documentation says: """This is equivalent to choice(range(start, stop, step)), but doesn?t actually build a range object.""" but for choice(seq) it says: """If seq is empty, raises IndexError.""" so it's not entirely equivalent. From jason.swails at gmail.com Mon Oct 24 16:13:50 2011 From: jason.swails at gmail.com (Jason Swails) Date: Mon, 24 Oct 2011 16:13:50 -0400 Subject: CSV writer question In-Reply-To: References: Message-ID: On Mon, Oct 24, 2011 at 3:03 AM, Chris Angelico wrote: > On Mon, Oct 24, 2011 at 4:18 PM, Jason Swails > wrote: > > my_csv = csv.writer(open('temp.1.csv', 'wb')) > > > > Have you confirmed, or can you confirm, whether or not the file gets > closed automatically when the writer gets destructed? If so, all you > need to do is: > > my_csv = something_else > # or: > del my_csv > I'm not sure why I decided against this approach in the first place. This does work (at least with my test), so it's what I'll do. I probably wasn't confident that it would clean itself up properly, but that's probably rather un-pythonic and would not have made it into the stdlib if that was the case. Thanks! Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at andros.org.uk Mon Oct 24 16:35:13 2011 From: lists at andros.org.uk (Andrew McLean) Date: Mon, 24 Oct 2011 21:35:13 +0100 Subject: CSV writer question In-Reply-To: References: Message-ID: <4EA5CC01.9040007@andros.org.uk> On 24/10/2011 08:03, Chris Angelico wrote: > On Mon, Oct 24, 2011 at 4:18 PM, Jason Swails wrote: >> my_csv = csv.writer(open('temp.1.csv', 'wb')) >> > Have you confirmed, or can you confirm, whether or not the file gets > closed automatically when the writer gets destructed? If so, all you > need to do is: > > my_csv = something_else > # or: > del my_csv > > to unbind what I assume is the only reference to the csv.writer, upon > which it should promptly clean itself up. My understanding is that in cpython the file does get closed when the writer is deleted, however, it's not guaranteed to happen in other Python implementations (e.g. IronPython, PyPy and Jython). Andrew From candide at free.invalid Mon Oct 24 16:35:28 2011 From: candide at free.invalid (candide) Date: Mon, 24 Oct 2011 22:35:28 +0200 Subject: randrange exceptional behavior In-Reply-To: References: <4ea5bc04$0$6448$426a74cc@news.free.fr> Message-ID: <4ea5cc11$0$18839$426a74cc@news.free.fr> Le 24/10/2011 22:09, MRAB a ?crit : > but for choice(seq) it says: > Ah of course, I should have checked there > """If seq is empty, raises IndexError.""" > Thanks From gordon at panix.com Mon Oct 24 16:38:34 2011 From: gordon at panix.com (John Gordon) Date: Mon, 24 Oct 2011 20:38:34 +0000 (UTC) Subject: Importing a module from a non-cwd References: <4ea5c1da$0$3708$426a74cc@news.free.fr> Message-ID: In <4ea5c1da$0$3708$426a74cc at news.free.fr> candide writes: > For instance, suppose I have a file, say my_file.py, located in the cwd, > say /home/candide/ and suppose the module to be imported, say > my_module.py, is located in the /home/candide/foo/ directory. > How my_file.py can import the my_module.py module ? If PYTHONPATH and/or sys.path contain /home/candide/foo/, then you should be able to: import my_module Or, if foo/ is a real module (i.e. it contains an __init__.py file), this should work: import foo.my_module -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From __peter__ at web.de Mon Oct 24 17:09:16 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Oct 2011 23:09:16 +0200 Subject: CSV writer question References: Message-ID: Jason Swails wrote: > Hello, > > I have a question about a csv.writer instance. I have a utility that I > want to write a full CSV file from lots of data, but due to performance > (and memory) considerations, there's no way I can write the data > sequentially. Therefore, I write the data in chunks to temporary files, > then combine them > all at the end. For convenience, I declare each writer instance via a > statement like > > my_csv = csv.writer(open('temp.1.csv', 'wb')) > > so the open file object isn't bound to any explicit reference, and I don't > know how to reference it inside the writer class (the documentation > doesn't > say, unless I've missed the obvious). Thus, the only way I can think of > to make sure that all of the data is written before I start copying these > files sequentially into the final file is to unbuffer them so the above > command is changed to > > my_csv = csv.writer(open('temp.1.csv', 'wb', 0)) > > unless, of course, I add an explicit reference to track the open file > object > and manually close or flush it (but I'd like to avoid it if possible). My > question is 2-fold. Is there a way to do that directly via the CSV API, > or is the approach I'm taking the only way without binding the open file > object > to another reference? Secondly, if these files are potentially very large > (anywhere from ~1KB to 20 GB depending on the amount of data present), > what kind of performance hit will I be looking at by disabling buffering > on these types of files? > > Tips, answers, comments, and/or suggestions are all welcome. > > Thanks a lot! > Jason > > As an afterthought, I suppose I could always subclass the csv.writer class > and add the reference I want to that, which I may do if there's no other > convenient solution. A contextmanager might help: import csv from contextlib import contextmanager @contextmanager def filewriter(filename): with open(filename, "wb") as outstream: yield csv.writer(outstream) if __name__ == "__main__": with filewriter("tmp.csv") as writer: writer.writerows([ ["alpha", "beta"], ["gamma", "delta"]]) From bahamutzero8825 at gmail.com Mon Oct 24 17:29:25 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Mon, 24 Oct 2011 16:29:25 -0500 Subject: Creating very similar functions with different parameters Message-ID: <4EA5D8B5.8040703@gmail.com> I want to create a decorator with two different (but very similar) versions of the wrapper function, but without copying giant chunks of similar code. The main difference is that one version takes extra parameters. def test_dec(func, extra=False): if extra: def wrapper(ex_param1, ex_param2, *args, **kwargs): print('bla bla') print('more bla') print(ex_param1) print(ex_param2) func(ex_param1, ex_param2, *args, **kwargs) else: def wrapper(*args, **kwargs): print('bla bla') print('more bla') func(*args, **kwargs) return wrapper If the function I'm wrapping takes ex_param1 and ex_param2 as parameters, then the decorator should print them and then execute the function, otherwise just execute the function. I'd rather not write separate wrappers that are mostly the same. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 From ben+python at benfinney.id.au Mon Oct 24 17:36:46 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 25 Oct 2011 08:36:46 +1100 Subject: Python as a replacement to PL/SQL References: <87bot6sb2j.fsf@dpt-info.u-strasbg.fr> Message-ID: <87sjmijclt.fsf@benfinney.id.au> Alec Taylor writes: > What else is there besides PL/Python (for any DB) in the context of > writing stored procedures in function? I know of no server-side language other than SQL which can reasonably be expected to work ?for any DB?. PostgreSQL supports PL/pgSQL, PL/Python, PL/tcl, PL/Perl, and others . -- \ Moriarty: ?Forty thousand million billion dollars? That money | `\ must be worth a fortune!? ?The Goon Show, _The Sale of | _o__) Manhattan_ | Ben Finney From tjreedy at udel.edu Mon Oct 24 18:14:31 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Oct 2011 18:14:31 -0400 Subject: spawnl issues with Win 7 access rights In-Reply-To: <4EA573C8.1080502@timgolden.me.uk> References: <4EA565A3.3030909@timgolden.me.uk> <4EA573C8.1080502@timgolden.me.uk> Message-ID: On 10/24/2011 10:18 AM, Tim Golden wrote: > On 24/10/2011 14:18, Tim Golden wrote: > I ran this (on Python 2.7 on Win7): >> >> >> import os >> >> os.spawnl (os.P_NOWAIT, r"c:\windows\notepad.exe") >> >> >> >> and Python crashed hard! Long time since I've seen that happen. Same with 3.2 and Win7, interpreter or IDLE. > OK; the python 2.7 issues is http://bugs.python.org/issue8036 The example there used P_WAIT instead of P_NOWAIT, but I added comment. -- Terry Jan Reedy From tjreedy at udel.edu Mon Oct 24 18:16:46 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Oct 2011 18:16:46 -0400 Subject: spawnl issues with Win 7 access rights In-Reply-To: References: Message-ID: On 10/24/2011 9:47 AM, Propad wrote: y > nice. I can't imagine anything of such importance was not tested at > all during the beta phase - so it could be the tests were not run with > such a tricky configuration of windows. The coverage of the test suite is still being improved as people volunteer to write more tests. This mostly happens as part of bug fixing. -- Terry Jan Reedy From miki.tebeka at gmail.com Mon Oct 24 20:21:02 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 24 Oct 2011 17:21:02 -0700 (PDT) Subject: spawnl issues with Win 7 access rights In-Reply-To: References: Message-ID: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> Please use the subprocess module, it's the one who's actively maintained. http://docs.python.org/library/subprocess.html#replacing-the-os-spawn-family From philr at aspexconsulting.co.nz Mon Oct 24 20:30:41 2011 From: philr at aspexconsulting.co.nz (Phil Runciman) Date: Tue, 25 Oct 2011 13:30:41 +1300 Subject: Stack Architecture - was "Good books in computer science?" Message-ID: This was part of an earlier discussion in this forum. I want to correct the impression created by Lawrence D'Oliveiro that those who implemented stacks were not designing for efficiency. > What I can say is that for scientific/engineering calculations the RPN of > KDF9 was Great because assembler was no harder than using algol60 for the > calculations part of the problems I worked on. Lawrence D'Oliveiro ldo at geek-central.gen.new_zealand Mon Jun 22 03:52:55 CEST 2009 Unfortunately, we had to learn the hard way that machine instruction sets must be designed for efficiency of execution, not ease of use by humans. Stack-based architectures, for all their charm, cannot match register-based ones in this regard. FWIW: "Efficiency" is a slippery notion with contextual connotations. KDF9 had two stacks in its CPU. (The SJNS and the Nesting Store or Nest - see Eric's thesis.) I am not suggesting that you are ill-informed, but that stacks are insufficiently represented in the literature. The use of call return stacks to support subroutine returns is almost universal. For the evaluation of arithmetical expressions, the use of hardware stacks is the most efficient. From what I have read, it is compiler writers who find it hard to emulate the efficiencies achieved by assembler programmers. Are hardware designers considering the compiler writers' problems when they design their hardware? This would be heavy irony indeed. That is why stacks came into existence in the first place. Regards, Phil References: http://is.uwaterloo.ca/Eric_LaForest_Thesis.pdf discusses the confusion of first and second generation stack-based architectures. It includes a rebuttal of the arguments against stack computers, cited by Hennessy and Patterson, showing that they are applicable to the first generation of stack computers, but not the second. Christopher Bailey's "Optimisation Techniques for Stack-Based Processors", PhD thesis, University of Teesside, UK, July 1996, Amongst other things, analyzes the use of stack buffers to reduce memory traffic. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nvidhya01 at gmail.com Mon Oct 24 22:40:29 2011 From: nvidhya01 at gmail.com (n v) Date: Mon, 24 Oct 2011 19:40:29 -0700 (PDT) Subject: python royals @@@@@@@@@ Message-ID: http://123maza.com/48/silver424/ From wuwei23 at gmail.com Mon Oct 24 23:01:49 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 24 Oct 2011 20:01:49 -0700 (PDT) Subject: Creating very similar functions with different parameters References: Message-ID: <036b09e0-d404-4c1b-848b-e216316fa882@u10g2000prl.googlegroups.com> Guido wrote an article on a quick and easy multimethod implementation using a decorator: http://www.artima.com/weblogs/viewpost.jsp?thread=101605 From wuwei23 at gmail.com Mon Oct 24 23:34:46 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 24 Oct 2011 20:34:46 -0700 (PDT) Subject: revive a generator References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <0ff5c9b6-1314-4553-8378-deec2520e0ab@j36g2000prh.googlegroups.com> On Oct 21, 11:46?am, Yingjie Lan wrote: > I am still not sure why should we enforce that? > a generator can not be reused after an explicit? > request to revive it? No one is "enforcing" anything, you're simply resisting implementing this yourself. Consider the following generator: import random def randgen(): for _ in xrange(10): yield random.choice(['Hi','Lo']) >>> [x for x in randgen()] ['Hi', 'Hi', 'Lo', 'Hi', 'Lo', 'Lo', 'Lo', 'Lo', 'Hi', 'Hi'] What would you expect when you reset that generator? A newly randomised set of values, or the _same_ set of values? What if the generator is reading from an external source, like temperature values? Once revived, should it return the exact same sequence it originally did, or should it retrieve new values? Now, no matter which decision you made, why is your expectation of behaviour the right one? Why should the generator protocol support your convience in particular? If you need your generator to be re-usable, make a factory that creates it. From wuwei23 at gmail.com Mon Oct 24 23:37:49 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 24 Oct 2011 20:37:49 -0700 (PDT) Subject: revive a generator References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> Message-ID: <1615ba72-2b64-4164-8beb-b8a1b2752802@d33g2000prb.googlegroups.com> On Oct 21, 12:09?pm, Yingjie Lan wrote: > Secondly, it would be nice to automatically revive it. Sure, it's always nice when your expectation of a language feature exactly matches with its capabilities. When it doesn't, you suck it up and code around it. Because at the very least it's a hell of a lot quicker than waiting for the language to change for you. From steve+comp.lang.python at pearwood.info Mon Oct 24 23:46:36 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 25 Oct 2011 03:46:36 GMT Subject: Creating very similar functions with different parameters References: Message-ID: <4ea6311b$0$29973$c3e8da3$5496439d@news.astraweb.com> On Mon, 24 Oct 2011 16:29:25 -0500, Andrew Berg wrote: > I want to create a decorator with two different (but very similar) > versions of the wrapper function, but without copying giant chunks of > similar code. The main difference is that one version takes extra > parameters. > > def test_dec(func, extra=False): > if extra: > def wrapper(ex_param1, ex_param2, *args, **kwargs): > print('bla bla') > print('more bla') > print(ex_param1) > print(ex_param2) > func(ex_param1, ex_param2, *args, **kwargs) > else: > def wrapper(*args, **kwargs): > print('bla bla') > print('more bla') > func(*args, **kwargs) > return wrapper > > If the function I'm wrapping takes ex_param1 and ex_param2 as > parameters, then the decorator should print them and then execute the > function, otherwise just execute the function. I'd rather not write > separate wrappers that are mostly the same. In principle you could inspect the function's calling signature using the inspect module, and then decide how to decorate it from that. But I recommend against that: it's too much like magic. This is how I would do it: from functools import wraps def decorator_factory(extras=None): """Factory function which returns a decorator. Usage: @decorator_factory(): # Note you need the parentheses. def spam(...): return ... @decorator_factory((extra1, extra2)): def spam(...): return ... """ # Inner function performing common functionality. def preamble(): print('bla bla') print('more bla') # Decide what sort of decorator is needed. if extras is None: # Create decorator style 1. def decorator(func): @wraps(func) def inner(*args, **kwargs): preamble() return func(*args, **kwargs) return inner else: # Create decorator style 2. extra1, extra2 = extras def decorator(func): @wraps(func) def inner(*args, **kwargs): preamble() print(extra1) print(extra2) return func(extra1, extra2, *args, **kwargs) return inner return decorator If you don't like nested functions inside nested functions, you can pull out the inner functions: def preamble(): print('bla bla') print('more bla') def plain_decorator(func): @wraps(func) def inner(*args, **kwargs): preamble() return func(*args, **kwargs) return inner def extra_decorator(func): @wraps(extra1, extra2, func) def inner(*args, **kwargs): preamble() print(extra1) print(extra2) return func(extra1, extra2, *args, **kwargs) return inner def decorator_factory(plain): if plain: return plain_decorator else: return extra_decorator -- Steven From ulrich.eckhardt at dominolaser.com Tue Oct 25 02:49:59 2011 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Tue, 25 Oct 2011 08:49:59 +0200 Subject: Exception Handling (C - extending python) In-Reply-To: References: <75930aea-ed09-44f8-b7ca-0fa9f72e6b12@g27g2000pro.googlegroups.com> Message-ID: Am 23.10.2011 14:41, schrieb Stefan Behnel: > That's just fine. If you are interested in the inner mechanics of the > CPython runtime, reading the source is a very good way to start getting > involved with the project. > > However, many extension module authors don't care about these inner > mechanics and just use Cython instead. That keeps them from having to > learn the C-API of CPython, and from tying their code too deeply into > the CPython runtime itself. Could you elaborate a bit? What are the pros and cons of writing an extension module using the Cython API compared to using the CPyothon API? In particular, how portable is it? Can I compile a module in one and use it in the other? Don't I just tie myself to a different API, but tie myself nonetheless? Thank you! Uli From npropadovic at googlemail.com Tue Oct 25 03:01:13 2011 From: npropadovic at googlemail.com (Propad) Date: Tue, 25 Oct 2011 00:01:13 -0700 (PDT) Subject: spawnl issues with Win 7 access rights References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> Message-ID: <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> On 25 Okt., 02:21, Miki Tebeka wrote: > Please use the subprocess module, it's the one who's actively maintained.http://docs.python.org/library/subprocess.html#replacing-the-os-spawn... Thnx again for all the answers. As stated before, I'm limited in my options. One of them just might be to switch to Python 2.5, rewrite the code that crashes using the subprocess module, and then somehow patch the library I use (which I'm not suposed to do, but... oh well :-)). I can just hope subrocess was already mature adn offering the relevant functionality in 2.5. Cheers, Nenad From gilles.lenfant at gmail.com Tue Oct 25 03:13:50 2011 From: gilles.lenfant at gmail.com (Gilles Lenfant) Date: Tue, 25 Oct 2011 00:13:50 -0700 (PDT) Subject: [wanted] python-ldap for Python 2.3 / Win32 Message-ID: <16595266.1315.1319526830836.JavaMail.geo-discussion-forums@yqhp35> Hi, I have spent a couple of hours asking google, browsing Pypi, SF, and of course the official www.python-ldap.org site searching for a python-ldap installer for Python 2.3 on Windows 32 bits. Unsuccessfully :( As I need to add this to an ooold Plone site, it is not easy to upgrade to a newer Python version. So, please don't tell me to upgrade ;) Many thanks by advance to the people who will help me. You can send this package via mail to gillesDOTlenfantATgmailDOTcom. -- Gilles Lenfant From michael at stroeder.com Tue Oct 25 03:50:54 2011 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 25 Oct 2011 09:50:54 +0200 Subject: UnicodeError instead of UnicodeWarning Message-ID: HI! For tracking the cause of a UnicodeWarning I'd like to make the Python interpreter to raise an UnicodeError exception with full stack trace. Is there a short trick to achieve this? Many thanks in advance. Ciao, Michael. From ramapraba2653 at gmail.com Tue Oct 25 03:51:24 2011 From: ramapraba2653 at gmail.com (SUPREME) Date: Tue, 25 Oct 2011 00:51:24 -0700 (PDT) Subject: HOT HOT HOT Message-ID: <3a89a6d6-9628-4629-8b5c-fbc4bb0f129b@x16g2000prd.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html SAKUNI MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/sakuni-movie-stills.html 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html SNEHA ULLAL HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/sneha-ullal-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html From as at sci.fi Tue Oct 25 04:11:02 2011 From: as at sci.fi (Anssi Saari) Date: Tue, 25 Oct 2011 11:11:02 +0300 Subject: What is wrong with my code? References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> Message-ID: apometron writes: > Now it is another > thing, entirely. Rename1.py and Rename2.py works, but why Rename3.py > dont works? Well, Rename3.py works for me, even in Windows 7. Maybe you should test it again? From clp2 at rebertia.com Tue Oct 25 04:11:39 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 25 Oct 2011 01:11:39 -0700 Subject: UnicodeError instead of UnicodeWarning In-Reply-To: References: Message-ID: 2011/10/25 Michael Str?der : > HI! > > For tracking the cause of a UnicodeWarning I'd like to make the Python > interpreter to raise an UnicodeError exception with full stack trace. Is there > a short trick to achieve this? from exceptions import UnicodeWarning from warnings import filterwarnings filterwarnings(action="error", category=UnicodeWarning) This will cause UnicodeWarnings to be raised as exceptions when they occur. Cheers, Chris -- http://rebertia.com From stefan_ml at behnel.de Tue Oct 25 04:22:04 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 25 Oct 2011 10:22:04 +0200 Subject: Exception Handling (C - extending python) In-Reply-To: References: <75930aea-ed09-44f8-b7ca-0fa9f72e6b12@g27g2000pro.googlegroups.com> Message-ID: Ulrich Eckhardt, 25.10.2011 08:49: > Am 23.10.2011 14:41, schrieb Stefan Behnel: >> That's just fine. If you are interested in the inner mechanics of the >> CPython runtime, reading the source is a very good way to start getting >> involved with the project. >> >> However, many extension module authors don't care about these inner >> mechanics and just use Cython instead. That keeps them from having to >> learn the C-API of CPython, and from tying their code too deeply into >> the CPython runtime itself. > > Could you elaborate a bit? What are the pros and cons of writing an > extension module using the Cython API compared to using the CPyothon API? No cons. ;) Cython is not an API, it's a programming language. It's Python, but with extended support for talking to C/C++ code (and also Fortran). That means that you don't have to use the C-API yourself, because Cython will do it for you. > In particular, how portable is it? Can I compile a module in one and use it > in the other? They both use the CPython C-API internally. It's just that you are not using it explicitly in your code, so you (can) keep your own code free of CPython-isms. It's substantially more portable than the "usual" hand-written code, because it generates C code for you that compiles and works in CPython 2.4 up to the latest 3.3 in-development version, and also with all major C/C++ compilers, etc. It also generates faster glue code than you would write, e.g. for data type conversion and argument unpacking in function calls. So it speeds up thin wrappers automatically for you. That doesn't mean that you can't get the same level of speed and portability in hand-written code. It just means that you don't have to do it yourself. Saves a lot of time, both during development and later during the maintenance cycle. Basically, it allows you to focus on the functionality you want to implement, rather than the implementation details of CPython, and also keeps the maintenance overhead at that level for you. > Don't I just tie myself to a different API, but tie myself > nonetheless? There's a port to plain Python+ctypes underways, for example, which you could eventually use in PyPy. Try to do that at the C-API level. Stefan From __peter__ at web.de Tue Oct 25 04:22:11 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Oct 2011 10:22:11 +0200 Subject: UnicodeError instead of UnicodeWarning References: Message-ID: Michael Str?der wrote: > For tracking the cause of a UnicodeWarning I'd like to make the Python > interpreter to raise an UnicodeError exception with full stack trace. Is > there a short trick to achieve this? You can control warning behaviour with the -W commandline option: $ cat unicodewarning_demo.py # -*- coding: utf-8 -*- def g(): "?" == u"?" def f(n=3): if n: f(n-1) else: g() if __name__ == "__main__": f() $ python unicodewarning_demo.py unicodewarning_demo.py:4: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal "?" == u"?" $ python -W error::UnicodeWarning unicodewarning_demo.py Traceback (most recent call last): File "unicodewarning_demo.py", line 13, in f() File "unicodewarning_demo.py", line 8, in f f(n-1) File "unicodewarning_demo.py", line 8, in f f(n-1) File "unicodewarning_demo.py", line 8, in f f(n-1) File "unicodewarning_demo.py", line 10, in f g() File "unicodewarning_demo.py", line 4, in g "?" == u"?" UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal $ From apometron.listas.cinco at gmail.com Tue Oct 25 04:24:22 2011 From: apometron.listas.cinco at gmail.com (apometron) Date: Tue, 25 Oct 2011 06:24:22 -0200 Subject: What is wrong with my code? In-Reply-To: References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> Message-ID: <4EA67236.5040907@gmail.com> I did it very much times, Anssi. Beyond of run it on Python 2.7 latest build, what do you suggest? Do install Python 3.2 along the Python 2.7 installation could give me any problems? cheers, Apometron http://about.me/apometron On 10/25/2011 6:11 AM, Anssi Saari wrote: > apometron writes: > >> Now it is another >> thing, entirely. Rename1.py and Rename2.py works, but why Rename3.py >> dont works? > Well, Rename3.py works for me, even in Windows 7. Maybe you should test > it again? From michael at stroeder.com Tue Oct 25 04:36:35 2011 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 25 Oct 2011 10:36:35 +0200 Subject: [wanted] python-ldap for Python 2.3 / Win32 In-Reply-To: <16595266.1315.1319526830836.JavaMail.geo-discussion-forums@yqhp35> References: <16595266.1315.1319526830836.JavaMail.geo-discussion-forums@yqhp35> Message-ID: Gilles Lenfant wrote: > I have spent a couple of hours asking google, browsing Pypi, SF, and of > course the official www.python-ldap.org site searching for a python-ldap > installer for Python 2.3 on Windows 32 bits. Unsuccessfully :( In theory even recent python-ldap 2.4.3 should still work with Python 2.3. Please post your inquiry on the mailing-list python-ldap at python.org (subscribe before post). Maybe you can convince the maintainer of the Win32 packages there. Ciao, Michael. From d at davea.name Tue Oct 25 05:34:11 2011 From: d at davea.name (Dave Angel) Date: Tue, 25 Oct 2011 05:34:11 -0400 Subject: [Tutor] What is wrong with my code? In-Reply-To: <4EA67236.5040907@gmail.com> References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> <4EA67236.5040907@gmail.com> Message-ID: <4EA68293.9070805@davea.name> (Once again, please don't top-post. It makes your responses out of order) On 10/25/2011 04:24 AM, apometron wrote: > I did it very much times, Anssi. > > Beyond of run it on Python 2.7 latest build, what do you suggest? > > Do install Python 3.2 along the Python 2.7 installation could give me > any problems? > Why don't you say publicly that you aren't using cmd ? If your file manager is not running the equivalent of python yourprogram.py filename.txt then everyone here is chasing a wild goose. Switch to the command line, issue a sequence of commands that cause the failure, and paste them in a message here. Then if it works, but doesn't from your file manager, you/we/they can address the differences from the working command line. -- DaveA From apometron.listas.cinco at gmail.com Tue Oct 25 06:09:38 2011 From: apometron.listas.cinco at gmail.com (apometron) Date: Tue, 25 Oct 2011 08:09:38 -0200 Subject: [Tutor] What is wrong with my code? In-Reply-To: <4EA68293.9070805@davea.name> References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> <4EA67236.5040907@gmail.com> <4EA68293.9070805@davea.name> Message-ID: <4EA68AE2.2080309@gmail.com> On 10/25/2011 7:34 AM, Dave Angel wrote: > (Once again, please don't top-post. It makes your responses out of > order) > > On 10/25/2011 04:24 AM, apometron wrote: >> I did it very much times, Anssi. >> >> Beyond of run it on Python 2.7 latest build, what do you suggest? >> >> Do install Python 3.2 along the Python 2.7 installation could give me >> any problems? >> > > Why don't you say publicly that you aren't using cmd ? > > If your file manager is not running the equivalent of > > > python yourprogram.py filename.txt > > > then everyone here is chasing a wild goose. > > Switch to the command line, issue a sequence of commands that cause > the failure, and paste them in a message here. Then if it works, but > doesn't from your file manager, you/we/they can address the > differences from the working command line. > I found out what it is. It is the File Commander giving wrong informations to the script. In Take Command command line it works sweet. I will show all this to the File Commander author and ask him some way to solve this. It turns out do the thing in command line every time is not best way. I need do it by the file manager. But the file manager was puting stones in the way. Take Command has a script language also, but I would like do the things in Python, if possible. And this difficulty with File Commander makes use Python a thing less easy to do. Question solved. It was not Take Command the problem and I was sure it was not. Enter in command line to do things is a pain. =( I mean, e-ve-ry ti-me. But then, good news, all the three scripts works smoothly in the command line. Do you believe drag and drop in the Windows Explorer can be my salvation? Cool thing to try. []s Apometron http://about.me/apometron From fabiofz at gmail.com Tue Oct 25 07:09:28 2011 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Tue, 25 Oct 2011 09:09:28 -0200 Subject: Strange classmethod mock behavior Message-ID: I'm trying to mock a classmethod in a superclass but when restoring it a strange behavior happens in subclasses (tested on Python 2.5) Anyone knows why this happens? (see test case below for details) Is there any way to restore that original method to have the original behavior? import unittest class Test(unittest.TestCase): def testClassmethod(self): class Super(): @classmethod def GetCls(cls): return cls class Sub(Super): pass self.assertEqual(Sub.GetCls(), Sub) original = Super.GetCls #Mock Super.GetCls, and do tests... Super.GetCls = original #Restore the original classmethod self.assertEqual(Sub.GetCls(), Sub) #The call to the classmethod subclass returns the cls as Super and not Sub as expected! if __name__ == '__main__': unittest.main() From __peter__ at web.de Tue Oct 25 08:08:08 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Oct 2011 14:08:08 +0200 Subject: Strange classmethod mock behavior References: Message-ID: Fabio Zadrozny wrote: > I'm trying to mock a classmethod in a superclass but when restoring it > a strange behavior happens in subclasses (tested on Python 2.5) > > Anyone knows why this happens? (see test case below for details) > Is there any way to restore that original method to have the original > behavior? > > import unittest > > class Test(unittest.TestCase): > > def testClassmethod(self): > class Super(): > @classmethod > def GetCls(cls): > return cls > > class Sub(Super): > pass > > self.assertEqual(Sub.GetCls(), Sub) > > original = Super.GetCls > #Mock Super.GetCls, and do tests... > Super.GetCls = original #Restore the original classmethod > self.assertEqual(Sub.GetCls(), Sub) #The call to the > classmethod subclass returns the cls as Super and not Sub as expected! > > if __name__ == '__main__': > unittest.main() [Not related to your problem] When working with descriptors it's a good idea to use newstyle classes, i. e. have Super inherit from object. The Super.GetCls attribute access is roughly equivalent to Super.__dict___["GetCls"].__get__(classmethod_instance, None, Super) and returns an object that knows about its class. So when you think you are restoring the original method you are actually setting the GetCls attribute to something else. You can avoid the problem by accessing the attribute explicitly: >>> class Super(object): ... @classmethod ... def m(cls): return cls ... >>> bad = Super.m >>> good = Super.__dict__["m"] >>> class Sub(Super): pass ... >>> Sub.m() >>> Super.m = bad >>> Sub.m() >>> Super.m = good >>> Sub.m() From mail at timgolden.me.uk Tue Oct 25 08:19:28 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 25 Oct 2011 13:19:28 +0100 Subject: spawnl issues with Win 7 access rights In-Reply-To: <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> Message-ID: <4EA6A950.6090706@timgolden.me.uk> On 25/10/2011 08:01, Propad wrote: > Thnx again for all the answers. As stated before, I'm limited in my > options. One of them just might be to switch to Python 2.5, rewrite > the code that crashes using the subprocess module, and then somehow > patch the library I use (which I'm not suposed to do, but... oh > well :-)). I can just hope subrocess was already mature adn offering > the relevant functionality in 2.5. I must admit I'm more than slightly surprised by this. My test case is to use os.spawnl to run c:/windows/notepad.exe. From the docs, I would expect to use os.spawnl (os.P_WAIT, "c:/windows/notepad.exe"). (I only want to open notepad.exe; there's no need for additional args). These are my test cases: (1) os.spawnl ( os.P_WAIT, "c:/windows/notepad.exe" ) (2) os.spawnl ( os.P_WAIT, "c:/windows/notepad.exe", "c:/windows/notepad.exe" ) (3) os.spawnl ( os.P_WAIT, "c:/windows/notepad.exe", "c:/windows/notepad.exe", "c:/temp.txt" ) And the results: ============================================================== Python | Platform | Case | Result -------------------------------------------------------------- 2.2.2 | WinXP | 1 | Works (empty notepad) 2.2.2 | WinXP | 2 | Works (empty notepad) 2.2.2 | WinXP | 3 | Works (notepad temp.txt) -------------------------------------------------------------- 2.2.2 | Win7 | 1 | OSError 2.2.2 | Win7 | 2 | Works (empty notepad) 2.2.2 | Win7 | 3 | Works (notepad temp.txt) -------------------------------------------------------------- 2.7.2 | WinXP | 1 | Crashes 2.7.2 | WinXP | 2 | Works (empty notepad) 2.7.2 | WinXP | 3 | Works (notepad temp.txt) -------------------------------------------------------------- 2.7.2 | Win7 | 1 | Crashes 2.7.2 | Win7 | 2 | Works (empty notepad) 2.7.2 | Win7 | 3 | Works (notepad temp.txt) ============================================================== Add to this a look at the mscrt source which ships with VS 2008 and the MSDN docs for spawnl: http://msdn.microsoft.com/en-us/library/wweek9sc%28v=vs.80%29.aspx and we see that the first args parameter must be the same as the path parameter. FWIW, at no extra cost, I went to the trouble of testing it on some flavour of Linux with Python 2.6 and got the same results as per 2.2.2 on WinXP. (Basically: everything works). Which leaves us with http://bugs.python.org/issue8036 in which recent versions of Python crash when the (arbitrary) second parameter isn't passed. And with an inexplicable behaviour change between the same version of Python running on WinXP and on Win7. It looks as though the workaround for your problem (or, possibly, your failure to fulfil some artificial parameter requirements) is to add the executable again as the third parameter. issue8036 (which also affects the execl family) has a patch waiting for review, which hopefully we can get round to fixing. As far as I can tell, the execl/spawnl family of functions isn't currently represented in the testsuite. TJG From gandalf at shopzeus.com Tue Oct 25 09:50:59 2011 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 25 Oct 2011 15:50:59 +0200 Subject: webapp development in pure python Message-ID: <4EA6BEC3.5010206@shopzeus.com> Hi, Anyone knows a framework for webapp development? I'm not talking about javascript/html compilers and ajax frameworks. I need something that does not require javascript knowledge, just pure Python. (So qooxdoo is not really an option, because it cannot be programmed in Python. You cannot even put out a window on the center of the screen without using javascript code, and you really have to be a javascript expert to write useful applications with qooxdoo.) What I need is a programmable GUI with windows, event handlers and extensible widgets, for creating applications that use http/https and a web browser for rendering. Is there something like this already available? Thanks, Laszlo From anurag.chourasia at gmail.com Tue Oct 25 10:12:28 2011 From: anurag.chourasia at gmail.com (Anurag Chourasia) Date: Tue, 25 Oct 2011 19:42:28 +0530 Subject: webapp development in pure python In-Reply-To: <4EA6BEC3.5010206@shopzeus.com> References: <4EA6BEC3.5010206@shopzeus.com> Message-ID: Have you considered Django ? http://www.djangoproject.com/ Regards, Anurag On Tue, Oct 25, 2011 at 7:20 PM, Laszlo Nagy wrote: > > Hi, > > Anyone knows a framework for webapp development? I'm not talking about > javascript/html compilers and ajax frameworks. I need something that does > not require javascript knowledge, just pure Python. (So qooxdoo is not > really an option, because it cannot be programmed in Python. You cannot even > put out a window on the center of the screen without using javascript code, > and you really have to be a javascript expert to write useful applications > with qooxdoo.) > > What I need is a programmable GUI with windows, event handlers and > extensible widgets, for creating applications that use http/https and a web > browser for rendering. > > Is there something like this already available? > > Thanks, > > Laszlo > > > > -- > http://mail.python.org/**mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at gmail.com Tue Oct 25 10:13:45 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Tue, 25 Oct 2011 15:13:45 +0100 Subject: webapp development in pure python In-Reply-To: <4EA6BEC3.5010206@shopzeus.com> References: <4EA6BEC3.5010206@shopzeus.com> Message-ID: On 25 October 2011 14:50, Laszlo Nagy wrote: > > ?Hi, > > Anyone knows a framework for webapp development? I'm not talking about > javascript/html compilers and ajax frameworks. I need something that does > not require javascript knowledge, just pure Python. (So qooxdoo is not > really an option, because it cannot be programmed in Python. You cannot even > put out a window on the center of the screen without using javascript code, > and you really have to be a javascript expert to write useful applications > with qooxdoo.) > > What I need is a programmable GUI with windows, event handlers and > extensible widgets, for creating applications that use http/https and a web > browser for rendering. So you're looking for something like Google Web Toolkit but using Python instead of Java... Do you know about pyjamas (http://pyjs.org/)? I've never used it, but I think it endeavours to be what you are looking for. HTH -- Arnaud From martin.hellwig at gmail.com Tue Oct 25 10:19:52 2011 From: martin.hellwig at gmail.com (Martin P. Hellwig) Date: Tue, 25 Oct 2011 15:19:52 +0100 Subject: webapp development in pure python In-Reply-To: References: <4EA6BEC3.5010206@shopzeus.com> Message-ID: On 10/25/11 15:13, Arnaud Delobelle wrote: > On 25 October 2011 14:50, Laszlo Nagy wrote: >> >> Hi, >> >> Anyone knows a framework for webapp development? I'm not talking about >> javascript/html compilers and ajax frameworks. I need something that does >> not require javascript knowledge, just pure Python. (So qooxdoo is not >> really an option, because it cannot be programmed in Python. You cannot even >> put out a window on the center of the screen without using javascript code, >> and you really have to be a javascript expert to write useful applications >> with qooxdoo.) >> >> What I need is a programmable GUI with windows, event handlers and >> extensible widgets, for creating applications that use http/https and a web >> browser for rendering. > > So you're looking for something like Google Web Toolkit but using > Python instead of Java... > > Do you know about pyjamas (http://pyjs.org/)? I've never used it, but > I think it endeavours to be what you are looking for. > > HTH > Second that, I use it for a couple of my projects for exactly that. -- mph From ian.g.kelly at gmail.com Tue Oct 25 10:40:48 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 25 Oct 2011 08:40:48 -0600 Subject: Creating very similar functions with different parameters In-Reply-To: <4EA5D8B5.8040703@gmail.com> References: <4EA5D8B5.8040703@gmail.com> Message-ID: On Mon, Oct 24, 2011 at 3:29 PM, Andrew Berg wrote: > I want to create a decorator with two different (but very similar) > versions of the wrapper function, but without copying giant chunks of > similar code. The main difference is that one version takes extra > parameters. > > def test_dec(func, extra=False): > ? ? ? ?if extra: > ? ? ? ? ? ? ? ?def wrapper(ex_param1, ex_param2, *args, **kwargs): > ? ? ? ? ? ? ? ? ? ? ? ?print('bla bla') > ? ? ? ? ? ? ? ? ? ? ? ?print('more bla') > ? ? ? ? ? ? ? ? ? ? ? ?print(ex_param1) > ? ? ? ? ? ? ? ? ? ? ? ?print(ex_param2) > ? ? ? ? ? ? ? ? ? ? ? ?func(ex_param1, ex_param2, *args, **kwargs) > ? ? ? ?else: > ? ? ? ? ? ? ? ?def wrapper(*args, **kwargs): > ? ? ? ? ? ? ? ? ? ? ? ?print('bla bla') > ? ? ? ? ? ? ? ? ? ? ? ?print('more bla') > ? ? ? ? ? ? ? ? ? ? ? ?func(*args, **kwargs) > ? ? ? ?return wrapper > > If the function I'm wrapping takes ex_param1 and ex_param2 as > parameters, then the decorator should print them and then execute the > function, otherwise just execute the function. I'd rather not write > separate wrappers that are mostly the same. Others have given more involved suggestions, but in this case you could just make the wrapper a closure and check the flag there: def test_dec(func, extra=False): def wrapper(*args, **kwargs): print('bla bla') print('more bla') if extra: ex_param1, ex_param2 = args[:2] print(ex_param1) print(ex_param2) func(*args, **kwargs) return wrapper Cheers, Ian From dihedral88888 at googlemail.com Tue Oct 25 11:39:09 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Tue, 25 Oct 2011 08:39:09 -0700 (PDT) Subject: Creating very similar functions with different parameters In-Reply-To: References: <4EA5D8B5.8040703@gmail.com> Message-ID: <22702775.328.1319557149527.JavaMail.geo-discussion-forums@prms22> Thanks for the debug modes in functional programing! Everything functional is true in CS at least in the theroy! From dihedral88888 at googlemail.com Tue Oct 25 11:39:09 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Tue, 25 Oct 2011 08:39:09 -0700 (PDT) Subject: Creating very similar functions with different parameters In-Reply-To: References: <4EA5D8B5.8040703@gmail.com> Message-ID: <22702775.328.1319557149527.JavaMail.geo-discussion-forums@prms22> Thanks for the debug modes in functional programing! Everything functional is true in CS at least in the theroy! From sidorenko.andrey at gmail.com Tue Oct 25 11:51:27 2011 From: sidorenko.andrey at gmail.com (spintronic) Date: Tue, 25 Oct 2011 08:51:27 -0700 (PDT) Subject: Data acquisition Message-ID: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Dear friends, I have a trouble with understanding the following. I have a very short script (shown below) which works fine if I "run" step by step (or line by line) in Python shell (type the first line/command -> press Enter, etc.). I can get all numbers (actually, there are no numbers but a long string, but this is not a problem) I need from a device: '0.3345098119,0.01069121274,0.02111624694,0.03833379529,0.02462816409,0.0774275008,0.06554297421,0.07366750919,0.08122602002,0.004018369318,0.03508462415,0.04829900696,0.06383554085, ...' However, when I start very the same list of commands as a script, it gives me the following, which is certainly wrong: [0.0, 0.0, 0.0, 0.0, 0.0,...] Any ideas? Why there is a difference when I run the script or do it command by command? =========================== from visa import * mw = instrument("GPIB0::20::INSTR", timeout = None) mw.write("*RST") mw.write("CALC1:DATA? FDATA") a=mw.read() print a =========================== (That is really all!) PS In this case I use Python Enthought for Windows, but I am not an expert in Windows (I work usually in Linux but now I need to run this data acquisition under Windows). From jeanmichel at sequans.com Tue Oct 25 12:15:22 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 25 Oct 2011 18:15:22 +0200 Subject: Data acquisition In-Reply-To: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: <4EA6E09A.5000403@sequans.com> spintronic wrote: > Dear friends, > > I have a trouble with understanding the following. I have a very short > script (shown below) which works fine if I "run" step by step (or line > by line) in Python shell (type the first line/command -> press Enter, > etc.). I can get all numbers (actually, there are no numbers but a > long string, but this is not a problem) I need from a device: > > '0.3345098119,0.01069121274,0.02111624694,0.03833379529,0.02462816409,0.0774275008,0.06554297421,0.07366750919,0.08122602002,0.004018369318,0.03508462415,0.04829900696,0.06383554085, ...' > > However, when I start very the same list of commands as a script, it > gives me the following, which is certainly wrong: > > [0.0, 0.0, 0.0, 0.0, 0.0,...] > > Any ideas? Why there is a difference when I run the script or do it > command by command? > > =========================== > from visa import * > > mw = instrument("GPIB0::20::INSTR", timeout = None) > > mw.write("*RST") > mw.write("CALC1:DATA? FDATA") > > a=mw.read() > > print a > =========================== > (That is really all!) > > > PS In this case I use Python Enthought for Windows, but I am not an > expert in Windows (I work usually in Linux but now I need to run this > data acquisition under Windows). > Just in case you have a local installation of visa and it silently fails on some import, try to add at the begining of your script: import sys sys.path.append('') When using the python shell cmd line, '' is added to sys.path by the shell, that is one difference that can make relative imports fail in your script. If it's still not working, well, it means the problem is somewhere else. JM From nicholas.dokos at hp.com Tue Oct 25 12:29:45 2011 From: nicholas.dokos at hp.com (Nick Dokos) Date: Tue, 25 Oct 2011 12:29:45 -0400 Subject: Data acquisition In-Reply-To: Message from spintronic of "Tue, 25 Oct 2011 08:51:27 PDT." <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: <4784.1319560185@alphaville.dokosmarshall.org> spintronic wrote: > Dear friends, > > I have a trouble with understanding the following. I have a very short > script (shown below) which works fine if I "run" step by step (or line > by line) in Python shell (type the first line/command -> press Enter, > etc.). I can get all numbers (actually, there are no numbers but a > long string, but this is not a problem) I need from a device: > > '0.3345098119,0.01069121274,0.02111624694,0.03833379529,0.02462816409,0.0774275008,0.06554297421,0.07366750919,0.08122602002,0.004018369318,0.03508462415,0.04829900696,0.06383554085, ...' > > However, when I start very the same list of commands as a script, it > gives me the following, which is certainly wrong: > > [0.0, 0.0, 0.0, 0.0, 0.0,...] > > Any ideas? Why there is a difference when I run the script or do it > command by command? > > =========================== > from visa import * > > mw = instrument("GPIB0::20::INSTR", timeout = None) > > mw.write("*RST") > mw.write("CALC1:DATA? FDATA") > > a=mw.read() > > print a > =========================== > (That is really all!) > > > PS In this case I use Python Enthought for Windows, but I am not an > expert in Windows (I work usually in Linux but now I need to run this > data acquisition under Windows). > -- > http://mail.python.org/mailman/listinfo/python-list > Shot in the dark: could it be that you have to add delays to give the instrument time to adjust? When you do it from the python shell, line by line, there is a long delay between one line and the next. Nick From gandalf at shopzeus.com Tue Oct 25 12:33:30 2011 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 25 Oct 2011 18:33:30 +0200 Subject: webapp development in pure python In-Reply-To: References: <4EA6BEC3.5010206@shopzeus.com> Message-ID: <4EA6E4DA.2080307@shopzeus.com> >>> Anyone knows a framework for webapp development? I'm not talking about >>> javascript/html compilers and ajax frameworks. I need something that >>> does >>> not require javascript knowledge, just pure Python. (So qooxdoo is not >>> really an option, because it cannot be programmed in Python. You >>> cannot even >>> put out a window on the center of the screen without using >>> javascript code, >>> and you really have to be a javascript expert to write useful >>> applications >>> with qooxdoo.) >>> >>> What I need is a programmable GUI with windows, event handlers and >>> extensible widgets, for creating applications that use http/https >>> and a web >>> browser for rendering. >> >> So you're looking for something like Google Web Toolkit but using >> Python instead of Java... >> >> Do you know about pyjamas (http://pyjs.org/)? I've never used it, but >> I think it endeavours to be what you are looking for. As I told, I'm not talking about javascript/html compilers and ajax frameworks. Pyjamas is both a javascript compiler and an ajax framework. My Python module would connect to a database server and query some data, then display it in a grid. This cannot be compiled into javascript because of the database server connection. With pyjamas, I would have to create the server side part separately, the user interface separately, and hand-code the communication between the widets and the server side. I would like to use this theoretical web based framework just like pygtk or wxPython: create windows, place widgets on them, implement event handlers etc. and access the widgets and other server side resources (for example, a database connection) from the same source code. Transparently. So the web part would really just be the rendering part of the user inferface. This may not be possible at all.. My other idea was to use a freenx server and wxPython. Is it a better solution? Have anyone used this combination from an android tablet, for example? Would it work? Thanks, Laszlo From gordon at panix.com Tue Oct 25 12:43:42 2011 From: gordon at panix.com (John Gordon) Date: Tue, 25 Oct 2011 16:43:42 +0000 (UTC) Subject: Data acquisition References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: In <362e368f-829e-4477-bcfc-c0650d231029 at j7g2000yqi.googlegroups.com> spintronic writes: > Any ideas? Why there is a difference when I run the script or do it > command by command? Are you running the same python program in both cases? Are you in the same directory in both cases? Does PYTHONPATH and/or sys.path have the same value in both cases? Show us an exact transscript of both executions. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From sidorenko.andrey at gmail.com Tue Oct 25 13:22:39 2011 From: sidorenko.andrey at gmail.com (spintronic) Date: Tue, 25 Oct 2011 10:22:39 -0700 (PDT) Subject: Data acquisition References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: On Oct 25, 6:29?pm, Nick Dokos wrote: > Shot in the dark: could it be that you have to add delays to give the > instrument time to adjust? When you do it from the python shell, line by > line, there is a long delay between one line and the next. > > Nick Hi, Nick! Thanks! You are right but it was the first thing I thought about. So I have tried to delay using sleep(t) from the time module (I also sent "*OPC?" or "*WAI" commands to a device for synchronization). However, it does not help ... Best, AS From sidorenko.andrey at gmail.com Tue Oct 25 13:31:04 2011 From: sidorenko.andrey at gmail.com (spintronic) Date: Tue, 25 Oct 2011 10:31:04 -0700 (PDT) Subject: Data acquisition References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: <86e6bfb8-17e1-4544-97ba-7299db8a8140@p16g2000yqj.googlegroups.com> On Oct 25, 6:43?pm, John Gordon wrote: Thanks, John! > Are you running the same python program in both cases? Yes, the same. > Are you in the same directory in both cases? > Does PYTHONPATH and/or sys.path have the same value in both cases? It looks that yes but how can it matter? All I need it is to import the visa module and it works well. > Show us an exact transscript of both executions. There is nothing but "numbers". Or do you mean something else? I do not receive any errors, only different results ... Best, AS From sidorenko.andrey at gmail.com Tue Oct 25 13:35:42 2011 From: sidorenko.andrey at gmail.com (spintronic) Date: Tue, 25 Oct 2011 10:35:42 -0700 (PDT) Subject: Data acquisition References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: <8692a942-5e33-4063-a55f-7c02f3690b4a@hv4g2000vbb.googlegroups.com> On Oct 25, 6:15?pm, Jean-Michel Pichavant wrote: > spintronic wrote: > > Dear friends, > > > I have a trouble with understanding the following. I have a very short > > script (shown below) which works fine if I "run" step by step (or line > > by line) in Python shell (type the first line/command -> press Enter, > > etc.). I can get all numbers (actually, there are no numbers but a > > long string, but this is not a problem) I need from a device: > > > '0.3345098119,0.01069121274,0.02111624694,0.03833379529,0.02462816409,0.0774275008,0.06554297421,0.07366750919,0.08122602002,0.004018369318,0.03508462415,0.04829900696,0.06383554085, ...' > > > However, when I start very the same list of commands as a script, it > > gives me the following, which is certainly wrong: > > > [0.0, 0.0, 0.0, 0.0, 0.0,...] > > > Any ideas? Why there is a difference when I run the script or do it > > command by command? > > > =========================== > > from visa import * > > > mw = instrument("GPIB0::20::INSTR", timeout = None) > > > mw.write("*RST") > > mw.write("CALC1:DATA? FDATA") > > > a=mw.read() > > > print a > > =========================== > > (That is really all!) > > > PS In this case I use Python Enthought for Windows, but I am not an > > expert in Windows (I work usually in Linux but now I need to run this > > data acquisition under Windows). > > Just in case you have a local installation of visa and it silently fails > on some import, > > try to add at the begining of your script: > import sys > sys.path.append('') > > When using the python shell cmd line, '' is added to sys.path by the > shell, that is one difference that can make relative imports fail in > your script. > > If it's still not working, well, it means the problem is somewhere else. > > JM Hi! Thanks! I have just tried. Unfortunately, it does not work ... Best, AS From gordon at panix.com Tue Oct 25 14:34:41 2011 From: gordon at panix.com (John Gordon) Date: Tue, 25 Oct 2011 18:34:41 +0000 (UTC) Subject: Data acquisition References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> <86e6bfb8-17e1-4544-97ba-7299db8a8140@p16g2000yqj.googlegroups.com> Message-ID: In <86e6bfb8-17e1-4544-97ba-7299db8a8140 at p16g2000yqj.googlegroups.com> spintronic writes: > > Are you in the same directory in both cases? > > Does PYTHONPATH and/or sys.path have the same value in both cases? > It looks that yes but how can it matter? All I need it is to import > the visa module and it works well. If you run the two cases from different directories, and the current directory is in PYTHONPATH or sys.path, and one of the directories contains a python file named "visa.py" and the other doesn't, that culd account for the difference in output. Do you have access to the visa.py source code? Can you add a simple print statement near the top of the module so that we know the same visa.py module is being imported in both cases? > > Show us an exact transscript of both executions. > There is nothing but "numbers". Or do you mean something else? I do > not receive any errors, only different results ... I was more interested in the exact commands you used to run both cases, rather than the output. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From ameyer2 at yahoo.com Tue Oct 25 15:50:59 2011 From: ameyer2 at yahoo.com (Alan Meyer) Date: Tue, 25 Oct 2011 15:50:59 -0400 Subject: How to isolate a constant? In-Reply-To: References: Message-ID: <4EA71323.2030500@yahoo.com> On 10/22/2011 8:46 PM, MRAB wrote: > On 23/10/2011 01:26, Gnarlodious wrote: >> Say this: >> >> class tester(): >> _someList = [0, 1] >> def __call__(self): >> someList = self._someList >> someList += "X" >> return someList >> >> test = tester() >> >> But guess what, every call adds to the variable that I am trying to >> copy each time: >> test() >>> [0, 1, 'X'] >> test() >>> [0, 1, 'X', 'X'] ... > Python will copy something only when you tell it to copy. A simple way > of copying a list is to slice it: > > someList = self._someList[:] And another simple way: ... someList = list(self._someList) ... Alan From ian.g.kelly at gmail.com Tue Oct 25 16:05:49 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 25 Oct 2011 14:05:49 -0600 Subject: How to isolate a constant? In-Reply-To: <4EA71323.2030500@yahoo.com> References: <4EA71323.2030500@yahoo.com> Message-ID: On Tue, Oct 25, 2011 at 1:50 PM, Alan Meyer wrote: >> Python will copy something only when you tell it to copy. A simple way >> of copying a list is to slice it: >> >> someList = self._someList[:] > > And another simple way: > > ? ?... > ? ?someList = list(self._someList) > ? ?... I generally prefer the latter. It's clearer, and it guarantees that the result will be a list, which is usually what you want in these situations, rather than whatever unexpected type was passed in. Cheers, Ian From slc at publicus.net Tue Oct 25 17:18:07 2011 From: slc at publicus.net (Steven Clift) Date: Tue, 25 Oct 2011 16:18:07 -0500 Subject: Python developers interested in local communities, GroupServer Message-ID: My non-profit uses the GPL Python-based http://GroupServer.org platform to host local neighborhood online communities in the U.S., the UK, and New Zealand. We are users of GroupServer and not the owner of the project. We are plotting a future new features hackathon (in person in Minneapolis and perhaps simultaneously elsewhere) and are looking for python programmers with a particular interest in connecting people in local places. If you are interested in learning more, please contact us at team at e-democracy.org or http://e-democracy.org/contact Or join the GroupServer development group - http://groupserver.org/groups/development - where we will definitely making an announcement. We will also announce it here on the Local Labs online group: http://e-democracy.org/labs Thanks, Steven Clift E-Democracy.org P.S. GroupServer is probably the best open source hybrid e-mail list/web forum out there. Not the best e-mail list. And not the best web forum. But the best fully integrated approach. Example use with some customizations: http://e-democracy.org From waldemar.osuch at gmail.com Tue Oct 25 17:19:08 2011 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Tue, 25 Oct 2011 14:19:08 -0700 (PDT) Subject: [wanted] python-ldap for Python 2.3 / Win32 In-Reply-To: References: <16595266.1315.1319526830836.JavaMail.geo-discussion-forums@yqhp35> Message-ID: <4818553.676.1319577549027.JavaMail.geo-discussion-forums@yqnv12> I did try to build it using my current setup but it failed with some linking errors. Oh well. Google gods were nicer to me. Here is a couple alternative links. Maybe they will work for you. http://web.archive.org/web/20081101060042/http://www.agescibs.org/mauro/ http://old.zope.org/Members/volkerw/LdapWin32/ Waldemar From news at schwertberger.de Tue Oct 25 17:31:52 2011 From: news at schwertberger.de (Dietmar Schwertberger) Date: Tue, 25 Oct 2011 23:31:52 +0200 Subject: Data acquisition In-Reply-To: References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: Am 25.10.2011 19:22, schrieb spintronic: > On Oct 25, 6:29 pm, Nick Dokos wrote: >> Shot in the dark: could it be that you have to add delays to give the >> instrument time to adjust? When you do it from the python shell, line by >> line, there is a long delay between one line and the next. > Thanks! You are right but it was the first thing I thought about. So I > have tried to delay using sleep(t) from the time module (I also sent > "*OPC?" or "*WAI" commands to a device for synchronization). However, > it does not help ... RST is resetting all data and CALC is somehow calculating and returning data. Without a trigger between RST and CALC, I would not expect any data... Maybe the equipment is triggering continuously e.g. every second. When you were using the shell, you had a good chance to see a trigger between RST and CALC. With a script, it's not so likely. OPC won't help, as it would wait for completion of a measurement, but if you don't trigger, it won't wait. What kind of instrument are you using? Check for the trigger command. It may be something like INIT:IMM Regards, Dietmar From gilles.lenfant at gmail.com Tue Oct 25 17:56:26 2011 From: gilles.lenfant at gmail.com (Gilles Lenfant) Date: Tue, 25 Oct 2011 14:56:26 -0700 (PDT) Subject: [wanted] python-ldap for Python 2.3 / Win32 In-Reply-To: <4818553.676.1319577549027.JavaMail.geo-discussion-forums@yqnv12> References: <16595266.1315.1319526830836.JavaMail.geo-discussion-forums@yqhp35> <4818553.676.1319577549027.JavaMail.geo-discussion-forums@yqnv12> Message-ID: <10174006.847.1319579786925.JavaMail.geo-discussion-forums@yqlb4> So many thanks for your valuable help Waldemar, this is exactly what I needed. I have no Windows machine to compile with the source bundle all this, and must install this directly in a production server. I'll keep these precious links and files in a trunk. Many thanks again -- Gilles Lenfant From psimon at sonic.net Tue Oct 25 18:06:31 2011 From: psimon at sonic.net (Paul Simon) Date: Tue, 25 Oct 2011 15:06:31 -0700 Subject: Data acquisition References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: <4ea7331e$0$1715$742ec2ed@news.sonic.net> "spintronic" wrote in message news:362e368f-829e-4477-bcfc-c0650d231029 at j7g2000yqi.googlegroups.com... > Dear friends, > > I have a trouble with understanding the following. I have a very short > script (shown below) which works fine if I "run" step by step (or line > by line) in Python shell (type the first line/command -> press Enter, > etc.). I can get all numbers (actually, there are no numbers but a > long string, but this is not a problem) I need from a device: > > '0.3345098119,0.01069121274,0.02111624694,0.03833379529,0.02462816409,0.0774275008,0.06554297421,0.07366750919,0.08122602002,0.004018369318,0.03508462415,0.04829900696,0.06383554085, > ...' > > However, when I start very the same list of commands as a script, it > gives me the following, which is certainly wrong: > > [0.0, 0.0, 0.0, 0.0, 0.0,...] > > Any ideas? Why there is a difference when I run the script or do it > command by command? > > =========================== > from visa import * > > mw = instrument("GPIB0::20::INSTR", timeout = None) > > mw.write("*RST") > mw.write("CALC1:DATA? FDATA") > > a=mw.read() > > print a > =========================== > (That is really all!) > > > PS In this case I use Python Enthought for Windows, but I am not an > expert in Windows (I work usually in Linux but now I need to run this > data acquisition under Windows). I'm almost certain that there is a turnaround timing issue that is causing the problem. These are common problems in data aquisition systems. The simplest solution is to loop and wait for end of line from the sending end and if necessary put in a time delay. After receiving the data, check the received data for correct format, correct first and last characters, and if possible, check sum. I've worked through this problem with rs-485 data collection systems where there is no hand shaking and would not be surprised to expect the same even with rs-232. Paul Simon From invalid at invalid.invalid Tue Oct 25 18:50:57 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 25 Oct 2011 22:50:57 +0000 (UTC) Subject: How to pretty-print ctypes composite data types? Message-ID: I'm using ctypes with a library that requires a handful of structure definitions. The actual definitions and usage aren't a problem. When it comes time to print out the values in a structure or array, there doesn't seem to be simple/general way to do that. Am I missing something? I presume one can recursively iterate through the fields in a structure and elements in an array, recursing on any composite types and printing the values when one finds a type, but I'm surprised that's not something that's already in the ctypes library somewhere -- the authors certainly seem to have thought of everything else. -- Grant Edwards grant.b.edwards Yow! I own seven-eighths of at all the artists in downtown gmail.com Burbank! From fabiofz at gmail.com Tue Oct 25 18:59:26 2011 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Tue, 25 Oct 2011 20:59:26 -0200 Subject: Strange classmethod mock behavior In-Reply-To: References: Message-ID: On Tue, Oct 25, 2011 at 10:08 AM, Peter Otten <__peter__ at web.de> wrote: > Fabio Zadrozny wrote: > >> I'm trying to mock a classmethod in a superclass but when restoring it >> a strange behavior happens in subclasses (tested on Python 2.5) >> >> Anyone knows why this happens? (see test case below for details) >> Is there any way to restore that original method to have the original >> behavior? >> >> import unittest >> >> class Test(unittest.TestCase): >> >> ? ? def testClassmethod(self): >> ? ? ? ? class Super(): >> ? ? ? ? ? ? @classmethod >> ? ? ? ? ? ? def GetCls(cls): >> ? ? ? ? ? ? ? ? return cls >> >> ? ? ? ? class Sub(Super): >> ? ? ? ? ? ? pass >> >> ? ? ? ? self.assertEqual(Sub.GetCls(), Sub) >> >> ? ? ? ? original = Super.GetCls >> ? ? ? ? #Mock Super.GetCls, and do tests... >> ? ? ? ? Super.GetCls = original #Restore the original classmethod >> ? ? ? ? self.assertEqual(Sub.GetCls(), Sub) #The call to the >> classmethod subclass returns the cls as Super and not Sub as expected! >> >> if __name__ == '__main__': >> ? ? unittest.main() > > [Not related to your problem] When working with descriptors it's a good idea > to use newstyle classes, i. e. have Super inherit from object. > > The Super.GetCls attribute access is roughly equivalent to > > Super.__dict___["GetCls"].__get__(classmethod_instance, None, Super) > > and returns an object that knows about its class. So when you think you are > restoring the original method you are actually setting the GetCls attribute > to something else. You can avoid the problem by accessing the attribute > explicitly: > >>>> class Super(object): > ... ? ? @classmethod > ... ? ? def m(cls): return cls > ... >>>> bad = Super.m >>>> good = Super.__dict__["m"] >>>> class Sub(Super): pass > ... >>>> Sub.m() > >>>> Super.m = bad >>>> Sub.m() > >>>> Super.m = good >>>> Sub.m() > > Hi Peter, thanks for the explanation. Printing it helped me understand it even better... print(Super.__dict__['GetCls']) print(Super.GetCls) > Cheers, Fabio From ian.g.kelly at gmail.com Tue Oct 25 20:30:32 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 25 Oct 2011 18:30:32 -0600 Subject: How to isolate a constant? In-Reply-To: References: <4EA71323.2030500@yahoo.com> Message-ID: On Tue, Oct 25, 2011 at 6:08 PM, Dennis Lee Bieber wrote: > Where's the line form to split those who'd prefer the first vs the > second result in this sample : > >>>> unExpected = "What about a string" >>>> firstToLast = unExpected[:] Strings are immutable. That doesn't suffice to copy them, even assuming you would want to do so in the first place. >>> unExpected is firstToLast True If you find yourself needing to make a copy, that usually means that you plan on modifying either the original or the copy, which in turn means that you need a type that supports modification operations, which usually means a list. If you pass in a string and then copy it with [:] and then try to modify it, you'll get an exception. If you don't try to modify it, then you probably didn't need to copy it in the first place. Cheers, Ian From tjreedy at udel.edu Tue Oct 25 21:11:15 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 Oct 2011 21:11:15 -0400 Subject: spawnl issues with Win 7 access rights In-Reply-To: <4EA6A950.6090706@timgolden.me.uk> References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> <4EA6A950.6090706@timgolden.me.uk> Message-ID: On 10/25/2011 8:19 AM, Tim Golden wrote: > On 25/10/2011 08:01, Propad wrote: >> Thnx again for all the answers. As stated before, I'm limited in my >> options. One of them just might be to switch to Python 2.5, rewrite >> the code that crashes using the subprocess module, and then somehow >> patch the library I use (which I'm not suposed to do, but... oh >> well :-)). I can just hope subrocess was already mature adn offering >> the relevant functionality in 2.5. > > I must admit I'm more than slightly surprised by this. My test case > is to use os.spawnl to run c:/windows/notepad.exe. From the docs, > I would expect to use os.spawnl (os.P_WAIT, "c:/windows/notepad.exe"). > (I only want to open notepad.exe; there's no need for additional args). > > These are my test cases: > > (1) > > os.spawnl ( > os.P_WAIT, > "c:/windows/notepad.exe" > ) > > (2) > > os.spawnl ( > os.P_WAIT, > "c:/windows/notepad.exe", > "c:/windows/notepad.exe" > ) > > (3) > > os.spawnl ( > os.P_WAIT, > "c:/windows/notepad.exe", > "c:/windows/notepad.exe", > "c:/temp.txt" > ) > > > And the results: > > ============================================================== > Python | Platform | Case | Result > -------------------------------------------------------------- > 2.2.2 | WinXP | 1 | Works (empty notepad) > 2.2.2 | WinXP | 2 | Works (empty notepad) > 2.2.2 | WinXP | 3 | Works (notepad temp.txt) > -------------------------------------------------------------- > 2.2.2 | Win7 | 1 | OSError > 2.2.2 | Win7 | 2 | Works (empty notepad) > 2.2.2 | Win7 | 3 | Works (notepad temp.txt) > -------------------------------------------------------------- > 2.7.2 | WinXP | 1 | Crashes > 2.7.2 | WinXP | 2 | Works (empty notepad) > 2.7.2 | WinXP | 3 | Works (notepad temp.txt) > -------------------------------------------------------------- > 2.7.2 | Win7 | 1 | Crashes > 2.7.2 | Win7 | 2 | Works (empty notepad) > 2.7.2 | Win7 | 3 | Works (notepad temp.txt) > ============================================================== > > > Add to this a look at the mscrt source which ships with VS 2008 > and the MSDN docs for spawnl: > > http://msdn.microsoft.com/en-us/library/wweek9sc%28v=vs.80%29.aspx > > and we see that the first args parameter must be the same as the > path parameter. > > FWIW, at no extra cost, I went to the trouble of testing it on some > flavour of Linux with Python 2.6 and got the same results > as per 2.2.2 on WinXP. (Basically: everything works). > > Which leaves us with http://bugs.python.org/issue8036 in which recent > versions of Python crash when the (arbitrary) second parameter isn't > passed. And with an inexplicable behaviour change between the same > version of Python running on WinXP and on Win7. OP reports 2.6 with XP works. Did that use VS 2005? Maybe C runtime changed (regressed). Also, could there be a 32 v. 64 bit issue? -- Terry Jan Reedy From mwilson at the-wire.com Tue Oct 25 22:48:12 2011 From: mwilson at the-wire.com (Mel) Date: Tue, 25 Oct 2011 22:48:12 -0400 Subject: How to isolate a constant? References: <4EA71323.2030500@yahoo.com> Message-ID: Dennis Lee Bieber wrote: > Where's the line form to split those who'd prefer the first vs the > second result in this sample : > >>>> unExpected = "What about a string" >>>> firstToLast = unExpected[:] >>>> repr(firstToLast) > "'What about a string'" >>>> explicitList = list(unExpected) >>>> repr(explicitList) > "['W', 'h', 'a', 't', ' ', 'a', 'b', 'o', 'u', 't', ' ', 'a', ' ', 's', > 't', 'r', 'i', 'n', 'g']" >>>> Well, as things stand, there's a way to get whichever result you need. The `list` constructor builds a single list from a single iterable. The list literal enclosed by `[`, `]` makes a list containing a bunch of items. Strings being iterable introduces a wrinkle, but `list('abcde')` doesn't create `['abcde']` just as `list(1)` doesn't create `[1]`. Mel. From fred.sells at adventistcare.org Tue Oct 25 23:00:52 2011 From: fred.sells at adventistcare.org (Sells, Fred) Date: Tue, 25 Oct 2011 23:00:52 -0400 Subject: webapp development in pure python In-Reply-To: <4EA6E4DA.2080307@shopzeus.com> References: <4EA6BEC3.5010206@shopzeus.com> <4EA6E4DA.2080307@shopzeus.com> Message-ID: Quixote may be what you want, but it's been years since I've used it and I don't know if it is still alive and kicking. It was from MEMS if I remember correctly. Using django and Flex is one way to avoid html and javascript and it works great for datagrids. Fred. From wuwei23 at gmail.com Tue Oct 25 23:15:21 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 25 Oct 2011 20:15:21 -0700 (PDT) Subject: webapp development in pure python References: <4EA6BEC3.5010206@shopzeus.com> Message-ID: <571a97cb-5ebc-4882-ad67-1ff7953383b7@u10g2000prl.googlegroups.com> Laszlo Nagy wrote: > My Python module would connect to a database server and query > some data, then display it in a grid. This cannot be compiled into > javascript because of the database server connection. So what you want is for everything to happen server-side, with html output sent to the client? Perhaps you could build on top of ToscaWidgets. They encapsulate HTML & JS, so you'll still need to work with them for custom widgets. > With pyjamas, I > would have to create the server side part separately, the user interface > separately, and hand-code the communication between the widets and the > server side. That's pretty much true of all non-trivial web development, though. There's a lot to be said for sucking it up and embracing traditional methods rather than flying against common wisdom and cobbling together something that works against web technologies rather than with them. From puntabluda at gmail.com Wed Oct 26 03:29:10 2011 From: puntabluda at gmail.com (Rebelo) Date: Wed, 26 Oct 2011 00:29:10 -0700 (PDT) Subject: webapp development in pure python In-Reply-To: References: <4EA6BEC3.5010206@shopzeus.com> Message-ID: <18902163.1637.1319614150053.JavaMail.geo-discussion-forums@yqp37> Try Pylons. Use html templates which get populated with data from your database and then just render them. If you just want to display data, with simple forms for editing and adding Pylons framework is more then enough. http://pylonsbook.com/en/1.1/ http://www.pylonsproject.org/ From puntabluda at gmail.com Wed Oct 26 03:29:10 2011 From: puntabluda at gmail.com (Rebelo) Date: Wed, 26 Oct 2011 00:29:10 -0700 (PDT) Subject: webapp development in pure python In-Reply-To: References: <4EA6BEC3.5010206@shopzeus.com> Message-ID: <18902163.1637.1319614150053.JavaMail.geo-discussion-forums@yqp37> Try Pylons. Use html templates which get populated with data from your database and then just render them. If you just want to display data, with simple forms for editing and adding Pylons framework is more then enough. http://pylonsbook.com/en/1.1/ http://www.pylonsproject.org/ From vinay_sajip at yahoo.co.uk Wed Oct 26 05:12:58 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Wed, 26 Oct 2011 09:12:58 +0000 (UTC) Subject: logging: warn() methods and function to be deprecated. References: <4EA4A65F.2090205@gmail.com> <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> <4EA5787F.1050906@vrplumber.com> Message-ID: Mike C. Fletcher vrplumber.com> writes: > I actually consider .warning() a nit :) . After all, it's 3 extra > characters :) , and *who* actually reads documentation instead of just > poking around and finding the shortest-named method in the instance? Readability counts :-) Are you saying there's no need to bother documenting stuff ??? ;-) > Anyway, I personally don't see this as worth the breakage. What breakage are we really talking about? Remember, Python 2.x will not change in this area - the proposed change is for Python 3.3 and later only, and will not be backported :-) As far as I know, Trac doesn't work with Python 3 anyway. Most of the code out there (which Mark found via Google Code Search) is Python 2.x. When porting from 2 to 3.3, it's just one extra little thing to deal with - small compared with other issues which come up when doing such ports. Regards, Vinay Sajip From amirouche.boubekki at gmail.com Wed Oct 26 05:14:02 2011 From: amirouche.boubekki at gmail.com (Amirouche Boubekki) Date: Wed, 26 Oct 2011 11:14:02 +0200 Subject: Forking simplejson Message-ID: H?llo, I would like to fork simplejson [1] and implement serialization rules based on protocols instead of types [2], plus special cases for protocol free objects, that breaks compatibility. The benefit will be a better API for json serialization of custom classes and in the case of iterable it will avoid a calls like: >>> simplejson.dumps(list(my_iterable)) The serialization of custom objects is documented in the class instead of the ``default`` function of current simplejson implementation [3]. The encoding algorithm works with a priority list that is summarized in the next table: +-------------------+---------------+ | Python protocol | JSON | | or special case | | +===================+===============+ | (?) __json__ | see (?) | +-------------------+---------------| | map | object | +-------------------+---------------+ | iterable | array | +-------------------+---------------+ | (*) float,int,long| number | +-------------------+---------------+ | (*) True | true | +-------------------+---------------+ | (*) False | false | +-------------------+---------------+ | (*) None | null | +-------------------+---------------+ | (?) unicode | see (?) | +-------------------+---------------+ (?) if the object implements a __json__ method, the returned value is used as the serialization of the object (*) special objects which are protocol free are serialized the same way it's done currently in simplejson (?) if the algorithm arrives here, call unicode (with proper encoding rule) on the object and use the result as json serialization As soon as an object match a rule, it's serialized. What do you think ? Do you find this API an improvement over simplejson ? Is it worth to code ? Where are documented the different protocols implemented by Python objects ? Regards, Amirouche [1] https://github.com/simplejson/simplejson [2] https://github.com/simplejson/simplejson/blob/master/simplejson/encoder.py#L75 [3] http://simplejson.readthedocs.org/en/latest/index.html#simplejson.JSONEncoder.default -------------- next part -------------- An HTML attachment was scrubbed... URL: From mcfletch at vrplumber.com Wed Oct 26 09:01:11 2011 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Wed, 26 Oct 2011 09:01:11 -0400 Subject: logging: warn() methods and function to be deprecated. In-Reply-To: References: <4EA4A65F.2090205@gmail.com> <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> <4EA5787F.1050906@vrplumber.com> Message-ID: <4EA80497.9050600@vrplumber.com> On 11-10-26 05:12 AM, Vinay Sajip wrote: > Mike C. Fletcher vrplumber.com> writes: > >> I actually consider .warning() a nit :) . After all, it's 3 extra >> characters :) , and *who* actually reads documentation instead of just >> poking around and finding the shortest-named method in the instance? > Readability counts :-) Are you saying there's no need to bother documenting > stuff ??? ;-) More: an undocumented entry point is not "deprecated" because, after all, it shows up in PyDoc as a regular method. > >> Anyway, I personally don't see this as worth the breakage. > > What breakage are we really talking about? Remember, Python 2.x will not change > in this area - the proposed change is for Python 3.3 and later only, and will > not be backported :-) > > As far as I know, Trac doesn't work with Python 3 anyway. Most of the code out > there (which Mark found via Google Code Search) is Python 2.x. When porting from > 2 to 3.3, it's just one extra little thing to deal with - small compared with > other issues which come up when doing such ports. Sure, but most of *everything* is Python 2.x, and porting to Python 3.x is already enough of a pain that key-stone projects like Trac still aren't there :) . This isn't going to be easily amenable to auto-translation via 2to3 (because you generally are calling log.warn() rather than logging.warning, but sometimes you are doing getattr( log, log_level ) and then passing that method around a few times), and it will often fall into the small percentage of untested code in most projects (coverage is often poor for logging messages in corner cases), so often won't get caught by test suites. Not a 3.x user, but expecting to have to be some day in the future, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From roy at panix.com Wed Oct 26 09:06:14 2011 From: roy at panix.com (Roy Smith) Date: Wed, 26 Oct 2011 09:06:14 -0400 Subject: webapp development in pure python References: <4EA6BEC3.5010206@shopzeus.com> <18902163.1637.1319614150053.JavaMail.geo-discussion-forums@yqp37> Message-ID: In article <18902163.1637.1319614150053.JavaMail.geo-discussion-forums at yqp37>, Rebelo wrote: > Try Pylons. Use html templates which get populated with data from your > database and then just render them. If you just want to display data, with > simple forms for editing and adding Pylons framework is more then enough. > > http://pylonsbook.com/en/1.1/ > http://www.pylonsproject.org/ If you're looking at web frameworks, you should also look at http://www.tornadoweb.org/. It's more of a HTTP engine than a application framework, but has some elements of both. We use it for lots of small HTTP tools we write. But, to go back to the OP's request: > What I need is a programmable GUI with windows, event handlers and > extensible widgets, for creating applications that use http/https and a web > browser for rendering. combined with: > I need something that does not require javascript knowledge, just pure Python. I'm not sure there's a good answer to that. If you're talking GUIs, windows, and extensible widgets, it really sounds like the kinds of things you're trying to do are going to require javascript. I'm not a huge fan of javascript, but the reality today is that for any kind of interactive UI in a web browser, you need to go there. Well, or Flash, but that's probably even more evil. You might want to look at [[Dart (programming language)]], but that's more of a research project than a tool at the moment. Check out that wikipedia page, however, it's got some pointers to other similar projects people are working on. From projetmbc at gmail.com Wed Oct 26 09:42:07 2011 From: projetmbc at gmail.com (projetmbc) Date: Wed, 26 Oct 2011 06:42:07 -0700 (PDT) Subject: Parsing using one gramar with contexts Message-ID: <28f0eeb3-da28-4738-8d1b-8e4e373c0e3e@f13g2000vbv.googlegroups.com> Hello, I'm seeking for one friendly library to parse one language with taking care of the context. For example, I would like to parse text in one docstring differently than the other code, or to add special keyword for the parsing when I'm in one class... Is there existing python tools for that ? From andrea.crotti.0 at gmail.com Wed Oct 26 10:22:00 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Wed, 26 Oct 2011 15:22:00 +0100 Subject: services/daemons Message-ID: <4EA81788.8080706@gmail.com> Running pypiserver as a service? I'm writing some scripts which in theory should be able to: - start up a local pypi server as a daemon (or well a service on Windows) - run "python setup.py develop" on a potentially very big set of eggs, possibly discovering automatically for changes. In theory using develop changes should be automatically seen, but if I move/rename something of course things might not work anymore. - run/debug/develop applications using this big set of eggs. On the distutils list it was suggested to use the "-m" option to easy_install, which avoids writing on the global easy_install.pth, which is one of the current problems. For the first one reading I thought I might use pypiserver (which ships also as a single file) and create a windows service/unix daemon from it. For the second I've seen watchdog: https://github.com/gorakhargosh/watchdog/ which looks interesting. As last thing the whole process should be as transparent and robust as possible, anyone did something similar or has suggestions? From mail at timgolden.me.uk Wed Oct 26 10:38:42 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 26 Oct 2011 15:38:42 +0100 Subject: spawnl issues with Win 7 access rights In-Reply-To: References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> <4EA6A950.6090706@timgolden.me.uk> Message-ID: <4EA81B72.7040008@timgolden.me.uk> On 26/10/2011 02:11, Terry Reedy wrote: > OP reports 2.6 with XP works. Where do you see that, Terry? (Or was there an offlist email?) > Did that use VS 2005? Maybe C runtime > changed (regressed). That's possible -- and is essentially my main guess (faute de mieux). I've got the same results on 32 & 64-bit machines. Hopefully the workaround I suggested -- doubling up the executable filepath -- will get round the user's particular issue. I'm not going to fight CRT changes, but if no-one else gets there, I will try to address issue8036 TJG From vinay_sajip at yahoo.co.uk Wed Oct 26 10:51:21 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Wed, 26 Oct 2011 14:51:21 +0000 (UTC) Subject: logging: warn() methods and function to be deprecated. References: <4EA4A65F.2090205@gmail.com> <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> <4EA5787F.1050906@vrplumber.com> <4EA80497.9050600@vrplumber.com> Message-ID: Mike C. Fletcher vrplumber.com> writes: > More: an undocumented entry point is not "deprecated" because, after > all, it shows up in PyDoc as a regular method. Deprecated methods also show up in PyDoc. Of course, if the deprecation is mentioned in the docstring, users would see this - but if it isn't, they wouldn't know until they got a DeprecationWarning. > auto-translation via 2to3 (because you generally are calling log.warn() > rather than logging.warning, but sometimes you are doing getattr( log, > log_level ) and then passing that method around a few times), and it That doesn't sound like a good usage pattern to me, especially as loggers have a log method which takes the logging level. There shouldn't be any need to pass a bound method around. Regards, Vinay Sajip From challb at gmail.com Wed Oct 26 11:51:44 2011 From: challb at gmail.com (Chris Hall) Date: Wed, 26 Oct 2011 08:51:44 -0700 (PDT) Subject: Review Python site with useful code snippets Message-ID: <98598900-8b72-4bb2-b21e-13666c9f823b@p16g2000yqd.googlegroups.com> I am looking to get reviews, comments, code snippet suggestions, and feature requests for my site. I intend to grow out this site with all kinds of real world code examples to learn from and use in everyday coding. The site is: http://www.pythonsnippet.com If you have anything to contribute or comment, please post it on the site or email me directly. Thanks, Chris From sidorenko.andrey at gmail.com Wed Oct 26 11:58:45 2011 From: sidorenko.andrey at gmail.com (spintronic) Date: Wed, 26 Oct 2011 08:58:45 -0700 (PDT) Subject: Data acquisition References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: <1059c1c4-4581-412d-ad08-6fba6289444d@l12g2000vby.googlegroups.com> Dear friends! Thank you for the discussion. It was really helpful. As mentioned, it was necessary to have a longer delay. Previously I have used a delay of 5 and 10 s but it was not long enough. Now it is 25 s and everything works fine. Thank you again! Best, AS From mcfletch at vrplumber.com Wed Oct 26 12:20:06 2011 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Wed, 26 Oct 2011 12:20:06 -0400 Subject: logging: warn() methods and function to be deprecated. In-Reply-To: References: <4EA4A65F.2090205@gmail.com> <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> <4EA5787F.1050906@vrplumber.com> <4EA80497.9050600@vrplumber.com> Message-ID: <4EA83336.2020903@vrplumber.com> On 11-10-26 10:51 AM, Vinay Sajip wrote: ... > auto-translation via 2to3 (because you generally are calling log.warn() >> rather than logging.warning, but sometimes you are doing getattr( log, >> log_level ) and then passing that method around a few times), and it > That doesn't sound like a good usage pattern to me, especially as loggers have a > log method which takes the logging level. There shouldn't be any need to pass a > bound method around. Bound methods also pull along to *which* log you are going to send the message, but then I suppose you could just use the logging key as well as a piece of data. I'll withdraw the suggestion that it is not a trivial thing to add to 2to3, though I'll leave the implementation to someone else. Have fun, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From nathan.alexander.rice at gmail.com Wed Oct 26 13:34:04 2011 From: nathan.alexander.rice at gmail.com (Nathan Rice) Date: Wed, 26 Oct 2011 13:34:04 -0400 Subject: Forking simplejson In-Reply-To: References: Message-ID: Since this happily went off to the wrong recipient the first time... The python json module/simpljson are badly in need of an architecture update. The fact that you can't override the encode method of JSONEncoder and have it work reliably without monkey patching the pure python encoder is a sign that something is horribly wrong. On Wed, Oct 26, 2011 at 5:14 AM, Amirouche Boubekki wrote: > H?llo, > > I would like to fork simplejson [1] and implement serialization rules based > on protocols instead of types [2], plus special cases for protocol free > objects, that breaks compatibility. The benefit will be a better API for > json serialization of custom classes and in the case of iterable it will > avoid a calls like: > >>>> simplejson.dumps(list(my_iterable)) > > The serialization of custom objects is documented in the class instead of > the ``default`` function of current simplejson implementation [3]. > > The encoding algorithm works with a priority list that is summarized in the > next table: > > +-------------------+---------------+ > | Python protocol | JSON | > > > | or special case | | > +===================+===============+ > | (?) __json__ | see (?) | > > > +-------------------+---------------| > > | map | object | > > > +-------------------+---------------+ > | iterable | array | > +-------------------+---------------+ > | (*) float,int,long| number | > > > +-------------------+---------------+ > | (*) True | true | > +-------------------+---------------+ > | (*) False | false | > > > +-------------------+---------------+ > | (*) None | null | > +-------------------+---------------+ > | (?) unicode | see (?) | > > > +-------------------+---------------+ > > (?) if the object implements a __json__ method, the returned value is used > as the serialization of the object > > > (*) special objects which are protocol free are serialized the same way it's > done currently in simplejson > (?) if the algorithm arrives here, call unicode (with proper encoding rule) > on the object and use the result as json serialization > > > As soon as an object match a rule, it's serialized. > > What do you think ? Do you find this API an improvement over simplejson ? Is > it worth to code ? > > Where are documented the different protocols implemented by Python objects ? > > > > Regards, > > Amirouche > > [1] https://github.com/simplejson/simplejson > [2] > https://github.com/simplejson/simplejson/blob/master/simplejson/encoder.py#L75 > [3] > http://simplejson.readthedocs.org/en/latest/index.html#simplejson.JSONEncoder.default > > -- > http://mail.python.org/mailman/listinfo/python-list > > From news at schwertberger.de Wed Oct 26 13:35:03 2011 From: news at schwertberger.de (Dietmar Schwertberger) Date: Wed, 26 Oct 2011 19:35:03 +0200 Subject: Data acquisition In-Reply-To: <1059c1c4-4581-412d-ad08-6fba6289444d@l12g2000vby.googlegroups.com> References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> <1059c1c4-4581-412d-ad08-6fba6289444d@l12g2000vby.googlegroups.com> Message-ID: Am 26.10.2011 17:58, schrieb spintronic: > Thank you for the discussion. It was really helpful. As mentioned, it > was necessary to have a longer delay. Previously I have used a delay > of 5 and 10 s but it was not long enough. Now it is 25 s and > everything works fine. If you use the correct sequence of trigger and OPC/WAIT, I'm sure you can reduce the waiting time to the required minimum time and still your script will be more robust... Regards, Dietmar From tjreedy at udel.edu Wed Oct 26 15:20:12 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 Oct 2011 15:20:12 -0400 Subject: spawnl issues with Win 7 access rights In-Reply-To: <4EA81B72.7040008@timgolden.me.uk> References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> <4EA6A950.6090706@timgolden.me.uk> <4EA81B72.7040008@timgolden.me.uk> Message-ID: On 10/26/2011 10:38 AM, Tim Golden wrote: > On 26/10/2011 02:11, Terry Reedy wrote: >> OP reports 2.6 with XP works. > > Where do you see that, Terry? (Or was there an offlist email?) The first message of http://bugs.python.org/issue8036 "Python 2.6 is however happy and just reports invalid arg." -- Terry Jan Reedy From tjreedy at udel.edu Wed Oct 26 15:29:09 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 Oct 2011 15:29:09 -0400 Subject: Forking simplejson In-Reply-To: References: Message-ID: On 10/26/2011 5:14 AM, Amirouche Boubekki wrote: > H?llo, > > I would like to fork simplejson [1] and implement serialization rules > based on protocols instead of types [2], plus special cases for protocol > free objects, that breaks compatibility. The benefit will be a better > API for json serialization of custom classes and in the case of iterable > it will avoid a calls like: > > >>> simplejson.dumps(list(my_iterable)) > > The serialization of custom objects is documented in the class instead > of the ``default`` function of current simplejson implementation [3]. > > The encoding algorithm works with a priority list that is summarized in > the next table: > > +-------------------+---------------+ > | Python protocol | JSON | > | or special case | | > +===================+===============+ > | (?) __json__ | see (?) | > +-------------------+---------------| > | map | object | I am curious what you mean by the 'map' protocol. > Where are documented the different protocols implemented by Python objects ? Ref 3.3 special method names (and elsewhere ;-) http://docs.python.org/py3k/reference/datamodel.html#special-method-names --- Terry Jan Reedy From ross at biostat.ucsf.edu Wed Oct 26 15:48:01 2011 From: ross at biostat.ucsf.edu (Ross Boylan) Date: Wed, 26 Oct 2011 12:48:01 -0700 Subject: inserting \ in regular expressions Message-ID: <1319658482.13425.9.camel@corn.betterworld.us> I want to replace every \ and " (the two characters for backslash and double quotes) with a \ and the same character, i.e., \ -> \\ " -> \" I have not been able to figure out how to do that. The documentation for re.sub says "repl can be a string or a function; if it is a string, any backslash escapes in it are processed.That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes such as \j are left alone." \\ is apparently unknown, and so is left as is. So I'm unable to get a single \. Here are some tries in Python 2.5.2. The document suggested the result of a function might not be subject to the same problem, but it seems to be. >>> def f(m): ... return "\\"+m.group(1) ... >>> re.sub(r"([\\\"])", f, 'Silly " quote') 'Silly \\" quote' >>> re.sub(r"([\\\"])", r"\\1", 'Silly " quote') 'Silly \\1 quote' >>> re.sub(r"([\\\"])", "\\\\1", 'Silly " quote') 'Silly \\1 quote' >>> re.sub(r"([\\\"])", "\\\\\1", 'Silly " quote') 'Silly \\\x01 quote' >>> re.sub(r"([\\\"])", "\\\\\\1", 'Silly " quote') 'Silly \\" quote' Or perhaps I'm confused about what the displayed results mean. If a string has a literal \, does it get shown as \\? I'd appreciate it if you cc me on the reply. Thanks. Ross Boylan From michael at stroeder.com Wed Oct 26 15:48:46 2011 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 26 Oct 2011 21:48:46 +0200 Subject: ANN: python-ldap 2.4.4 Message-ID: Find a new release of python-ldap: http://pypi.python.org/pypi/python-ldap/2.4.4 python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). Project's web site: http://www.python-ldap.org/ Ciao, Michael. ---------------------------------------------------------------- Released 2.4.4 2011-10-26 Changes since 2.4.3: Modules/ * Format intermediate messages as 3-tuples instead of 4-tuples to match the format of other response messages. (thanks to Chris Mikkelson) * Fixes for memory leaks (thanks to Chris Mikkelson) Lib/ * New experimental(!) sub-module ldap.syncrepl implementing syncrepl consumer (see RFC 4533, thanks to Chris Mikkelson) Doc/ * Cleaned up rst files * Added missing classes From ian.g.kelly at gmail.com Wed Oct 26 16:26:45 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 26 Oct 2011 14:26:45 -0600 Subject: inserting \ in regular expressions In-Reply-To: <1319658482.13425.9.camel@corn.betterworld.us> References: <1319658482.13425.9.camel@corn.betterworld.us> Message-ID: On Wed, Oct 26, 2011 at 1:48 PM, Ross Boylan wrote: > Or perhaps I'm confused about what the displayed results mean. ?If a > string has a literal \, does it get shown as \\? In the repr, yes. If you try printing the string, you'll see that it only contains one \. By the way, regular expressions are overkill here. You can use the str.replace method for this: >>> print(r'Silly \ " quote'.replace('\\', '\\\\').replace('"', r'\"')) Silly \\ \" quote Cheers, Ian From michael at stroeder.com Wed Oct 26 16:34:19 2011 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 26 Oct 2011 22:34:19 +0200 Subject: [wanted] python-ldap for Python 2.3 / Win32 In-Reply-To: <4818553.676.1319577549027.JavaMail.geo-discussion-forums@yqnv12> References: <16595266.1315.1319526830836.JavaMail.geo-discussion-forums@yqhp35> <4818553.676.1319577549027.JavaMail.geo-discussion-forums@yqnv12> Message-ID: Waldemar Osuch wrote: > I did try to build it using my current setup but it failed with some linking errors. > Oh well. Waldemar, I really appreciate your Win32 support. > Google gods were nicer to me. Here is a couple alternative links. > Maybe they will work for you. > http://web.archive.org/web/20081101060042/http://www.agescibs.org/mauro/ > http://old.zope.org/Members/volkerw/LdapWin32/ Puh, this is really ancient stuff... For Python historians: http://python-ldap.cvs.sourceforge.net/python-ldap/python-ldap/CHANGES?view=markup Ciao, Michael. From d at davea.name Wed Oct 26 16:47:54 2011 From: d at davea.name (Dave Angel) Date: Wed, 26 Oct 2011 16:47:54 -0400 Subject: inserting \ in regular expressions In-Reply-To: <1319658482.13425.9.camel@corn.betterworld.us> References: <1319658482.13425.9.camel@corn.betterworld.us> Message-ID: <4EA871FA.2090804@davea.name> On 10/26/2011 03:48 PM, Ross Boylan wrote: > I want to replace every \ and " (the two characters for backslash and > double quotes) with a \ and the same character, i.e., > \ -> \\ > " -> \" > > I have not been able to figure out how to do that. The documentation > for re.sub says "repl can be a string or a function; if it is a string, > any backslash escapes in it are processed.That is, \n is converted to a > single newline character, \r is converted to a carriage return, and so > forth. Unknown escapes such as \j are left alone." > > \\ is apparently unknown, and so is left as is. So I'm unable to get a > single \. > > Here are some tries in Python 2.5.2. The document suggested the result > of a function might not be subject to the same problem, but it seems to > be. >>>> def f(m): > ... return "\\"+m.group(1) > ... >>>> re.sub(r"([\\\"])", f, 'Silly " quote') > 'Silly \\" quote' > >>> re.sub(r"([\\\"])", "\\\\\\1", 'Silly " quote') > 'Silly \\" quote' > > Or perhaps I'm confused about what the displayed results mean. If a > string has a literal \, does it get shown as \\? > > I'd appreciate it if you cc me on the reply. > > Thanks. > Ross Boylan > I can't really help on the regex aspect of your code, but I can tell you a little about backslashes, quote literals, the interpreter, and python. First, I'd scrap the interpreter and write your stuff to a file. Then test it by running that file. The reason for that is that the interpreter is helpfully trying to reconstruct the string you'd have to type in order to get that result. So while you may have successfully turned a double bacdkslash into a single one, the interpreter helpfully does the inverse, and you don't see whether you're right or not. Next, always assign to variables, and test those variables on a separate line with the regex. This is probably what your document meant when it mentioned the result of a function. Now some details about python. When python compiles/interprets a quote literal, the syntax parsing has to decide where the literal stops, so quotes are treated specially. Sometimes you can sidestep the problem of embedding quotes inside literals by using single quotes on the outside and double inside, or vice versa. As you did on the 'Silly " quote' example. But the more general way to put funny characters into a quote literal is to escape each with a backslash. So there a bunch of two-character escapes. backslash-quote is how you can put either kind of quote into a literal, regardless of what's being used to delimit it. backslash-n gets a newline, which would similarly be bad syntax. backslash-t and some others are usually less troublesome, but can be surprising. And backslash-backslash represents a single backslash. There are also backslash codes to represent arbitrary characters you might not have on your keyboard. And these may use multiple characters after the backslash. So write a bunch of lines like a = 'this is\'nt a surprise' print a and experiment. Notice that if you use \n in such a string, the print will put it on two lines. Likewise the tab is executed. Now for a digression. The interpreter uses repr() to display strings. You can experiment with that by doing print a print repr(a) Notice the latter puts quotes around the string. They are NOT part of the string object in a. And it re-escapes any embedded funny characters, sometimes differently than the way you entered them. Now, once you're confident that you can write a literal to express any possible string, try calling your regex. print re.sub(a, b, c) or whatever. Now, one way to cheat on the string if you know you'll want to put actual backslashes is to use the raw string. That works quite well unless you want the string to end with a backslash. There isn't a way to enter that as a single raw literal. You'd have to do something string like a = r"strange\literal\with\some\stuff" + "\\" My understanding is that no valid regex ends with a backslash, so this may not affect you. Now there are other ways to acquire a string object. If you got it from a raw_input() call, it doesn't need to be escaped, but it can't have an embedded newline, since the enter key is how the input is completed. If you read it from a file, it doesn't need to be escaped. Now you're ready to see what other funny requirements regex needs. You will be escaping stuff for their purposes, and sometimes that means your literal might have 4 or even more backslashes in a row. But hopefully now you'll see how to separate the different problems. -- DaveA From wallenpb at gmail.com Wed Oct 26 17:32:24 2011 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 26 Oct 2011 16:32:24 -0500 Subject: passing Python data to a javascript function Message-ID: I am writing a Python CGI and am needing to pass a data value from Python to a javascript function. My understanding is that I should use JSON as the middleman. However, I have not found a good example of doing this. The piece of data is a simple integer, but I converting that to a string first. Here is what I am trying, but unsuccessfully. I know this code is broken in at least two places. I may be going about this completely the wrong way. Any help would be appreciated. Thanks, Bill Allen #!/usr/bin/python import json import os import cgi import cgitb cgitb.enable() pid = [{'p':str(os.getpid())}] pid_data = json.dumps(pid) print "Content-type: text/html" print print """ showPID ####This is where I am not sure how to pass the value to the javascript function

Hello World!
""" -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Wed Oct 26 17:47:03 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 26 Oct 2011 17:47:03 -0400 Subject: webapp development in pure python In-Reply-To: <4EA6E4DA.2080307@shopzeus.com> References: <4EA6BEC3.5010206@shopzeus.com> <4EA6E4DA.2080307@shopzeus.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF126AA8@EMARC112VS01.exchad.jpmchase.net> I am not really an expert web developer, so this is just my two cents. > My Python module would connect to a database server and query >some data, then display it in a grid. This cannot be compiled into >javascript because of the database server connection. You technically can connect to databases from JavaScript. It is a terrible idea, but achievable. Not really sure how it would get "compiled" into JavaScript, so it is possible that is the stumbling block. http://stackoverflow.com/questions/857670/how-to-connect-to-sql-server-database-from-javascript >I would have to create the server side part separately, the user interface separately, and hand-code the communication between the widets and the server side. As far as I know, this is the Right way to do a web/GUI apps; you may want to read about the MVC design pattern. >I would like to use this theoretical web based framework just like pygtk or wxPython Even in wxPython/pygtk, you should be using MVC pattern. Usually if your app is one class, you either have a trivial application or you are doing it wrong. Of course, that really applies to larger projects more than hacked together code for personal use. Apologies in advance if I misunderstood something. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From wallenpb at gmail.com Wed Oct 26 18:18:36 2011 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 26 Oct 2011 17:18:36 -0500 Subject: passing Python data to a javascript function Message-ID: I am writing a Python CGI and am needing to pass a data value from Python to a javascript function. My understanding is that I should use JSON as the middleman. However, I have not found a good example of doing this. The piece of data is a simple integer, but I could easily covert that to a string first if necessary. Here is what I am trying, but unsuccessfully. I am sure that I have more than one issue in this code. #!/usr/bin/python import json, os, cgi, cgitb cgitb.enable() pid = [{'p':str(os.getpid())}] pid_data = json.dumps(pid) print "Content-type: text/html" print print """ Test Page

""".format(pid_data) -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Wed Oct 26 18:38:37 2011 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 26 Oct 2011 23:38:37 +0100 Subject: inserting \ in regular expressions In-Reply-To: <1319658482.13425.9.camel@corn.betterworld.us> References: <1319658482.13425.9.camel@corn.betterworld.us> Message-ID: <4EA88BED.7040706@mrabarnett.plus.com> On 26/10/2011 20:48, Ross Boylan wrote: > I want to replace every \ and " (the two characters for backslash and > double quotes) with a \ and the same character, i.e., > \ -> \\ > " -> \" > > I have not been able to figure out how to do that. The documentation > for re.sub says "repl can be a string or a function; if it is a string, > any backslash escapes in it are processed.That is, \n is converted to a > single newline character, \r is converted to a carriage return, and so > forth. Unknown escapes such as \j are left alone." > > \\ is apparently unknown, and so is left as is. So I'm unable to get a > single \. > [snip] The backspace character is also used for escaping in a regex, so you need to escape it with a backslash: >>> print('Silly " quote or \\ backslash') Silly " quote or \ backslash >>> print (re.sub(r'([\\\\"])', r"\\\1", 'Silly " quote or \\ backslash')) Silly \" quote or \\ backslash From benjamin.kaplan at case.edu Wed Oct 26 18:58:07 2011 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 26 Oct 2011 18:58:07 -0400 Subject: passing Python data to a javascript function In-Reply-To: References: Message-ID: On Wed, Oct 26, 2011 at 6:18 PM, Bill Allen wrote: > > I am writing a Python CGI and am needing to pass a data value from Python to a javascript function.?? My understanding is that I should use JSON as the middleman.? However, I have not found a good example of doing this.?? The piece of data is a simple integer, but I could easily covert that to a string first if necessary.?? Here is what I am trying, but unsuccessfully.? I am sure that I have more than one issue in this code. > > > > #!/usr/bin/python > > import json, os, cgi, cgitb > cgitb.enable() > > pid = [{'p':str(os.getpid())}] > pid_data = json.dumps(pid) > > print "Content-type: text/html" > print > > print """ > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> > > Test Page > > > > >

> > > """.format(pid_data) > You're making this much more difficult than it needs to be. JSON is used for sending data to JavaScript, meaning the JavaScript asks the server for a bunch of data, the server sends the client JSON, and everyone is happy. In your case, the information is available when the javascript is being generated so you can just pass in the number, no JSON needed. From web at naveed.net Wed Oct 26 22:06:16 2011 From: web at naveed.net (web at naveed.net) Date: Wed, 26 Oct 2011 19:06:16 -0700 (PDT) Subject: No more Python support in NetBeans 7.0 In-Reply-To: <4a98.4d8b560e.5ebee@altium.nl> References: <4a98.4d8b560e.5ebee@altium.nl> Message-ID: <4892437.584.1319681177024.JavaMail.geo-discussion-forums@yqp37> Sorry to comment on an old topic, but I wanted to clarify for others like me who might get the wrong idea. It looks like this is no longer true. Netbeans 7 might be supporting python after all. http://wiki.netbeans.org/Python70Roadmap From wallenpb at gmail.com Wed Oct 26 22:25:16 2011 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 26 Oct 2011 21:25:16 -0500 Subject: passing Python data to a javascript function In-Reply-To: References: Message-ID: Benjamin, I was afraid I was doing that. I have simplified it quite a bit, still not getting the output I am looking for. I am down to that I am not passing the value in the onload=showPID() call correctly. I know this is getting a bit far from a Python issue now, but if you have more insight on this, I would appreciate it. Is there another way of passing the data from the Python script to the javascript than what I am doing in this CGI? Thanks, Bill code now is: import os, cgi, cgitb cgitb.enable() pid_data = str(os.getpid()) print "Content-type: text/html" print print """ Test Page Hello World!


""" print "html: "+pid_data+"
" print """ """ If I use I get this for output: Hello World! html: 4900 If I use I get this for output: Hello World! js: pid_data html: 4708 On Wed, Oct 26, 2011 at 17:58, Benjamin Kaplan wrote: > On Wed, Oct 26, 2011 at 6:18 PM, Bill Allen wrote: > > > > I am writing a Python CGI and am needing to pass a data value from Python > to a javascript function. My understanding is that I should use JSON as > the middleman. However, I have not found a good example of doing this. > The piece of data is a simple integer, but I could easily covert that to a > string first if necessary. Here is what I am trying, but unsuccessfully. > I am sure that I have more than one issue in this code. > > > > > > > > #!/usr/bin/python > > > > import json, os, cgi, cgitb > > cgitb.enable() > > > > pid = [{'p':str(os.getpid())}] > > pid_data = json.dumps(pid) > > > > print "Content-type: text/html" > > print > > > > print """ > > > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> > > > > Test Page > > > > > > > > > >

> > > > > > """.format(pid_data) > > > > You're making this much more difficult than it needs to be. JSON is > used for sending data to JavaScript, meaning the JavaScript asks the > server for a bunch of data, the server sends the client JSON, and > everyone is happy. In your case, the information is available when the > javascript is being generated so you can just pass in the number, no > JSON needed. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed Oct 26 22:42:09 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 26 Oct 2011 19:42:09 -0700 Subject: passing Python data to a javascript function In-Reply-To: References: Message-ID: On Wed, Oct 26, 2011 at 7:25 PM, Bill Allen wrote: > > Benjamin, > > I was afraid I was doing that.?? I have simplified it quite a bit, still not > getting the output I am looking for.?? I am down to that I am not passing > the value in the onload=showPID() call correctly.? I know this is getting a > bit far from a Python issue now, but if you have more insight on this, I > would appreciate it.? Is there another way of passing the data from the > Python script to the javascript than what I am doing in this CGI? The problem is that you're not passing the data at all. You never interpolate the pid_data value into the string(s) constituting your embedded JavaScript (though you did do it just fine in the pure HTML). The Python variable `pid_data` is not somehow magically accessible to JavaScript; you must explicitly insert its value somewhere. > pid_data = str(os.getpid()) > print """ > Change that line to: As an example, if the PID happens to be 42, then the outputted fragment will end up being: As a sidenote, I would recommend using something higher-level than the `cgi` module. Python has an abundance of web frameworks and templating languages; take your pick. Cheers, Chris -- http://rebertia.com From rosuav at gmail.com Wed Oct 26 23:05:33 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 27 Oct 2011 14:05:33 +1100 Subject: webapp development in pure python In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF126AA8@EMARC112VS01.exchad.jpmchase.net> References: <4EA6BEC3.5010206@shopzeus.com> <4EA6E4DA.2080307@shopzeus.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF126AA8@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Thu, Oct 27, 2011 at 8:47 AM, Prasad, Ramit wrote: > You technically can connect to databases from JavaScript. It is a terrible idea, but achievable. Not really sure how it would get "compiled" into JavaScript, so it is possible that is the stumbling block. > http://stackoverflow.com/questions/857670/how-to-connect-to-sql-server-database-from-javascript > Strongly recommend against this. I haven't confirmed, but by the look of it the code there is IE-only and MS SQL Server only. Also, remote database access is a major security concern. I would recommend keeping it all on the server (more efficient that way, too). ChrisA From wallenpb at gmail.com Wed Oct 26 23:51:34 2011 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 26 Oct 2011 22:51:34 -0500 Subject: passing Python data to a javascript function In-Reply-To: References: Message-ID: Chris, Wow, that seems so simple now that I see it. I was dancing around that all day, but just not landing on it. Thanks so very much for the assist. --Bill Final code that works perfectly, passes the value from the Python script to the javascript correctly: #!/usr/bin/python import json, os, cgi, cgitb cgitb.enable() pid_data = str(os.getpid()) print "Content-type: text/html" print print """ Test Page Hello World!


""" print "html: "+pid_data+"
" print """ """ Output of above code is the following, which is just the PID of the Python CGI itself at runtime, displayed via javascript and via HTML. Hello World! js: 1308 html: 1308 On Wed, Oct 26, 2011 at 21:42, Chris Rebert wrote: > On Wed, Oct 26, 2011 at 7:25 PM, Bill Allen wrote: > > The problem is that you're not passing the data at all. You never > interpolate the pid_data value into the string(s) constituting your > embedded JavaScript (though you did do it just fine in the pure HTML). > The Python variable `pid_data` is not somehow magically accessible to > JavaScript; you must explicitly insert its value somewhere. > > > > pid_data = str(os.getpid()) > > > print """ > > > > > Change that line to: > > > As an example, if the PID happens to be 42, then the outputted > fragment will end up being: > > > As a sidenote, I would recommend using something higher-level than the > `cgi` module. Python has an abundance of web frameworks and templating > languages; take your pick. > > Cheers, > Chris > -- > http://rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Wed Oct 26 23:55:28 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 27 Oct 2011 14:55:28 +1100 Subject: passing Python data to a javascript function In-Reply-To: References: Message-ID: On Thu, Oct 27, 2011 at 2:51 PM, Bill Allen wrote: > Chris, > > Wow, that seems so simple now that I see it.? I was dancing around that all > day, but just not landing on it.?? Thanks so very much for the assist. > > --Bill > > Final code that works perfectly, passes the value from the Python script to > the javascript correctly: > > Congratulations! You've just written code that writes code. It takes a bit to get your head around it (especially when you start worrying about literal strings that might contain quotes, for instance), but it's really cool and seriously powerful stuff. Your server-side Python code can generate client-side Javascript code any way it likes... unlimited possibilities. ChrisA From dihedral88888 at googlemail.com Thu Oct 27 01:04:09 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Wed, 26 Oct 2011 22:04:09 -0700 (PDT) Subject: webapp development in pure python In-Reply-To: References: <4EA6BEC3.5010206@shopzeus.com> <4EA6E4DA.2080307@shopzeus.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF126AA8@EMARC112VS01.exchad.jpmchase.net> Message-ID: <3173882.1086.1319691849561.JavaMail.geo-discussion-forums@prlk36> I am thinking one has to distinguish between programs for database servers of the commercial applications in banks or insurance companies that cant be hacked in low costs, and experiments to chunk out database servers for games and videos all over the world! From dihedral88888 at googlemail.com Thu Oct 27 01:04:09 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Wed, 26 Oct 2011 22:04:09 -0700 (PDT) Subject: webapp development in pure python In-Reply-To: References: <4EA6BEC3.5010206@shopzeus.com> <4EA6E4DA.2080307@shopzeus.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF126AA8@EMARC112VS01.exchad.jpmchase.net> Message-ID: <3173882.1086.1319691849561.JavaMail.geo-discussion-forums@prlk36> I am thinking one has to distinguish between programs for database servers of the commercial applications in banks or insurance companies that cant be hacked in low costs, and experiments to chunk out database servers for games and videos all over the world! From rosuav at gmail.com Thu Oct 27 01:18:47 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 27 Oct 2011 16:18:47 +1100 Subject: webapp development in pure python In-Reply-To: <3173882.1086.1319691849561.JavaMail.geo-discussion-forums@prlk36> References: <4EA6BEC3.5010206@shopzeus.com> <4EA6E4DA.2080307@shopzeus.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF126AA8@EMARC112VS01.exchad.jpmchase.net> <3173882.1086.1319691849561.JavaMail.geo-discussion-forums@prlk36> Message-ID: On Thu, Oct 27, 2011 at 4:04 PM, 88888 Dihedral wrote: > I am thinking one has to distinguish between programs for database servers of ? the commercial applications in banks or insurance companies that cant be hacked in low costs, and experiments to chunk out database servers for games and videos all over the world! I don't know about that. Best practices are often best for everyone; it's more critical for a bank than for a game server, but that doesn't mean the game server can afford to use swiss cheese as armor plate. Particularly if it's the livelihood of the game designer; in fact, that might even make it _more_ important than for a bank. ChrisA From dihedral88888 at googlemail.com Thu Oct 27 02:37:01 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Wed, 26 Oct 2011 23:37:01 -0700 (PDT) Subject: webapp development in pure python In-Reply-To: References: <4EA6BEC3.5010206@shopzeus.com> <4EA6E4DA.2080307@shopzeus.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF126AA8@EMARC112VS01.exchad.jpmchase.net> <3173882.1086.1319691849561.JavaMail.geo-discussion-forums@prlk36> Message-ID: <27201394.206.1319697421295.JavaMail.geo-discussion-forums@prng5> OK, lets start a framework in using python in the server side and the client side. (1). requirements of the server side first: 1. sending HTML, XML documents to be displayed in the browsers of the clients and receiving for user inputs are easy in modpython, django, and etc. 2. Data received in the server side has to be stored and verified for later accesses performed from client's requests 3. data and traffic amounts to be estimated for the server in order to process requests in terms of numbers of clients and costs per defined operation period, well, a slow database engine that consumes a lot CPU time in the server really sucks! (2). Lets check the client side, too! In scenario 1 the client side has the browser operating only via port 80. In scenario 2 the client side has an AP. that could be invoked in the browser, e.g. Adobe PDF reader or Apple's quick time engine In scenario 3 AP. can invoke the browser to a cyber page in the client side with multiple sockets via TCPIP/UDP of various ports in the AP., e.g. skype, msn, and etc.. Assuming that programmers can use a customized python package installed in the AP. of the client side with other tools is allowed. From dihedral88888 at googlemail.com Thu Oct 27 02:37:01 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Wed, 26 Oct 2011 23:37:01 -0700 (PDT) Subject: webapp development in pure python In-Reply-To: References: <4EA6BEC3.5010206@shopzeus.com> <4EA6E4DA.2080307@shopzeus.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF126AA8@EMARC112VS01.exchad.jpmchase.net> <3173882.1086.1319691849561.JavaMail.geo-discussion-forums@prlk36> Message-ID: <27201394.206.1319697421295.JavaMail.geo-discussion-forums@prng5> OK, lets start a framework in using python in the server side and the client side. (1). requirements of the server side first: 1. sending HTML, XML documents to be displayed in the browsers of the clients and receiving for user inputs are easy in modpython, django, and etc. 2. Data received in the server side has to be stored and verified for later accesses performed from client's requests 3. data and traffic amounts to be estimated for the server in order to process requests in terms of numbers of clients and costs per defined operation period, well, a slow database engine that consumes a lot CPU time in the server really sucks! (2). Lets check the client side, too! In scenario 1 the client side has the browser operating only via port 80. In scenario 2 the client side has an AP. that could be invoked in the browser, e.g. Adobe PDF reader or Apple's quick time engine In scenario 3 AP. can invoke the browser to a cyber page in the client side with multiple sockets via TCPIP/UDP of various ports in the AP., e.g. skype, msn, and etc.. Assuming that programmers can use a customized python package installed in the AP. of the client side with other tools is allowed. From zapyon at gmx.net Thu Oct 27 04:11:15 2011 From: zapyon at gmx.net (Andreas Neudecker) Date: Thu, 27 Oct 2011 10:11:15 +0200 Subject: Philosophical Python: 2*b or not 2*b Message-ID: Not the answers I expected: ;-) >>> b = True >>> 2*b or not 2*b 2 >>> b = False >>> 2*b or not 2*b True It all becomes clear when you look at: >>> b = False >>> 2*b 0 >>> b = True >>> 2*b 2 No surprise there really. But fun anyway. Any more philsophical Python code out there? From zapyon at gmx.net Thu Oct 27 04:23:37 2011 From: zapyon at gmx.net (Andreas Neudecker) Date: Thu, 27 Oct 2011 10:23:37 +0200 Subject: Genehmigt vom Ministerium =?ISO-8859-15?Q?f=FCr_alberne_Gang?= =?ISO-8859-15?Q?arten?= Message-ID: http://blog.stuttgarter-zeitung.de/fundstucke/2011/10/27/genehmigt-vom-ministerium-fur-alberne-gangarten/ From mcepl at redhat.com Thu Oct 27 04:50:04 2011 From: mcepl at redhat.com (mcepl) Date: Thu, 27 Oct 2011 01:50:04 -0700 (PDT) Subject: Presenting recursive dict (json_diff) Message-ID: Hi, I have here a simple script (https://gitorious.org/json_diff/mainline) which makes a diff between two JSON files. So for JSON objects { "a": 1, "b": 2, "son": { "name": "Jano?ek" } } and { "a": 2, "c": 3, "daughter": { "name": "Maru?ka" } } it generates { "append": { "c": 3, "daughter": { "name": "Maru?ka" } }, "remove": { "b": 2, "son": { "name": "Jano?ek" } }, "update": { "a": 2 } } (obvious problems with name conflicts between internal keys and the investigated keys will be somehow addressed later; any simple Pythonic suggestions how?) Now, I would like to create a script (or class) to present such diff object in HTML (and mind you the diffs might be large, hopefully not too much deeply nested, by with many many keys). Any suggestions how to do it? Any libraries to use? I would love to use some templating language, but I am not sure which simple ones (e.g., I like pystache) could do recursive templating. So currently I am tending towards generating strings. I am currently tending towards something like (not cleaned to be CSS- only yet):
  'c' = 3
'b' = 2 --
'a' = 2
children
* son = 'Iv?nek'
* daughter = 'Maru?ka'
but I cannot say I like it. Any suggestions? Thank, Mat?j From faucheuses at gmail.com Thu Oct 27 04:57:55 2011 From: faucheuses at gmail.com (faucheuse) Date: Thu, 27 Oct 2011 01:57:55 -0700 (PDT) Subject: Problem using execvp Message-ID: <1c03dba0-3d9b-47ab-a4fc-b42210ed35ff@o15g2000yqj.googlegroups.com> Hi, I'm trying to launch my python program with another process name than "python.exe". In order to do that I'm trying to use the os.execvp function : os.execvp("./Launch.py", ["ProcessName"]) Launch.py is the file that Launch the program and ProcessName is the ... Process Name ^^ I get this error : OSError : [Errno 8] Exec format error. I searched and found many solutions like : os.execvp("./Launch.py", ["./Launch.py","ProcessName"]), but nothing worked so far. Can you help me plz ? From mcepl at redhat.com Thu Oct 27 05:24:42 2011 From: mcepl at redhat.com (mcepl) Date: Thu, 27 Oct 2011 02:24:42 -0700 (PDT) Subject: Presenting recursive dict (json_diff) References: Message-ID: On 27 ??j, 10:50, mcepl wrote: > Hi, > > I have here a simple script (https://gitorious.org/json_diff/mainline) > which makes a diff between two JSON files. So for JSON objects and I have completely burried to lead on this. The point is that the resulting object can be endlessly recursively nested. On each level I can have not only append/remove/update subobjects, but also number of subtrees. Something like this would be better picture: { "append": { "c": 3 }, "remove": { "b": 2 }, "update": { "a": 2, "children": { "update": { "son": "Iv?nek" }, "append": { "daughter": "Maru?ka" } } } } From hansmu at xs4all.nl Thu Oct 27 05:27:04 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Thu, 27 Oct 2011 11:27:04 +0200 Subject: Problem using execvp In-Reply-To: <1c03dba0-3d9b-47ab-a4fc-b42210ed35ff@o15g2000yqj.googlegroups.com> References: <1c03dba0-3d9b-47ab-a4fc-b42210ed35ff@o15g2000yqj.googlegroups.com> Message-ID: <4ea923e8$0$6863$e4fe514c@news2.news.xs4all.nl> On 27/10/11 10:57:55, faucheuse wrote: > I'm trying to launch my python program with another process name than > "python.exe". Which version of Python are you using? Which version of which operating system? > In order to do that I'm trying to use the os.execvp function : > > os.execvp("./Launch.py", ["ProcessName"]) > > Launch.py is the file that Launch the program and ProcessName is > the ... Process Name ^^ > > I get this error : OSError : [Errno 8] Exec format error. Maybe ./Lauch.py is not executable..... Can you run ./Launch.py from the command line? Does it have a valid shebang line? Is the 'x' bit set? What does "file ./Launch.py" report? > I searched and found many solutions like : os.execvp("./Launch.py", > ["./Launch.py","ProcessName"]), but nothing worked so far. This works for me: os.execvp("./Launch.py", ["ProcessName"]]) -- HansM From candide at free.invalid Thu Oct 27 06:08:45 2011 From: candide at free.invalid (candide) Date: Thu, 27 Oct 2011 12:08:45 +0200 Subject: __dict__ attribute for built-in types Message-ID: <4ea92dae$0$20639$426a74cc@news.free.fr> I realize that built-in types objects don't provide a __dict__ attribute and thereby i can't set an attribute to a such object, for instance >>> a=[42,421] >>> a.foo="bar" Traceback (most recent call last): File "", line 1, in AttributeError: 'list' object has no attribute 'foo' >>> a.__dict__ Traceback (most recent call last): File "", line 1, in AttributeError: 'list' object has no attribute '__dict__' >>> So, i was wondering : -- why this behaviour ? -- where the official documentation refers to this point ? From gelonida at gmail.com Thu Oct 27 06:09:29 2011 From: gelonida at gmail.com (Gelonida N) Date: Thu, 27 Oct 2011 12:09:29 +0200 Subject: python logging multiple processes to one file (via socket server) Message-ID: Hi, I have a rather 'simple' problem. Logging from multiple processes to the same file AND be sure, that no log message is lost, 1.) Log multiple processes to one file: ------------------------------------------ I have a python program, which I want to log, but which forks several times. Due to the forking logging to files with the default logging.FileHandler seems out of question. It seems, that I could use a SocketHandler, which collects data from all different processes and logs then to one file. Does anybody have a working example. 2.) Ensure, that no log message is lost. ------------------------------------------ If I understood the doc of the SocketHandler, then it will drop messages if the socket handler is not available. However for my current activity I would prefer, that it aborts if it cannot connect to the socket and that it blocks if the log server doesn't handle the sent data fast enough. Is this possible. Thanlks a lot in advance. What I found so far: http://docs.python.org/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes It states: "The following section documents this approach in more detail and includes a working socket receiver which can be used as a starting point for you to adapt in your own applications." Somehow I have a mental block though and fail to see the 'following section'. I also found http://code.google.com/p/python-loggingserver/ and ran first tests. However it seems, that this server stops logging my application after about 128 log entries. (the number varies and is not necessarily exactly 128), whereas the console loggier continues logging. I'm not really show why and would prefer a simpler example first. Thanks in advance for any code example, idea, link, comment. From npropadovic at googlemail.com Thu Oct 27 06:27:22 2011 From: npropadovic at googlemail.com (Propad) Date: Thu, 27 Oct 2011 03:27:22 -0700 (PDT) Subject: spawnl issues with Win 7 access rights References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> <4EA6A950.6090706@timgolden.me.uk> <4EA81B72.7040008@timgolden.me.uk> Message-ID: <98460dba-9e08-4d1a-8bf6-4e8fdbea2d0c@19g2000yqk.googlegroups.com> Hello Gentelmen, the suggestion to add the optional second parameter fixed the problem, spawnl now works on the Win 7 computer I'm responsible for (with Python 2.2). So the suggested cause seems to be right. Thank you for the great help! Cheers, Nenad On 26 Okt., 21:20, Terry Reedy wrote: > On 10/26/2011 10:38 AM, Tim Golden wrote: > > > On 26/10/2011 02:11, Terry Reedy wrote: > >> OP reports 2.6 with XP works. > > > Where do you see that, Terry? (Or was there an offlist email?) > > The first message ofhttp://bugs.python.org/issue8036 > "Python 2.6 is however happy and just reports invalid arg." > > -- > Terry Jan Reedy From james.e.m.housden at googlemail.com Thu Oct 27 06:35:47 2011 From: james.e.m.housden at googlemail.com (James Housden) Date: Thu, 27 Oct 2011 03:35:47 -0700 (PDT) Subject: Problem using execvp References: <1c03dba0-3d9b-47ab-a4fc-b42210ed35ff@o15g2000yqj.googlegroups.com> <4ea923e8$0$6863$e4fe514c@news2.news.xs4all.nl> Message-ID: <1b0cfe66-5b53-4294-a2cd-47e81e034c22@hj4g2000vbb.googlegroups.com> On Oct 27, 11:27?am, Hans Mulder wrote: > On 27/10/11 10:57:55, faucheuse wrote: > > > I'm trying to launch my python program with another process name than > > "python.exe". > > Which version of Python are you using? > Which version of which operating system? > > > In order to do that I'm trying to use the os.execvp function : > > > os.execvp("./Launch.py", ["ProcessName"]) > > > Launch.py is the file that Launch the program and ProcessName is > > the ... Process Name ^^ > > > I get this error : OSError : [Errno 8] Exec format error. > > Maybe ./Lauch.py is not executable..... > > Can you run ./Launch.py from the command line? > Does it have a valid shebang line? > Is the 'x' bit set? > What does "file ./Launch.py" report? > > > I searched and found many solutions like : os.execvp("./Launch.py", > > ["./Launch.py","ProcessName"]), but nothing worked so far. > > This works for me: > > ? ? ?os.execvp("./Launch.py", ["ProcessName"]]) > > -- HansM Hello, This worked for me: os.execvp("./Launch.py", ["python", "ProcessName"]) Best regards, James From mail at timgolden.me.uk Thu Oct 27 06:36:17 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 27 Oct 2011 11:36:17 +0100 Subject: spawnl issues with Win 7 access rights In-Reply-To: <98460dba-9e08-4d1a-8bf6-4e8fdbea2d0c@19g2000yqk.googlegroups.com> References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> <4EA6A950.6090706@timgolden.me.uk> <4EA81B72.7040008@timgolden.me.uk> <98460dba-9e08-4d1a-8bf6-4e8fdbea2d0c@19g2000yqk.googlegroups.com> Message-ID: <4EA93421.1090905@timgolden.me.uk> On 27/10/2011 11:27, Propad wrote: > the suggestion to add the optional second parameter fixed the problem, > spawnl now works on the Win 7 computer I'm responsible for (with > Python 2.2). So the suggested cause seems to be right. FWIW, although it's not obvious, the args parameter to spawnl is intended to become the sys.args (in Python terms) of the newly-spawned process. Which is why the first element is expected to be the name of the process. It took me some time to realise this myself :) Anyway, glad we could be of help. TJG From arnodel at gmail.com Thu Oct 27 06:36:54 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Thu, 27 Oct 2011 11:36:54 +0100 Subject: __dict__ attribute for built-in types In-Reply-To: <4ea92dae$0$20639$426a74cc@news.free.fr> References: <4ea92dae$0$20639$426a74cc@news.free.fr> Message-ID: On 27 October 2011 11:08, candide wrote: > I realize that built-in types objects don't provide a __dict__ attribute and > thereby i can't set an attribute to a such object, for instance > > >>>> a=[42,421] >>>> a.foo="bar" > Traceback (most recent call last): > ?File "", line 1, in > AttributeError: 'list' object has no attribute 'foo' >>>> a.__dict__ > Traceback (most recent call last): > ?File "", line 1, in > AttributeError: 'list' object has no attribute '__dict__' >>>> Some built in types have a __dict__: >>> def foo(): pass ... >>> foo.__dict__ {} >>> import random >>> len(random.__dict__) 57 > > So, i was wondering : > > -- why this behaviour ? Performance reasons I guess. > -- where the official documentation refers to this point ? I don't know this one :) -- Arnaud From duncan.booth at invalid.invalid Thu Oct 27 07:03:17 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Oct 2011 11:03:17 GMT Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> Message-ID: candide wrote: > I realize that built-in types objects don't provide a __dict__ attribute > and thereby i can't set an attribute to a such object, for instance > > > >>> a=[42,421] > >>> a.foo="bar" > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'list' object has no attribute 'foo' > >>> a.__dict__ > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'list' object has no attribute '__dict__' > >>> > > > So, i was wondering : > > -- why this behaviour ? Types without a __dict__ use less memory. Also, if you couldn't have a type that didn't have a `__dict__` then any `dict` would also need its own `__dict__` which would either result in infinite memory use or recursive dictionaries. It isn't just built-in types, you can choose for any type you define whether or not to have a '__dict__' attribute >>> class Fixed(object): __slots__ = ('foo', 'bar') readonly = 42 >>> f = Fixed() >>> f.foo, f.bar = 1, 2 >>> f.foo, f.bar, f.readonly (1, 2, 42) >>> f.readonly = 24 Traceback (most recent call last): File "", line 1, in f.readonly = 24 AttributeError: 'Fixed' object attribute 'readonly' is read-only >>> f.baz = 'whatever' Traceback (most recent call last): File "", line 1, in f.baz = 'whatever' AttributeError: 'Fixed' object has no attribute 'baz' > -- where the official documentation refers to this point ? > See http://docs.python.org/reference/datamodel.html for the docs about __slots__ There is also the API documentation which describes at a low level how to control whether or not instances have a dict: http://docs.python.org/c-api/typeobj.html#tp_dictoffset I'm not sure though where you find a higher level statement of which builtin types have a __dict__. -- Duncan Booth http://kupuguy.blogspot.com From paul at subsignal.org Thu Oct 27 08:18:38 2011 From: paul at subsignal.org (=?ISO-8859-1?Q?Paul_K=F6lle?=) Date: Thu, 27 Oct 2011 14:18:38 +0200 Subject: Forking simplejson In-Reply-To: References: Message-ID: Am 26.10.2011 19:34, schrieb Nathan Rice: > Since this happily went off to the wrong recipient the first time... > > The python json module/simpljson are badly in need of an architecture > update. The fact that you can't override the encode method of > JSONEncoder and have it work reliably without monkey patching the pure > python encoder is a sign that something is horribly wrong. +1 I wonder why the builtin json didn't implemented the __json__ hook. Now you need to write encoders for possibly arbitrary (imported/third party) objects.... Looks like it's not so hard to extend json.JSONEncoder to look for __json__ though: >>> import json >>> from functools import partial >>> from types import MethodType >>> class Encoder(json.JSONEncoder): ... def default(self, obj): fn = getattr(obj, '__json__', None) ... if fn and type(fn) == MethodType: ... return obj.__json__() ... return json.JSONEncoder.default(self, obj) ... >>> class T(object): ... def __json__(self): ... return 'foo' ... >>> t = T() >>> dumps = partial(json.dumps, cls=Encoder) >>> dumps(dict([(1,1), (2,2), ('test',t)])) '{"test": "foo", "1": 1, "2": 2}' >>> cheers Paul [snip] From icanbob at gmail.com Thu Oct 27 08:41:18 2011 From: icanbob at gmail.com (bobicanprogram) Date: Thu, 27 Oct 2011 05:41:18 -0700 (PDT) Subject: python logging multiple processes to one file (via socket server) References: Message-ID: <7a3ebd15-5f65-4c3c-8fa0-2cf42bdf5972@i19g2000yqf.googlegroups.com> On Oct 27, 6:09 am, Gelonida N wrote: > Hi, > > I have a rather 'simple' problem. > Logging from multiple processes to the same file AND be sure, that no > log message is lost, > > 1.) Log multiple processes to one file: > ------------------------------------------ > > I have a python program, which I want to log, but which forks several times. > > Due to the forking logging to files with the default logging.FileHandler > seems out of question. > > It seems, that I could use a SocketHandler, which collects data from all > different processes and logs then to one file. > > Does anybody have a working example. > > 2.) Ensure, that no log message is lost. > ------------------------------------------ > If I understood the doc of the SocketHandler, then > it will drop messages if the socket handler is not available. > > However for my current activity I would prefer, that it aborts if it > cannot connect to the socket and that it blocks if the log server > doesn't handle the sent data fast enough. > > Is this possible. > > Thanlks a lot in advance. > > What I found so far:http://docs.python.org/howto/logging-cookbook.html#logging-to-a-singl... > > It states: > "The following section documents this approach in more detail and > includes a working socket receiver which can be used as a starting point > for you to adapt in your own applications." > > Somehow I have a mental block though and fail to see the 'following > section'. > > I also foundhttp://code.google.com/p/python-loggingserver/and ran > first tests. > > However it seems, that this server stops logging my application after > about 128 log entries. (the number varies and is not necessarily exactly > 128), whereas the console loggier continues logging. > > I'm not really show why and would prefer a simpler example first. > > Thanks in advance for any code example, idea, link, comment. You might want to check out the SIMPL toolkit (http:// www.icanprogram.com/06py/main.html). A SIMPL receiver will "naturally" queue and serialize messages from multiple senders. bob From rosuav at gmail.com Thu Oct 27 09:25:19 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Oct 2011 00:25:19 +1100 Subject: __dict__ attribute for built-in types In-Reply-To: References: <4ea92dae$0$20639$426a74cc@news.free.fr> Message-ID: On Thu, Oct 27, 2011 at 10:03 PM, Duncan Booth wrote: > Types without a __dict__ use less memory. Also, if you couldn't have a > type that didn't have a `__dict__` then any `dict` would also need its > own `__dict__` which would either result in infinite memory use or > recursive dictionaries. > Easy, just self-reference. a = {} a.__dict__ is a --> True Yeah, it's recursion, but no different from types: >>> type(type) is type True If you want this behavior, you can do it easily enough. >>> class dictdict(dict): def __init__(self): self.__dict__=self >>> a=dictdict() >>> a.__dict__ is a True However, the more compelling argument is that a __slots__ object can be WAY more efficient. ChrisA From amirouche.boubekki at gmail.com Thu Oct 27 09:55:15 2011 From: amirouche.boubekki at gmail.com (Amirouche Boubekki) Date: Thu, 27 Oct 2011 15:55:15 +0200 Subject: Forking simplejson In-Reply-To: References: Message-ID: > +-------------------+---------------+ >> | Python protocol | JSON | >> | or special case | | >> +===================+=========**======+ >> | (?) __json__ | see (?) | >> +-------------------+---------**------| >> | map | object | >> > > I am curious what you mean by the 'map' protocol. I mean dictionnary-like objects -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwa at kuwata-lab.com Thu Oct 27 10:00:59 2011 From: kwa at kuwata-lab.com (Makoto Kuwata) Date: Thu, 27 Oct 2011 23:00:59 +0900 Subject: [ANN] pyKook 0.6.0 - task automation tool for Python, similar to Rake or Ant Message-ID: Hi, I have released pyKook 0.6.0. http://pypi.python.org/pypi/Kook/0.6.0 http://www.kuwata-lab.com/kook/ http://www.kuwata-lab.com/kook/pykook-users-guide.html In this release, a lot of enhancements are introduced. pyKook Overview --------------- pyKook is a task automation tool for Python, similar to Rake or Ant. (Kookbook.py): kookbook.default = 'build' @recipe(None, ['hello']) def build(c): """build all""" pass @recipe('hello', ['hello.o']) def file_hello(c): """build 'hello' from 'hello.o'""" system(c%'gcc -o $(product) $(ingred)') @recipe('*.o', ['$(1).c', '$(1).h']) def file_o(c): system(c%'gcc -c $(ingred)') Command-line: bash> kk # or pykook $ gcc -c hello.c ### *** hello.o (recipe=file_o) $ gcc -c hello.c ### ** hello (recipe=file_hello) $ gcc -o hello hello.o ### * build (recipe=build) See http://www.kuwata-lab.com/kook/pykook-users-guide.html for details. Enhancements in this release ---------------------------- * 'kookbook' variable is available in your cookbook to specify materials or default product. * Recipe meta-programming support. You can manipulate recipe objects directly. * Load other cookbooks by kookbook.load(). This enables you to split your Kookbook.py into several files. * Support some useful task recipes: clean, sweep, and all. * Namespace is now supported. It is called as 'Category' in Kook. * Concatenation supported. You can concatenate your cookbook and pyKook libraries into a file. Using concatenated file, user doesn't need to install pyKook at all. * Argument description is available. * Private spice option is available. * New command 'pushd()' provided. See http://www.kuwata-lab.com/kook/pykook-CHANGES.txt for details. Have fun! -- regards, makoto kuwata From candide at free.invalid Thu Oct 27 10:01:25 2011 From: candide at free.invalid (candide) Date: Thu, 27 Oct 2011 16:01:25 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: References: <4ea92dae$0$20639$426a74cc@news.free.fr> Message-ID: <4ea96437$0$24971$426a74cc@news.free.fr> Le 27/10/2011 13:03, Duncan Booth a ?crit : > >> -- where the official documentation refers to this point ? >> > See http://docs.python.org/reference/datamodel.html for the docs about > __slots__ > > There is also the API documentation which describes at a low level how > to control whether or not instances have a dict: > http://docs.python.org/c-api/typeobj.html#tp_dictoffset > > I'm not sure though where you find a higher level statement of which > builtin types have a __dict__. > OK, thanks for the information abouts the slots. Nevertheless, this cannot answer completely my question. Some builtin types like string, lists, integer, float, dictionaries, etc have the property that instances of those types don't provide a __dict__ attribute. I can't imagine the documentation lets pass silently this point. But beside this, how to recognise classes whose object doesn't have a __dict__ attribute ? From clp2 at rebertia.com Thu Oct 27 10:07:12 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 Oct 2011 07:07:12 -0700 Subject: Forking simplejson In-Reply-To: References: Message-ID: On Thu, Oct 27, 2011 at 6:55 AM, Amirouche Boubekki wrote: > >>> +-------------------+---------------+ >>> | Python protocol | JSON | >>> | or special case | | >>> +===================+===============+ >>> | (?) __json__ | see (?) | >>> +-------------------+---------------| >>> ? ? ?| map ? ? ? ? ? ? ? | object ? ? ? ?| >> >> I am curious what you mean by the 'map' protocol. > > I mean dictionnary-like objects How do you propose to detect such objects? isinstance(x, collections.Mapping) ? Cheers, Chris From clp2 at rebertia.com Thu Oct 27 10:16:46 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 Oct 2011 07:16:46 -0700 Subject: Forking simplejson In-Reply-To: References: Message-ID: On Wed, Oct 26, 2011 at 2:14 AM, Amirouche Boubekki wrote: > H?llo, > > I would like to fork simplejson [1] and implement serialization rules based > on protocols instead of types [2], plus special cases for protocol free > objects, that breaks compatibility. The benefit will be a better API for > json serialization of custom classes and in the case of iterable it will > avoid a calls like: > >>>> simplejson.dumps(list(my_iterable)) > > The serialization of custom objects is documented in the class instead of > the ``default`` function of current simplejson implementation [3]. > > The encoding algorithm works with a priority list that is summarized in the > next table: > > +-------------------+---------------+ > | Python protocol | JSON | > | or special case | | > +===================+===============+ > | (?) unicode | see (?) | > (?) if the algorithm arrives here, call unicode (with proper encoding rule) > on the object and use the result as json serialization I would prefer a TypeError in such cases, for the same reason str.join() doesn't do an implicit str() on its operands: - Explicit is better than implicit. - (Likely) errors should never pass silently. - In the face of ambiguity, refuse the temptation to guess. Cheers, Chris -- http://rebertia.com From johnroth1 at gmail.com Thu Oct 27 10:18:25 2011 From: johnroth1 at gmail.com (John Roth) Date: Thu, 27 Oct 2011 07:18:25 -0700 (PDT) Subject: inserting \ in regular expressions References: <1319658482.13425.9.camel@corn.betterworld.us> Message-ID: <4ffb88f5-eeb3-4eb8-a481-94f852be81f2@p20g2000prm.googlegroups.com> On Oct 26, 2:47?pm, Dave Angel wrote: > On 10/26/2011 03:48 PM, Ross Boylan wrote: > > > > > > > > > I want to replace every \ and " (the two characters for backslash and > > double quotes) with a \ and the same character, i.e., > > \ -> ?\\ > > " -> ?\" > > > I have not been able to figure out how to do that. ?The documentation > > for re.sub says "repl can be a string or a function; if it is a string, > > any backslash escapes in it are processed.That is, \n is converted to a > > single newline character, \r is converted to a carriage return, and so > > forth. Unknown escapes such as \j are left alone." > > > \\ is apparently unknown, and so is left as is. So I'm unable to get a > > single \. > > > Here are some tries in Python 2.5.2. ?The document suggested the result > > of a function might not be subject to the same problem, but it seems to > > be. > >>>> def f(m): > > ... ? ?return "\\"+m.group(1) > > ... > >>>> re.sub(r"([\\\"])", f, 'Silly " quote') > > 'Silly \\" quote' > > > >>> re.sub(r"([\\\"])", "\\\\\\1", 'Silly " quote') > > 'Silly \\" quote' > > > Or perhaps I'm confused about what the displayed results mean. ?If a > > string has a literal \, does it get shown as \\? > > > I'd appreciate it if you cc me on the reply. > > > Thanks. > > Ross Boylan > > I can't really help on the regex aspect of your code, but I can tell you > a little about backslashes, quote literals, the interpreter, and python. > > > ? Now, one way to cheat on the string if you know you'll want to put > actual backslashes is to use the raw string. That works quite well > unless you want the string to end with a backslash. ?There isn't a way > to enter that as a single raw literal. ?You'd have to do something > string like > ? ? ? a = r"strange\literal\with\some\stuff" + "\\" > > My understanding is that no valid regex ends with a backslash, so this > may not affect you. > > -- > > DaveA Dave's answer is excellent background. I've snipped everything except the part I want to emphasize, which is to use raw strings. They were put into Python specifically for your problem: that is, how to avoid the double and triple backslashes while writing regexes. John Roth From duncan.booth at invalid.invalid Thu Oct 27 10:36:19 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Oct 2011 14:36:19 GMT Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> Message-ID: Chris Angelico wrote: > On Thu, Oct 27, 2011 at 10:03 PM, Duncan Booth > wrote: >> Types without a __dict__ use less memory. Also, if you couldn't have a >> type that didn't have a `__dict__` then any `dict` would also need its >> own `__dict__` which would either result in infinite memory use or >> recursive dictionaries. >> > > Easy, just self-reference. > a = {} > a.__dict__ is a --> True > > Yeah, it's recursion, but no different from types: > Try thinking that one through. Imagine you could set up a dictionary the way you describe: >>> class DictWithDict(dict): def __init__(self, *args, **kw): dict.__init__(self, *args, **kw) self.__dict__ = self >>> d = DictWithDict() >>> d.keys() dict_keys([]) >>> d = DictWithDict({'a': 42}) >>> d.keys() dict_keys(['a']) >>> d['keys'] = lambda: 'oops' >>> d.keys() 'oops' >>> A dict with itself as its own __dict__ becomes like a javascript object where subscripting and attribute access are mostly interchangeable. -- Duncan Booth http://kupuguy.blogspot.com From vinay_sajip at yahoo.co.uk Thu Oct 27 11:07:39 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Thu, 27 Oct 2011 08:07:39 -0700 (PDT) Subject: python logging multiple processes to one file (via socket server) References: Message-ID: <15e35c86-588e-4da3-ad59-abaa5d7c25dd@g21g2000yqc.googlegroups.com> On Oct 27, 11:09?am, Gelonida N wrote: > "The following section documents this approach in more detail and > includes a working socket receiver which can be used as a starting point > for you to adapt in your own applications." > > Somehow I have a mental block though and fail to see the 'following > section'. You're right, the link got lost in a reorganisation of the documentation. Working example is here: http://docs.python.org/howto/logging-cookbook.html#sending-and-receiving-logging-events-across-a-network Regards, Vinay Sajip From amirouche.boubekki at gmail.com Thu Oct 27 11:24:24 2011 From: amirouche.boubekki at gmail.com (Amirouche Boubekki) Date: Thu, 27 Oct 2011 17:24:24 +0200 Subject: Forking simplejson In-Reply-To: References: Message-ID: 2011/10/27 Chris Rebert > On Wed, Oct 26, 2011 at 2:14 AM, Amirouche Boubekki > wrote: > > H?llo, > > > > I would like to fork simplejson [1] and implement serialization rules > based > > on protocols instead of types [2], plus special cases for protocol free > > objects, that breaks compatibility. The benefit will be a better API for > > json serialization of custom classes and in the case of iterable it will > > avoid a calls like: > > > >>>> simplejson.dumps(list(my_iterable)) > > > > The serialization of custom objects is documented in the class instead of > > the ``default`` function of current simplejson implementation [3]. > > > > The encoding algorithm works with a priority list that is summarized in > the > > next table: > > > > +-------------------+---------------+ > > | Python protocol | JSON | > > | or special case | | > > +===================+===============+ > > > | (?) unicode | see (?) | > > > (?) if the algorithm arrives here, call unicode (with proper encoding > rule) > > on the object and use the result as json serialization > > I would prefer a TypeError in such cases, for the same reason > str.join() doesn't do an implicit str() on its operands: > - Explicit is better than implicit. > - (Likely) errors should never pass silently. > - In the face of ambiguity, refuse the temptation to guess. > granted it's better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ladasky at my-deja.com Thu Oct 27 11:37:07 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 27 Oct 2011 08:37:07 -0700 (PDT) Subject: Philosophical Python: 2*b or not 2*b References: Message-ID: <7699e647-98fb-4a6e-aff4-1694d06fd705@h39g2000prh.googlegroups.com> On Oct 27, 1:11?am, Andreas Neudecker wrote: > Any more philsophical Python code out there? That is the question. From amirouche.boubekki at gmail.com Thu Oct 27 11:49:20 2011 From: amirouche.boubekki at gmail.com (Amirouche Boubekki) Date: Thu, 27 Oct 2011 17:49:20 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: <4ea92dae$0$20639$426a74cc@news.free.fr> References: <4ea92dae$0$20639$426a74cc@news.free.fr> Message-ID: 2011/10/27 candide > I realize that built-in types objects don't provide a __dict__ attribute > and thereby i can't set an attribute to a such object, for instance > > > >>> a=[42,421] > >>> a.foo="bar" > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'list' object has no attribute 'foo' > >>> a.__dict__ > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'list' object has no attribute '__dict__' > >>> > > > So, i was wondering : > > -- why this behaviour ? > performance > -- where the official documentation refers to this point ? > it's here and there in python documentation. I did not find specific documentation about the __dict__ property. Have a look at : - naming conventions in http://www.python.org/dev/peps/pep-0008/ - http://docs.python.org/library/stdtypes.html#modules __dict__ is similar to other __*__ properties and has a function that actually use it to do something usefull aka. dir http://docs.python.org/library/functions.html#dir The way I understand it is that it's for internal use but it's exposed for debugging (and learning ?) purpose. -------------- next part -------------- An HTML attachment was scrubbed... URL: From amirouche.boubekki at gmail.com Thu Oct 27 11:53:40 2011 From: amirouche.boubekki at gmail.com (Amirouche Boubekki) Date: Thu, 27 Oct 2011 17:53:40 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: <4ea96437$0$24971$426a74cc@news.free.fr> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> Message-ID: > But beside this, how to recognise classes whose object doesn't have a > __dict__ attribute ? > Why do you need to access __dict__ ? maybe dir is enough see the other message -------------- next part -------------- An HTML attachment was scrubbed... URL: From c.m.ackerman at gmail.com Thu Oct 27 12:29:10 2011 From: c.m.ackerman at gmail.com (quarterlife) Date: Thu, 27 Oct 2011 09:29:10 -0700 (PDT) Subject: xmlrpclib threadsafe? Message-ID: I need to talk to an xmlrpc server. I open one connection and then create a pile of threads communicating to that server. Based on some limited testing, it seems to work really well. The next step is to turn it into a pool. But before I continue, the question is: Does anyone know if the xmlrpclib is really threadsafe? From dihedral88888 at googlemail.com Thu Oct 27 13:35:37 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Thu, 27 Oct 2011 10:35:37 -0700 (PDT) Subject: python logging multiple processes to one file (via socket server) In-Reply-To: <15e35c86-588e-4da3-ad59-abaa5d7c25dd@g21g2000yqc.googlegroups.com> References: <15e35c86-588e-4da3-ad59-abaa5d7c25dd@g21g2000yqc.googlegroups.com> Message-ID: <25498691.487.1319736937890.JavaMail.geo-discussion-forums@prfp13> Well, please check the byte code compiled results. This is useful. I know that a lot people are working on increasing the speed of execution scripts written in python, say, psyco, pyrex for packages released! From missive at hotmail.com Thu Oct 27 15:38:29 2011 From: missive at hotmail.com (Lee Harr) Date: Fri, 28 Oct 2011 00:08:29 +0430 Subject: Need Windows user / developer to help with Pynguin Message-ID: I develop the free python-based turtle graphics application pynguin. http://pynguin.googlecode.com/ Lately I have been getting a lot of positive comments from people who use the program, but I am also getting a lot of feedback from people on Windows (mostly beginners) who are having trouble getting the program running. I don't use Windows myself, though I have found access occasionally to fix bugs. I just don't know enough about Windows culture to be able to make a reliable method for installing or running the program. The method that I wrote for Linux also works on Windows, but it has to be run from the command prompt. I am hoping someone can look at what is there and come up with a reliable method or a simple set of steps that people can follow to get up and running. Hopefully without having to resort to the command prompt. I started a wiki page here: http://code.google.com/p/pynguin/wiki/InstallingPynguinOnWindows but I can't even test if it actually works.... Thanks for any help. From bahamutzero8825 at gmail.com Thu Oct 27 15:47:35 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Thu, 27 Oct 2011 14:47:35 -0500 Subject: Need Windows user / developer to help with Pynguin In-Reply-To: References: Message-ID: <4EA9B557.20100@gmail.com> On 10/27/2011 2:38 PM, Lee Harr wrote: > I am hoping someone can look at what is there and come up with a > reliable method or a simple set of steps that people can follow to get > up and running. Hopefully without having to resort to the command > prompt. > > I started a wiki page here: > http://code.google.com/p/pynguin/wiki/InstallingPynguinOnWindows > but I can't even test if it actually works.... > > > Thanks for any help. Apparently, the US is a forbidden country and Google won't let me download. Otherwise, I'd test it for you. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 From tjreedy at udel.edu Thu Oct 27 15:49:47 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Oct 2011 15:49:47 -0400 Subject: Presenting recursive dict (json_diff) In-Reply-To: References: Message-ID: On 10/27/2011 4:50 AM, mcepl wrote: > Hi, > > I have here a simple script (https://gitorious.org/json_diff/mainline) > which makes a diff between two JSON files. So for JSON objects > > { > "a": 1, > "b": 2, > "son": { > "name": "Jano?ek" > } > } > > and > > { > "a": 2, > "c": 3, > "daughter": { > "name": "Maru?ka" > } > } > > it generates > > { > "append": { > "c": 3, > "daughter": { > "name": "Maru?ka" > } > }, > "remove": { > "b": 2, > "son": { > "name": "Jano?ek" > } > }, > "update": { > "a": 2 > } > } > > (obvious problems with name conflicts between internal keys and the > investigated keys will be somehow addressed later; any simple Pythonic > suggestions how?) Use '_append', etc, much like namedtuple does, for the same reason. -- Terry Jan Reedy From tjreedy at udel.edu Thu Oct 27 15:53:30 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Oct 2011 15:53:30 -0400 Subject: spawnl issues with Win 7 access rights In-Reply-To: <4EA93421.1090905@timgolden.me.uk> References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> <4EA6A950.6090706@timgolden.me.uk> <4EA81B72.7040008@timgolden.me.uk> <98460dba-9e08-4d1a-8bf6-4e8fdbea2d0c@19g2000yqk.googlegroups.com> <4EA93421.1090905@timgolden.me.uk> Message-ID: On 10/27/2011 6:36 AM, Tim Golden wrote: > On 27/10/2011 11:27, Propad wrote: >> the suggestion to add the optional second parameter fixed the problem, >> spawnl now works on the Win 7 computer I'm responsible for (with >> Python 2.2). So the suggested cause seems to be right. > > FWIW, although it's not obvious, the args parameter to spawnl > is intended to become the sys.args (in Python terms) of the > newly-spawned process. Which is why the first element is expected > to be the name of the process. It took me some time to realise > this myself :) > > Anyway, glad we could be of help. Can we make this fix automatic for Win7 to fix #8036? -- Terry Jan Reedy From dingbat at codesmiths.com Thu Oct 27 15:59:57 2011 From: dingbat at codesmiths.com (Andy Dingley) Date: Thu, 27 Oct 2011 12:59:57 -0700 (PDT) Subject: Dynamically creating properties? Message-ID: I have some XML, with a variable and somewhat unknown structure. I'd like to encapsulate this in a Python class and expose the text of the elements within as properties. How can I dynamically generate properties (or methods) and add them to my class? I can easily produce a dictionary of the required element names and their text values, but how do I create new properties at run time? Thanks, From gordon at panix.com Thu Oct 27 16:14:47 2011 From: gordon at panix.com (John Gordon) Date: Thu, 27 Oct 2011 20:14:47 +0000 (UTC) Subject: Dynamically creating properties? References: Message-ID: In Andy Dingley writes: > How can I dynamically generate properties (or methods) and add them to > my class? I can easily produce a dictionary of the required element > names and their text values, but how do I create new properties at run > time? You can set dynamic attributes on class objects without any special processing at all. Just do it, like so: class X(object): pass myx = X() myx.color = 'red' myx.food = 'french fries' myx.lucky_number = 7 Or, if you don't know the attribute name beforehand: setattr(myx, 'occupation', 'programmer') For methods, use an existing method name (without the trailing parentheses) as the attribute value, like so: myx.method = float # assigns the built-in method float() -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From pmaupin at gmail.com Thu Oct 27 16:34:28 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 27 Oct 2011 13:34:28 -0700 (PDT) Subject: Assigning generator expressions to ctype arrays Message-ID: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> Bug or misunderstanding? Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> x = 32 * [0] >>> x[:] = (x for x in xrange(32)) >>> from ctypes import c_uint >>> x = (32 * c_uint)() >>> x[:] = xrange(32) >>> x[:] = (x for x in xrange(32)) Traceback (most recent call last): File "", line 1, in ValueError: Can only assign sequence of same size >>> Thanks, Pat From mcepl at redhat.com Thu Oct 27 16:58:45 2011 From: mcepl at redhat.com (Matej Cepl) Date: Thu, 27 Oct 2011 22:58:45 +0200 Subject: Presenting recursive dict (json_diff) In-Reply-To: References: Message-ID: Dne 27.10.2011 21:49, Terry Reedy napsal(a): > Use '_append', etc, much like namedtuple does, for the same reason. Right, done. What about the presentation issue? Any ideas? Best, Mat?j From devplayer at gmail.com Thu Oct 27 17:48:54 2011 From: devplayer at gmail.com (DevPlayer) Date: Thu, 27 Oct 2011 14:48:54 -0700 (PDT) Subject: Dynamically creating properties? References: Message-ID: On Oct 27, 3:59?pm, Andy Dingley wrote: > I have some XML, with a variable and somewhat unknown structure. I'd > like to encapsulate this in a Python class and expose the text of the > elements within as properties. > > How can I dynamically generate properties (or methods) and add them to > my class? ?I can easily produce a dictionary of the required element > names and their text values, but how do I create new properties at run > time? > > Thanks, class MyX(object): pass myx = myx() xml_tag = parse( file.readline() ) # should be a valid python named-reference syntax, # although any object that can be a valid dict key is allowed. # generally valid python named reference would be the answer to your question attribute = validate( xml_tag ) # dynamicly named property setattr( myx, attribute, property(get_func, set_func, del_func, attr_doc) ) # "dynamicly named method" # really should be a valid python named-reference syntax myfunc_name = validate(myfunc_name) def somefunc(x): return x+x # or somefunc = lambda x: x + x setattr( myx, myfunc_name, somefunc ) So beaware of: # \\\\\\\\\\\\\\\\\\\\\\\\\ setattr(myx, '1', 'one') myx.1 File "", line 1 x.1 ^ SyntaxError: invalid syntax # \\\\\\\\\\\\\\\\\\\\\\\\\ x.'1' File "", line 1 x.'1' ^ SyntaxError: invalid syntax # \\\\\\\\\\\\\\\\\\\\\\\\\ x.__dict__['1'] # returns 'one' x.__dict__ # returns {'1': 'one'} So you should validate your variable names if you are getting them from somewhere. From steve+comp.lang.python at pearwood.info Thu Oct 27 18:19:18 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 27 Oct 2011 22:19:18 GMT Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> Message-ID: <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> On Thu, 27 Oct 2011 16:01:25 +0200, candide wrote: > OK, thanks for the information abouts the slots. Nevertheless, this > cannot answer completely my question. Some builtin types like string, > lists, integer, float, dictionaries, etc have the property that > instances of those types don't provide a __dict__ attribute. I can't > imagine the documentation lets pass silently this point. What, you think it goes against the laws of physics that nobody thought to mention it in the docs? > But beside this, how to recognise classes whose object doesn't have a > __dict__ attribute ? The same way as you would test for any other attribute. >>> hasattr(42, '__dict__') False -- Steven From steve+comp.lang.python at pearwood.info Thu Oct 27 18:31:45 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 27 Oct 2011 22:31:45 GMT Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> Message-ID: <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> On Thu, 27 Oct 2011 13:34:28 -0700, Patrick Maupin wrote: > Bug or misunderstanding? > > Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> x = 32 * [0] >>>> x[:] = (x for x in xrange(32)) >>>> from ctypes import c_uint >>>> x = (32 * c_uint)() >>>> x[:] = xrange(32) >>>> x[:] = (x for x in xrange(32)) > Traceback (most recent call last): > File "", line 1, in > ValueError: Can only assign sequence of same size >From the outside, you can't tell how big a generator expression is. It has no length: >>> g = (x for x in xrange(32)) >>> len(g) Traceback (most recent call last): File "", line 1, in TypeError: object of type 'generator' has no len() Since the array object has no way of telling whether the generator will have the correct size, it refuses to guess. I would argue that it should raise a TypeError with a less misleading error message, rather than a ValueError, so "bug". The simple solution is to use a list comp instead of a generator expression. If you have an arbitrary generator passed to you from the outside, and you don't know how long it is yourself, you can use itertools.islice to extract just the number of elements you want. Given g some generator expression, rather than doing this: # risky, if g is huge, the temporary list will also be huge x[:] = list(g)[:32] do this instead: # use lazy slices guaranteed not to be unexpectedly huge x[:] = list(itertools.islice(g, 32)) -- Steven From missive at hotmail.com Thu Oct 27 18:36:17 2011 From: missive at hotmail.com (Lee Harr) Date: Fri, 28 Oct 2011 03:06:17 +0430 Subject: Need Windows user / developer to help with Pynguin Message-ID: >> I started a wiki page here:????????????????????????????????????????????????????????????????????????????????????????????????? >> http://code.google.com/p/pynguin/wiki/InstallingPynguinOnWindows???????????????????????????????????????????????????????????? >> but I can't even test if it actually works....?????????????????????????????????????????????????????????????????????????????? > Apparently, the US is a forbidden country and Google won't let me????????????????????????????????????????????????????????????? > download. Otherwise, I'd test it for you. I don't understand. Where are you located? What message do you get when trying to download? From rosuav at gmail.com Thu Oct 27 18:39:34 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Oct 2011 09:39:34 +1100 Subject: __dict__ attribute for built-in types In-Reply-To: References: <4ea92dae$0$20639$426a74cc@news.free.fr> Message-ID: On Fri, Oct 28, 2011 at 1:36 AM, Duncan Booth wrote: > Try thinking that one through. Imagine you could set up a dictionary the > way you describe > > A dict with itself as its own __dict__ becomes like a javascript object > where subscripting and attribute access are mostly interchangeable. Yeah; I never said it was a good thing, just that it's possible. "Everything is permissible" - but not everything is beneficial. "Everything is permissible" - but not everything is constructive. (1 Corinthians 10:23, NIV translation.) ChrisA From candide at free.invalid Thu Oct 27 18:52:40 2011 From: candide at free.invalid (candide) Date: Fri, 28 Oct 2011 00:52:40 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4ea9e0ba$0$2261$426a74cc@news.free.fr> Le 28/10/2011 00:19, Steven D'Aprano a ?crit : > > What, you think it goes against the laws of physics that nobody thought > to mention it in the docs? No but I'm expecting from Python documentation to mention the laws of Python ... > >> But beside this, how to recognise classes whose object doesn't have a >> __dict__ attribute ? > > The same way as you would test for any other attribute. > >>>> hasattr(42, '__dict__') > False > > OK but I'm talking about classes, not instances : 42 has no __dict__ attribute but, may be, 43 _has_ such attribute, who knows in advance ? ;) Let'have a try : >>> hasattr(43, '__dict__') False >>> so we have proved by induction that no integer instance has a dictionnary attribute ;) From hniksic at xemacs.org Thu Oct 27 18:57:36 2011 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 28 Oct 2011 00:57:36 +0200 Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> Message-ID: <87pqhi2gbj.fsf@xemacs.org> candide writes: > But beside this, how to recognise classes whose object doesn't have a > __dict__ attribute ? str, list and others aren't classes, they are types. While all (new-style) classes are types, not all types are classes. It's instances of classes (types created by executing the "class" statement or its equivalent) that automatically get a __dict__, unless __slots__ was used at class definition time to suppress it. Built-in and extension types can choose whether to implement __dict__. (Mechanics of defining built-in and extension types are of course implementation-specific. CPython allows adding __dict__ to any extension type by setting the tp_dictoffset member of the type definition struct to the appropriate offset into the instance struct.) From devplayer at gmail.com Thu Oct 27 19:00:57 2011 From: devplayer at gmail.com (DevPlayer) Date: Thu, 27 Oct 2011 16:00:57 -0700 (PDT) Subject: Dynamically creating properties? References: Message-ID: Personally I like to use this function instead of a "try: except:" because try-except will allow names like __metaclass__. Remember, setattr(obj, attr_name, value) allows attr_name to be any valid str(). For example: '!@kdafk11', or '1_1', '1e-20', '0.0', '*one', '\n%%', etc. def isvalid_named_reference( astring ): # "varible name" is really a named_reference # import string # would be cleaner valid_first_char = '_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' valid_rest = '_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' # I think it's ok here for the rare type-check # as unicode named-references are not allowed if type(astring) is not str: return False if len(astring) == 0: return False if astring[0] not in valid_first_char: return False for c in astring[1:]: if c not in valid_rest: return False # Python keywords not allowed as named references (variable names) for astr in ['and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'yield',]: if astring == astr: return False # valid names but bad idea if astring == '__builtins__': return None if astring == '__metaclass__': return None for astr in dir(__builtins__): if astring == astr: return None # use None as a warning # there might be more like __slots__, and other # module level effecting special names like '__metaclass__' return True Also when using dynamically created "varible names" to check if your objects have an attribute with that name already. From devplayer at gmail.com Thu Oct 27 19:15:01 2011 From: devplayer at gmail.com (DevPlayer) Date: Thu, 27 Oct 2011 16:15:01 -0700 (PDT) Subject: Dynamically creating properties? References: Message-ID: <43b77f11-fc3e-4e73-8e94-9ad43e2f6d49@a17g2000yqj.googlegroups.com> At least one error: change: > for astr in dir(__builtins__): to: for astr in __builtins__.__dict__: From candide at free.invalid Thu Oct 27 19:36:41 2011 From: candide at free.invalid (candide) Date: Fri, 28 Oct 2011 01:36:41 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: <87pqhi2gbj.fsf@xemacs.org> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <87pqhi2gbj.fsf@xemacs.org> Message-ID: <4ea9eb0b$0$637$426a34cc@news.free.fr> Le 28/10/2011 00:57, Hrvoje Niksic a ?crit : > was used at class definition time to suppress it. Built-in and > extension types can choose whether to implement __dict__. > Is it possible in the CPython implementation to write something like this : "foo".bar = 42 without raising an attribute error ? From python at mrabarnett.plus.com Thu Oct 27 20:02:52 2011 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 28 Oct 2011 01:02:52 +0100 Subject: __dict__ attribute for built-in types In-Reply-To: <4ea9eb0b$0$637$426a34cc@news.free.fr> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <87pqhi2gbj.fsf@xemacs.org> <4ea9eb0b$0$637$426a34cc@news.free.fr> Message-ID: <4EA9F12C.8030904@mrabarnett.plus.com> On 28/10/2011 00:36, candide wrote: > Le 28/10/2011 00:57, Hrvoje Niksic a ?crit : > >> was used at class definition time to suppress it. Built-in and >> extension types can choose whether to implement __dict__. >> > > Is it possible in the CPython implementation to write something like this : > > "foo".bar = 42 > > without raising an attribute error ? No, built-in classes written in C have certain limitations, but why would you want to do that anyway? From pmaupin at gmail.com Thu Oct 27 20:09:34 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 27 Oct 2011 17:09:34 -0700 (PDT) Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> On Oct 27, 5:31?pm, Steven D'Aprano wrote: > From the outside, you can't tell how big a generator expression is. It has no length: I understand that. > Since the array object has no way of telling whether the generator will have the correct size, it refuses to guess. It doesn't have to guess. It can assume that I, the programmer, know what the heck I am doing, and then validate that assumption -- trust, but verify. It merely needs to fill the slice and then ask for one more and check that StopIteration is raised. > I would argue that it should raise a TypeError > with a less misleading error message, rather > than a ValueError, so "bug". And I would argue that it should simply work, unless someone can present a more compelling reason why not. > The simple solution is to use a list comp > instead of a generator expression. I know how to work around the issue. I'm not sure I should have to. It violates the principle of least surprise for the ctypes array to not be able to interoperate with the iterator protocol in this fashion. Regards, Pat From devplayer at gmail.com Thu Oct 27 20:35:14 2011 From: devplayer at gmail.com (DevPlayer) Date: Thu, 27 Oct 2011 17:35:14 -0700 (PDT) Subject: Dynamically creating properties? References: <43b77f11-fc3e-4e73-8e94-9ad43e2f6d49@a17g2000yqj.googlegroups.com> Message-ID: Second error def isvalid_named_reference( astring ): # "varible name" is really a named_reference import __builtin__ # add line From stevenbird1 at gmail.com Thu Oct 27 21:21:10 2011 From: stevenbird1 at gmail.com (Steven Bird) Date: Fri, 28 Oct 2011 12:21:10 +1100 Subject: NLTK and package structure Message-ID: The Natural Language Toolkit (NLTK) is a suite of open source Python packages for natural language processing, available at http://nltk.org/, together with an O'Reilly book which is available online for free. Development is now hosted at http://github.com/nltk -- get it here: git at github.com:nltk/nltk.git I am seeking advice on how to speed up our import process. The contents of several sub-packages are made available at the top level, for the convenience of programmers and so that the examples published in the book are more concise. This has been done by having lots of "from subpackage import *" in the top-level __init__.py. Some of these imports are lazy. Unfortunately, any import of nltk leads to cascading imports which pull in most of the library, unacceptably slowing down the load time. https://github.com/nltk/nltk/blob/master/nltk/__init__.py I am looking for a solution that meets the following requirements: 1) import nltk is as fast as possible 2) published code examples are not broken (or are easily fixed by calling nltk.load_subpackages() before the rest of the code) 3) popular subpackage names are available at the top level (e.g. nltk.probability.ConditionalFreqDist as nltk.ConditionalFreqDist) The existing discussion of this issue amongst our developers is posted here: http://code.google.com/p/nltk/issues/detail?id=378 Our practice in structuring subpackages is described here: http://code.google.com/p/nltk/wiki/PackageStructure Thanks for any advice. -Steven Bird (NLTK Project coordinator) From nobody at nowhere.com Thu Oct 27 22:00:28 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 28 Oct 2011 03:00:28 +0100 Subject: Problem using execvp References: <1c03dba0-3d9b-47ab-a4fc-b42210ed35ff@o15g2000yqj.googlegroups.com> Message-ID: On Thu, 27 Oct 2011 01:57:55 -0700, faucheuse wrote: > I get this error : OSError : [Errno 8] Exec format error. The most likely reason for this error is a missing or invalid shebang, e.g.: #!/usr/bin/python or: #!/usr/bin/env python The "#!" must be the first two bytes in the file. Beware of text editors adding a Unicode BOM (byte order mark) at the beginning of the file. Forgetting to add execute permission would result in EPERM (errno=13, "Permission denied"). An invalid interpreter results in ENOENT (errno=2, "No such file or directory"). From tjreedy at udel.edu Thu Oct 27 22:44:26 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Oct 2011 22:44:26 -0400 Subject: __dict__ attribute for built-in types In-Reply-To: <4ea9e0ba$0$2261$426a74cc@news.free.fr> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> <4ea9e0ba$0$2261$426a74cc@news.free.fr> Message-ID: On 10/27/2011 6:52 PM, candide wrote: > No but I'm expecting from Python documentation to mention the laws of > Python ... The details of CPython builtin classes are not laws of Python. It *is* a 'law of Python' that classes can use 'slots = ' to restrict the attributes of instances. By implication, builtin classes in any implementation do not have to allow attribute assignment. I do not believe it would be a violation if some implementation did so. None of this is to say that we could not say something on the subject at the beginning of the 'built-in types' chapter of the lib manual. > OK but I'm talking about classes, not instances : Yes you are. The class determines whether its instances have assignable new attributes. > 42 has no __dict__ > attribute but, > may be, 43 _has_ such attribute, who knows in advance ? ;) True, in a sense, but if the class allowed a user to execute "42.__dict__ = {}" then you could safely assume that "43.xxx = z" should work also. -- Terry Jan Reedy From candide at free.invalid Thu Oct 27 22:46:17 2011 From: candide at free.invalid (candide) Date: Fri, 28 Oct 2011 04:46:17 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <87pqhi2gbj.fsf@xemacs.org> <4ea9eb0b$0$637$426a34cc@news.free.fr> Message-ID: <4eaa177c$0$25902$426a74cc@news.free.fr> Le 28/10/2011 02:02, MRAB a ?crit : > > No, built-in classes written in C have certain limitations, but why > would you want to do that anyway? Mainly for learning purpose and Python better understanding. Actually, I have a class of mine for drawing graphs with the Graphviz software. The nodes of the graph to be represented was supposed to have 2 attributes, say title and shortName. Now, I want to plot a graph whose nodes are pure string. So to fit the class interface, I was trying to add title and shortName attribute to every string node. From wuwei23 at gmail.com Thu Oct 27 22:48:32 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 27 Oct 2011 19:48:32 -0700 (PDT) Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> <4ea9e0ba$0$2261$426a74cc@news.free.fr> Message-ID: <761cb498-1193-4c33-a8e4-6c0adef7170b@d37g2000prg.googlegroups.com> On Oct 28, 8:52?am, candide wrote: > No but I'm expecting from Python documentation to mention the laws of > Python ... It's not a "law", it's an _implementation detail_. The docs don't tend to mention every such decision made because that's what the source is for. > But beside this, how to recognise classes whose object doesn't have a > __dict__ attribute ? The better question is: why do you need to be able to? > Is it possible in the CPython implementation to write something like this : > "foo".bar = 42 > without raising an attribute error ? Why are you trying to modify an immutible object? If you really want to assign attributes to string objects, subclass str. From huhai102 at gmail.com Thu Oct 27 22:50:06 2011 From: huhai102 at gmail.com (wholesale brand sunglasses) Date: Thu, 27 Oct 2011 19:50:06 -0700 (PDT) Subject: cheap air jordan shoes in www.nike-black.com Message-ID: <53a94ffc-9f41-4a81-bde0-492ea892ef3e@s32g2000prj.googlegroups.com> ? (www.nike-black.com) cheap wholesale nike air Jordan shoes , air force one shoes ? Air Jordan 2011 ? Air Jordan 1 I ? Air Jordan 2 II ? Air Jordan 3 III ? Air Jordan 4 IV ? Air Jordan 5 V ? Air Jordan 6 Rings(www.nike-black.com) ? Air Jordan 6 VI ? Air Jordan 7 VII ? Air Jordan 8 VIII ? Air Jordan 9 IX ? Air Jordan 10 X ? Air Jordan 11 XI ? Air Jordan 12 XII ? Air Jordan 13 XIII ? Air Jordan 14 XIV(www.nike-black.com) ? Air Jordan 15 XV ? Air Jordan 16 XVI ? Air Jordan 17 XVII ? Air Jordan 18 XVIII ? Air Jordan 19 XIX ? Air Jordan 20 XX ? Air Jordan 2009 ? Air Jordan 2010(www.nike-black.com) ? Air Jordan 21 XXI ? Air Jordan 22 XXII ? Air Jordan 23 Classic ? Air Jordan 23 XXIII ? Air Jordan Accolades ? Air Jordan All Day ? Air Jordan Alpha 1(www.nike-black.com) ? Air Jordan B Loyal ? Air Jordan Blase ? Air Jordan Chris Paul ? Air Jordan Classic 87 ? Air Jordan Dub Zero(www.nike-black.com) ? Air Jordan Esterno ? Air Jordan Flight 45 ? Air Jordan Flight 9 ? Air Jordan Fusions-> ? Air Jordan High Heels ? Air Jordan L'Style ? Air Jordan Melo M5 ? Air Jordan Nu Retro(www.nike-black.com) ? Air Jordan Ol School ? Air Jordan Ol School II ? Air Jordan Ol School III ? Air Jordan Olympia ? Air Jordan Phly ? Air Jordan Pro Classic(www.nike-black.com) ? Air Jordan Rare Air ? Air Jordan S.U. Trainer ? Air Jordan Spizikes ? Air Jordan Street Classic ? Air Jordan Team Elite ? Air Jordan Team Elite II(www.nike-black.com) ? Air Jordan Team ISO ? Air Jordan True Flight ? Air Jordan Women ? Jordan 1 Flight(www.nike-black.com) ? Jordan 25th Anniversary ? Jordan Big Fund ? Jordan Countdown ? Jordan Elements(www.nike-black.com) ? Jordan Sixty Plus 60+ ? Jordan Team-> ? Jordan Team Strong ? Jordan Trunner Q4 ? Jordan Winterized Spizike(www.nike-black.com) ? Nike Air Yeezy Website : http://www.nike-black.com From pmaupin at gmail.com Thu Oct 27 23:02:57 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 27 Oct 2011 20:02:57 -0700 (PDT) Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <87pqhi2gbj.fsf@xemacs.org> <4ea9eb0b$0$637$426a34cc@news.free.fr> <4eaa177c$0$25902$426a74cc@news.free.fr> Message-ID: <3aa6d44a-6015-485c-8745-d129941cb17a@g1g2000vbd.googlegroups.com> On Oct 27, 9:46?pm, candide wrote: > Le 28/10/2011 02:02, MRAB a crit : > > > > > No, built-in classes written in C have certain limitations, but why > > would you want to do that anyway? > > Mainly for learning purpose and Python better understanding. > > Actually, I have a class of mine for drawing graphs with the Graphviz > software. The nodes of the graph to be represented was supposed to have > 2 attributes, say title and shortName. Now, I want to plot a graph whose > nodes are pure string. So to fit the class interface, I was trying to > add title and shortName attribute to every string node. You can easily do that by subclassing a string: class AnnotatedStr(str): pass x = AnnotatedStr('Node1') x.title = 'Title for node 1' etc. The fact that you subclass it (unless your subclass uses __slots__) will give it a dict. From flt.johnson at gmail.com Thu Oct 27 23:05:13 2011 From: flt.johnson at gmail.com (Fletcher Johnson) Date: Thu, 27 Oct 2011 20:05:13 -0700 (PDT) Subject: Unicode literals and byte string interpretation. Message-ID: <8de0e9b7-aaac-44a4-8a07-9c1a20bfc3eb@s7g2000yqa.googlegroups.com> If I create a new Unicode object u'\x82\xb1\x82\xea\x82\xcd' how does this creation process interpret the bytes in the byte string? Does it assume the string represents a utf-16 encoding, at utf-8 encoding, etc...? For reference the string is ??? in the 'shift-jis' encoding. From huhai102 at gmail.com Thu Oct 27 23:06:12 2011 From: huhai102 at gmail.com (wholesale brand sunglasses) Date: Thu, 27 Oct 2011 20:06:12 -0700 (PDT) Subject: discount air jordan shoes in www.nike-black.com Message-ID: ? (www.nike-black.com) cheap wholesale nike air Jordan shoes , air force one shoes ? Air Jordan 2011 ? Air Jordan 1 I ? Air Jordan 2 II ? Air Jordan 3 III ? Air Jordan 4 IV ? Air Jordan 5 V ? Air Jordan 6 Rings(www.nike-black.com) ? Air Jordan 6 VI ? Air Jordan 7 VII ? Air Jordan 8 VIII ? Air Jordan 9 IX ? Air Jordan 10 X ? Air Jordan 11 XI ? Air Jordan 12 XII ? Air Jordan 13 XIII ? Air Jordan 14 XIV(www.nike-black.com) ? Air Jordan 15 XV ? Air Jordan 16 XVI ? Air Jordan 17 XVII ? Air Jordan 18 XVIII ? Air Jordan 19 XIX ? Air Jordan 20 XX ? Air Jordan 2009 ? Air Jordan 2010(www.nike-black.com) ? Air Jordan 21 XXI ? Air Jordan 22 XXII ? Air Jordan 23 Classic ? Air Jordan 23 XXIII Website : http://www.nike-black.com From tjreedy at udel.edu Thu Oct 27 23:23:04 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Oct 2011 23:23:04 -0400 Subject: Assigning generator expressions to ctype arrays In-Reply-To: <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> Message-ID: On 10/27/2011 8:09 PM, Patrick Maupin wrote: > x[:] = (x for x in xrange(32)) This translates to s.__setitem__(slice(None,None), generator_object) where 'generator_object' is completely opaque, except that it will yield 0 to infinity objects in response to next() before raising StopIteration. Given that a cytpe_array is a *fixed-length* array, *unlike* Python's extensible lists and arrays, failure is a possibility due to mis-matched lengths. So ctype_array can either look first, as it does, by calling len(value_object), or leap first and create a temporary array, see if it fills up exactly right, and if it does, copy it over. > I know how to work around the issue. I'm not sure I should have to. I do not think everyone else should suffer substantial increase in space and run time to avoid surprising you. > It violates the principle of least surprise for ctypes to do what is most efficient in 99.9% of uses? > for the ctypes array to > not be able to interoperate with the iterator protocol in this > fashion. It could, but at some cost. Remember, people use ctypes for efficiency, so the temp array path would have to be conditional. When you have a patch, open a feature request on the tracker. -- Terry Jan Reedy From fraveydank at gmail.com Thu Oct 27 23:37:01 2011 From: fraveydank at gmail.com (David Riley) Date: Thu, 27 Oct 2011 23:37:01 -0400 Subject: Unicode literals and byte string interpretation. In-Reply-To: <8de0e9b7-aaac-44a4-8a07-9c1a20bfc3eb@s7g2000yqa.googlegroups.com> References: <8de0e9b7-aaac-44a4-8a07-9c1a20bfc3eb@s7g2000yqa.googlegroups.com> Message-ID: On Oct 27, 2011, at 11:05 PM, Fletcher Johnson wrote: > If I create a new Unicode object u'\x82\xb1\x82\xea\x82\xcd' how does > this creation process interpret the bytes in the byte string? Does it > assume the string represents a utf-16 encoding, at utf-8 encoding, > etc...? > > For reference the string is ??? in the 'shift-jis' encoding. Try it and see! One test case is worth a thousand words. And Python has an interactive interpreter. :-) - Dave From rosuav at gmail.com Thu Oct 27 23:38:39 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Oct 2011 14:38:39 +1100 Subject: Unicode literals and byte string interpretation. In-Reply-To: <8de0e9b7-aaac-44a4-8a07-9c1a20bfc3eb@s7g2000yqa.googlegroups.com> References: <8de0e9b7-aaac-44a4-8a07-9c1a20bfc3eb@s7g2000yqa.googlegroups.com> Message-ID: On Fri, Oct 28, 2011 at 2:05 PM, Fletcher Johnson wrote: > If I create a new Unicode object u'\x82\xb1\x82\xea\x82\xcd' how does > this creation process interpret the bytes in the byte string? Does it > assume the string represents a utf-16 encoding, at utf-8 encoding, > etc...? > > For reference the string is ??? in the 'shift-jis' encoding. Encodings define how characters are represented in bytes. I think probably what you're looking for is a byte string with those hex values in it, which you can then turn into a Unicode string: >>> a=b'\x82\xb1\x82\xea\x82\xcd' >>> unicode(a,"shift-jis") # use 'str' instead of 'unicode' in Python 3 u'\u3053\u308c\u306f' The u'....' notation is for Unicode strings, which are not encoded in any way. The last line of the above is a valid way of entering that string in your source code, identifying Unicode characters by their codepoints. ChrisA From lie.1296 at gmail.com Thu Oct 27 23:42:34 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 28 Oct 2011 14:42:34 +1100 Subject: Dynamically creating properties? In-Reply-To: References: Message-ID: On 10/28/2011 08:48 AM, DevPlayer wrote: > On Oct 27, 3:59 pm, Andy Dingley wrote: >> I have some XML, with a variable and somewhat unknown structure. I'd >> like to encapsulate this in a Python class and expose the text of the >> elements within as properties. >> >> How can I dynamically generate properties (or methods) and add them to >> my class? I can easily produce a dictionary of the required element >> names and their text values, but how do I create new properties at run >> time? >> >> Thanks, > > class MyX(object): > pass > myx = myx() > > xml_tag = parse( file.readline() ) > > # should be a valid python named-reference syntax, > # although any object that can be a valid dict key is allowed. > # generally valid python named reference would be the answer to > your question > attribute = validate( xml_tag ) > > # dynamicly named property > setattr( myx, attribute, property(get_func, set_func, del_func, > attr_doc) ) > > # "dynamicly named method" > # really should be a valid python named-reference syntax > myfunc_name = validate(myfunc_name) > > def somefunc(x): > return x+x > # or > somefunc = lambda x: x + x > > setattr( myx, myfunc_name, somefunc ) > > > So beaware of: > # \\\\\\\\\\\\\\\\\\\\\\\\\ > setattr(myx, '1', 'one') > > myx.1 > File "", line 1 > x.1 > ^ > SyntaxError: invalid syntax > > # \\\\\\\\\\\\\\\\\\\\\\\\\ > x.'1' > File "", line 1 > x.'1' > ^ > SyntaxError: invalid syntax > > # \\\\\\\\\\\\\\\\\\\\\\\\\ > x.__dict__['1'] # returns > 'one' > > x.__dict__ # returns > {'1': 'one'} > > So you should validate your variable names if you are getting them > from somewhere. XML does not allow attribute names to start with a number, so I doubt you need to worry about that. In addition, if you also need to dynamically access attributes and you have zero control of the name, you can use getattr(). From tjreedy at udel.edu Fri Oct 28 00:16:30 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Oct 2011 00:16:30 -0400 Subject: Need Windows user / developer to help with Pynguin In-Reply-To: References: Message-ID: On 10/27/2011 3:38 PM, Lee Harr wrote: > > I develop the free python-based turtle graphics application pynguin. > > http://pynguin.googlecode.com/ > > > Lately I have been getting a lot of positive comments from people > who use the program, but I am also getting a lot of feedback from > people on Windows (mostly beginners) who are having trouble > getting the program running. > > I don't use Windows myself, though I have found access occasionally > to fix bugs. I just don't know enough about Windows culture to be > able to make a reliable method for installing or running the program. > > The method that I wrote for Linux also works on Windows, but it has > to be run from the command prompt. > > I am hoping someone can look at what is there and come up with a > reliable method or a simple set of steps that people can follow to get > up and running. Hopefully without having to resort to the command > prompt. > > I started a wiki page here: > http://code.google.com/p/pynguin/wiki/InstallingPynguinOnWindows > but I can't even test if it actually works.... In my experience, double clicking on x.zip should open the zip in the zip program (xp) but not actually extract. Win7, with zip built in, just treats x.zip as a directory in Explorer, with no external program required. You pynguin.zip contains one top level file -- a directory called pynguin that contains multiple files*. Extracting pynguin.zip to a pynguin directory in the same directory as pynguin.zip, the default behavior with Win7 at least, creates a new pynguin directory that contains the extracted pynguin directory. So one has to run pynguin/pynguin/setup.py. In other words, there is one level too many. People can erase 'pynguin' from the target list to avoid this. (I am not sure 7zip on xp has the same default.) *You would make things easier, at least for Windows users, if you added the proper extensions. pynguin => pynguin.py README => README.txt etc for other text files. If you are using setup.py, I do not know of any alternative to using a command prompt. But do tell people to find it with Start/All Programs/Accessories/Command Prompt. Then two choices that I know of. 1."cd dir", where dir is the path to the directory containing setup.py. Of course, for "python setup.py install" to work, people must have the Python installation path python-dir in the PATH environmental variable, which it will not be unless they put it there. Without that, "python-dir\python setup.py install" is required. 2. "cd python-dir" followed by "python pynguin-dir\setup.py install" I may have missed something, but I do not actually run many Python apps. One I have used (renpy) makes separate installers for Windows, *nix, and Mac. As I remember, is does a standard Windows installation with one of the free installers, asking where to put the files and if Start menu icons are wanted. I ran it with a desktop shortcup to the main program. The new disutiles2/distribute/packaging package plus a new python launcher for Windows should make things easier within a year, by the time 3.3 is out. For the occasion library package, I prefer to directly extract to site-packages. -- Terry Jan Reedy From tjreedy at udel.edu Fri Oct 28 00:18:30 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Oct 2011 00:18:30 -0400 Subject: Presenting recursive dict (json_diff) In-Reply-To: References: Message-ID: On 10/27/2011 4:58 PM, Matej Cepl wrote: > Dne 27.10.2011 21:49, Terry Reedy napsal(a): >> Use '_append', etc, much like namedtuple does, for the same reason. > > Right, done. What about the presentation issue? Any ideas? No. -- Terry Jan Reedy From nobody at nowhere.com Fri Oct 28 01:49:08 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 28 Oct 2011 06:49:08 +0100 Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> Message-ID: On Thu, 27 Oct 2011 12:08:45 +0200, candide wrote: > I realize that built-in types objects don't provide a __dict__ attribute > and thereby i can't set an attribute to a such object, for instance Note that possession or absence of a __dict__ attribute doesn't necessarily mean that you can or can't set attributes, as the class can override __setattr__(). Ultimately, there is no guaranteed mechanism to determine in advance whether or not an attempt to set an attribute will succeed. From steve+comp.lang.python at pearwood.info Fri Oct 28 02:21:44 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 28 Oct 2011 06:21:44 GMT Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <87pqhi2gbj.fsf@xemacs.org> <4ea9eb0b$0$637$426a34cc@news.free.fr> Message-ID: <4eaa49f8$0$29968$c3e8da3$5496439d@news.astraweb.com> On Fri, 28 Oct 2011 01:36:41 +0200, candide wrote: > Le 28/10/2011 00:57, Hrvoje Niksic a ?crit : > >> was used at class definition time to suppress it. Built-in and >> extension types can choose whether to implement __dict__. >> >> > Is it possible in the CPython implementation to write something like > this : > > "foo".bar = 42 > > without raising an attribute error ? No, because built-in strings don't have a __dict__ and so you cannot add new attributes that didn't already exist. But you can subclass str and do whatever you like. class Str(str): pass Str("foo").bar = 42 -- Steven From steve+comp.lang.python at pearwood.info Fri Oct 28 03:06:08 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 28 Oct 2011 07:06:08 GMT Subject: Unicode literals and byte string interpretation. References: <8de0e9b7-aaac-44a4-8a07-9c1a20bfc3eb@s7g2000yqa.googlegroups.com> Message-ID: <4eaa545f$0$29968$c3e8da3$5496439d@news.astraweb.com> On Thu, 27 Oct 2011 20:05:13 -0700, Fletcher Johnson wrote: > If I create a new Unicode object u'\x82\xb1\x82\xea\x82\xcd' how does > this creation process interpret the bytes in the byte string? It doesn't, because there is no byte-string. You have created a Unicode object from a literal string of unicode characters, not bytes. Those characters are: Dec Hex Char 130 0x82 ? 177 0xb1 ? 130 0x82 ? 234 0xea ? 130 0x82 ? 205 0xcd ? Don't be fooled that all of the characters happen to be in the range 0-255, that is irrelevant. > Does it > assume the string represents a utf-16 encoding, at utf-8 encoding, > etc...? None of the above. It assumes nothing. It takes a string of characters, end of story. > For reference the string is ??? in the 'shift-jis' encoding. No it is not. The way to get a unicode literal with those characters is to use a unicode-aware editor or terminal: >>> s = u'???' >>> for c in s: ... print ord(c), hex(ord(c)), c ... 12371 0x3053 ? 12428 0x308c ? 12399 0x306f ? You are confusing characters with bytes. I believe that what you are thinking of is the following: you start with a byte string, and then decode it into unicode: >>> bytes = '\x82\xb1\x82\xea\x82\xcd' # not u'...' >>> text = bytes.decode('shift-jis') >>> print text ??? If you get the encoding wrong, you will get the wrong characters: >>> print bytes.decode('utf-16') ??? If you start with the Unicode characters, you can encode it into various byte strings: >>> s = u'???' >>> s.encode('shift-jis') '\x82\xb1\x82\xea\x82\xcd' >>> s.encode('utf-8') '\xe3\x81\x93\xe3\x82\x8c\xe3\x81\xaf' -- Steven From steve+comp.lang.python at pearwood.info Fri Oct 28 03:21:47 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 28 Oct 2011 07:21:47 GMT Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> Message-ID: <4eaa580a$0$29968$c3e8da3$5496439d@news.astraweb.com> On Thu, 27 Oct 2011 17:09:34 -0700, Patrick Maupin wrote: > On Oct 27, 5:31?pm, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: >> From the outside, you can't tell how big a generator expression is. It >> has no length: > > I understand that. > >> Since the array object has no way of telling whether the generator will >> have the correct size, it refuses to guess. > > It doesn't have to guess. It can assume that I, the programmer, know > what the heck I am doing, and then validate that assumption -- trust, > but verify. It merely needs to fill the slice and then ask for one more > and check that StopIteration is raised. Simple, easy, and wrong. It needs to fill in the slice, check that the slice has exactly the right number of elements (it may have fewer), and then check that the iterator is now empty. If the slice has too few elements, you've just blown away the entire iterator for no good reason. If the slice is the right length, but the iterator doesn't next raise StopIteration, you've just thrown away one perfectly good value. Hope it wasn't something important. >> I would argue that it should raise a TypeError with a less misleading >> error message, rather than a ValueError, so "bug". > > And I would argue that it should simply work, unless someone can present > a more compelling reason why not. I think that "the iterator protocol as it exists doesn't allow it to work the way you want" is a pretty compelling reason. >> The simple solution is to use a list comp instead of a generator >> expression. > > I know how to work around the issue. I'm not sure I should have to. It > violates the principle of least surprise for the ctypes array to not be > able to interoperate with the iterator protocol in this fashion. Perhaps you're too easily surprised by the wrong things. -- Steven From steve+comp.lang.python at pearwood.info Fri Oct 28 03:42:50 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 28 Oct 2011 07:42:50 GMT Subject: Dynamically creating properties? References: Message-ID: <4eaa5cfa$0$29968$c3e8da3$5496439d@news.astraweb.com> On Thu, 27 Oct 2011 16:00:57 -0700, DevPlayer wrote: > def isvalid_named_reference( astring ): > # "varible name" is really a named_reference > # import string # would be cleaner I don't understand the comment about "variable name". > valid_first_char = > '_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' > valid_rest = > '_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' This would be better: import string valid_first_char = '_' + string.ascii_letters valid_rest = string.digits + valid_first_char > # I think it's ok here for the rare type-check > # as unicode named-references are not allowed > if type(astring) is not str: return False In Python 3 they are: http://www.python.org/dev/peps/pep-3131/ > if len(astring) == 0: return False > if astring[0] not in valid_first_char: return False > for c in astring[1:]: > if c not in valid_rest: return False > > # Python keywords not allowed as named references (variable names) > for astr in ['and', 'assert', 'break', 'class', 'continue', > 'def', 'del', 'elif', 'else', 'except', 'exec', > 'finally', 'for', 'from', 'global', 'if', 'import', > 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', > 'raise', 'return', 'try', 'while', 'yield',]: > if astring == astr: return False You missed 'as' and 'with'. And 'nonlocal' in Python 3. Possibly others. Try this instead: from keywords import iskeyword if iskeyword(astring): return False -- Steven From steve+comp.lang.python at pearwood.info Fri Oct 28 04:01:15 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 28 Oct 2011 08:01:15 GMT Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> <4ea9e0ba$0$2261$426a74cc@news.free.fr> Message-ID: <4eaa614b$0$29968$c3e8da3$5496439d@news.astraweb.com> On Fri, 28 Oct 2011 00:52:40 +0200, candide wrote: > Le 28/10/2011 00:19, Steven D'Aprano a ?crit : >> >> What, you think it goes against the laws of physics that nobody thought >> to mention it in the docs? > > > No but I'm expecting from Python documentation to mention the laws of > Python ... You seem to have missed my point. You said "I can't imagine" that the Python docs fail to mention that built-ins don't allow the addition of new attributes. I can, easily. The people writing the documentation are only human, and if they failed to mention it, oh well, perhaps they didn't think of it. This is hardly a surprise. Wanting to add arbitrary attributes to built-ins is not exactly an everyday occurrence. >>> But beside this, how to recognise classes whose object doesn't have a >>> __dict__ attribute ? >> >> The same way as you would test for any other attribute. >> >>>>> hasattr(42, '__dict__') >> False > > OK but I'm talking about classes, not instances : 42 has no __dict__ > attribute but, may be, 43 _has_ such attribute, who knows in advance ? > ;) True, it is theoretically possible that (say) only odd numbers get a __dict__, or primes, or the smallest multiple of seventeen larger than the natural logarithm of a googol (10**100). But it's a safe bet that nothing so arbitrary will happen. Dunder attributes ("Double UNDERscore") like __dict__ are reserved for use by Python, and __dict__ has known semantics. You can safely assume that either *all* instances of a type will have a __dict__, or *no* instances will have one. If some class violates that, oh well, your code can't be expected to support every badly-designed stupid class in the world. Also, keep in mind the difference between a *class* __dict__ and an *instance* __dict__. >>> hasattr(int, '__dict__') # Does the int class/type have a __dict__? True >>> hasattr(42, '__dict__') # Does the int instance have a __dict__? False -- Steven From tjreedy at udel.edu Fri Oct 28 04:19:26 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Oct 2011 04:19:26 -0400 Subject: Assigning generator expressions to ctype arrays In-Reply-To: <4eaa580a$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> <4eaa580a$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/28/2011 3:21 AM, Steven D'Aprano wrote: > If the slice has too few elements, you've just blown away the entire > iterator for no good reason. > If the slice is the right length, but the iterator doesn't next raise > StopIteration, you've just thrown away one perfectly good value. Hope it > wasn't something important. You have also over-written values that should be set back to what they were, before the exception is raised, which is why I said the test needs to be done with a temporary array. -- Terry Jan Reedy From mail at timgolden.me.uk Fri Oct 28 04:22:00 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 28 Oct 2011 09:22:00 +0100 Subject: spawnl issues with Win 7 access rights In-Reply-To: References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> <4EA6A950.6090706@timgolden.me.uk> <4EA81B72.7040008@timgolden.me.uk> <98460dba-9e08-4d1a-8bf6-4e8fdbea2d0c@19g2000yqk.googlegroups.com> <4EA93421.1090905@timgolden.me.uk> Message-ID: <4EAA6628.4070309@timgolden.me.uk> On 27/10/2011 20:53, Terry Reedy wrote: > On 10/27/2011 6:36 AM, Tim Golden wrote: >> On 27/10/2011 11:27, Propad wrote: >>> the suggestion to add the optional second parameter fixed the problem, >>> spawnl now works on the Win 7 computer I'm responsible for (with >>> Python 2.2). So the suggested cause seems to be right. >> >> FWIW, although it's not obvious, the args parameter to spawnl >> is intended to become the sys.args (in Python terms) of the >> newly-spawned process. Which is why the first element is expected >> to be the name of the process. It took me some time to realise >> this myself :) >> >> Anyway, glad we could be of help. > > Can we make this fix automatic for Win7 to fix #8036? > It's tempting, but I think not. In principle, the caller can pass any value as the first arg of spawn: it'll simply end up as sys.argv[0] in Python terms. If spawnl were the way of the future, I'd be inclined to argue for the change. As it it, though, I'd simply apply the patch and, possibly, add a line to the docs indicating that the args must be non-empty. (I started to import the patch yesterday but something got in the way; I'll see if I can get it done today). TJG From hniksic at xemacs.org Fri Oct 28 05:08:13 2011 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 28 Oct 2011 11:08:13 +0200 Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <87pqhi2gbj.fsf@xemacs.org> <4ea9eb0b$0$637$426a34cc@news.free.fr> Message-ID: <87lis5jxfm.fsf@xemacs.org> candide writes: > Le 28/10/2011 00:57, Hrvoje Niksic a ?crit : > >> was used at class definition time to suppress it. Built-in and >> extension types can choose whether to implement __dict__. >> > > Is it possible in the CPython implementation to write something like this : > > "foo".bar = 42 > > without raising an attribute error ? No, and for good reason. Strings are immutable, so that you needn't care which particular instance of "foo" you're looking at, they're all equivalent. The interpreter uses that fact to cache instances of short strings such as Python identifiers, so that most places that look at a string like "foo" are in fact dealing with the same instance. If one could change an attribute of a particular instance of "foo", it would no longer be allowed for the interpreter to transparently cache them. The same goes for integers and other immutable built-in objects. If you really need to attach state to strings, subclass them as Steven explained. All code that accepts strings (including all built-ins) will work just fine, transparent caching will not happen, and attributes are writable. From moky.math at gmail.com Fri Oct 28 05:29:01 2011 From: moky.math at gmail.com (Laurent) Date: Fri, 28 Oct 2011 11:29:01 +0200 Subject: Entre local et global In-Reply-To: References: <7a7f1c9e-7a6e-42b6-8d53-023834f8b1a1@gk10g2000vbb.googlegroups.com> <4EA9736D.7040202@gmail.com> Message-ID: <4EAA75DD.2080200@gmail.com> Le 28/10/2011 10:43, ll.snark a ?crit : > On 27 oct, 17:06, Laurent Claessens wrote: >> > J'aimerais donc pouvoir indiquer dans fonca, que la variable lst est >> > celle d?finie dans fonc1. >> > Je ne veux pas d'une variable locale ? fonca, ni une variable globale >> > ? tout mon fichier (cf exemple ci-dessous) >> >> > Une id?e ? >> >> Je ne suis pas tr?s s?r que ?a r?ponse ? la question, mais une piste >> serait de faire de fonca une classe avec une m?thode __call__ et une >> variable de classe: >> >> class fonc2(object): >> fonc1.lst=[] >> def __call__(self,v): >> if len(fonc1.lst)<3: >> fonc1.lst=fonc1.lst+[v] >> print fonc1.lst >> > > > Effectivement, ?a r?pond en partie ? la question. > Il faudra que je vois si en faisant comme ?a, je peux r?soudre mon pb > de d?part sur les d?corateurs. MAis je suppose qu'entre une fonction > et une classe qui poss?de une > m?thode __call__, il n'y a pas tant de diff?rence que ?a... Moi je dirais que oui, il y a une diff?rence ?norme : dans une classe tu peux mettre beaucoup plus de choses ;) class Exemple(object): def __init__(self,a): self.a=a def __call__(self,x): return a+x f=Exemple(2) g=Exemple(10) f(1) # 3 g(1) # 11 f.a=6 f(1) # 7 Faire ?a avec une fonction, ?a me semblerait ardu, sauf ? faire comme tu faisais : une fonction qui contient une fonction et qui la retourne. (mais ? mon avis c'est moins lisible) > Merci pour la r?ponse en tous cas. Je suppose donc qu'il n'y a pas de > mot cl?, un peu comme global, mais qui > d?signe une port?e plus petite ? Je ne sais pas. > Je l'aurais sans doute vu dans la doc > ou dans des bouquin si ?a avait ?t? le cas, mais je trouve > que c'est bizarre. A priori, ?a ne me semble pas tellement bizarre. J'utiliserais une fonction seulement pour quelque chose qui a une entr?e et une sortie qui d?pend uniquement de l'entr?e. Pour quelque chose dont le comportement d?pend du contexte (c'est le cas de ce que tu demandes), j'utiliserais une classe dans les attributs de laquelle je mettrais les ?l?ments du contexte. Bon, je dis ?a, mais je ne suis pas assez fort pour pr?tendre ?tre certain de ce qui est "bizarre" ou non :) Bonne journ?e Laurent From candide at free.invalid Fri Oct 28 06:03:29 2011 From: candide at free.invalid (candide) Date: Fri, 28 Oct 2011 12:03:29 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: <4eaa614b$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> <4ea9e0ba$0$2261$426a74cc@news.free.fr> <4eaa614b$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4eaa7df3$0$16584$426a74cc@news.free.fr> Le 28/10/2011 10:01, Steven D'Aprano a ?crit : > didn't think of it. This is hardly a surprise. Wanting to add arbitrary > attributes to built-ins is not exactly an everyday occurrence. > Depends. Experimented programmers don't even think of it. But less advanced programmers can consider of it. It's is not uncommun to use a Python class like a C structure, for instance : class C:pass C.member1=foo C.member2=bar Why not with a built-in type instead of a custom class? > the natural logarithm of a googol (10**100). But it's a safe bet that > nothing so arbitrary will happen. betting when programming ? How curious! ;) > Also, keep in mind the difference between a *class* __dict__ and an > *instance* __dict__. > You mean this distinction >>> hasattr('', '__dict__') False >>> hasattr(''.__class__, '__dict__') True >>> ? From candide at free.invalid Fri Oct 28 06:04:14 2011 From: candide at free.invalid (candide) Date: Fri, 28 Oct 2011 12:04:14 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: <3aa6d44a-6015-485c-8745-d129941cb17a@g1g2000vbd.googlegroups.com> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <87pqhi2gbj.fsf@xemacs.org> <4ea9eb0b$0$637$426a34cc@news.free.fr> <4eaa177c$0$25902$426a74cc@news.free.fr> <3aa6d44a-6015-485c-8745-d129941cb17a@g1g2000vbd.googlegroups.com> Message-ID: <4eaa7e21$0$16584$426a74cc@news.free.fr> Le 28/10/2011 05:02, Patrick Maupin a ?crit : > You can easily do that by subclassing a string: > > class AnnotatedStr(str): > pass > > x = AnnotatedStr('Node1') > x.title = 'Title for node 1' > Less or more what I did. But requires to transport the string graph structure to the AnnotatedStr one. From candide at free.invalid Fri Oct 28 06:23:46 2011 From: candide at free.invalid (candide) Date: Fri, 28 Oct 2011 12:23:46 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: <87lis5jxfm.fsf@xemacs.org> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <87pqhi2gbj.fsf@xemacs.org> <4ea9eb0b$0$637$426a34cc@news.free.fr> <87lis5jxfm.fsf@xemacs.org> Message-ID: <4eaa82b5$0$8819$426a74cc@news.free.fr> Le 28/10/2011 11:08, Hrvoje Niksic a ?crit : > longer be allowed for the interpreter to transparently cache them. The > same goes for integers and other immutable built-in objects. On the other hand, immutability and optimization don't explain the whole thing because you can't do something like [].bar = 42. > > If you really need to attach state to strings, subclass them as Steven > explained. All code that accepts strings (including all built-ins) will > work just fine, transparent caching will not happen, and attributes are > writable. OK, thanks, I'll consider it seriously. Actually I have a directed graph whose nodes are given as string but it's oversimplistic to identify node and string (for nodes requiring specific methods). From moky.math at gmail.com Fri Oct 28 06:28:34 2011 From: moky.math at gmail.com (Laurent Claessens) Date: Fri, 28 Oct 2011 12:28:34 +0200 Subject: Entre local et global In-Reply-To: References: <7a7f1c9e-7a6e-42b6-8d53-023834f8b1a1@gk10g2000vbb.googlegroups.com> <4EA9736D.7040202@gmail.com> Message-ID: Woops. This was aimed to the french speaking python's usenet. Sorry. Laurent Le 28/10/2011 11:29, Laurent a ?crit : > Le 28/10/2011 10:43, ll.snark a ?crit : >> On 27 oct, 17:06, Laurent Claessens wrote: >>> > J'aimerais donc pouvoir indiquer dans fonca, que la variable lst est >>> > celle d?finie dans fonc1. >>> > Je ne veux pas d'une variable locale ? fonca, ni une variable globale >>> > ? tout mon fichier (cf exemple ci-dessous) >>> >>> > Une id?e ? [snip] From lists at cheimes.de Fri Oct 28 07:51:33 2011 From: lists at cheimes.de (Christian Heimes) Date: Fri, 28 Oct 2011 13:51:33 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: <4eaa614b$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> <4ea9e0ba$0$2261$426a74cc@news.free.fr> <4eaa614b$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 28.10.2011 10:01, schrieb Steven D'Aprano: >>>> hasattr(int, '__dict__') # Does the int class/type have a __dict__? > True >>>> hasattr(42, '__dict__') # Does the int instance have a __dict__? > False Also __dict__ doesn't have to be an instance of __dict__. Builtin types usually have a dictproxy instane as their __dict__. >>> type(int.__dict__) >>> int.__dict__["egg"] = "spam" Traceback (most recent call last): File "", line 1, in TypeError: 'dictproxy' object does not support item assignment From amirouche.boubekki at gmail.com Fri Oct 28 08:07:29 2011 From: amirouche.boubekki at gmail.com (Amirouche Boubekki) Date: Fri, 28 Oct 2011 14:07:29 +0200 Subject: Is Python in the browser a dead-end ? Message-ID: H?llo, There was a thread recently about the missed opportunity for Python to be a language that could replace Javascript in the browser. They are several attempts at doing something in this spirit here are the ones I'm aware of: - pyjamas aka. pyjs it is to Python what GWT is to Java : http://pyjs.org/ - py2js which compiles Python to Javascript without high level widget like pyjamas does https://github.com/qsnake/py2js - skulpt unlike py2js and pyjs there is no compilation phase http://www.skulpt.org/ And SubScript [1], which I am the creator, a Python-like language [2] and Sissi [3] which aims at being the stdlib of SubScript, currently it's implemented with py2js. It relies heavly on Google Closure tools [4]. I'm planning to add streamer [5] support if I can wrap my head around it. I'm done with self advertisement. Before starting SubScript I gave it some thoughts, and I think that it can bring value to web development. Here are articles that backs up my vision: - Javascript gurus claims that Javascript is indeed the "assembly" of the web [6], which means that Javascript is viable target for a compiler - Similar projects exists with Coffescript and ClojureScript which seems to have the lead and are gaining traction in web development community. Dart is another example. - The thing that makes Javascript development difficult is that it's hard to debug, but map JS [7] is making its way into Firefox which will help greatly Why do people think that this projects are doomed ? I ask this question to understand other point of views before commiting myself at finish SubScript & Sissi, I don't want to code something that will be useless. Thanks in advance, Amirouche [1] https://bitbucket.org/abki/subscript [2] currently Subscript code is parsed by Python parsing library the exact same syntax should be supported [3] https://bitbucket.org/abki/sissi/overview [4] http://code.google.com/intl/fr/closure/ [5] https://github.com/Gozala/streamer [6] http://www.hanselman.com/blog/JavaScriptIsAssemblyLanguageForTheWebSematicMarkupIsDeadCleanVsMachinecodedHTML.aspx [7] https://bugzilla.mozilla.org/show_bug.cgi?id=618650 -------------- next part -------------- An HTML attachment was scrubbed... URL: From billy.earney at gmail.com Fri Oct 28 11:03:10 2011 From: billy.earney at gmail.com (Billy Earney) Date: Fri, 28 Oct 2011 10:03:10 -0500 Subject: Is Python in the browser a dead-end ? In-Reply-To: References: Message-ID: I believe that python maybe had missed an opportunity to get in early and be able to take over a large market share from javascript. But that doesn't mean python is dead in the browser, it just means it will have more competition if it wants to replace javascript for Rich Internet Applications. there's also emscripten, which takes c code and compiles it into javascript. the c python compiler is one of its primary examples as you can see here: http://syntensity.com/static/python.html I've also contributed some code to Skupt so that a person can do something like Hopefully eventually, the code I submitted will be of use someday! :) On Fri, Oct 28, 2011 at 7:07 AM, Amirouche Boubekki < amirouche.boubekki at gmail.com> wrote: > H?llo, > > There was a thread recently about the missed opportunity for Python to be a > language that could replace Javascript in the browser. > > They are several attempts at doing something in this spirit here are the > ones I'm aware of: > > - pyjamas aka. pyjs it is to Python what GWT is to Java : http://pyjs.org/ > - py2js which compiles Python to Javascript without high level widget like > pyjamas does https://github.com/qsnake/py2js > - skulpt unlike py2js and pyjs there is no compilation phase > http://www.skulpt.org/ > > And SubScript [1], which I am the creator, a Python-like language [2] and > Sissi [3] which aims at being the stdlib of SubScript, currently it's > implemented with py2js. It relies heavly on Google Closure tools [4]. I'm > planning to add streamer [5] support if I can wrap my head around it. > > I'm done with self advertisement. > > Before starting SubScript I gave it some thoughts, and I think that it can > bring value to web development. > > Here are articles that backs up my vision: > > - Javascript gurus claims that Javascript is indeed the "assembly" of the > web [6], which means that Javascript is viable target for a compiler > > - Similar projects exists with Coffescript and ClojureScript which seems to > have the lead and are gaining traction in web development community. Dart is > another example. > > - The thing that makes Javascript development difficult is that it's hard > to debug, but map JS [7] is making its way into Firefox which will help > greatly > > Why do people think that this projects are doomed ? > > I ask this question to understand other point of views before commiting > myself at finish SubScript & Sissi, I don't want to code something that will > be useless. > > Thanks in advance, > > Amirouche > > [1] https://bitbucket.org/abki/subscript > [2] currently Subscript code is parsed by Python parsing library the exact > same syntax should be supported > [3] https://bitbucket.org/abki/sissi/overview > [4] http://code.google.com/intl/fr/closure/ > [5] https://github.com/Gozala/streamer > [6] > http://www.hanselman.com/blog/JavaScriptIsAssemblyLanguageForTheWebSematicMarkupIsDeadCleanVsMachinecodedHTML.aspx > [7] https://bugzilla.mozilla.org/show_bug.cgi?id=618650 > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ppearson at nowhere.invalid Fri Oct 28 11:52:49 2011 From: ppearson at nowhere.invalid (Peter Pearson) Date: 28 Oct 2011 15:52:49 GMT Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> <4ea9e0ba$0$2261$426a74cc@news.free.fr> Message-ID: <9h01ehF8ogU1@mid.individual.net> On Fri, 28 Oct 2011 00:52:40 +0200, candide wrote: [snip] >>>>> hasattr(42, '__dict__') >> False [snip] > > Let'have a try : > > >>> hasattr(43, '__dict__') > False > >>> > > so we have proved by induction that no integer instance has a > dictionnary attribute ;) You left out an important step in this proof by induction. Observe: >>> n = 0 >>> hasattr(n, "__dict__") False >>> if hasattr(n, "__dict__") is False: ... hasattr(n+1, "__dict__") is False ... True There, now it's proven by induction. -- To email me, substitute nowhere->spamcop, invalid->net. From hanss at libero.it Fri Oct 28 13:03:35 2011 From: hanss at libero.it (Gabriele) Date: Fri, 28 Oct 2011 10:03:35 -0700 (PDT) Subject: getting columns attributes in declarative style with sqlalchemy Message-ID: <372ac973-575c-466a-9322-a879f099d86a@v5g2000vbh.googlegroups.com> Hi, I'm tryed to write my first application using SqlAlchemy. I'm using declarative style. I need to get the attributes of the columns of my table. This is an example of my very simple model-class: class Country(base): __tablename__ = "bookings_countries" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True) canceled = sqlalchemy.Column(sqlalchemy.Boolean, nullable=False, default=False) description = sqlalchemy.Column(Description) def __init__(self, canceled, description): self.canceled = canceled self.description = description def __repr__(self): return "" % (self.description) I want to populate a wx grid using the name of the fields as labels of the columns. I found three different solutions of my problem, but none satisfeid me: a) using column_descriptions in query object. col = (model.Country.canceled, model.Country.description) q = self.parent.session.query(*col).order_by(model.Country.description) l = [column["name"] for column in q.column_descriptions] in this way, l contains exactly what I need, but I don't like because I must execute an useless query only for having informations about the structure of my table. Ok, it's not so big problem, but IMO is not a very good solution b) reflecting the table c) using inspector lib from sqlachemy.engine I don't like because I have to use directly the name of the table in the database... It sounds me better and logical to use my class Country... but I can't find the simple way for doing that... maybe it's very simple, but... Someone can help me? Thanks Gabriele From nathan.alexander.rice at gmail.com Fri Oct 28 13:20:38 2011 From: nathan.alexander.rice at gmail.com (Nathan Rice) Date: Fri, 28 Oct 2011 13:20:38 -0400 Subject: Forking simplejson In-Reply-To: References: Message-ID: Just a random note, I actually set about the task of re-implementing a json encoder which can be subclassed, is highly extensible, and uses (mostly) sane coding techniques (those of you who've looked at simplejson's code will know why this is a good thing). So far preliminary tests show the json only subclass of the main encoder basically tied in performance with the python implementation of simplejson. The C version of simplejson does turn in a performance about 12x faster, but that's apples to oranges. The design of the encoder would also make a XML serializer pretty straight forward to implement as well (not that I care about XML, *blech*). I'm torn between just moving on to some of my other coding tasks and putting some time into this to make it pass the simplejson/std lib json tests. I really do think the standard lib json encoder is bad and I would like to see an alternative in there but I'm hesitant to get involved. Nathan On Thu, Oct 27, 2011 at 11:24 AM, Amirouche Boubekki wrote: > > > 2011/10/27 Chris Rebert >> >> On Wed, Oct 26, 2011 at 2:14 AM, Amirouche Boubekki >> wrote: >> > H?llo, >> > >> > I would like to fork simplejson [1] and implement serialization rules >> > based >> > on protocols instead of types [2], plus special cases for protocol free >> > objects, that breaks compatibility. The benefit will be a better API for >> > json serialization of custom classes and in the case of iterable it will >> > avoid a calls like: >> > >> >>>> simplejson.dumps(list(my_iterable)) >> > >> > The serialization of custom objects is documented in the class instead >> > of >> > the ``default`` function of current simplejson implementation [3]. >> > >> > The encoding algorithm works with a priority list that is summarized in >> > the >> > next table: >> > >> > ? ? +-------------------+---------------+ >> > ? ? | Python protocol ? | JSON ? ? ? ? ?| >> > ? ? | ?or special case ?| ? ? ? ? ? ? ? | >> > ? ? +===================+===============+ >> >> > ? ? | (?) unicode ? ? ? | see (?) ? ? ? | >> >> > (?) if the algorithm arrives here, call unicode (with proper encoding >> > rule) >> > on the object and use the result as json serialization >> >> I would prefer a TypeError in such cases, for the same reason >> str.join() doesn't do an implicit str() on its operands: >> - Explicit is better than implicit. >> - (Likely) errors should never pass silently. >> - In the face of ambiguity, refuse the temptation to guess. > > granted it's better. > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From dhyams at gmail.com Fri Oct 28 13:34:35 2011 From: dhyams at gmail.com (dhyams) Date: Fri, 28 Oct 2011 10:34:35 -0700 (PDT) Subject: How to mix-in __getattr__ after the fact? Message-ID: <4630c4d0-86bc-4295-8bbb-6f58415191c8@v15g2000vbm.googlegroups.com> Python 2.7.2 I'm having trouble in a situation where I need to mix-in the functionality of __getattr__ after the object has already been created. Here is a small sample script of the situation: =============snip import types class Cow(object): pass # this __getattr__ works as advertised. #def __getattr__(self,a): # print "CAUGHT INCLASS: Attempting to get attribute ",a def attrgetter(self,a): print "CAUGHT: Attempting to get attribute ",a bessie = Cow() bessie.__getattr__ = types.MethodType(attrgetter,bessie,Cow) # here, I should see my printout "attempting to get attribute" # but I get an AttributeException print bessie.milk ======================snip If I call __getattr__ directly, as in bessie.__getattr__('foo'), it works as it should obviously; so the method is bound and ready to be called. But Python does not seem to want to call __getattr__ appropriately if I mix it in after the object is already created. Is there a workaround, or am I doing something wrongly? Thanks, From pmaupin at gmail.com Fri Oct 28 14:05:05 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 28 Oct 2011 11:05:05 -0700 (PDT) Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> Message-ID: <20aeed48-8d77-445a-a4b6-85f0309e714f@f36g2000vbm.googlegroups.com> On Oct 27, 10:23?pm, Terry Reedy wrote: > I do not think everyone else should suffer substantial increase in space > and run time to avoid surprising you. What substantial increase? There's already a check that winds up raising an exception. Just make it empty an iterator instead. > > It violates the principle of least surprise > > for ctypes to do what is most efficient in 99.9% of uses? It doesn't work at all with an iterator, so it's most efficient 100% of the time now. How do you know how many people would use iterators if it worked? > > It could, but at some cost. Remember, people use ctypes for efficiency, yes, you just made my argument for me. Thank you. It is incredibly inefficient to have to create a temp array. > so the temp array path would have to be conditional. I don't understand this at all. Right now, it just throws up its hands and says "I don't work with iterators." Why would it be a problem to change this? From michaelm at plumbersstock.com Fri Oct 28 14:10:14 2011 From: michaelm at plumbersstock.com (Michael McGlothlin) Date: Fri, 28 Oct 2011 12:10:14 -0600 Subject: Fast recursive generators? Message-ID: I'm trying to generate a list of values where each value is dependent on the previous value in the list and this bit of code needs to be repeatedly so I'd like it to be fast. It doesn't seem that comprehensions will work as each pass needs to take the result of the previous pass as it's argument. map() doesn't seem likely. filter() or reduce() seem workable but not very clean. Is there a good way to do this? About the best I can get is this: l = [ func ( start ) ] f = lambda a: func ( l[-1] ) or a filter ( f, range ( big_number, -1, -1 ) ) I guess I'm looking for something more like: l = do ( lambda a: func ( a ), big_number, start ) Thanks, Michael McGlothlin From malaclypse2 at gmail.com Fri Oct 28 14:14:34 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 28 Oct 2011 14:14:34 -0400 Subject: How to mix-in __getattr__ after the fact? In-Reply-To: <4630c4d0-86bc-4295-8bbb-6f58415191c8@v15g2000vbm.googlegroups.com> References: <4630c4d0-86bc-4295-8bbb-6f58415191c8@v15g2000vbm.googlegroups.com> Message-ID: On Fri, Oct 28, 2011 at 1:34 PM, dhyams wrote: > If I call __getattr__ directly, as in bessie.__getattr__('foo'), it > works as it should obviously; so the method is bound and ready to be > called. ?But Python does not seem to want to call __getattr__ > appropriately if I mix it in after the object is already created. ?Is > there a workaround, or am I doing something wrongly? Python looks up special methods on the class, not the instance (see http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes). It seems like you ought to be able to delegate the special attribute access from the class to the instance somehow, but I couldn't figure out how to do it in a few minutes of fiddling at the interpreter. -- Jerry From ethan at stoneleaf.us Fri Oct 28 14:20:20 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 28 Oct 2011 11:20:20 -0700 Subject: How to mix-in __getattr__ after the fact? In-Reply-To: <4630c4d0-86bc-4295-8bbb-6f58415191c8@v15g2000vbm.googlegroups.com> References: <4630c4d0-86bc-4295-8bbb-6f58415191c8@v15g2000vbm.googlegroups.com> Message-ID: <4EAAF264.1050307@stoneleaf.us> dhyams wrote: > Python 2.7.2 > > I'm having trouble in a situation where I need to mix-in the > functionality of __getattr__ after the object has already been > created. Here is a small sample script of the situation: > > =============snip > > import types > > class Cow(object): > pass > # this __getattr__ works as advertised. > #def __getattr__(self,a): > # print "CAUGHT INCLASS: Attempting to get attribute ",a > > > def attrgetter(self,a): > print "CAUGHT: Attempting to get attribute ",a > > bessie = Cow() > > bessie.__getattr__ = types.MethodType(attrgetter,bessie,Cow) > > # here, I should see my printout "attempting to get attribute" > # but I get an AttributeException > print bessie.milk > ======================snip > > If I call __getattr__ directly, as in bessie.__getattr__('foo'), it > works as it should obviously; so the method is bound and ready to be > called. But Python does not seem to want to call __getattr__ > appropriately if I mix it in after the object is already created. Is > there a workaround, or am I doing something wrongly? > > Thanks, Python only looks up __xxx__ methods in new-style classes on the class itself, not on the instances. So this works: 8<---------------------------------------------------------------- class Cow(object): pass def attrgetter(self, a): print "CAUGHT: Attempting to get attribute", a bessie = Cow() Cow.__getattr__ = attrgetter print bessie.milk 8<---------------------------------------------------------------- ~Ethan~ From tjreedy at udel.edu Fri Oct 28 16:24:02 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Oct 2011 16:24:02 -0400 Subject: Assigning generator expressions to ctype arrays In-Reply-To: <20aeed48-8d77-445a-a4b6-85f0309e714f@f36g2000vbm.googlegroups.com> References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> <20aeed48-8d77-445a-a4b6-85f0309e714f@f36g2000vbm.googlegroups.com> Message-ID: On 10/28/2011 2:05 PM, Patrick Maupin wrote: > On Oct 27, 10:23 pm, Terry Reedy wrote: >> I do not think everyone else should suffer substantial increase in space >> and run time to avoid surprising you. > > What substantial increase? of time and space, as I said, for the temporary array that I think would be needed and which I also described in the previous paragraph that you clipped > There's already a check that winds up > raising an exception. Just make it empty an iterator instead. It? I have no idea what you intend that to refer to. >>> It violates the principle of least surprise >> for ctypes to do what is most efficient in 99.9% of uses? > > It doesn't work at all with an iterator, so it's most efficient 100% > of the time now. How do you know how many people would use iterators > if it worked? I doubt it would be very many because it is *impossible* to make it work in the way that I think people would want it to. >> It could, but at some cost. Remember, people use ctypes for efficiency, > yes, you just made my argument for me. Thank you. It is incredibly > inefficient to have to create a temp array. But necessary to work with blank box iterators. Now you are agreeing with my argument. >> so the temp array path would have to be conditional. > I don't understand this at all. Right now, it just throws up its > hands and says "I don't work with iterators." If ctype_array slice assignment were to be augmented to work with iterators, that would, in my opinion (and see below), require use of temporary arrays. Since slice assignment does not use temporary arrays now (see below), that augmentation should be conditional on the source type being a non-sequence iterator. > Why would it be a problem to change this? CPython comes with immutable fixed-length arrays (tuples) that do not allow slice assignment and mutable variable-length arrays (lists) that do. The definition is 'replace the indicated slice with a new slice built from all values from an iterable'. Point 1: This works for any properly functioning iterable that produces any finite number of items. Iterators are always exhausted. Replace can be thought of as delete follewed by add, but the implementation is not that naive. Point 2: If anything goes wrong and an exception is raised, the list is unchanged. This means that there must be temporary internal storage of either old or new references. An example that uses an improperly functioning generator. >>> a [0, 1, 2, 3, 4, 5, 6, 7] >>> def g(): yield None raise ValueError >>> a[3:6]=g() Traceback (most recent call last): File "", line 1, in a[3:6]=g() File "", line 3, in g raise ValueError ValueError >>> a [0, 1, 2, 3, 4, 5, 6, 7] A c_uint array is a new kind of beast: a fixed-length mutable array. So it has to have a different definition of slice assignment than lists. Thomas Heller, the ctypes author, apparently chose 'replacement by a sequence with exactly the same number of items, else raise an exception'. though I do not know what the doc actually says. An alternative definition would have been to replace as much of the slice as possible, from the beginning, while ignoring any items in excess of the slice length. This would work with any iterable. However, partial replacement of a slice would be a surprising innovation to most. The current implementation assumes that the reported length of a sequence matches the valid indexes and dispenses with temporary storage. This is shown by the following: from ctypes import c_uint n = 20 class Liar: def __len__(self): return n def __getitem__(self, index): if index < 10: return 1 else: raise ValueError() x = (n * c_uint)() print(list(x)) x[:] = range(n) print(list(x)) try: x[:] = Liar() except: pass print(list(x)) >>> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] I consider such unintended partial replacement to be a glitch. An exception could be raised, but without adding temp storage, the array could not be restored. And making a change *and* raising an exception would be a different sort of glitch. (One possible with augmented assignment involving a mutable member of a tuple.) So I would leave this as undefined behavior for an input outside the proper domain of the function. Anyway, as I said before, you are free to propose a specific change ('work with iterators' is too vague) and provide a corresponding patch. -- Terry Jan Reedy From tjreedy at udel.edu Fri Oct 28 16:45:21 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Oct 2011 16:45:21 -0400 Subject: Fast recursive generators? In-Reply-To: References: Message-ID: On 10/28/2011 2:10 PM, Michael McGlothlin wrote: > I'm trying to generate a list of values Better to think of a sequence of values, whether materialized as a 'list' or not. > where each value is dependent > on the previous value in the list and this bit of code needs to be > repeatedly so I'd like it to be fast. It doesn't seem that > comprehensions will work as each pass needs to take the result of the > previous pass as it's argument. map() doesn't seem likely. filter() or Comprehensions combine map and filter, both of which conceptually work on each item of a pre-existing list independently. (I am aware that the function passed can stash away values to create dependence. > reduce() seem workable but not very clean. Is there a good way to do > this? About the best I can get is this: > > l = [ func ( start ) ] > f = lambda a: func ( l[-1] ) or a > filter ( f, range ( big_number, -1, -1 ) ) > > > I guess I'm looking for something more like: > > l = do ( lambda a: func ( a ), big_number, start ) Something like def do(func, N, value): yield value for i in range(1,N): value = func(value) yield value ? For more generality, make func a function of both value and i. If you need a list, "l = list(do(f,N,x))", but if you do not, you can do "for item in do(f,N,x):" and skip making the list. -- Terry Jan Reedy From gelonida at gmail.com Fri Oct 28 16:47:42 2011 From: gelonida at gmail.com (Gelonida N) Date: Fri, 28 Oct 2011 22:47:42 +0200 Subject: save tuple of simple data types to disk (low memory foot print) Message-ID: Hi, I would like to save many dicts with a fixed amount of keys tuples to a file in a memory efficient manner (no random, but only sequential access is required) As the keys are the same for each entry I considered converting them to tuples. The tuples contain only strings, ints (long ints) and floats (double) and the data types for each position within the tuple are fixed. The fastest and simplest way is to pickle the data or to use json. Both formats however are not that optimal. I could store ints and floats with pack. As strings have variable length I'm not sure how to save them efficiently (except adding a length first and then the string. Is there already some 'standard' way or standard library to store such data efficiently? Thanks in advance for any suggestion. From tjreedy at udel.edu Fri Oct 28 16:52:43 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Oct 2011 16:52:43 -0400 Subject: Forking simplejson In-Reply-To: References: Message-ID: On 10/28/2011 1:20 PM, Nathan Rice wrote: > Just a random note, I actually set about the task of re-implementing a > json encoder which can be subclassed, is highly extensible, and uses > (mostly) sane coding techniques (those of you who've looked at > simplejson's code will know why this is a good thing). So far > preliminary tests show the json only subclass of the main encoder > basically tied in performance with the python implementation of > simplejson. The C version of simplejson does turn in a performance > about 12x faster, but that's apples to oranges. The design of the > encoder would also make a XML serializer pretty straight forward to > implement as well (not that I care about XML, *blech*). > > I'm torn between just moving on to some of my other coding tasks and > putting some time into this to make it pass the simplejson/std lib > json tests. I really do think the standard lib json encoder is bad Python is the result of people who thought *something* was 'bad' > and I would like to see an alternative in there and volunteered the effort to make something better. > but I'm hesitant to get involved. As someone who is involved and tries to encourage others, I am curious why. -- Terry Jan Reedy From pmaupin at gmail.com Fri Oct 28 17:51:19 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 28 Oct 2011 14:51:19 -0700 (PDT) Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> <4eaa580a$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1e1764c6-d49d-468b-a0bd-cec3033acfee@t8g2000yql.googlegroups.com> On Oct 28, 3:19?am, Terry Reedy wrote: > On 10/28/2011 3:21 AM, Steven D'Aprano wrote: > > > If the slice has too few elements, you've just blown away the entire > > iterator for no good reason. > > If the slice is the right length, but the iterator doesn't next raise > > StopIteration, you've just thrown away one perfectly good value. Hope it > > wasn't something important. > > You have also over-written values that should be set back to what they > were, before the exception is raised, which is why I said the test needs > to be done with a temporary array. > Sometimes when exceptions happen, data is lost. You both make a big deal out of simultaneously (a) not placing burden on the normal case and (b) defining the normal case by way of what happens during an exception. Iterators are powerful and efficient, and ctypes are powerful and efficient, and the only reason you've managed to give why I shouldn't be able to fill a ctype array slice from an iterator is that, IF I SCREW UP and the iterator doesn't produce the right amount of data, I will have lost some data. Regards, Pat From nathan.alexander.rice at gmail.com Fri Oct 28 18:49:05 2011 From: nathan.alexander.rice at gmail.com (Nathan Rice) Date: Fri, 28 Oct 2011 18:49:05 -0400 Subject: Forking simplejson In-Reply-To: References: Message-ID: I've found that in a lot of cases getting a patch submitted is only half about good engineering. The other half is politics. I like one of those things, I don't like the other, and I don't want to take time out of my coding schedule to write something if in the end a reviewer shoots down my patch for contrived reasons. I don't know what the python committers are like but I guess you could say I'm once bitten twice shy. Nathan On Fri, Oct 28, 2011 at 4:52 PM, Terry Reedy wrote: > On 10/28/2011 1:20 PM, Nathan Rice wrote: >> >> Just a random note, I actually set about the task of re-implementing a >> json encoder which can be subclassed, is highly extensible, and uses >> (mostly) sane coding techniques (those of you who've looked at >> simplejson's code will know why this is a good thing). ?So far >> preliminary tests show the json only subclass of the main encoder >> basically tied in performance with the python implementation of >> simplejson. ?The C version of simplejson does turn in a performance >> about 12x faster, but that's apples to oranges. ?The design of the >> encoder would also make a XML serializer pretty straight forward to >> implement as well (not that I care about XML, *blech*). >> >> I'm torn between just moving on to some of my other coding tasks and >> putting some time into this to make it pass the simplejson/std lib >> json tests. ?I really do think the standard lib json encoder is bad > > Python is the result of people who thought *something* was 'bad' > >> and I would like to see an alternative in there > > and volunteered the effort to make something better. > >> but I'm hesitant to get involved. > > As someone who is involved and tries to encourage others, I am curious why. > > -- > Terry Jan Reedy > > -- > http://mail.python.org/mailman/listinfo/python-list > From roy at panix.com Fri Oct 28 19:08:42 2011 From: roy at panix.com (Roy Smith) Date: Fri, 28 Oct 2011 19:08:42 -0400 Subject: save tuple of simple data types to disk (low memory foot print) References: Message-ID: In article , Gelonida N wrote: > I would like to save many dicts with a fixed amount of keys > tuples to a file in a memory efficient manner (no random, but only > sequential access is required) There's two possible scenarios here. One, which you seem to be exploring, is to carefully study your data and figure out the best way to externalize it which reduces volume. The other is to just write it out in whatever form is most convenient (JSON is a reasonable thing to try first), and compress the output. Let the compression algorithms worry about extracting the entropy. You may be surprised at how well it works. It's also an easy experiment to try, so if it doesn't work well, at least it didn't cost you much to find out. From pmaupin at gmail.com Fri Oct 28 19:27:37 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 28 Oct 2011 16:27:37 -0700 (PDT) Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> <4eaa580a$0$29968$c3e8da3$5496439d@news.astraweb.com> <1e1764c6-d49d-468b-a0bd-cec3033acfee@t8g2000yql.googlegroups.com> Message-ID: <88b69248-5faf-473b-b12c-543973fbb8a0@f36g2000vbm.googlegroups.com> On Oct 28, 4:51?pm, Patrick Maupin wrote: > On Oct 28, 3:19?am, Terry Reedy wrote: > > > On 10/28/2011 3:21 AM, Steven D'Aprano wrote: > > > > If the slice has too few elements, you've just blown away the entire > > > iterator for no good reason. > > > If the slice is the right length, but the iterator doesn't next raise > > > StopIteration, you've just thrown away one perfectly good value. Hope it > > > wasn't something important. > > > You have also over-written values that should be set back to what they > > were, before the exception is raised, which is why I said the test needs > > to be done with a temporary array. > > Sometimes when exceptions happen, data is lost. You both make a big > deal out of simultaneously (a) not placing burden on the normal case > and (b) defining the normal case by way of what happens during an > exception. ?Iterators are powerful and efficient, and ctypes are > powerful and efficient, and the only reason you've managed to give why > I shouldn't be able to fill a ctype array slice from an iterator is > that, IF I SCREW UP and the iterator doesn't produce the right amount > of data, I will have lost some data. > > Regards, > Pat And, BTW, the example you give of, e.g. a,b,c = (some generator expression) ALREADY LOSES DATA if the iterator isn't the right size and it raises an exception. It doesn't overwrite a or b or c, but you're deluding yourself if you think that means it hasn't altered the system state. From michaelm at plumbersstock.com Fri Oct 28 20:49:15 2011 From: michaelm at plumbersstock.com (Michael McGlothlin) Date: Fri, 28 Oct 2011 18:49:15 -0600 Subject: Fast recursive generators? In-Reply-To: References: Message-ID: >> I'm trying to generate a list of values > > Better to think of a sequence of values, whether materialized as a 'list' or > not. The final value will actually be a string but it seems it is usually faster to join a list of strings than to concat them one by one. >> where each value is dependent >> on the previous value in the list and this bit of code needs to be >> repeatedly so I'd like it to be fast. It doesn't seem that >> comprehensions will work as each pass needs to take the result of the >> previous pass as it's argument. map() doesn't seem likely. filter() or > > Comprehensions combine map and filter, both of which conceptually work on > each item of a pre-existing list independently. (I am aware that the > function passed can stash away values to create dependence. The problem is I don't really have a pre-existing list. I just want a tight loop to generate the list from the initial value. Probably I could do something similar to my filter() method below but it seems really convoluted. I thought maybe there was a better way I just didn't know about. Python is full of neat tricks but it can be hard to remember them all. >> reduce() seem workable but not very clean. Is there a good way to do >> this? About the best I can get is this: >> >> l = [ func ( start ) ] >> f = lambda a: func ( l[-1] ) or a >> filter ( f, range ( big_number, -1, -1 ) ) >> >> >> I guess I'm looking for something more like: >> >> l = do ( lambda a: func ( a ), big_number, start ) > > Something like > > def do(func, N, value): > ? ?yield value > ? ?for i in range(1,N): > ? ? ? ?value = func(value) > ? ? ? ?yield value > > ? > For more generality, make func a function of both value and i. > If you need a list, "l = list(do(f,N,x))", but if you do not, you can do > "for item in do(f,N,x):" and skip making the list. Generators seem considerably slower than using comprehension or map/filter/reduce. I have tons of memory to work in (~100GB actual RAM) and the resulting data isn't that big so I'm more concerned about CPU. Thanks. From steve+comp.lang.python at pearwood.info Fri Oct 28 21:00:17 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 29 Oct 2011 01:00:17 GMT Subject: save tuple of simple data types to disk (low memory foot print) References: Message-ID: <4eab5021$0$29968$c3e8da3$5496439d@news.astraweb.com> On Fri, 28 Oct 2011 22:47:42 +0200, Gelonida N wrote: > Hi, > > I would like to save many dicts with a fixed amount of keys tuples to a > file in a memory efficient manner (no random, but only sequential > access is required) What do you call "many"? Fifty? A thousand? A thousand million? How many items in each dict? Ten? A million? What do you mean "keys tuples"? > As the keys are the same for each entry I considered converting them to > tuples. I don't even understand what that means. You're going to convert the keys to tuples? What will that accomplish? > The tuples contain only strings, ints (long ints) and floats (double) > and the data types for each position within the tuple are fixed. > > The fastest and simplest way is to pickle the data or to use json. Both > formats however are not that optimal. How big are your JSON files? 10KB? 10MB? 10GB? Have you tried using pickle's space-efficient binary format instead of text format? Try using protocol=2 when you call pickle.Pickler. Or have you considered simply compressing the files? > I could store ints and floats with pack. As strings have variable length > I'm not sure how to save them efficiently (except adding a length first > and then the string. This isn't 1980 and you're very unlikely to be using 720KB floppies. Premature optimization is the root of all evil. Keep in mind that when you save a file to disk, even if it contains only a single bit of data, the actual space used will be an entire block, which on modern hard drives is very likely to be 4KB. Trying to compress files smaller than a single block doesn't actually save you any space. > Is there already some 'standard' way or standard library to store such > data efficiently? Yes. Pickle and JSON plus zip or gzip. -- Steven From steve+comp.lang.python at pearwood.info Fri Oct 28 21:01:56 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 29 Oct 2011 01:01:56 GMT Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> <4eaa580a$0$29968$c3e8da3$5496439d@news.astraweb.com> <1e1764c6-d49d-468b-a0bd-cec3033acfee@t8g2000yql.googlegroups.com> <88b69248-5faf-473b-b12c-543973fbb8a0@f36g2000vbm.googlegroups.com> Message-ID: <4eab5084$0$29968$c3e8da3$5496439d@news.astraweb.com> On Fri, 28 Oct 2011 16:27:37 -0700, Patrick Maupin wrote: > And, BTW, the example you give of, e.g. > > a,b,c = (some generator expression) > > ALREADY LOSES DATA if the iterator isn't the right size and it raises an > exception. Yes. What's your point? This fact doesn't support your proposal in the slightest. You have argued against using a temporary array. I quote: "It is incredibly inefficient to have to create a temp array." [Aside: how do you know this is not just inefficient but *incredibly* so?] But that's exactly what happens in tuple unpacking: the generator on the right hand side is unpacked into a temporary tuple, and then assigned to the targets on the left hand side. If the number of elements on both sides aren't the same, the assignment fails. That is, tuple unpacking behaves like this pseudo-code: targets = left hand side values = tuple(right hand side) if len(targets) != len(values): fail otherwise: for each pair target, value: target = value This has the important property that the assignment is atomic: it either succeeds in full, or it doesn't occur. The only side-effect is to exhaust the generator, which is unavoidable given that generators don't have a length. Without temporary storage for the right hand side, you lose the property of atomicism. That would be unacceptable. In the case of the ctypes array, the array slice assignment is also treated as atomic: it either succeeds in full, or it fails in full. This is an important property. Unlike tuple unpacking, the array is even more conservative about what is on the right hand size: it doesn't accept iterators at all, only sequences. This is a sensible default, because it is *easy* to work around: if you want to unpack the iterator, just make a temporary list: array[:] = list(x+1 for x in range(32)) Assignment remains atomic, and the generator will be unpacked into a temporary list at full C speed. If you don't care about assignment being atomic -- and it's your right to weaken the array contract in your own code -- feel free to write your own helper function based on your earlier suggestion: "It merely needs to fill the slice and then ask for one more and check that StopIteration is raised." def array_assign(array, values): try: if len(values) == len(array): array[:] = values # runs at full C speed except TypeError: try: for i in xrange(len(array)): array[i] = next(values) # or values.next in Python 2.5 except StopIteration: raise TypeError('too few items') try: next(values) except StopIteration: pass else: raise TypeError('too many values') But this non-atomic behaviour would be entirely inappropriate as the default behaviour for a ctypes array. -- Steven From bahamutzero8825 at gmail.com Fri Oct 28 21:25:24 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Fri, 28 Oct 2011 20:25:24 -0500 Subject: Need Windows user / developer to help with Pynguin In-Reply-To: References: Message-ID: <4EAB5604.6000509@gmail.com> On 10/27/2011 5:36 PM, Lee Harr wrote: > What message do you get when trying to download? It said something like "You're trying to download from a forbidden country. That's all we know." Anyway, I was able to get the files. Once everything is set up, it seems to work. I haven't done any serious testing, but it opens and I can move the penguin and use the examples. BTW, you may want to look into py2exe or cx_Freeze to make Windows binaries. Also, the Python installer associates .py and .pyw files with python.exe and pythonw.exe respectively, so if you add the extension as Terry mentioned, it should work. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 From pmaupin at gmail.com Fri Oct 28 22:14:18 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 28 Oct 2011 19:14:18 -0700 (PDT) Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> <4eaa580a$0$29968$c3e8da3$5496439d@news.astraweb.com> <1e1764c6-d49d-468b-a0bd-cec3033acfee@t8g2000yql.googlegroups.com> <88b69248-5faf-473b-b12c-543973fbb8a0@f36g2000vbm.googlegroups.com> <4eab5084$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <6452ce55-bf89-4c30-87f2-bc651763667a@r2g2000vbj.googlegroups.com> On Oct 28, 8:01?pm, Steven D'Aprano > > ALREADY LOSES DATA if the iterator isn't the right size and it raises an > > exception. > > Yes. What's your point? This fact doesn't support your proposal in the > slightest. You earlier made the argument that "If the slice has too few elements, you've just blown away the entire iterator for no good reason. If the slice is the right length, but the iterator doesn't next raise StopIteration, you've just thrown away one perfectly good value. Hope it wasn't something important." In other words, you WERE arguing that it's very important not to lose information. Now that I show that information is ALREADY LOST in a similar scenario, you are arguing that's irrelevant. Whatever. > You have argued against using a temporary array. I quote: > > [Aside: how do you know this is not just inefficient but *incredibly* so?] By profiling my app, looking for places to save time without having to resort to C. > But that's exactly what happens in tuple unpacking: > the generator on the right hand side is unpacked into > a temporary tuple, and then assigned to the targets > on the left hand side. Agreed. But Terry was making the (correct) argument that people using ctypes are often looking for efficiency. > If the number of elements on both sides aren't the same, > the assignment fails. That is, tuple unpacking behaves > like (snip) Yes, and that loses information from the right hand side if it fails and the right hand side happens to be an iterator. For some reason you're OK with that in this case, but it was the worst thing in the world a few messages ago. > This has the important property that the > assignment is atomic: it either succeeds in full, > or it doesn't occur. Not right at all. >The only side-effect is to exhaust the generator, > which is unavoidable given that generators don't have a > length. Yes. But earlier you were acting like it would be problematic for me to lose information out of the generator if there were a failure, and now the sanctity of the information on the LHS is so much more than on the RHS. Frankly, that's all a crock. In your earlier email, you argued that my proposal loses information, when in fact, in some cases it PRESERVES information (the very information you are trying to transfer) that ISN'T preserved when this temp array is tossed, and the only information it LOSES is information the programmer declared his clear intent to kill. But that's an edge case anyway. > Without temporary storage for the right hand side, > you lose the property of atomicism. That would be > unacceptable. As if the temporary storage workaround exhibited the "necessary" atomicity, or as if you have even showed a valid argument why the atomicity is important for this case. > In the case of the ctypes array, the array slice assignment is also > treated as atomic: it either succeeds in full, or it fails in full. > This is an important property. Unlike tuple unpacking, the array is even more > conservative about what is on the right hand size: it doesn't accept > iterators at all, only sequences. This is a sensible default, How it works is not a bad start, but it's arguably unfinished. > because it is *easy* to work around: if you want to unpack the iterator, just make a temporary list: (snip) I already said I know the workaround. I don't know why you can't believe that. But one of the purposes of the iterator protocol is to reduce the number of cases where you have to create huge lists. > Assignment remains atomic, and the generator will be unpacked into a > temporary list at full C speed. Which can be very slow if your list has several million items in it. > If you don't care about assignment being atomic -- and it's your right to > weaken the array contract in your own code Currently, there IS no contract between ctype arrays and generators. I'm suggesting that it would be useful to create one, and further suggesting that if a programmer attempts to load a ctypes array from a generator of the wrong size, it is certainly important to let the programmer know he screwed up, but it is not at all important that some elements of the ctypes array, that the programmer was in fact trying to replace, were in fact correctly replaced before the size error was noticed. > -- feel free to write your own > helper function based on your earlier suggestion: (snip) Doing this in Python is also slow and painful, and the tradeoff of this vs the temp list depends on the system, the caching, the amount of memory available, and the size of the data to be transferred. I could do it in C, but that defeats my whole purpose of using ctypes to avoid having to ship C code to customers. > But this non-atomic behaviour would be entirely inappropriate as the > default behaviour for a ctypes array. That's obviously your opinion, but your supporting arguments are quite weak. Regards, Pat From lie.1296 at gmail.com Fri Oct 28 22:26:31 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 29 Oct 2011 13:26:31 +1100 Subject: How to mix-in __getattr__ after the fact? In-Reply-To: <4EAAF264.1050307@stoneleaf.us> References: <4630c4d0-86bc-4295-8bbb-6f58415191c8@v15g2000vbm.googlegroups.com> <4EAAF264.1050307@stoneleaf.us> Message-ID: On 10/29/2011 05:20 AM, Ethan Furman wrote: > > Python only looks up __xxx__ methods in new-style classes on the class > itself, not on the instances. > > So this works: > > 8<---------------------------------------------------------------- > class Cow(object): > pass > > def attrgetter(self, a): > print "CAUGHT: Attempting to get attribute", a > > bessie = Cow() > > Cow.__getattr__ = attrgetter > > print bessie.milk > 8<---------------------------------------------------------------- a minor modification might be useful: bessie = Cow() bessie.__class__.__getattr__ = attrgetter From tjreedy at udel.edu Fri Oct 28 22:27:40 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Oct 2011 22:27:40 -0400 Subject: Fast recursive generators? In-Reply-To: References: Message-ID: On 10/28/2011 8:49 PM, Michael McGlothlin wrote: >> Better to think of a sequence of values, whether materialized as a 'list' or >> not. > > The final value will actually be a string but it seems it is usually > faster to join a list of strings than to concat them one by one. .join() takes an iterable of strings as its argument >> Comprehensions combine map and filter, both of which conceptually work on >> each item of a pre-existing list independently. (I am aware that the >> function passed can stash away values to create dependence. > > The problem is I don't really have a pre-existing list. So, as I said, map, filter, and comprehensions are not applicable to your problem. >> def do(func, N, value): >> yield value >> for i in range(1,N): >> value = func(value) >> yield value >> >> For more generality, make func a function of both value and i. >> If you need a list, "l = list(do(f,N,x))", but if you do not, you can do >> "for item in do(f,N,x):" and skip making the list. > > Generators seem considerably slower than using comprehension or > map/filter So what? A saw may cut faster than a hammer builds, but I hope you don't grab a saw when you need a hammer. > /reduce. Do you actually have an example where ''.join(reduce(update, N, start)) is faster than ''.join(update_gen(N, start))? Resuming a generator n times should be *faster* than n calls to the update function of reduce (which will actually have to build a list). --- Terry Jan Reedy From gagsl-py2 at yahoo.com.ar Fri Oct 28 23:18:04 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Oct 2011 00:18:04 -0300 Subject: Fast recursive generators? References: Message-ID: En Fri, 28 Oct 2011 15:10:14 -0300, Michael McGlothlin escribi?: > I'm trying to generate a list of values where each value is dependent > on the previous value in the list and this bit of code needs to be > repeatedly so I'd like it to be fast. It doesn't seem that > comprehensions will work as each pass needs to take the result of the > previous pass as it's argument. map() doesn't seem likely. filter() or > reduce() seem workable but not very clean. Is there a good way to do > this? About the best I can get is this: > > l = [ func ( start ) ] > f = lambda a: func ( l[-1] ) or a > filter ( f, range ( big_number, -1, -1 ) ) > > > I guess I'm looking for something more like: > > l = do ( lambda a: func ( a ), big_number, start ) What about a generator function? def my_generator(): prev = 1 yield prev while True: this = 2*prev yield this prev = this print list(itertools.islice(my_generator(), 10)) -- Gabriel Genellina From patx44 at gmail.com Sat Oct 29 01:54:52 2011 From: patx44 at gmail.com (patx) Date: Sat, 29 Oct 2011 01:54:52 -0400 Subject: Introducing pickleDB; a simple, lightweight, and fast key-value database. Message-ID: Hello I have recently started work on a new project called pickleDB. It is a lightweight key-value database engine (inspired by redis). Check it out at http://packages.python.org/pickleDB -- Harrison Erd -------------- next part -------------- An HTML attachment was scrubbed... URL: From dihedral88888 at googlemail.com Sat Oct 29 05:10:27 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Sat, 29 Oct 2011 02:10:27 -0700 (PDT) Subject: Fast recursive generators? In-Reply-To: References: Message-ID: <31591999.1755.1319879427800.JavaMail.geo-discussion-forums@prlk36> I am thinking the bye code compiler in python can be faster if all known immutable instances up to the execution are compiled immutable objects to be assigned. From dihedral88888 at googlemail.com Sat Oct 29 05:10:27 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Sat, 29 Oct 2011 02:10:27 -0700 (PDT) Subject: Fast recursive generators? In-Reply-To: References: Message-ID: <31591999.1755.1319879427800.JavaMail.geo-discussion-forums@prlk36> I am thinking the bye code compiler in python can be faster if all known immutable instances up to the execution are compiled immutable objects to be assigned. From ramapraba2653 at gmail.com Sat Oct 29 05:19:35 2011 From: ramapraba2653 at gmail.com (SUPREME) Date: Sat, 29 Oct 2011 02:19:35 -0700 (PDT) Subject: `********AMAZING HOT PHOTOS & VIDEOS ******** Message-ID: <125f9a4d-4a56-47e2-a941-2b35fa27b388@x16g2000prd.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html SAKUNI MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/sakuni-movie-stills.html 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html FOR ONLY HOT GUYS SEE THIS TRISHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/trisha-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html SNEHA ULLAL HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/sneha-ullal-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html From g.rodola at gmail.com Sat Oct 29 06:15:18 2011 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Sat, 29 Oct 2011 12:15:18 +0200 Subject: ANN: psutil 0.4.0 released Message-ID: Hi folks, I'm pleased to announce the 0.4.0 release of psutil: http://code.google.com/p/psutil === About === psutil is a module providing an interface for retrieving information on all running processes and system utilization (CPU, disk, memory, network) in a portable way by using Python, implementing many functionalities offered by command line tools such as ps, top, free, lsof and others. It works on Linux, Windows, OSX and FreeBSD, both 32-bit and 64-bit, with Python versions from 2.4 to 3.3 by using a single code base. === Major enhancements === Aside from fixing different high priority bugs this release introduces two new important features: disks and network IO counters. With these, you can monitor disks usage and network traffic. 2 scripts were added to provide an example of what kind of applications can be written with these two hooks: http://code.google.com/p/psutil/source/browse/trunk/examples/iotop.py http://code.google.com/p/psutil/source/browse/trunk/examples/nettop.py ...and here you can see some screenshots: http://code.google.com/p/psutil/#Example_applications === Other enhancements == - Process.get_connections() has a new 'kind' parameter to filters for connections by using different criteria. - timeout=0 parameter can now be passed to Process.wait() to make it return immediately (non blocking). - Python 3.2 installer for Windows 64 bit is now provided in downloads section. - (FreeBSD) addeed support for Process.getcwd() - (FreeBSD) Process.get_open_files() has been rewritten in C and no longer relies on lsof. - various crashes on module import across differnt platforms were fixed. For a complete list of features and bug fixes see: http://psutil.googlecode.com/svn/trunk/HISTORY === New features by example === >>> import psutil >>> >>> psutil.disk_io_counters() iostat(read_count=8141, write_count=2431, read_bytes=290203, write_bytes=537676, read_time=5868, write_time=94922) >>> >>> psutil.disk_io_counters(perdisk=True) {'sda1' :iostat(read_count=8141, write_count=2431, read_bytes=290203, write_bytes=537676, read_time=5868, write_time=94922), 'sda2' :iostat(read_count=811241, write_count=31, read_bytes=1245, write_bytes=11246, read_time=768008, write_time=922)} >>> >>> >>> psutil.network_io_counters() iostat(bytes_sent=1270374, bytes_recv=7828365, packets_sent=9810, packets_recv=11794) >>> >>> psutil.network_io_counters(pernic=True) {'lo': iostat(bytes_sent=800251705, bytes_recv=800251705, packets_sent=455778, packets_recv=455778), 'eth0': iostat(bytes_sent=813731756, bytes_recv=4183672213, packets_sent=3771021, packets_recv=4199213)} >>> >>> >>> import os >>> p = psutil.Process(os.getpid()) >>> p.get_connections(kind='tcp') [connection(fd=115, family=2, type=1, local_address=('10.0.0.1', 48776), remote_address=('93.186.135.91', 80), status='ESTABLISHED')] >>> p.get_connections(kind='udp6') [] >>> p.get_connections(kind='inet6') [] >>> === Links === * Home page: http://code.google.com/p/psutil * Source tarball: http://psutil.googlecode.com/files/psutil-0.4.0.tar.gz * Api Reference: http://code.google.com/p/psutil/wiki/Documentation As a final note I'd like to thank Jeremy Whitlock, who kindly contributed disk/network io counters code for OSX and Windows. Please try out this new release and let me know if you experience any problem by filing issues on the bug tracker. Thanks in advance. --- Giampaolo Rodola' http://code.google.com/p/pyftpdlib/ http://code.google.com/p/psutil/ From missive at hotmail.com Sat Oct 29 10:43:13 2011 From: missive at hotmail.com (Lee Harr) Date: Sat, 29 Oct 2011 19:13:13 +0430 Subject: Need Windows user / developer to help with Pynguin Message-ID: Thanks to all those who tested and replied! > For Windows users who want to just run Pyguin (not modify or tinker > with the source code), it would be best to bundle Pynguin up with > Py2exe I considered that, but I agree that licensing issues would make it problematic. > the Python installer associates .py and .pyw files with > python.exe and pythonw.exe respectively, so if you add the extension as > Terry mentioned, it should work. I think this is the best way to go. > pynguin => pynguin.py Would it be better to go with pynguin.pyw ? Actually, I was thinking of just copying that script to something like run_pynguin.pyw Anyone able to test if just making that single change makes it so that a user can just unpack the .zip file and double click on run_pynguin.pyw to run the app? > Win7, with zip built in, just > treats x.zip as a directory in Explorer So, is that going to be a problem? The user just sees it as a folder, goes in and double-clicks on run_pynguin.pyw and once python is running what does it see? Are the contents of the virtually "unpacked" folder going to be available to the script? > You pynguin.zip contains one top level file -- a directory called > pynguin that contains multiple files I feel that this is the correct way to create a .zip file. I have run in to so many poorly formed .zip files (ones that extract all of their files to the current directory) that when extracting any .zip I always create a dummy folder and put the .zip in there before extracting. Mine is actually called pynguin-0.12.zip and extracts to a folder called pynguin-0.12 > Extracting pynguin.zip to a > pynguin directory in the same directory as pynguin.zip, the default > behavior with Win7 at least, creates a new pynguin directory that > contains the extracted pynguin directory. So, windows now creates the dummy folder automatically? Is the problem that the .zip has the same name (minus the extension)? Would it solve the problem to just change the name of the archive to something like pynguin012.zip ? > README => README.txt Just out of curiosity, what happens if you double-click the README sans .txt? Does it make you choose which app to open with? From pmaupin at gmail.com Sat Oct 29 10:43:34 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 29 Oct 2011 07:43:34 -0700 (PDT) Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> <20aeed48-8d77-445a-a4b6-85f0309e714f@f36g2000vbm.googlegroups.com> Message-ID: <4eaa454d-d1cd-4518-8476-96e06580ebfa@hj4g2000vbb.googlegroups.com> On Oct 28, 3:24?pm, Terry Reedy wrote: > On 10/28/2011 2:05 PM, Patrick Maupin wrote: > > > On Oct 27, 10:23 pm, Terry Reedy ?wrote: > >> I do not think everyone else should suffer substantial increase in space > >> and run time to avoid surprising you. > > > What substantial increase? > > of time and space, as I said, for the temporary array that I think would > be needed and which I also described in the previous paragraph that you > clipped That's because I don't think it needs a temporary array. A temporary array would provide some invariant guarantees that are nice but not necessary in a lot of real-world cases. > > > ?There's already a check that winds up > > raising an exception. ?Just make it empty an iterator instead. > > It? I have no idea what you intend that to refer to. Sorry, code path. There is already a "code path" that says "hey I can't handle this." To modify this code path to handle the case of a generic iterable would add a tiny bit of code, but would not add any appreciable space (no temp array needed for my proposal) and would not add any runtime to people who are not passing in iterables or doing other things that currently raise exceptions. > I doubt it would be very many because it is *impossible* to make it work > in the way that I think people would want it to. How do you know? I have a use case that I really don't think is all that rare. I know exactly how much data I am generating, but I am generating it piecemeal using iterators. > >> It could, but at some cost. Remember, people use ctypes for efficiency, > > yes, you just made my argument for me. ?Thank you. ?It is incredibly > > inefficient to have to create a temp array. No, I don't think I did "make your argument for you." I am currently making a temp list because I have to, and am proposing that with a small change to the ctypes library, that wouldn't always need to be done. > But necessary to work with blank box iterators. With your own preconceived set of assumptions. (Which I will admit, you have given quite a bit of thought to, which I appreciate.) > Now you are agreeing with my argument. Nope, still not doing that. > If ctype_array slice assignment were to be augmented to work with > iterators, that would, in my opinion (and see below), That's better for not being absolute. Thank you for admitting other possibilities. > require use of > temporary arrays. Since slice assignment does not use temporary arrays > now (see below), that augmentation should be conditional on the source > type being a non-sequence iterator. I don't think any temporary array is required, but in any case, yes the code path through the ctypes array library __setslice__ would have to be modified where it gives up now, in order to decide to do something different if it is passed an iterable. > CPython comes with immutable fixed-length arrays (tuples) that do not > allow slice assignment and mutable variable-length arrays (lists) that > do. The definition is 'replace the indicated slice with a new slice > built from all values from an iterable'. Point 1: This works for any > properly functioning iterable that produces any finite number of items. Agreed. > Iterators are always exhausted. And my proposal would continue to exhaust iterators, or would raise an exception if the iterator wasn't exhausted. > Replace can be thought of as delete follewed by add, but the > implementation is not that naive. Sure, on a mutable length item. > Point 2: If anything goes wrong and an > exception is raised, the list is unchanged. This may be true on lists, and is quite often true (and is nice when it happens), but it isn't always true in general. For example, with the current tuple packing/unpacking protocol across an assignment, the only real guarantee is that everything is gathered up into a single object before the assignment is done. It is not the case that nothing will be unpacked unless everything can be unpacked. For example: >>> >>> a,b,c,d,e,f,g,h,i = range(100,109) >>> (a,b,c,d), (e,f), (g,h,i) = (1,2,3,4), (5,6,7), (8,9) Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack >>> a,b,c,d,e,f,g,h,i (1, 2, 3, 4, 104, 105, 106, 107, 108) >>> > This means that there must > be temporary internal storage of either old or new references. As I show with the tuple unpacking example, it is not an inviolate law that Python won't unpack a little unless it can unpack everything. > An > example that uses an improperly functioning generator. (snip) Yes, I agree that lists are wondrously robust. But one of the reasons for this is the "flexible" interpretation of slice start and end points, that can be as surprising to a beginner as anything I'm proposing. > A c_uint array is a new kind of beast: a fixed-length mutable > array. So it has to have a different definition of slice > assignment than lists. Thomas Heller, the ctypes author, > apparently chose 'replacement by a sequence with exactly > the same number of items, else raise an exception'. though > I do not know what the doc actually says. Yes, but ctypes was designed and developed before generator expressions were available, and before or contemporaneously with the first cut of itertools. We arguably use Python differently than we did in those days. > An alternative definition would have been to replace as much of the > slice as possible, from the beginning, while ignoring any items in > excess of the slice length. This would work with any iterable. I think that an iterable that doesn't match the slice length should be an error condition and raise an exception. Both for too much data and too little data. > However, partial replacement of a slice would be a surprising innovation to most. Yes, but when an exception is raised it doesn't always mean that nothing got replaced. See my tuple unpacking example earlier. > The current implementation assumes that the reported length of a > sequence matches the valid indexes and dispenses with temporary storage. This is shown by the following: (snip) > I consider such unintended partial replacement to be a glitch. Now that's actually interesting. I agree with you that it's not desired behavior to not raise an exception. OTOH, exploiting this misfeature might actually increase performance for my specific case. > An > exception could be raised, but without adding temp storage, the array > could not be restored. And making a change *and* raising an exception > would be a different sort of glitch. (One possible with augmented > assignment involving a mutable member of a tuple.) It's also possible with non-augmented assignments with immutable tuples, as I showed above. > So I would leave this as undefined behavior for an input > outside the proper domain of the function. Not sure what you mean by "this." I don't think that the interpreter should always paternalistically say "no, you can't assign an item that doesn't have a __len__ attribute because you obviously don't know what you're doing if you're trying to do that." I think the interpreter should do the same as it does on my tuple unpacking example -- try to do the right thing, and raise an exception if it fails during the process. > Anyway, as I said before, you are free to propose a specific change > ('work with iterators' is too vague) and provide a corresponding patch. I will try to see if I can do that some time in the next few months, if I ever get out of crunch mode. Thanks, Pat From bahamutzero8825 at gmail.com Sat Oct 29 11:01:42 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sat, 29 Oct 2011 10:01:42 -0500 Subject: Need Windows user / developer to help with Pynguin In-Reply-To: References: Message-ID: <4EAC1556.8060307@gmail.com> On 10/29/2011 9:43 AM, Lee Harr wrote: > So, windows now creates the dummy folder automatically? That is the default choice, but users are given a prompt to choose an arbitrary directory. Note that this only applies to the ZIP extractor in Explorer; other archive programs have their own behavior. I agree with you on having a top-level directory in an archive, but MS figures users are more likely to be annoyed with files scattered around the current directory than a nested directory. Unfortunately, many archives out in the wild have a top-level directory while many others don't, so one can rarely ever be certain how a given archive is organized without opening it. > Is the problem that the .zip has the same name (minus the extension)? Not at all. > Just out of curiosity, what happens if you double-click the > README sans .txt? Does it make you choose which app to open with? Typically, that is the case because files without extensions are not registered by default. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 From gelonida at gmail.com Sat Oct 29 12:44:14 2011 From: gelonida at gmail.com (Gelonida N) Date: Sat, 29 Oct 2011 18:44:14 +0200 Subject: save tuple of simple data types to disk (low memory foot print) In-Reply-To: <4eab5021$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <4eab5021$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/29/2011 03:00 AM, Steven D'Aprano wrote: > On Fri, 28 Oct 2011 22:47:42 +0200, Gelonida N wrote: > >> Hi, >> >> I would like to save many dicts with a fixed amount of keys tuples to a >> file in a memory efficient manner (no random, but only sequential >> access is required) > > What do you mean "keys tuples"? Corrected phrase: I would like to save many dicts with a fixed (and known) amount of keys in a memory efficient manner (no random, but only sequential access is required) to a file (which can later be sent over a slow expensive network to other machines) Example: Every dict will have the keys 'timestamp', 'floatvalue', 'intvalue', 'message1', 'message2' 'timestamp' is an integer 'floatvalue' is a float 'intvalue' an int 'message1' is a string with a length of max 2000 characters, but can often be very short 'message2' the same as message1 so a typical dict will look like { 'timetamp' : 12, 'floatvalue': 3.14159, 'intvalue': 42, 'message1' : '', 'message2' : '=' * 1999 } > > What do you call "many"? Fifty? A thousand? A thousand million? How many > items in each dict? Ten? A million? File size can be between 100kb and over 100Mb per file. Files will be accumulated over months. I just want to use the smallest possible space, as the data is collected over a certain time (days / months) and will be transferred via UMTS / EDGE / GSM network, where the transfer takes already for quite small data sets several minutes. I want to reduce the transfer time, when requesting files on demand (and the amount of data in order to not exceed the monthly quota) >> As the keys are the same for each entry I considered converting them to >> tuples. > > I don't even understand what that means. You're going to convert the keys > to tuples? What will that accomplish? >> As the keys are the same for each entry I considered converting them (the before mentioned dicts) to tuples. so the dict { 'timetamp' : 12, 'floatvalue': 3.14159, 'intvalue': 42, 'message1' : '', 'message2' : '=' * 1999 } would become [ 12, 3.14159, 42, '', ''=' * 1999 ] > > >> The tuples contain only strings, ints (long ints) and floats (double) >> and the data types for each position within the tuple are fixed. >> >> The fastest and simplest way is to pickle the data or to use json. Both >> formats however are not that optimal. > > How big are your JSON files? 10KB? 10MB? 10GB? > > Have you tried using pickle's space-efficient binary format instead of > text format? Try using protocol=2 when you call pickle.Pickler. No. This is probably already a big step forward. As I know the data types if each element in the tuple I would however prefer a representation, which is not storing the data types for each typle over and over again (as they are the same for each dict / tuple) > > Or have you considered simply compressing the files? Compression makes sense but the inital file format should be already rather 'compact' > >> I could store ints and floats with pack. As strings have variable length >> I'm not sure how to save them efficiently (except adding a length first >> and then the string. > > This isn't 1980 and you're very unlikely to be using 720KB floppies. > Premature optimization is the root of all evil. Keep in mind that when > you save a file to disk, even if it contains only a single bit of data, > the actual space used will be an entire block, which on modern hard > drives is very likely to be 4KB. Trying to compress files smaller than a > single block doesn't actually save you any space. > > >> Is there already some 'standard' way or standard library to store such >> data efficiently? > > Yes. Pickle and JSON plus zip or gzip. > pickle protocol-2 + gzip of the tuple derived from the dict, might be good enough for the start. I have to create a little more typical data in order to see how many percent of my payload would consist of repeating the data types for each tuple. From gelonida at gmail.com Sat Oct 29 12:47:57 2011 From: gelonida at gmail.com (Gelonida N) Date: Sat, 29 Oct 2011 18:47:57 +0200 Subject: save tuple of simple data types to disk (low memory foot print) In-Reply-To: References: Message-ID: On 10/29/2011 01:08 AM, Roy Smith wrote: > In article , > Gelonida N wrote: > >> I would like to save many dicts with a fixed amount of keys >> tuples to a file in a memory efficient manner (no random, but only >> sequential access is required) > > There's two possible scenarios here. One, which you seem to be > exploring, is to carefully study your data and figure out the best way > to externalize it which reduces volume. > > The other is to just write it out in whatever form is most convenient > (JSON is a reasonable thing to try first), and compress the output. Let > the compression algorithms worry about extracting the entropy. You may > be surprised at how well it works. It's also an easy experiment to try, > so if it doesn't work well, at least it didn't cost you much to find out. Yes I have to make some more tests to see the defference between just compressing aplain format (JSON / pickle) and compressing the 'optimized' representation. From python.list at tim.thechases.com Sat Oct 29 13:47:42 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 29 Oct 2011 12:47:42 -0500 Subject: save tuple of simple data types to disk (low memory foot print) In-Reply-To: References: <4eab5021$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4EAC3C3E.3030309@tim.thechases.com> On 10/29/11 11:44, Gelonida N wrote: > I would like to save many dicts with a fixed (and known) amount of keys > in a memory efficient manner (no random, but only sequential access is > required) to a file (which can later be sent over a slow expensive > network to other machines) > > Example: > Every dict will have the keys 'timestamp', 'floatvalue', 'intvalue', > 'message1', 'message2' > 'timestamp' is an integer > 'floatvalue' is a float > 'intvalue' an int > 'message1' is a string with a length of max 2000 characters, but can > often be very short > 'message2' the same as message1 > > so a typical dict will look like > { 'timetamp' : 12, 'floatvalue': 3.14159, 'intvalue': 42, > 'message1' : '', 'message2' : '=' * 1999 } > > >> >> What do you call "many"? Fifty? A thousand? A thousand million? How many >> items in each dict? Ten? A million? > > File size can be between 100kb and over 100Mb per file. Files will be > accumulated over months. If Steven's pickle-protocol2 solution doesn't quite do what you need, you can do something like the code below. Gzip is pretty good at addressing... >> Or have you considered simply compressing the files? > Compression makes sense but the inital file format should be > already rather 'compact' ...by compressing out a lot of the duplicate aspects. Which also mitigates some of the verbosity of CSV. It serializes the data to a gzipped CSV file then unserializes it. Just point it at the appropriate data-source, adjust the column-names and data-types -tkc from gzip import GzipFile from csv import writer, reader data = [ # use your real data here { 'timestamp': 12, 'floatvalue': 3.14159, 'intvalue': 42, 'message1': 'hello world', 'message2': '=' * 1999, }, ] * 10000 f = GzipFile('data.gz', 'wb') try: w = writer(f) for row in data: w.writerow([ row[name] for name in ( # use your real col-names here 'timestamp', 'floatvalue', 'intvalue', 'message1', 'message2', )]) finally: f.close() output = [] for row in reader(GzipFile('data.gz')): d = dict(( (name, f(row[i])) for i, (f,name) in enumerate(( # adjust for your column-names/data-types (int, 'timestamp'), (float, 'floatvalue'), (int, 'intvalue'), (str, 'message1'), (str, 'message2'), )))) output.append(d) # or output = [ dict(( (name, f(row[i])) for i, (f,name) in enumerate(( # adjust for your column-names/data-types (int, 'timestamp'), (float, 'floatvalue'), (int, 'intvalue'), (str, 'message1'), (str, 'message2'), )))) for row in reader(GzipFile('data.gz')) ] From geoff.bache at gmail.com Sat Oct 29 17:06:12 2011 From: geoff.bache at gmail.com (Geoff Bache) Date: Sat, 29 Oct 2011 14:06:12 -0700 (PDT) Subject: Customizing class attribute access in classic classes Message-ID: Hi, I'm wondering if there is any way to customize class attribute access on classic classes? So this works: class Meta(type): def __getattr__(cls, name): return "Customized " + name class A: __metaclass__ = Meta print A.blah but it turns A into a new-style class. If "Meta" does not inherit from type, the customization works but A ends up not being a class at all, severely restricting its usefulness. I then hoped I could get "Meta" to inherit from types.ClassType but that wasn't allowed either. Is there any way to do this or is it just a limitation of classic classes? Regards, Geoff Bache From jason at powerpull.net Sat Oct 29 17:15:52 2011 From: jason at powerpull.net (Jason Friedman) Date: Sat, 29 Oct 2011 21:15:52 +0000 Subject: Review Python site with useful code snippets In-Reply-To: <98598900-8b72-4bb2-b21e-13666c9f823b@p16g2000yqd.googlegroups.com> References: <98598900-8b72-4bb2-b21e-13666c9f823b@p16g2000yqd.googlegroups.com> Message-ID: On Wed, Oct 26, 2011 at 3:51 PM, Chris Hall wrote: > I am looking to get reviews, comments, code snippet suggestions, and > feature requests for my site. > I intend to grow out this site with all kinds of real world code > examples to learn from and use in everyday coding. > The site is: > > http://www.pythonsnippet.com > > If you have anything to contribute or comment, please post it on the > site or email me directly. Great sentiment, but there is already http://code.activestate.com/, http://code.google.com/p/python-code-snippets/ and http://stackoverflow.com/questions/2032462/python-code-snippets. Pretty site you put up, though. From ben+python at benfinney.id.au Sat Oct 29 22:16:24 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 30 Oct 2011 13:16:24 +1100 Subject: Customizing class attribute access in classic classes References: Message-ID: <87wrbnmdfr.fsf@benfinney.id.au> Geoff Bache writes: > I'm wondering if there is any way to customize class attribute access > on classic classes? Why do that? What is it you're hoping to achieve, and why limit it to classic classes only? > So this works: > > class Meta(type): > def __getattr__(cls, name): > return "Customized " + name > > class A: > __metaclass__ = Meta > > print A.blah > > but it turns A into a new-style class. Yes, A is a new-style class *because* it inherits from ?type? . Why does that not meet your needs? -- \ Contentsofsignaturemaysettleduringshipping. | `\ | _o__) | Ben Finney From lie.1296 at gmail.com Sun Oct 30 01:15:07 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 30 Oct 2011 16:15:07 +1100 Subject: Convert DDL to ORM In-Reply-To: References: Message-ID: On 10/25/2011 03:30 AM, Alec Taylor wrote: > Good morning, > > I'm often generating DDLs from EER->Logical diagrams using tools such > as PowerDesigner and Oracle Data Modeller. > > I've recently come across an ORM library (SQLalchemy), and it seems > like a quite useful abstraction. > > Is there a way to convert my DDL to ORM code? It's called reverse engineering. Some ORMs, e.g. Django's ORM can reverse engineer the database into Django Models by using `./manage.py inspectdb`. I believe the equivalent in SQLalchemy would be SQL Autocode, see http://turbogears.org/2.1/docs/main/Utilities/sqlautocode.html and http://code.google.com/p/sqlautocode/ From geoff.bache at gmail.com Sun Oct 30 05:05:09 2011 From: geoff.bache at gmail.com (Geoff Bache) Date: Sun, 30 Oct 2011 02:05:09 -0700 (PDT) Subject: Customizing class attribute access in classic classes References: <87wrbnmdfr.fsf@benfinney.id.au> Message-ID: <0128c52e-1e20-453a-881c-0abe3f7a09a0@y36g2000yqm.googlegroups.com> On Oct 30, 4:16?am, Ben Finney wrote: > Geoff Bache writes: > > I'm wondering if there is any way to customize class attribute access > > on classic classes? > > Why do that? What is it you're hoping to achieve, and why limit it to > classic classes only? > I'm building a mocking tool, CaptureMock, which works by intercepting and capturing particular calls, recording and replaying them. A user can just say "intercept httplib for me" and it will record all the interactions with httplib and allow a test that can be run without doing anything via http or writing any handcrafted "mock-code". So I need to be able to intercept also static attribute access, say httplib.HTTPConnection.request. httplib.HTTPConnection is a classic class. I can make my intercepting version of it into a new-style class but the risk is that that will change its behaviour in subtle ways, negating the point of the tool. As for limiting it to classic classes only, I obviously need to do it on new-style classes also. But I know how to do that... Regards, Geoff Bache From steve+comp.lang.python at pearwood.info Sun Oct 30 05:23:26 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 30 Oct 2011 09:23:26 GMT Subject: Customizing class attribute access in classic classes References: Message-ID: <4ead178e$0$29968$c3e8da3$5496439d@news.astraweb.com> On Sat, 29 Oct 2011 14:06:12 -0700, Geoff Bache wrote: > Hi, > > I'm wondering if there is any way to customize class attribute access on > classic classes? > > So this works: > > class Meta(type): > def __getattr__(cls, name): > return "Customized " + name > > class A: > __metaclass__ = Meta > > print A.blah > > but it turns A into a new-style class. And why is this a problem? In any case, metaclasses work for classic classes. Metaclasses go back to pre-Python 1.5, long before new-style classes and type unification. http://www.python.org/doc/essays/metaclasses/ You just have to do a lot more work: class Meta: def __init__(self, name, bases, namespace): self.__name__ = name self.__bases__ = bases self.__dict__ = namespace def __str__(self): return "" __repr__ = __str__ def __getattr__(self, name): return "Customized " + name def __call__(self): return self (The purpose of the __str__ and __repr__ methods is to make it possible to experiment in the interactive interpreter, without a lot of mysterious and puzzling "str object is not callable" TypeErrors. Trust me on this.) And in use: >>> class Spam: ... __metaclass__ = Meta ... a = 1 ... >>> Spam.b 'Customized b' But note that using classic classes, there is no equivalent of __getattribute__ or descriptors, so there is no way to customize access of an attribute which actually does exist: >>> Spam.a 1 -- Steven From geoff.bache at gmail.com Sun Oct 30 06:02:35 2011 From: geoff.bache at gmail.com (Geoff Bache) Date: Sun, 30 Oct 2011 03:02:35 -0700 (PDT) Subject: Customizing class attribute access in classic classes References: <4ead178e$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9ccffb27-a8d0-4fc2-b308-ba9239dc2c13@p16g2000yqd.googlegroups.com> Thanks for this Steven. I'm however gettings some pretty odd effects, both on method access and inheritance. I expanded your example a bit... class Meta: def __init__(self, name, bases, namespace): self.__name__ = name self.__bases__ = bases self.__dict__ = namespace def __str__(self): return "" __repr__ = __str__ def __getattr__(self, name): return "Customized " + name def __call__(self): return self class Base: def basemethod(self): return "base" class A(Base): __metaclass__ = Meta def method(self): return "answer" The effect seems to be to make all methods of A into static methods, and to ignore its base classes altogether: >>> a = A() >>> print a.blah2 Customized blah2 >>> print a.method() Traceback (most recent call last): File "", line 1, in TypeError: method() takes exactly 1 argument (0 given) >>> print a.method(1) answer >>> print A.method(1) answer >>> print a.basemethod() Traceback (most recent call last): File "", line 1, in TypeError: 'str' object is not callable >>> isinstance(a, Base) False Regards, Geoff Bache From skippy.hammond at gmail.com Sun Oct 30 07:03:08 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Sun, 30 Oct 2011 22:03:08 +1100 Subject: Need Windows user / developer to help with Pynguin In-Reply-To: References: Message-ID: <4EAD2EEC.5050707@gmail.com> On 30/10/2011 1:43 AM, Lee Harr wrote: >> For Windows users who want to just run Pyguin (not modify or tinker >> with the source code), it would be best to bundle Pynguin up with >> Py2exe > > I considered that, but I agree that licensing issues would make it > problematic. What licensing issues concern you? The py2exe license shouldn't be a problem and py2exe or something like it is good advice. Mark From devplayer at gmail.com Sun Oct 30 10:11:25 2011 From: devplayer at gmail.com (DevPlayer) Date: Sun, 30 Oct 2011 07:11:25 -0700 (PDT) Subject: Dynamically creating properties? References: <4eaa5cfa$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4382a97c-0517-4fca-be14-181d480038a6@4g2000yqu.googlegroups.com> To be honest, I was hoping someone would have posted a link to a well known and tested recipe. You'd think this function would be in the standard library or a specific Exception tied directly with setattr() and getattr() (and possibly __getattr__(), __getattribute__(), __setattr__()) The main thing I wanted to point out though is when you start using dynamically named references, there's more to it then just letting a dynamic file define it. If there's a way to reference a set of data, it really shouldn't be with a "dynamically named reference" too often. Databases are a good example. Perhaps this is a better way for example: If you have a bunch of tables in your DB -is- it better to get the table def and create a Python class with dynamically named "fields"? Or is it better to create a Table class with name attribute and a Field class with a name attribute (named "name") SO instead of : field_name = xml_parse.get_next_field_name(xml_table_definition) my_table = Table() setattr(my_table, field_name, empty_list_to_later_contain_field_data) Perhaps: field_name = xml_parse.get_next_field_name(xml_table_definition) my_table = Table() my_table.fields[field_name] = empty_list_to_later_contain_field_data # or my_table.add_field( Field(field_name) ) From boyee118 at gmail.com Sun Oct 30 10:49:16 2011 From: boyee118 at gmail.com (Korobase) Date: Sun, 30 Oct 2011 22:49:16 +0800 Subject: [Help] python ctypes to process C pointer! Message-ID: A c code snippet,the c file compiled to a dll file named libxxx.dll: typedef void* HND; typedef unsigned char UCHAR; typedef short int SWORD; ....... int Connect( HND* hnd, UCHAR* ipaddr, SWORD port){ ...... return 1; } then How to handle function Connect using python and ctypes. especially the parameter hnd? My python code: from ctypes import * xxx = cdll.libxxx xxx.Connect.restype=c_int xxx.Connect.argstype=[c_wchar_p,c_wchar_p,c_int] hnd=c_char_p() buf=create_string_buffer("127.0.0.1\0") ipaddr=cast(buf,POINTER(c_char)) xxx.Connect(byref(hnd),ipaddr,8000) But I always result a error: WindowsError: exception: access violation writing 0x00000000 How to fix this problem? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gnarlodious at gmail.com Sun Oct 30 11:02:22 2011 From: gnarlodious at gmail.com (Gnarlodious) Date: Sun, 30 Oct 2011 08:02:22 -0700 (PDT) Subject: __init__ with multiple list values Message-ID: <1acb0d4c-069b-4356-8a9e-cd5640023c2b@g27g2000pre.googlegroups.com> Initializing a list of objects with one value: class Order: def __init__(self, ratio): self.ratio=ratio def __call__(self): return self.ratio ratio=[1, 2, 3, 4, 5] Orders=[Order(x) for x in ratio] But now I want to __init__ with 3 values: class Order: def __init__(self, ratio, bias, locus): self.ratio=ratio self.bias=bias self.locus=locus def __call__(self): return self.ratio, self.bias, self.locus ratio=[1, 2, 3, 4, 5] bias=[True, False, True, False, True] locus=['A', 'B', 'C', 'D', 'E'] Orders=[Order(x,y,z) for x,y,z in [ratio, bias, locus]] >>> ValueError: too many values to unpack (expected 3) How to do it? -- Gnarlie From i.mehrzad at gmail.com Sun Oct 30 11:14:38 2011 From: i.mehrzad at gmail.com (Mehrzad Irani) Date: Sun, 30 Oct 2011 08:14:38 -0700 (PDT) Subject: Review Python site with useful code snippets In-Reply-To: <98598900-8b72-4bb2-b21e-13666c9f823b@p16g2000yqd.googlegroups.com> References: <98598900-8b72-4bb2-b21e-13666c9f823b@p16g2000yqd.googlegroups.com> Message-ID: <29976477.1418.1319987678361.JavaMail.geo-discussion-forums@prep8> Considering that the site is going to grow over time, putting the snippets in a drop-down menu isn't a wise idea in my opinion. Snippets on a separate page like activestate python would make it more convenient. Nice initiative, and would be very helpful when it grows over time. From rosuav at gmail.com Sun Oct 30 11:15:21 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 31 Oct 2011 02:15:21 +1100 Subject: __init__ with multiple list values In-Reply-To: <1acb0d4c-069b-4356-8a9e-cd5640023c2b@g27g2000pre.googlegroups.com> References: <1acb0d4c-069b-4356-8a9e-cd5640023c2b@g27g2000pre.googlegroups.com> Message-ID: On Mon, Oct 31, 2011 at 2:02 AM, Gnarlodious wrote: > Orders=[Order(x,y,z) for x,y,z in [ratio, bias, locus]] > Assuming that you intend to take the first element of each list, then the second, and so on, you'll want to use zip(): Orders=[Order(x,y,z) for x,y,z in zip(ratio, bias, locus)] With your syntax, Python iterates over a three-element list. The first iteration, it looks at 'ratio' and tries to unpack that into x,y,z; this doesn't work, because ratio has five elements. The second iteration would try to unpack 'bias', and the third would go for 'locus'. The zip function returns tuples of (ratio[N], bias[N], locus[N]) for successive Ns: >>> list(zip(ratio,bias,locus)) [(1, True, 'A'), (2, False, 'B'), (3, True, 'C'), (4, False, 'D'), (5, True, 'E')] ChrisA From irmen.NOSPAM at xs4all.nl Sun Oct 30 11:46:38 2011 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 30 Oct 2011 16:46:38 +0100 Subject: [ANN] Pyrolite 1.3 - native Pyro and Pickle library for Java and .NET Message-ID: <4ead715e$0$6847$e4fe514c@news2.news.xs4all.nl> Hello, I'd like to announce Pyrolite 1.3, a tiny (~50k) Pyro client library for Java and .NET. Q: "what is a java/.net library doing in this newsgroup?" A.1: This library is meant to connect a Java or .NET program to Python in a very simple way, using the Pyro protocol. Pyro is my remote object library or Python. A.2: Pyrolite contains an almost feature complete native implementation of Python's pickle protocol. This can be useful by itself to read/write pickles from Java or .NET programs. Download Pyrolite here: http://irmen.home.xs4all.nl/pyrolite/ More info on Pyrolite: http://irmen.home.xs4all.nl/pyrolite/README.txt More info on Pyro: http://irmen.home.xs4all.nl/pyro/ Enjoy, Irmen de Jong From gnarlodious at gmail.com Sun Oct 30 12:08:24 2011 From: gnarlodious at gmail.com (Gnarlodious) Date: Sun, 30 Oct 2011 09:08:24 -0700 (PDT) Subject: __init__ with multiple list values References: <1acb0d4c-069b-4356-8a9e-cd5640023c2b@g27g2000pre.googlegroups.com> Message-ID: On Oct 30, 9:15?am, Chris Angelico wrote: > Orders=[Order(x,y,z) for x,y,z in zip(ratio, bias, locus)] Brilliant, thanks! -- Gnarlie From missive at hotmail.com Sun Oct 30 12:33:30 2011 From: missive at hotmail.com (Lee Harr) Date: Sun, 30 Oct 2011 21:03:30 +0430 Subject: Need Windows user / developer to help with Pynguin In-Reply-To: <4EAD2EEC.5050707@gmail.com> References: , <4EAD2EEC.5050707@gmail.com> Message-ID: >>> Py2exe >> >> I considered that, but I agree that licensing issues would make it >> problematic. > > What licensing issues concern you? The py2exe license shouldn't be a > problem and py2exe or something like it is good advice. I think PyQt 4 would be the biggest issue. It is GPL 2 / 3. I think if this were just for my own use, or just for use in getting the program on to computers in my own school's labs then py2exe would be fine. I don't think I could post a py2exe'd version on the google code site for general distribution. Of course this is only my own personal (non-legal) opinion. From alec.taylor6 at gmail.com Sun Oct 30 14:48:33 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Mon, 31 Oct 2011 05:48:33 +1100 Subject: Need Windows user / developer to help with Pynguin In-Reply-To: References: Message-ID: Maybe push something onto pip or easy_install? On Fri, Oct 28, 2011 at 6:38 AM, Lee Harr wrote: > > I develop the free python-based turtle graphics application pynguin. > > http://pynguin.googlecode.com/ > > > Lately I have been getting a lot of positive comments from people > who use the program, but I am also getting a lot of feedback from > people on Windows (mostly beginners) who are having trouble > getting the program running. > > I don't use Windows myself, though I have found access occasionally > to fix bugs. I just don't know enough about Windows culture to be > able to make a reliable method for installing or running the program. > > > The method that I wrote for Linux also works on Windows, but it has > to be run from the command prompt. > > > I am hoping someone can look at what is there and come up with a > reliable method or a simple set of steps that people can follow to get > up and running. Hopefully without having to resort to the command > prompt. > > I started a wiki page here: > http://code.google.com/p/pynguin/wiki/InstallingPynguinOnWindows > but I can't even test if it actually works.... > > > Thanks for any help. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From python at mrabarnett.plus.com Sun Oct 30 15:30:38 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 30 Oct 2011 19:30:38 +0000 Subject: __init__ with multiple list values In-Reply-To: <1acb0d4c-069b-4356-8a9e-cd5640023c2b@g27g2000pre.googlegroups.com> References: <1acb0d4c-069b-4356-8a9e-cd5640023c2b@g27g2000pre.googlegroups.com> Message-ID: <4EADA5DE.6090302@mrabarnett.plus.com> On 30/10/2011 15:02, Gnarlodious wrote: > Initializing a list of objects with one value: > > class Order: > def __init__(self, ratio): > self.ratio=ratio > def __call__(self): > return self.ratio > > ratio=[1, 2, 3, 4, 5] > Orders=[Order(x) for x in ratio] > > > But now I want to __init__ with 3 values: > > class Order: > def __init__(self, ratio, bias, locus): > self.ratio=ratio > self.bias=bias > self.locus=locus > def __call__(self): > return self.ratio, self.bias, self.locus > > ratio=[1, 2, 3, 4, 5] > bias=[True, False, True, False, True] > locus=['A', 'B', 'C', 'D', 'E'] > Orders=[Order(x,y,z) for x,y,z in [ratio, bias, locus]] > >>>> ValueError: too many values to unpack (expected 3) > > How to do it? > Use 'zip': Orders=[Order(x,y,z) for x,y,z in zip(ratio, bias, locus)] From anders at flauntkit.com Sun Oct 30 16:33:29 2011 From: anders at flauntkit.com (Anders Gunnarsson) Date: Sun, 30 Oct 2011 13:33:29 -0700 (PDT) Subject: Calling JavaScript inside the webbrowser module Message-ID: <7045835.701.1320006809939.JavaMail.geo-discussion-forums@yqnx19> Hi! Is there anyway to communicate with JavaScript inside a website opened via the webbrowser module? | import webbrowser | webbrowser.open('http://python.org') Here I'd like to do something like webbrowser.call('alert(1)') and I'd like to be able to call the python app from javascript too. I've looked at pywebkitgtk, but it's messy running on win32. From darren at dvhart.com Sun Oct 30 17:04:30 2011 From: darren at dvhart.com (Darren Hart) Date: Sun, 30 Oct 2011 14:04:30 -0700 Subject: Appending to sys.path during module install with distutils Message-ID: I'm trying to use distutils to install a collection of modules in /usr/local/lib/python2.7/site-packages. My distribution (Fedora 15) doesn't include any /usr/local paths in sys.path, so the import fails when running the program. The distutils documentation suggests adding a $NAME.pth file to an existing site-packages directory in sys.path. Is there a preferred/accepted method of doing this? I considered just adding some code to my setup.py to generate a braindump.pth file containing something like: PREFIX/lib/pythonMAJOR.MINOR/site-packages and then walking the existing sys.path and picking one of those site-packages directories to install braindump.pth to. I'm not sure how to determine which is the appropriate path. Maybe I'm going about this completely wrong as well - anyone care to help steer me in the right direction? The project is located here: http://braindump.dvhart.com in case anyone wants it for reference. Thanks, -- Darren Hart From electronixtar at gmail.com Sun Oct 30 23:13:00 2011 From: electronixtar at gmail.com (est) Date: Mon, 31 Oct 2011 11:13:00 +0800 Subject: SSE4a with ctypes in python? (gcc __builtin_popcount) In-Reply-To: References: Message-ID: Hi guys, Here is the sample code http://stackoverflow.com/questions/6389841/efficiently-find-binary-strings-with-low-hamming-distance-in-large-set/6390606#6390606 static inline int distance(unsigned x, unsigned y) { return __builtin_popcount(x^y); } Is it possible to rewrite the above gcc code in python using ctypes (preferably Win/*nix compatible)? TIA! -------------- next part -------------- An HTML attachment was scrubbed... URL: From Ric at rdo Mon Oct 31 00:37:01 2011 From: Ric at rdo (Ric at rdo) Date: Sun, 30 Oct 2011 23:37:01 -0500 Subject: ttk Listbox Message-ID: What would be an equivalent widget in ttk like a Listbox and if possible a small example? I tried to look here http://docs.python.org/library/ttk.html but did not see anything. Maybe I did not look in the right place? tia From electronixtar at gmail.com Mon Oct 31 04:39:47 2011 From: electronixtar at gmail.com (est) Date: Mon, 31 Oct 2011 01:39:47 -0700 (PDT) Subject: SSE4a with ctypes in python? (gcc __builtin_popcount) Message-ID: Hi guys, Here is the sample code http://stackoverflow.com/questions/6389841/efficiently-find-binary-strings-with-low-hamming-distance-in-large-set/6390606#6390606 static inline int distance(unsigned x, unsigned y) { return __builtin_popcount(x^y); } Is it possible to rewrite the above gcc code in python using ctypes (preferably Win/*nix compatible)? TIA! From modelnine at modelnine.org Mon Oct 31 04:41:17 2011 From: modelnine at modelnine.org (Heiko Wundram) Date: Mon, 31 Oct 2011 09:41:17 +0100 Subject: SSE4a with ctypes in python? (gcc __builtin_popcount) In-Reply-To: References: Message-ID: <4EAE5F2D.9070804@modelnine.org> Am 31.10.2011 04:13, schrieb est: > Is it possible to rewrite the above gcc code in python using ctypes > (preferably Win/*nix compatible)? No; the (gcc-injected) functions starting with __builtin_* are not "real" functions in the sense that they can be called by calling into a library, but rather are converted to a series of assembler instructions by the compiler directly. Wrapping this (distance) primitive by writing a C-module for Python, thus exposing the respective gcc-generated assembler code to Python through a module, won't yield any relevant speedups either, because most of the time will be spent in the call sequence for calling the function, and not in the actual computation. -- --- Heiko. From __peter__ at web.de Mon Oct 31 04:53:00 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 31 Oct 2011 09:53 +0100 Subject: Introducing pickleDB; a simple, lightweight, and fast key-value database. References: Message-ID: patx wrote: > Hello I have recently started work on a new project called pickleDB. It is > a lightweight key-value database engine (inspired by redis). > > Check it out at http://packages.python.org/pickleDB > > import json as pickle # ;) > > def load(location): > global db > try: > db = pickle.load(open(location, 'rb')) > except IOError: > db = {} > global loco > loco = location > return True > > def set(key, value): > db[key] = value > pickle.dump(db, open(loco, 'wb')) > return True > > def get(key): > return db[key] Hmm, I don't think that will scale... From pennerandpen at web.de Mon Oct 31 06:00:26 2011 From: pennerandpen at web.de (user1024) Date: Mon, 31 Oct 2011 11:00:26 +0100 Subject: ttk Listbox In-Reply-To: References: Message-ID: hi http://www.tkdocs.com/tutorial/index.html remember that you have to import line from tkinter import ttk (at "from tkinter import *" ttk in not included) From pennerandpen at web.de Mon Oct 31 06:01:42 2011 From: pennerandpen at web.de (user1024) Date: Mon, 31 Oct 2011 11:01:42 +0100 Subject: ttk Listbox In-Reply-To: References: Message-ID: hi http://www.tkdocs.com/tutorial/index.html remember that you have to import like from tkinter import ttk (at "from tkinter import *" ttk in not included) From home3 at faustballmanager.de.vu Mon Oct 31 06:05:35 2011 From: home3 at faustballmanager.de.vu (autofelge) Date: Mon, 31 Oct 2011 11:05:35 +0100 Subject: ttk Listbox In-Reply-To: References: Message-ID: <4eae72f0$0$4151$6e1ede2f@read.cnntp.org> hi http://www.tkdocs.com/tutorial/index.html remember that you have to import like from tkinter import ttk (at "from tkinter import *" ttk in not included) From home3 at faustballmanager.de.vu Mon Oct 31 06:07:07 2011 From: home3 at faustballmanager.de.vu (autofelge) Date: Mon, 31 Oct 2011 11:07:07 +0100 Subject: ttk Listbox In-Reply-To: References: Message-ID: <4eae734b$0$4151$6e1ede2f@read.cnntp.org> hi http://www.tkdocs.com/tutorial/index.html remember that you have to import like from tkinter import ttk (at "from tkinter import *" ttk in not included) From user at 1024.de Mon Oct 31 06:10:53 2011 From: user at 1024.de (user1024) Date: Mon, 31 Oct 2011 11:10:53 +0100 Subject: ttk Listbox In-Reply-To: References: Message-ID: hi http://www.tkdocs.com/tutorial/index.html remember that you have to import like from tkinter import ttk (at "from tkinter import *" ttk in not included) From dhyams at gmail.com Mon Oct 31 08:01:40 2011 From: dhyams at gmail.com (dhyams) Date: Mon, 31 Oct 2011 05:01:40 -0700 (PDT) Subject: How to mix-in __getattr__ after the fact? References: <4630c4d0-86bc-4295-8bbb-6f58415191c8@v15g2000vbm.googlegroups.com> <4EAAF264.1050307@stoneleaf.us> Message-ID: <8bc11029-860e-4d3a-8770-062e16e31514@j39g2000yqc.googlegroups.com> Thanks for all of the responses; everyone was exactly correct, and obeying the binding rules for special methods did work in the example above. Unfortunately, I only have read-only access to the class itself (it was a VTK class wrapped with SWIG), so I had to find another way to accomplish what I was after. On Oct 28, 10:26?pm, Lie Ryan wrote: > On 10/29/2011 05:20 AM, Ethan Furman wrote: > > > > > > > > > > > > > Python only looks up __xxx__ methods in new-style classes on the class > > itself, not on the instances. > > > So this works: > > > 8<---------------------------------------------------------------- > > class Cow(object): > > pass > > > def attrgetter(self, a): > > print "CAUGHT: Attempting to get attribute", a > > > bessie = Cow() > > > Cow.__getattr__ = attrgetter > > > print bessie.milk > > 8<---------------------------------------------------------------- > > a minor modification might be useful: > > bessie = Cow() > bessie.__class__.__getattr__ = attrgetter From andrea.crotti.0 at gmail.com Mon Oct 31 10:00:03 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Mon, 31 Oct 2011 14:00:03 +0000 Subject: locate executables for different platforms Message-ID: <4EAEA9E3.50409@gmail.com> Suppose that I have a project which (should be)/is multiplatform in python, which, however, uses some executables as black-boxes. These executables are platform-dependent and at the moment they're just thrown inside the same egg, and using pkg_resources to get the path. I would like to rewrite this thing being able to: - detect the OS - find the right executable version - get the path and run it It would be nice to still be able to use pkg_resources, but at that point I think I would need to store all the executables in another egg, is that correct? Is there already something available to manage external multi-platform executables? Thanks, Andrea From kw at codebykevin.com Mon Oct 31 10:00:22 2011 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 31 Oct 2011 10:00:22 -0400 Subject: ttk Listbox In-Reply-To: References: Message-ID: On 10/31/11 12:37 AM, Ric at rdo wrote: > > What would be an equivalent widget in ttk like a Listbox and if > possible a small example? I tried to look here > http://docs.python.org/library/ttk.html but did not see anything. > > Maybe I did not look in the right place? > > tia The listbox isn't part of the themed ttk widgets. The ttk::treview is, and that can be set up as a single-column list display. There may be an example of how to do this in the docs or source code tree (I don't use the widget myself so I don't have any sample code to share). --Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From andrea.crotti.0 at gmail.com Mon Oct 31 10:24:40 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Mon, 31 Oct 2011 14:24:40 +0000 Subject: locate executables for different platforms In-Reply-To: <4EAEA9E3.50409@gmail.com> References: <4EAEA9E3.50409@gmail.com> Message-ID: <4EAEAFA8.80305@gmail.com> On 10/31/2011 02:00 PM, Andrea Crotti wrote: > Suppose that I have a project which (should be)/is multiplatform in > python, > which, however, uses some executables as black-boxes. > > These executables are platform-dependent and at the moment they're just > thrown inside the same egg, and using pkg_resources to get the path. > > I would like to rewrite this thing being able to: > - detect the OS > - find the right executable version > - get the path and run it > > It would be nice to still be able to use pkg_resources, but at that > point I think > I would need to store all the executables in another egg, is that > correct? > Is there already something available to manage external multi-platform > executables? > > Thanks, > Andrea The most simple possible way I can think of to solve this problem would be, to create a directory for each executable, and in each directory the executable with the platform in the name, like: - exec1: + exec1-linux2 + exec1-darwin ... And to look up would be very simple (as below), but I feel that is not very smart... import sys from os import path BASE_DIR = '.' exec_name = sys.argv[1] assert path.isdir(exec_name) plat = sys.platform name_ex = "%s-%s" % (exec_name, plat) if plat == 'win32': name_ex += '.exe' res_ex = path.join(exec_name, name_ex) assert path.isfile(res_ex) print path.abspath(res_ex) From devplayer at gmail.com Mon Oct 31 10:39:23 2011 From: devplayer at gmail.com (DevPlayer) Date: Mon, 31 Oct 2011 07:39:23 -0700 (PDT) Subject: Review Python site with useful code snippets References: <98598900-8b72-4bb2-b21e-13666c9f823b@p16g2000yqd.googlegroups.com> Message-ID: <7c5576ff-d4bf-47e7-8b18-9ed1893ef924@r2g2000vbj.googlegroups.com> When visitors visit your site to post their code; often such posts ask for username and email address; consider adding additional fields to generate some Python documenting feature like Sphinx or epydoc. and let your site inject the docstring (module string) into the snippet; primarily, author, url=YOUR url if not provided by them, date, python version, os, etc... See reStructuRE for possible fields to inject. From roland at catalogix.se Mon Oct 31 10:52:39 2011 From: roland at catalogix.se (Roland Hedberg) Date: Mon, 31 Oct 2011 15:52:39 +0100 Subject: Support for Galois/Counter Mode (GCM) ? Message-ID: <282F3AA8-AD7B-4499-93DF-8E617267EEC1@catalogix.se> Hi ! Is there a crypto library for Python that has support for GCM ?? -- Roland From pierre.quentel at gmail.com Mon Oct 31 10:55:36 2011 From: pierre.quentel at gmail.com (Pierre Quentel) Date: Mon, 31 Oct 2011 07:55:36 -0700 (PDT) Subject: [ANN] Karrigell-4.3.6 released Message-ID: <0d65a4a3-4eb8-4508-8153-7ef2f5fdb6e1@v5g2000vbh.googlegroups.com> Hi, A new version of the Karrigell web framework for Python 3.2+ has just been released on http://code.google.com/p/karrigell/ One of the oldest Python web frameworks around (the first version was released back in 2002), it now has 2 main versions, one for Python 2 and another one for Python 3. The Python 2.x version is available at http://karrigell.sf.net ; this branch is maintained, but no new feature is going to be developed All the development work is now focused on the version for Python 3. The first release was published in February and we are already at the 10th release Karrigell's design is about simplicity for the programmer and integration of all the web environment in the scripts namespace. For instance, the "Hello world" script requires 2 lines : def index(): return "Hello world" All the HTML tags are available as classes in the scripts namespace : def index(): return HTML(BODY("Hello world")) To build an HTML document as a tree, the HTML tags objects support the operators + (add brother) and <= (add child) : def index(): form = FORM(action="insert",method="post") form <= INPUT(name="foo")+BR()+INPUT(name="bar") form <= INPUT(Type="submit",value="Ok") return HTML(BODY(form)) The scripts can be served by a built-in web server, or through the Apache server, either on CGI mode or using the WSGI interface The package obvioulsy has built-in support for usual features such as cookie and session management, localization, user login/logout/role management. It also includes a complete documentation, with a tutorial and a set of how-to's A helpful and friendly community welcomes users at http://groups.google.com/group/karrigell Enjoy ! Pierre From devplayer at gmail.com Mon Oct 31 11:01:19 2011 From: devplayer at gmail.com (DevPlayer) Date: Mon, 31 Oct 2011 08:01:19 -0700 (PDT) Subject: locate executables for different platforms References: Message-ID: On Oct 31, 10:00?am, Andrea Crotti wrote: > Suppose that I have a project which (should be)/is multiplatform in python, > which, however, uses some executables as black-boxes. > > These executables are platform-dependent and at the moment they're just > thrown inside the same egg, and using pkg_resources to get the path. > > I would like to rewrite this thing being able to: > - detect the OS > - find the right executable version > - get the path and run it > > It would be nice to still be able to use pkg_resources, but at that > point I think > I would need to store all the executables in another egg, is that correct? > Is there already something available to manage external multi-platform > executables? > > Thanks, > Andrea While this doesn't answer your question fully, here is a beta snippet I wrote in Python, that returns a list of full pathnames, for a set of specified filenames, found in paths specified by PATH environment variable. Only tested on WIN32. Note on WIN32 systems the snippet tries to find filenames with extensions specified by the environment varible PATHEXT. On Unix it will also try with no extension, of cource (not tested). Enjoy. From devplayer at gmail.com Mon Oct 31 11:02:24 2011 From: devplayer at gmail.com (DevPlayer) Date: Mon, 31 Oct 2011 08:02:24 -0700 (PDT) Subject: locate executables for different platforms References: Message-ID: <32cd7f28-744e-414d-bedb-3268f66df5fe@k10g2000yqn.googlegroups.com> Oh forgot the link: http://pastebin.com/kFp0dJdS From rick.mansilla at gmail.com Mon Oct 31 12:18:24 2011 From: rick.mansilla at gmail.com (Ricardo Mansilla) Date: Mon, 31 Oct 2011 10:18:24 -0600 Subject: Tweepy: Invalid arguments at function call (tweepy.Stream()) Message-ID: Hi i'm trying to fetch realtime data from twitter using tweepy.Stream(). So I have tried the following... After successfully authenticate using oauth: auth = tweepy.OAuthHandler(...) (it works fine, i have my access_token.key and secret) i did: streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout='90') and: streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout='90') none of this works, it keeps giving me the same error: Traceback (most recent call last): File "", line 1, in streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout='60') TypeError: *init*() takes at least 4 arguments (4 given) then i have searched for the parameters of the function: tweedy.streaming.Stream(login,password,Listener(),...etc) but i thought this login and pass was the authentication method using in the basic authentication not in the oauth case. Now i'm really confused, a little help please? pd: As you can see, i'm trying to get realtime data from twitter (and make some further NLP with it), i have chose tweepy because the dev.twitter.compage recommended it, but if you have any other suggestion for doing this, it will be welcomed -------------- next part -------------- An HTML attachment was scrubbed... URL: From ckaynor at zindagigames.com Mon Oct 31 14:34:31 2011 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Mon, 31 Oct 2011 11:34:31 -0700 Subject: C API: Making a context manager Message-ID: I am currently rewritting a class using the Python C API to improve performance of it, however I have not been able to find any documentation?about how to make a context manager using the C API. The code I am working to produce is the following (its a method of a class): @contextlib.contextmanager def connected(self, *args, **kwargs): connection = self.connect(*args, **kwargs) try: yield finally: connection.disconnect() For this, my first question is: is there any built-in method to make this type of method in the C API? If not, is there a slot on the type object I am missing for __enter__ and __exit__, or should just be defined using the PyMethodDef struct on the class (presumably named the same as the Python functions)? Chris From brian.curtin at gmail.com Mon Oct 31 15:15:37 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Mon, 31 Oct 2011 14:15:37 -0500 Subject: C API: Making a context manager In-Reply-To: References: Message-ID: On Mon, Oct 31, 2011 at 13:34, Chris Kaynor wrote: > I am currently rewritting a class using the Python C API to improve > performance of it, however I have not been able to find any > documentation?about how to make a context manager using the C API. > > The code I am working to produce is the following (its a method of a class): > > @contextlib.contextmanager > def connected(self, *args, **kwargs): > ? ? ? ?connection = self.connect(*args, **kwargs) > ? ? ? ?try: > ? ? ? ? ? ? ? ?yield > ? ? ? ?finally: > ? ? ? ? ? ? ? ?connection.disconnect() > > For this, my first question is: is there any built-in method to make > this type of method in the C API? If not, is there a slot on the type > object I am missing for __enter__ and __exit__, or should just be > defined using the PyMethodDef struct on the class (presumably named > the same as the Python functions)? You'd just add "__enter__" and "__exit__" in the PyMethodDef. If you have the CPython source, we do it in there in a few places. Off the top of my head, PC\winreg.c contains at least one class that works as a context manager (PyHKEY), although there are a few others scattered around the source. From ckaynor at zindagigames.com Mon Oct 31 15:18:05 2011 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Mon, 31 Oct 2011 12:18:05 -0700 Subject: C API: Making a context manager In-Reply-To: References: Message-ID: On Mon, Oct 31, 2011 at 12:15 PM, Brian Curtin wrote: > > You'd just add "__enter__" and "__exit__" in the PyMethodDef. If you > have the CPython source, we do it in there in a few places. Off the > top of my head, PC\winreg.c contains at least one class that works as > a context manager (PyHKEY), although there are a few others scattered > around the source. > That is what I figured. I was just hoping there was some helper class similar to the contextmanager decorator that would make it easier to use, however at the same time it makes sense that there is not. Thanks, Chris From Ric at rdo Mon Oct 31 15:34:26 2011 From: Ric at rdo (Ric at rdo) Date: Mon, 31 Oct 2011 14:34:26 -0500 Subject: ttk Listbox References: Message-ID: On Mon, 31 Oct 2011 10:00:22 -0400, Kevin Walzer wrote: >On 10/31/11 12:37 AM, Ric at rdo wrote: >> >> What would be an equivalent widget in ttk like a Listbox and if >> possible a small example? I tried to look here >> http://docs.python.org/library/ttk.html but did not see anything. >> >> Maybe I did not look in the right place? >> >> tia > >The listbox isn't part of the themed ttk widgets. The ttk::treview is, >and that can be set up as a single-column list display. There may be an >example of how to do this in the docs or source code tree (I don't use >the widget myself so I don't have any sample code to share). > >--Kevin Thank you for the information. From python at bdurham.com Mon Oct 31 15:43:44 2011 From: python at bdurham.com (python at bdurham.com) Date: Mon, 31 Oct 2011 15:43:44 -0400 Subject: Experience with ActivateState Stackato or PiCloud SaaS/PaaS offerings? Message-ID: <1320090224.3316.140660992863349@webmail.messagingengine.com> Looking for feedback from anyone who has tried or is using ActiveState Stackato, PiCloud or other Python orientated SaaS/PaaS offerings? Pros, cons, advice, lessons learned? Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Mon Oct 31 15:54:34 2011 From: python at bdurham.com (python at bdurham.com) Date: Mon, 31 Oct 2011 15:54:34 -0400 Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? Message-ID: <1320090874.6062.140660992866273@webmail.messagingengine.com> Wondering if there's a fast/efficient built-in way to determine if a string has non-ASCII chars outside the range ASCII 32-127, CR, LF, or Tab? I know I can look at the chars of a string individually and compare them against a set of legal chars using standard Python code (and this works fine), but I will be working with some very large files in the 100's Gb to several Tb size range so I'd thought I'd check to see if there was a built-in in C that might handle this type of check more efficiently. Does this sound like a use case for cython or pypy? Thanks, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From Ric at rdo Mon Oct 31 16:03:58 2011 From: Ric at rdo (Ric at rdo) Date: Mon, 31 Oct 2011 15:03:58 -0500 Subject: ttk Listbox References: Message-ID: On Mon, 31 Oct 2011 10:00:22 -0400, Kevin Walzer wrote: >On 10/31/11 12:37 AM, Ric at rdo wrote: >> >> What would be an equivalent widget in ttk like a Listbox and if >> possible a small example? I tried to look here >> http://docs.python.org/library/ttk.html but did not see anything. >> >> Maybe I did not look in the right place? >> >> tia > >The listbox isn't part of the themed ttk widgets. The ttk::treview is, >and that can be set up as a single-column list display. There may be an >example of how to do this in the docs or source code tree (I don't use >the widget myself so I don't have any sample code to share). > >--Kevin Quick question: Then why is it mentioned here http://www.tkdocs.com/tutorial/morewidgets.html? Listboxes are created using the Listbox function: l = Listbox(parent, height=10) From pauldavidmena at gmail.com Mon Oct 31 16:16:25 2011 From: pauldavidmena at gmail.com (extraspecialbitter) Date: Mon, 31 Oct 2011 13:16:25 -0700 (PDT) Subject: How do I pass a variable to os.popen? Message-ID: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> I'm trying to write a simple Python script to print out network interfaces (as found in the "ifconfig -a" command) and their speed ("ethtool "). The idea is to loop for each interface and print out its speed. os.popen seems to be the right solution for the ifconfig command, but it doesn't seem to like me passing the interface variable as an argument. Code snippet is below: ============ #!/usr/bin/python # Quick and dirty script to print out available interfaces and their speed # Initializations output = " Interface: %s Speed: %s" import os, socket, types fp = os.popen("ifconfig -a") dat=fp.read() dat=dat.split('\n') for line in dat: if line[10:20] == "Link encap": interface=line[:9] cmd = 'ethtool %interface' print cmd gp = os.popen(cmd) fat=gp.read() fat=fat.split('\n') ============= I'm printing out "cmd" in an attempt to debug, and "interface" seems to be passed as a string and not a variable. Obviously I'm a newbie, and I'm hoping this is a simple syntax issue. Thanks in advance! From catdude at gmail.com Mon Oct 31 16:40:20 2011 From: catdude at gmail.com (Dan M) Date: 31 Oct 2011 20:40:20 GMT Subject: How do I pass a variable to os.popen? References: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> Message-ID: <9h8fdkFvt1U6@mid.individual.net> On Mon, 31 Oct 2011 13:16:25 -0700, extraspecialbitter wrote: > cmd = 'ethtool %interface' Do you perhaps mean: cmd = 'ethtool %s' % (interface, ) From ian.g.kelly at gmail.com Mon Oct 31 16:41:11 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 31 Oct 2011 14:41:11 -0600 Subject: How do I pass a variable to os.popen? In-Reply-To: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> References: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> Message-ID: On Mon, Oct 31, 2011 at 2:16 PM, extraspecialbitter wrote: > ? ?cmd = 'ethtool %interface' That is not Python syntax for string interpolation. Try: cmd = 'ethtool %s' % interface On a side note, os.popen is deprecated. You should look into using the higher-level subprocess.check_output instead. Cheers, Ian From dreadpiratejeff at gmail.com Mon Oct 31 16:46:09 2011 From: dreadpiratejeff at gmail.com (J) Date: Mon, 31 Oct 2011 16:46:09 -0400 Subject: How do I pass a variable to os.popen? In-Reply-To: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> References: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> Message-ID: On Mon, Oct 31, 2011 at 16:16, extraspecialbitter wrote: > ? ?if line[10:20] == "Link encap": > ? ? ? interface=line[:9] > ? ?cmd = 'ethtool %interface' > ? ?print cmd > ? ?gp = os.popen(cmd) because you're saying that cmd is 'ethtool %interface' as you pointed out later on... how about: cmd = 'ethtool %s' % interface note the spaces there... that tells it to convert the contents of interface to a string and insert them into the string you're assigning to cmd... assuming interface is things like eth0, you shoud now see "ethtool eth0" when the print statement runs. From clp2 at rebertia.com Mon Oct 31 16:48:02 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 31 Oct 2011 13:48:02 -0700 Subject: How do I pass a variable to os.popen? In-Reply-To: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> References: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> Message-ID: On Mon, Oct 31, 2011 at 1:16 PM, extraspecialbitter wrote: > I'm trying to write a simple Python script to print out network > interfaces (as found in the "ifconfig -a" command) and their speed > ("ethtool "). ?The idea is to loop for each interface and > print out its speed. ?os.popen seems to be the right solution for the os.popen() is somewhat deprecated. Use the subprocess module instead. > ifconfig command, but it doesn't seem to like me passing the interface > variable as an argument. ?Code snippet is below: > > ============ > > #!/usr/bin/python > > # Quick and dirty script to print out available interfaces and their > speed > > # Initializations > > output = " Interface: %s Speed: %s" > > import os, socket, types > > fp = os.popen("ifconfig -a") > dat=fp.read() > dat=dat.split('\n') > for line in dat: > ? ?if line[10:20] == "Link encap": > ? ? ? interface=line[:9] > ? ?cmd = 'ethtool %interface' cmd will literally contain a percent-sign and the word "interface". If your shell happens to use % as a prefix to indicate a variable, note that Python variables are completely separate from and not accessible from the shell. So either ethtool will get the literal string "%interface" as its argument, or since there is no such shell variable, after expansion it will end up getting no arguments at all. Perhaps you meant: cmd = "ethtool %s" % interface Which could be more succinctly written: cmd = "ethtool " + interface > ? ?print cmd > ? ?gp = os.popen(cmd) > ? ?fat=gp.read() The subprocess equivalent is: fat = subprocess.check_output(["ethtool", interface]) > ? ?fat=fat.split('\n') > > ============= > > I'm printing out "cmd" in an attempt to debug, and "interface" seems > to be passed as a string and not a variable. ?Obviously I'm a newbie, > and I'm hoping this is a simple syntax issue. ?Thanks in advance! Cheers, Chris -- http://rebertia.com From pauldavidmena at gmail.com Mon Oct 31 17:25:59 2011 From: pauldavidmena at gmail.com (Paul David Mena) Date: Mon, 31 Oct 2011 17:25:59 -0400 Subject: How do I pass a variable to os.popen? In-Reply-To: References: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> Message-ID: This was exactly what I was looking for. Thanks! On Mon, Oct 31, 2011 at 4:48 PM, Chris Rebert wrote: > On Mon, Oct 31, 2011 at 1:16 PM, extraspecialbitter > wrote: > > I'm trying to write a simple Python script to print out network > > interfaces (as found in the "ifconfig -a" command) and their speed > > ("ethtool "). The idea is to loop for each interface and > > print out its speed. os.popen seems to be the right solution for the > > os.popen() is somewhat deprecated. Use the subprocess module instead. > > > ifconfig command, but it doesn't seem to like me passing the interface > > variable as an argument. Code snippet is below: > > > > ============ > > > > #!/usr/bin/python > > > > # Quick and dirty script to print out available interfaces and their > > speed > > > > # Initializations > > > > output = " Interface: %s Speed: %s" > > > > import os, socket, types > > > > fp = os.popen("ifconfig -a") > > dat=fp.read() > > dat=dat.split('\n') > > for line in dat: > > if line[10:20] == "Link encap": > > interface=line[:9] > > cmd = 'ethtool %interface' > > cmd will literally contain a percent-sign and the word "interface". If > your shell happens to use % as a prefix to indicate a variable, note > that Python variables are completely separate from and not accessible > from the shell. So either ethtool will get the literal string > "%interface" as its argument, or since there is no such shell > variable, after expansion it will end up getting no arguments at all. > Perhaps you meant: > cmd = "ethtool %s" % interface > Which could be more succinctly written: > cmd = "ethtool " + interface > > > print cmd > > gp = os.popen(cmd) > > fat=gp.read() > > The subprocess equivalent is: > fat = subprocess.check_output(["ethtool", interface]) > > > fat=fat.split('\n') > > > > ============= > > > > I'm printing out "cmd" in an attempt to debug, and "interface" seems > > to be passed as a string and not a variable. Obviously I'm a newbie, > > and I'm hoping this is a simple syntax issue. Thanks in advance! > > Cheers, > Chris > -- > http://rebertia.com > -- Paul David Mena -------------------- pauldavidmena at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon Oct 31 17:32:04 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 31 Oct 2011 17:32:04 -0400 Subject: Tweepy: Invalid arguments at function call (tweepy.Stream()) In-Reply-To: References: Message-ID: On 10/31/2011 12:18 PM, Ricardo Mansilla wrote: > Hi i'm trying to fetch realtime data from twitter using tweepy.Stream(). A reference to your source for tweepy would help. The link below gives https://github.com/tweepy/tweepy for the current source. http://pypi.python.org/pypi/tweepy/1.7.1 has versions for 2.4,5,6 from May 2010. You neglected to mention which version of Python you are using > streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), > timeout='90') > and: > streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), > timeout='90') These look identical. > none of this works, it keeps giving me the same error: > > Traceback (most recent call last): > File "", line 1, in > streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), > timeout='60') > TypeError: *init*() takes at least 4 arguments (4 given) 3.2 prints the proper method name: __init__. I do not remember that older versions did that conversion, but maybe so. In any case, the error message us screwed up. It has been improved in current Python. > then i have searched for the parameters of the function: > > tweedy.streaming.Stream(login,password,Listener(),...etc) > but i thought this login and pass was the authentication method using in > the basic authentication not in the oauth case. > Now i'm really confused, a little help please? The current tweepy/streaming.py source code from the site above says: class Stream(object): def __init__(self, auth, listener, **options): self.auth = auth self.listener = listener self.running = False self.timeout = options.get("timeout", 300.0) According to this, __init__ takes 3 positional params, which is what you gave it. Perhaps, this was different in an earlier version. Look at the code you are running. > i have chose tweepy because the > dev.twitter.com page recommended it, That page mentions no libraries. Perhaps you meant https://dev.twitter.com/docs/twitter-libraries -- Terry Jan Reedy From d at davea.name Mon Oct 31 17:47:06 2011 From: d at davea.name (Dave Angel) Date: Mon, 31 Oct 2011 17:47:06 -0400 Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? In-Reply-To: <1320090874.6062.140660992866273@webmail.messagingengine.com> References: <1320090874.6062.140660992866273@webmail.messagingengine.com> Message-ID: <4EAF175A.6060508@davea.name> On 10/31/2011 03:54 PM, python at bdurham.com wrote: > Wondering if there's a fast/efficient built-in way to determine > if a string has non-ASCII chars outside the range ASCII 32-127, > CR, LF, or Tab? > > I know I can look at the chars of a string individually and > compare them against a set of legal chars using standard Python > code (and this works fine), but I will be working with some very > large files in the 100's Gb to several Tb size range so I'd > thought I'd check to see if there was a built-in in C that might > handle this type of check more efficiently. > > Does this sound like a use case for cython or pypy? > > Thanks, > Malcolm > How about doing a .replace() method call, with all those characters turning into '', and then see if there's anything left? -- DaveA From d at davea.name Mon Oct 31 18:08:00 2011 From: d at davea.name (Dave Angel) Date: Mon, 31 Oct 2011 18:08:00 -0400 Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? In-Reply-To: <4EAF175A.6060508@davea.name> References: <1320090874.6062.140660992866273@webmail.messagingengine.com> <4EAF175A.6060508@davea.name> Message-ID: <4EAF1C40.6030202@davea.name> On 10/31/2011 05:47 PM, Dave Angel wrote: > On 10/31/2011 03:54 PM, python at bdurham.com wrote: >> Wondering if there's a fast/efficient built-in way to determine >> if a string has non-ASCII chars outside the range ASCII 32-127, >> CR, LF, or Tab? >> >> I know I can look at the chars of a string individually and >> compare them against a set of legal chars using standard Python >> code (and this works fine), but I will be working with some very >> large files in the 100's Gb to several Tb size range so I'd >> thought I'd check to see if there was a built-in in C that might >> handle this type of check more efficiently. >> >> Does this sound like a use case for cython or pypy? >> >> Thanks, >> Malcolm >> > How about doing a .replace() method call, with all those characters > turning into '', and then see if there's anything left? > > > I was wrong once again. But a simple combination of translate() and split() methods might do it. Here I'm suggesting that the table replace all valid characters with space, so the split() can use its default behavior. -- DaveA From ian.g.kelly at gmail.com Mon Oct 31 18:52:53 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 31 Oct 2011 16:52:53 -0600 Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? In-Reply-To: <4EAF1C40.6030202@davea.name> References: <1320090874.6062.140660992866273@webmail.messagingengine.com> <4EAF175A.6060508@davea.name> <4EAF1C40.6030202@davea.name> Message-ID: On Mon, Oct 31, 2011 at 4:08 PM, Dave Angel wrote: > I was wrong once again. ?But a simple combination of ?translate() and > split() methods might do it. ?Here I'm suggesting that the table replace all > valid characters with space, so the split() can use its default behavior. That sounds overly complicated and error-prone. For instance, split() will split on vertical tab, which is not one of the characters the OP wanted. I would probably use a regular expression for this. import re if re.search(r'[^\r\n\t\040-\177]', string_to_test): print("Invalid!") Cheers, Ian From steve+comp.lang.python at pearwood.info Mon Oct 31 19:02:15 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 31 Oct 2011 23:02:15 GMT Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? References: <1320090874.6062.140660992866273@webmail.messagingengine.com> Message-ID: <4eaf28f7$0$29968$c3e8da3$5496439d@news.astraweb.com> On Mon, 31 Oct 2011 17:47:06 -0400, Dave Angel wrote: > On 10/31/2011 03:54 PM, python at bdurham.com wrote: >> Wondering if there's a fast/efficient built-in way to determine if a >> string has non-ASCII chars outside the range ASCII 32-127, CR, LF, or >> Tab? >> >> I know I can look at the chars of a string individually and compare >> them against a set of legal chars using standard Python code (and this >> works fine), but I will be working with some very large files in the >> 100's Gb to several Tb size range so I'd thought I'd check to see if >> there was a built-in in C that might handle this type of check more >> efficiently. >> >> Does this sound like a use case for cython or pypy? >> >> Thanks, >> Malcolm >> > How about doing a .replace() method call, with all those characters > turning into '', and then see if there's anything left? No offense Dave, but do you really think that making a copy of as much as a terabyte of data is *more* efficient than merely scanning the data and stopping on the first non-ASCII character you see? There is no way of telling whether a string includes non-ASCII characters without actually inspecting each character. So in the event that the string *is* fully ASCII text, you have to check every character, there can be no shortcuts. However, there is a shortcut if the string isn't fully ASCII text: once you've found a single non-text character, stop. So the absolute least amount of work you can do is: # Define legal characters: LEGAL = ''.join(chr(n) for n in range(32, 128)) + '\n\r\t\f' # everybody forgets about formfeed... \f # and are you sure you want to include chr(127) as a text char? def is_ascii_text(text): for c in text: if c not in LEGAL: return False return True Algorithmically, that's as efficient as possible: there's no faster way of performing the test, although one implementation may be faster or slower than another. (PyPy is likely to be faster than CPython, for example.) But can we get better in Python? Yes, I think so. First off, CPython is optimized for local variable lookups over globals, and since you are looking up the global LEGAL potentially 1000000000000 times, even a 1% saving per lookup will help a lot. So the first step is to make a local reference, by adding this line just above the for loop: legal = LEGAL But we can do even better still. Each time we test for "c not in legal", we do a linear search of 100 characters. On average, that will mean comparing 50 characters for equality at best. We can do better by using a set or frozenset, which gives us approximately constant time lookups: legal = frozenset(LEGAL) Finally, we can try to do as much work as possible in fast C code and as little as necessary in relatively slow Python: def is_ascii_text(text): legal = frozenset(LEGAL) return all(c in legal for c in text) Since all() is guaranteed to keep short-cut semantics, that will be as fast as possible in Python, and quite possibly just as fast as any C extension you might write. If that's still too slow, use smaller files or get a faster computer :) -- Steven From tjreedy at udel.edu Mon Oct 31 19:10:02 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 31 Oct 2011 19:10:02 -0400 Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? In-Reply-To: <1320090874.6062.140660992866273@webmail.messagingengine.com> References: <1320090874.6062.140660992866273@webmail.messagingengine.com> Message-ID: On 10/31/2011 3:54 PM, python at bdurham.com wrote: > Wondering if there's a fast/efficient built-in way to determine if a > string has non-ASCII chars outside the range ASCII 32-127, CR, LF, or Tab? I presume you also want to disallow the other ascii control chars? > I know I can look at the chars of a string individually and compare them > against a set of legal chars using standard Python code (and this works If, by 'string', you mean a string of bytes 0-255, then I would, in Python 3, where bytes contain ints in [0,255], make a byte mask of 256 0s and 1s (not '0's and '1's). Example: mask = b'\0\1'*121 for c in b'\0\1help': print(mask[c]) 1 0 1 0 1 1 In your case, use \1 for forbidden and replace the print with "if mask[c]: ; break" In 2.x, where iterating byte strings gives length 1 byte strings, you would need ord(c) as the index, which is much slower. > fine), but I will be working with some very large files in the 100's Gb > to several Tb size range so I'd thought I'd check to see if there was a > built-in in C that might handle this type of check more efficiently. > Does this sound like a use case for cython or pypy? Cython should get close to c speed, especially with hints. Make sure you compile something like the above as Py 3 code. -- Terry Jan Reedy From kw at codebykevin.com Mon Oct 31 20:00:13 2011 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 31 Oct 2011 20:00:13 -0400 Subject: ttk Listbox In-Reply-To: References: Message-ID: On 10/31/11 4:03 PM, Ric at rdo wrote: > On Mon, 31 Oct 2011 10:00:22 -0400, Kevin Walzer > wrote: > >> On 10/31/11 12:37 AM, Ric at rdo wrote: >>> >>> What would be an equivalent widget in ttk like a Listbox and if >>> possible a small example? I tried to look here >>> http://docs.python.org/library/ttk.html but did not see anything. >>> >>> Maybe I did not look in the right place? >>> >>> tia >> >> The listbox isn't part of the themed ttk widgets. The ttk::treview is, >> and that can be set up as a single-column list display. There may be an >> example of how to do this in the docs or source code tree (I don't use >> the widget myself so I don't have any sample code to share). >> >> --Kevin > > Quick question: > > Then why is it mentioned here > http://www.tkdocs.com/tutorial/morewidgets.html? > > Listboxes are created using the Listbox function: > > l = Listbox(parent, height=10) The listbox is a Tk widget, not a ttk widget. It's one of the original Tk/Tkinter widgets, and has no themed equivalent. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From python.list at tim.thechases.com Mon Oct 31 20:01:14 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 31 Oct 2011 19:01:14 -0500 Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? In-Reply-To: <4eaf28f7$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <1320090874.6062.140660992866273@webmail.messagingengine.com> <4eaf28f7$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4EAF36CA.5040409@tim.thechases.com> On 10/31/11 18:02, Steven D'Aprano wrote: > # Define legal characters: > LEGAL = ''.join(chr(n) for n in range(32, 128)) + '\n\r\t\f' > # everybody forgets about formfeed... \f > # and are you sure you want to include chr(127) as a text char? > > def is_ascii_text(text): > for c in text: > if c not in LEGAL: > return False > return True > > > Algorithmically, that's as efficient as possible: there's no faster way > of performing the test, although one implementation may be faster or > slower than another. (PyPy is likely to be faster than CPython, for > example.) Additionally, if one has some foreknowledge of the character distribution, one might be able to tweak your > def is_ascii_text(text): > legal = frozenset(LEGAL) > return all(c in legal for c in text) with some if/else chain that might be faster than the hashing involved in a set lookup (emphasis on the *might*, not being an expert on CPython internals) such as def is_ascii_text(text): return all( (' ' <= c <= '\x7a') or c == '\n' or c == '\t' for c in text) But Steven's main points are all spot on: (1) use an O(1) lookup; (2) return at the first sign of trouble; and (3) push it into the C implementation rather than a for-loop. (and the "locals are faster in CPython" is something I didn't know) -tkc From pmaupin at gmail.com Mon Oct 31 20:32:34 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Mon, 31 Oct 2011 17:32:34 -0700 (PDT) Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? References: <1320090874.6062.140660992866273@webmail.messagingengine.com> <4EAF175A.6060508@davea.name> <4EAF1C40.6030202@davea.name> Message-ID: <3bd5234e-dbbe-4f67-84fb-e654650decb6@hv4g2000vbb.googlegroups.com> On Mon, Oct 31, 2011 at 4:08 PM, Dave Angel wrote: Yes. Actually, you don't even need the split() -- you can pass an optional deletechars parameter to translate(). On Oct 31, 5:52?pm, Ian Kelly wrote: > That sounds overly complicated and error-prone. Not really. >?For instance, split() will split on vertical tab, > which is not one of the characters the OP wanted. That's just the default behavior. You can explicitly specify the separator to split on. But it's probably more efficient to just use translate with deletechars. > I would probably use a regular expression for this. I use 'em all the time, but not for stuff this simple. Regards, Pat From tjreedy at udel.edu Mon Oct 31 20:44:45 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 31 Oct 2011 20:44:45 -0400 Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? In-Reply-To: <4eaf28f7$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <1320090874.6062.140660992866273@webmail.messagingengine.com> <4eaf28f7$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/31/2011 7:02 PM, Steven D'Aprano wrote: > On Mon, 31 Oct 2011 17:47:06 -0400, Dave Angel wrote: > >> On 10/31/2011 03:54 PM, python at bdurham.com wrote: >>> Wondering if there's a fast/efficient built-in way to determine if a >>> string has non-ASCII chars outside the range ASCII 32-127, CR, LF, or >>> Tab? >>> >>> I know I can look at the chars of a string individually and compare >>> them against a set of legal chars using standard Python code (and this >>> works fine), but I will be working with some very large files in the >>> 100's Gb to several Tb size range so I'd thought I'd check to see if >>> there was a built-in in C that might handle this type of check more >>> efficiently. >>> >>> Does this sound like a use case for cython or pypy? >>> >>> Thanks, >>> Malcolm >>> >> How about doing a .replace() method call, with all those characters >> turning into '', and then see if there's anything left? > > > No offense Dave, but do you really think that making a copy of as much as > a terabyte of data is *more* efficient than merely scanning the data and > stopping on the first non-ASCII character you see? > > > There is no way of telling whether a string includes non-ASCII characters > without actually inspecting each character. So in the event that the > string *is* fully ASCII text, you have to check every character, there > can be no shortcuts. However, there is a shortcut if the string isn't > fully ASCII text: once you've found a single non-text character, stop. So > the absolute least amount of work you can do is: > > # Define legal characters: > LEGAL = ''.join(chr(n) for n in range(32, 128)) + '\n\r\t\f' > # everybody forgets about formfeed... \f > # and are you sure you want to include chr(127) as a text char? > > def is_ascii_text(text): > for c in text: > if c not in LEGAL: > return False > return True If text is 3.x bytes, this does not work ;-). OP did not specify bytes or unicode or Python version. > > > Algorithmically, that's as efficient as possible: This is a bit strange since you go on to explain that it is inefficient -- O(n*k) where n = text length and k = legal length -- whereas below is O(n). > there's no faster way > of performing the test, although one implementation may be faster or > slower than another. (PyPy is likely to be faster than CPython, for > example.) > > But can we get better in Python? Yes, I think so. First off, CPython is > optimized for local variable lookups over globals, and since you are > looking up the global LEGAL potentially 1000000000000 times, even a 1% > saving per lookup will help a lot. So the first step is to make a local > reference, by adding this line just above the for loop: > > legal = LEGAL > > But we can do even better still. Each time we test for "c not in legal", > we do a linear search of 100 characters. On average, that will mean > comparing 50 characters for equality at best. We can do better by using a > set or frozenset, which gives us approximately constant time lookups: > > legal = frozenset(LEGAL) > > Finally, we can try to do as much work as possible in fast C code and as > little as necessary in relatively slow Python: > > def is_ascii_text(text): > legal = frozenset(LEGAL) > return all(c in legal for c in text) > > Since all() is guaranteed to keep short-cut semantics, that will be as > fast as possible in Python, A dangerous statement to make. 'c in legal' has to get hash(c) and look that up in the hash table, possible skipping around a bit if t If text is byte string rather than unicode, a simple lookup 'mask[c]', where mask is a 0-1 byte array, should be faster (see my other post). On my new Pentium Win 7 machine, it is -- by albout 5%. For 100,000,000 legal bytes, a minimum of 8.69 versus 9.17 seconds. from time import clock legal_set = frozenset(range(32, 128)) legal_ray = 128 * b'\1' illegal = 128 * b'\0' # only testing legal char 'a' text = b'a' * 100000000 print(clock()) print(all(c in legal_set for c in text), clock()) # min 9.17 t = clock() print(all(legal_ray[c] for c in text), clock()-t) # min 8.69 ##for c in text: ## if illegal[c]: print(False); break # slower, about 9.7 ##print(True, clock()) The explicit loop took about 9.7 seconds. It is more flexible as it could detect the position of the first bad character, or of all of them. -- Terry Jan Reedy From d at davea.name Mon Oct 31 22:12:26 2011 From: d at davea.name (Dave Angel) Date: Mon, 31 Oct 2011 22:12:26 -0400 Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? In-Reply-To: <3bd5234e-dbbe-4f67-84fb-e654650decb6@hv4g2000vbb.googlegroups.com> References: <1320090874.6062.140660992866273@webmail.messagingengine.com> <4EAF175A.6060508@davea.name> <4EAF1C40.6030202@davea.name> <3bd5234e-dbbe-4f67-84fb-e654650decb6@hv4g2000vbb.googlegroups.com> Message-ID: <4EAF558A.7080602@davea.name> On 10/31/2011 08:32 PM, Patrick Maupin wrote: > On Mon, Oct 31, 2011 at 4:08 PM, Dave Angel wrote: > > Yes. Actually, you don't even need the split() -- you can pass an > optional deletechars parameter to translate(). > > > On Oct 31, 5:52 pm, Ian Kelly wrote: > >> That sounds overly complicated and error-prone. > Not really. > >> For instance, split() will split on vertical tab, >> which is not one of the characters the OP wanted. > That's just the default behavior. You can explicitly specify the > separator to split on. But it's probably more efficient to just use > translate with deletechars. > >> I would probably use a regular expression for this. > I use 'em all the time, but not for stuff this simple. > > Regards, > Pat I would claim that a well-written (in C) translate function, without using the delete option, should be much quicker than any python loop, even if it does copy the data. Incidentally, on the Pentium family, there's a machine instruction for that, to do the whole loop in one instruction (with rep prefix). I don't know if the library version is done so. And with the delete option, it wouldn't be copying anything, if the data is all legal. As for processing a gig of data, I never said to do it all in one pass. Process it maybe 4k at a time, and quit the first time you encounter a character not in the table. But I didn't try to post any code, since the OP never specified Python version, nor the encoding of the data. He just said string. And we all know that without measuring, it's all speculation. DaveA -- DaveA From rick.mansilla at gmail.com Mon Oct 31 22:36:23 2011 From: rick.mansilla at gmail.com (Ricardo Mansilla) Date: Mon, 31 Oct 2011 20:36:23 -0600 Subject: Tweepy: Invalid arguments at function call (tweepy.Stream()) (Terry Reedy) Message-ID: Thanks a lot for your answer. I'm using python 2.7.2 and tweetpy 1.7 >>> help(tweepy) Help on package tweepy: NAME tweepy - Tweepy Twitter API library (...) VERSION 1.7.1 and probably that is the problem, the link that you gave me refers to the 1.2 version page... Anyway, i already have their IRC direction and i think it would be easier to find support there. Thanks again. Ricardo Mansilla ps: sometimes i get lazy about writing the whole link to a precise direction which lacks of importance in my point; please, don't judge me for my exquisite way of keep the attention in the correct place... :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From flt.johnson at gmail.com Sat Oct 1 00:50:42 2011 From: flt.johnson at gmail.com (Fletcher Johnson) Date: Fri, 30 Sep 2011 21:50:42 -0700 (PDT) Subject: overloading operators for a function object Message-ID: Is it possible to overload operators for a function? For instance I would like to do something roughly like... def func_maker(): def func(): pass def __eq__(other): if other == "check": return True return False func.__eq__ = __eq__ return func newfunc = func_maker() newfunc == "check" #true newfunc == "no" #false From clp2 at rebertia.com Sat Oct 1 01:00:33 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 30 Sep 2011 22:00:33 -0700 Subject: overloading operators for a function object In-Reply-To: References: Message-ID: On Fri, Sep 30, 2011 at 9:50 PM, Fletcher Johnson wrote: > Is it possible to overload operators for a function? > > For instance I would like to do something roughly like... > > def func_maker(): > ?def func(): pass > > ?def __eq__(other): > ? ?if other == "check": ?return True > ? ?return False > > ?func.__eq__ = __eq__ > ?return func > > newfunc = func_maker() > newfunc == "check" #true > newfunc == "no" #false You can write a callable [wrapper] object to get the same effect: class SpecialFunction(object): def __call__(self, actual, args, go, here): return whatever def __eq__(self, other): return other == "check" newfunc = SpecialFunction() newfunc == "check" # => True newfunc(1, 2, 3, 4) #=> whatever Cheers, Chris -- http://rebertia.com From wuwei23 at gmail.com Sat Oct 1 01:10:55 2011 From: wuwei23 at gmail.com (alex23) Date: Fri, 30 Sep 2011 22:10:55 -0700 (PDT) Subject: Suggested coding style References: <27620bc4-edd2-473e-809f-18f17b426b4f@db5g2000vbb.googlegroups.com> Message-ID: > > On Sep 29, 10:23?pm, rantingrick wrote: > > > What is so bad about breaking code in obscure places? > On Sep 29, 9:50?pm, alex23 wrote: > > Try coding in PHP across minor release versions and see how you feel > > about deprecating core functions on a whim. On Sep 30, 11:54?pm, rantingrick wrote: > I never said we should remove it now, i said we should deprecate it > now. Actually, *I* said deprecate, *you* said break. I don't see the word 'remove' anywhere in my comment. > Please Google deprecate. Please read what I wrote rather than what you want me to have said. > Well "alex" i can't see a mob approaching with pitchforks because we > deprecate a misplaced and rarely used functionality of the stdlib. No, but you don't see a lot of things. You're genuinely convinced that your viewpoint is superior and singularly correct. I don't think you're a reasonable arbiter of what functionality should be added or removed from the stdlib. > Well "alex", like yourself, i hold expertise in many fields BESIDES > programming. One of which being psychology. That only makes the claims that you regularly post about others even more offensive. From jason.swails at gmail.com Sat Oct 1 02:31:18 2011 From: jason.swails at gmail.com (Jason Swails) Date: Sat, 1 Oct 2011 02:31:18 -0400 Subject: executing arbitrary statements Message-ID: Hello everyone, I'm probably missing something pretty obvious, but I was wondering if there was a way of executing an arbitrary line of code somehow (such as a line of code based on user-input). There's the obvious use of "eval" that will evaluate a function call, but that doesn't allow all things. For instance: >>> import sys >>> eval(r"sys.stdout.write('Hello world!\n')") Hello world! >>> eval(r"print 'Hello world!'") Traceback (most recent call last): File "", line 1, in File "", line 1 print 'Hello world!' ^ SyntaxError: invalid syntax >>> Because write is a function eval works fine for it. But since print isn't (2.7), it throws a syntax error. Likewise, variable assignments aren't allowed either as they are also not functions and lack a return value: >>> eval("j = 1") Traceback (most recent call last): File "", line 1, in File "", line 1 j = 1 ^ SyntaxError: invalid syntax What I'm more or less looking to do is present a (limited) form of an interpreter inside the application I'm writing for the advanced user. I'm also interested to hear if this is a particularly bad idea for any reason, and if there are security issues involved with allowing users to execute their own code inside my program (keeping in mind that some people may "donate" their scripts to others that may run them as black boxes). Is it enough to disallow import statements, thereby not giving direct access to the sys and os modules? I know more or less what I want to do, but I'd also appreciate any experienced input/advice/suggestions. Thanks! Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sat Oct 1 03:06:43 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 1 Oct 2011 00:06:43 -0700 Subject: executing arbitrary statements In-Reply-To: References: Message-ID: On Fri, Sep 30, 2011 at 11:31 PM, Jason Swails wrote: > Hello everyone, > > I'm probably missing something pretty obvious, but I was wondering if there > was a way of executing an arbitrary line of code somehow (such as a line of > code based on user-input).? There's the obvious use of "eval" that will > evaluate a function call, but that doesn't allow all things. > Because write is a function eval works fine for it.? But since print isn't > (2.7), it throws a syntax error.? Likewise, variable assignments aren't > allowed either as they are also not functions and lack a return value: Use the `exec` statement, which is capable of executing statements (as opposed to just expressions): http://docs.python.org/reference/simple_stmts.html#the-exec-statement > What I'm more or less looking to do is present a (limited) form of an > interpreter inside the application I'm writing for the advanced user. > > I'm also interested to hear if this is a particularly bad idea for any > reason, It's potentially rather hacky and ad-hoc to effectively directly inject arbitrary statements at certain points in your code. Assuming you were to trust the user-provided code, callbacks/hooks or plugin modules are typically much cleaner ways to integrate custom code from the user. Depending on your particular use case, the `cmd` module might also be a workable alternative: http://docs.python.org/library/cmd.html > and if there are security issues involved with allowing users to > execute their own code inside my program (keeping in mind that some people > may "donate" their scripts to others that may run them as black boxes). It is *very much* a security issue! > Is > it enough to disallow import statements, thereby not giving direct access to > the sys and os modules? Not by a long shot! There are a bunch of known tricks that exploit introspection to circumvent such restrictions. Secure execution of untrusted Python code is a difficult problem. Some have accomplished it to a degree, but typically only by modifying the interpreter itself or imposing relatively onerous restrictions on the untrusted code. > I know more or less what I want to do, but I'd also > appreciate any experienced input/advice/suggestions. I additionally came across this in researching my reply: http://pypi.python.org/pypi/RestrictedPython/ Apparently the speed of execution leaves something to be desired, but the package /supposedly/ works well otherwise. Cheers, Chris -- http://rebertia.com From ladasky at my-deja.com Sat Oct 1 05:22:41 2011 From: ladasky at my-deja.com (John Ladasky) Date: Sat, 1 Oct 2011 02:22:41 -0700 (PDT) Subject: Simplest way to resize an image-like array References: <9b0b8951-bfc2-4047-8b4e-1ee0af20af27@q24g2000vby.googlegroups.com> Message-ID: On Sep 30, 1:51?pm, Jon Clements wrote: > Is something like > http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresize.html > any use? There we go! That's the kind of method I was seeking. I didn't think to look outside of scipy.interpolate. Thanks, Jon. From ladasky at my-deja.com Sat Oct 1 05:24:32 2011 From: ladasky at my-deja.com (John Ladasky) Date: Sat, 1 Oct 2011 02:24:32 -0700 (PDT) Subject: Simplest way to resize an image-like array References: Message-ID: On Sep 30, 11:54?pm, Dennis Lee Bieber wrote: > ? ? ? ? How difficult would it be to convert the "array" to a PIL image? I'm > fairly certain PIL has operations to rescale images. Yes, I considered this approach -- but I have a lot of arrays to resample, and I didn't want to further slow what is likely to be an already-slow process. From emekamicro at gmail.com Sat Oct 1 08:41:22 2011 From: emekamicro at gmail.com (Emeka) Date: Sat, 1 Oct 2011 13:41:22 +0100 Subject: TK + MVC Message-ID: Hello All, I need a basic example where MVC pattern is used with Python TK. Regards, Emeka -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From julian.bilcke at gmail.com Sat Oct 1 11:13:45 2011 From: julian.bilcke at gmail.com (julian bilcke) Date: Sat, 1 Oct 2011 17:13:45 +0200 Subject: How to inspect slot wrappers arguments in Python? Message-ID: Hi, I would like to get the list of parameters I need to initialize an AST node. I'm trying to use the `inspect` module, however it seems I can't use it on a built-in (native?) class, or else I misunderstood. I'm using Python 2.7 and tried with Python 3.2. This is working: >>> import inspect >>> class C: ... def __init__(a,b=4): ... self.sum = a + b ... >>> inspect.getargspec(C.__init__) ArgSpec(args=['a', 'b'], varargs=None, keywords=None, defaults=(4,)) This is not working: >>> import inspect >>> import ast >>> inspect.getargspec(ast.If.__init__) Traceback (most recent call last): File "", line 1, in File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", line 813, in getargspec raise TypeError('{!r} is not a Python function'.format(func)) TypeError: is not a Python function I am wondering if there is another way to get these parameters automatically? (ie. without compiling myself a dict) Regards, J. Bilcke -------------- next part -------------- An HTML attachment was scrubbed... URL: From prakashr85 at gmail.com Sat Oct 1 13:25:38 2011 From: prakashr85 at gmail.com (Prakash) Date: Sat, 1 Oct 2011 10:25:38 -0700 (PDT) Subject: Need A script to open a excel file and extract the data using autofilter Message-ID: <4f3ec474-dd9f-4585-8f3c-41323d79b8de@z19g2000vby.googlegroups.com> Need A script to open a excel file and extract the data using autofilter and write it in a new sheet or new file like I have to select all rows in which all the columns contain pass as status From prakashr85 at gmail.com Sat Oct 1 13:35:06 2011 From: prakashr85 at gmail.com (Prakash) Date: Sat, 1 Oct 2011 10:35:06 -0700 (PDT) Subject: Need A script to open a excel file and extract the data using autofilter References: <4f3ec474-dd9f-4585-8f3c-41323d79b8de@z19g2000vby.googlegroups.com> Message-ID: <74fc7fc6-8d5d-40fd-b152-0ce022a78a0c@m5g2000vbe.googlegroups.com> On Oct 1, 10:25?pm, Prakash wrote: > Need ?A script to open a excel file and extract the data using > autofilter and write it in a new sheet or new file like I have to > select all rows in which all the columns contain pass as status from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlApp.Workbooks.Open(r'C:\Users\Administrator\Desktop\test.xls') xlApp.Visible = 1 after opening the text.xls file i need to filter all the rows in which the status column is passed and copy the whole sheet to another sheet From tavares at fe.up.pt Sat Oct 1 14:46:11 2011 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Sat, 1 Oct 2011 11:46:11 -0700 (PDT) Subject: Symposium "Image Processing and Visualization in Solid Mechanics Processes" within ESMC2012 - Announce & Call for Papers Message-ID: <44b88062-566a-487c-851a-08213655f7bd@p11g2000yqe.googlegroups.com> Dear Colleague, Within the 8th EUROMECH Solid Mechanics Conference - ESMC2012 (www.esmc2012.tugraz.at), to be held in Graz University of Technology, Austria, July 9-13, 2012, we are organizing the Symposium ?Image Processing and Visualization in Solid Mechanics Processes?. Examples of topics that will be considered in the symposium ?Image Processing and Visualization in Solid Mechanics Processes? are: Image Analysis; Image Restoration, Compression, Segmentation and Description; Object Tracking, Matching, Recognition, and Reconstruction; Visual Inspection; 3D Vision; Medical Imaging; Data Processing, Modeling and Analysis; Scientific Visualization; Enhanced Visualization; Human Computer Interaction; Virtual Reality; Simulation and Animation; Software Development for Image Processing and Visualization; Grid Computing in Image Processing and Visualization; and Applications of Image Processing and Visualization. Due to your research activities in those fields, we would like to invite you to submit your work and participate in the Symposium ?Image Processing and Visualization in Solid Mechanics Processes?. For instructions and submission, please, access to the conference website at: www.esmc2012.tugraz.at Please note that, when submitting your work you should select the Symposium ?Image Processing and Visualization in Solid Mechanics Processes?. Important dates: - Abstract submission (two-page): November 30, 2011; - Notification of acceptance: February 28, 2011. Kind regards, Jo?o Manuel R. S. Tavares (University of Porto, Portugal, tavares at fe.up.pt) Renato Natal Jorge (University of Porto, Portugal, rnatal at fe.up.pt) (Symposium organizers) From cmpython at gmail.com Sat Oct 1 14:50:59 2011 From: cmpython at gmail.com (CM) Date: Sat, 1 Oct 2011 11:50:59 -0700 (PDT) Subject: options for plotting points on geographic map References: <28071425.854.1317315127547.JavaMail.geo-discussion-forums@prfb12> Message-ID: <5f2e4914-e90c-41c0-be47-830482f023c1@k6g2000yql.googlegroups.com> On Sep 29, 12:52?pm, Miki Tebeka wrote: > Probably the google maps routes will be faster (maybe using embedded webkit window). However it requires internet connection. > > See alsohttp://www.scipy.org/Cookbook/Matplotlib/Maps Thanks. But I just needed a small radius, not the whole globe, and I need towns/cities indicated. I think Google Maps is the way to go. From cmpython at gmail.com Sat Oct 1 14:52:16 2011 From: cmpython at gmail.com (CM) Date: Sat, 1 Oct 2011 11:52:16 -0700 (PDT) Subject: options for plotting points on geographic map References: Message-ID: <129a7899-2f93-4b54-847c-d946c6cdd498@c1g2000yql.googlegroups.com> > You could create the webpage and then render > it in your desktop app. I have seen plenty of apps like that. That's a good idea. I was able to get the basics of the pymaps approach going, so I may do just this. Thanks. From alex.kapps at web.de Sat Oct 1 17:35:34 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Sat, 01 Oct 2011 23:35:34 +0200 Subject: TK + MVC In-Reply-To: References: Message-ID: <4E8787A6.8000903@web.de> On 01.10.2011 14:41, Emeka wrote: > Hello All, > > I need a basic example where MVC pattern is used with Python TK. I'm still not 100% sure if I really understand the MVC pattern. Some say the view and the model must not interact directly, some say the view must not access the controller (but the controller controls the view). Some insist on a certain interface, others just talk about a certain data/control flow, etc. But I think a simple (and quick 'n' dirty) Tk MVC example can look like this: #!/usr/bin/python import Tkinter as tk class Model(object): def __init__(self): self._data = ["foo", "bar", "baz"] self.controllers = [] def data(self): return self._data def add(self, value): self._data.append(value) self.changed() def delete(self, index): del self._data[index] self.changed() def changed(self): for controller in self.controllers: controller.update() class Controller(object): def __init__(self, model): self.model = model self.views = [] def handle_insert(self, value): self.model.add(value) def handle_delete(self, index): self.model.delete(index) def get_data(self): return self.model.data() def update(self): for view in self.views: view.update() class View(object): def __init__(self, master, controller): self.controller = controller self.master = master self.list = tk.Listbox(self.master) self.list.pack(expand=1, fill="both") self.entry = tk.Entry(self.master) self.entry.pack(fill="x", expand=1) self.entry.bind("", self.enter_handler) self.list.bind("", self.delete_handler) self.update() def enter_handler(self, event): text = self.entry.get() self.controller.handle_insert(text) def delete_handler(self, event): for index in self.list.curselection(): self.controller.handle_delete(int(index)) def update(self): self.list.delete(0, "end") for entry in self.controller.get_data(): self.list.insert("end", entry) def main(): root = tk.Tk() model = Model() controller = Controller(model) view = View(root, controller) model.controllers.append(controller) controller.views.append(view) root.mainloop() if __name__ == '__main__': main() From monaghand.david at gmail.com Sat Oct 1 18:00:07 2011 From: monaghand.david at gmail.com (David Monaghan) Date: Sat, 01 Oct 2011 23:00:07 +0100 Subject: Need A script to open a excel file and extract the data using autofilter References: <4f3ec474-dd9f-4585-8f3c-41323d79b8de@z19g2000vby.googlegroups.com> <74fc7fc6-8d5d-40fd-b152-0ce022a78a0c@m5g2000vbe.googlegroups.com> Message-ID: On Sat, 1 Oct 2011 10:35:06 -0700 (PDT), Prakash wrote: >On Oct 1, 10:25?pm, Prakash wrote: >> Need ?A script to open a excel file and extract the data using >> autofilter and write it in a new sheet or new file like I have to >> select all rows in which all the columns contain pass as status > >from win32com.client import Dispatch >xlApp = Dispatch("Excel.Application") >xlApp.Workbooks.Open(r'C:\Users\Administrator\Desktop\test.xls') >xlApp.Visible = 1 > >after opening the text.xls file i need to filter all the rows in which >the status column is passed and copy the whole sheet to another sheet I don't do this often enough to have it to mind, so what I normally do is record a Macro, convert it to VBS and then convert that to Python. I'll leave the final step for you to complete yourself, but this will do what you ask up to the point of copying the selected lines: from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlWbook = xlApp.Workbooks.Open(r"C:\Users\Administrator\Desktop\test.xls") xlApp.Visible = 1 xlWorksheet = xlWbook.Worksheets(1) xlWorksheet.Columns("A:V").Select() xlApp.Selection.AutoFilter( 2, "pass") # column number, filter criteria xlApp.Selection.AutoFilter( 3, "pass") xlApp.Selection.AutoFilter( 4, "pass") xlApp.Selection.AutoFilter( 5, "pass") #etc, etc - up to column 22 in this case xlApp.Selection.Copy() DaveM From monaghand.david at gmail.com Sat Oct 1 19:38:01 2011 From: monaghand.david at gmail.com (David Monaghan) Date: Sun, 02 Oct 2011 00:38:01 +0100 Subject: Need A script to open a excel file and extract the data using autofilter References: <4f3ec474-dd9f-4585-8f3c-41323d79b8de@z19g2000vby.googlegroups.com> <74fc7fc6-8d5d-40fd-b152-0ce022a78a0c@m5g2000vbe.googlegroups.com> Message-ID: <0k8f8714tlh3s031cm48vh3iivm2ih7tbk@4ax.com> On Sat, 01 Oct 2011 23:00:07 +0100, David Monaghan wrote: >from win32com.client import Dispatch >xlApp = Dispatch("Excel.Application") >xlWbook = xlApp.Workbooks.Open(r"C:\Users\Administrator\Desktop\test.xls") >xlApp.Visible = 1 >xlWorksheet = xlWbook.Worksheets(1) >xlWorksheet.Columns("A:V").Select() >xlApp.Selection.AutoFilter( 2, "pass") # column number, filter criteria >xlApp.Selection.AutoFilter( 3, "pass") >xlApp.Selection.AutoFilter( 4, "pass") >xlApp.Selection.AutoFilter( 5, "pass") >#etc, etc - up to column 22 in this case >xlApp.Selection.Copy() Or rather: from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlWbook = xlApp.Workbooks.Open(r'C:\Users\Administrator\Desktop\test.xls') xlApp.Visible = 1 xlWorksheet = xlWbook.Worksheets(1) xlWorksheet.Columns("A:V").Select() for column in range(2,23): xlApp.Selection.AutoFilter(column, "pass") xlApp.Selection.Copy() From greg.ewing at canterbury.ac.nz Sat Oct 1 22:17:33 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 02 Oct 2011 15:17:33 +1300 Subject: Benefit and belief In-Reply-To: References: <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> Message-ID: <9epvttFc2lU1@mid.individual.net> Chris Angelico wrote: > But what if I'm a great windowing magnate, owning windows all over the world? Like Bill Gates, you mean? -- Greg From greg.ewing at canterbury.ac.nz Sat Oct 1 22:40:41 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 02 Oct 2011 15:40:41 +1300 Subject: TK + MVC In-Reply-To: References: Message-ID: <9eq19cFmb2U1@mid.individual.net> Alexander Kapps wrote: > But I think a simple (and quick 'n' dirty) Tk MVC example can look like > this: The Controller doesn't seem to add any value in that example. You might as well connect the Model and Views directly to each other. -- Greg From steve+comp.lang.python at pearwood.info Sat Oct 1 23:03:11 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 02 Oct 2011 14:03:11 +1100 Subject: [OT] Chaos Theory [was Re: Benefit and belief] References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> Message-ID: <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> By the way, who removed the OT label from the subject line? Please don't unless it actually comes back on topic. DevPlayer wrote: > I still assert that contradiction is caused by narrow perspective. There's no doubt that some *apparent* contradictions are caused by lack of correct information. But: N is an even number; N (the same N, for avoidance of doubt) is an odd number is still a contradiction, no matter how you look at it. [...] > If I am correct; not sure here; but I think that is part of the new > math Choas theory. (The notion that not all variables are known and > the results of well defined functions may result in completely > different actual outcomes) [Missing variables in such data sets and > functions, to me is basically a narrow(er) perspective of the all the > revelent factors for such computations.] Chaos theory goes back to Henri Poincar? in the 1880s, and possibly even older. 130 years is hardly "new". The principle of Chaos Theory is not that there are some unknown variables, but that even if you know all the variables, even the slightest error or uncertainty in their values may lead to radically different results in the future. As so often is the case, something which seemed controversial when first proposed is actually quite obvious. Sometimes errors cancel, and a small uncertainty doesn't make any difference in the final result; sometimes errors add, and a small uncertainty increases to a large uncertainty in the final result; and sometimes errors multiply, and a small uncertainty can add to a huge uncertainty. Opposition to this idea was not based on mathematics, logic or common sense, but on the idea that God and/or Nature would not be so cruel as to allow errors to multiply. Or in other words, "if this were true, it would be unfortunate, therefore it can't be true". The story of Mankind, really. -- Steven From greg.ewing at canterbury.ac.nz Sat Oct 1 23:24:42 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 02 Oct 2011 16:24:42 +1300 Subject: [OT] Chaos Theory [was Re: Benefit and belief] In-Reply-To: <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9eq3rtF7l0U1@mid.individual.net> Steven D'Aprano wrote: > By the way, who removed the OT label from the subject line? Probably nobody "removed" it, they just replied to some earlier message that didn't have it. Despite the term, a newsgroup thread is not a linear structure, it's a tree. Changing the subject line on one branch doesn't magically affect the other branches. -- Greg From ericsnowcurrently at gmail.com Sat Oct 1 23:41:57 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Sat, 1 Oct 2011 21:41:57 -0600 Subject: lower-case names for builtin types Message-ID: Anyone know the story behind the lower-case names for the non-exception built-in types (like list and type)? I am guessing that they were originally factory functions that, at some point, graduated to full types; and the names were kept lower-case for backward compatibility. However, if we were to consider making a change for Python 4, I am not sure how I feel about Int("5") over int("5"). Maybe it would be Integer("5"). Regardless, perhaps the type names are still lower-case for some other valid reason. If so, I would love to know what that is. Is there any merit to having lower-cased class names? -eric From steve+comp.lang.python at pearwood.info Sat Oct 1 23:52:44 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 02 Oct 2011 14:52:44 +1100 Subject: [OT] Chaos Theory [was Re: Benefit and belief] References: <265946c5-3195-4f0e-896e-4e2e0a388525@k17g2000yqi.googlegroups.com> <8d467d85-355b-41b5-8ed0-8d465b4f5476@12g2000vbu.googlegroups.com> <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> <9eq3rtF7l0U1@mid.individual.net> Message-ID: <4e87e00d$0$29976$c3e8da3$5496439d@news.astraweb.com> Gregory Ewing wrote: > Steven D'Aprano wrote: >> By the way, who removed the OT label from the subject line? > > Probably nobody "removed" it, they just replied to some earlier > message that didn't have it. I started the "Benefit and belief" sub-thread, changing the subject line from "suggested coding style", and included a [OT] tag. So there was no earlier message of that subject without a tag to reply to. You know, I suspect this thread is a good example of chaos theory in action... for something that started off about coding styles, it has ended up in some fairly strange places... > Despite the term, a newsgroup thread is not a linear structure, > it's a tree. Changing the subject line on one branch doesn't > magically affect the other branches. I know that. I also know that it is irrelevant in this case. If your mail or news client has a threaded view, you can see for yourself who removed the tag. I was just being polite by not singling him out by name :) -- Steven From steve+comp.lang.python at pearwood.info Sun Oct 2 00:11:10 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 02 Oct 2011 15:11:10 +1100 Subject: lower-case names for builtin types References: Message-ID: <4e87e45f$0$29998$c3e8da3$5496439d@news.astraweb.com> Eric Snow wrote: > Anyone know the story behind the lower-case names for the > non-exception built-in types (like list and type)? I am guessing that > they were originally factory functions that, at some point, graduated > to full types; and the names were kept lower-case for backward > compatibility. Exactly. [steve at sylar ~]$ python1.5 Python 1.5.2 (#1, Apr 1 2009, 22:55:54) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> type(int) > However, if we were to consider making a change for Python 4, I am not > sure how I feel about Int("5") over int("5"). Maybe it would be > Integer("5"). > > Regardless, perhaps the type names are still lower-case for some other > valid reason. If so, I would love to know what that is. Is there any > merit to having lower-cased class names? Backwards compatibility and tradition. Many languages have functions to convert a value into a string, integer or float, which are usually written something like str(), int() and float(). It would seem strange to write them as Str(), Int() and Float() in Python just because they happen to be types. Maybe in Python 4000 there will be a push to rationalise the case of built-in types. -- Steven From ericsnowcurrently at gmail.com Sun Oct 2 00:41:47 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Sat, 1 Oct 2011 22:41:47 -0600 Subject: lower-case names for builtin types In-Reply-To: <4e87e45f$0$29998$c3e8da3$5496439d@news.astraweb.com> References: <4e87e45f$0$29998$c3e8da3$5496439d@news.astraweb.com> Message-ID: Thanks, Steven. On Sat, Oct 1, 2011 at 10:11 PM, Steven D'Aprano wrote: > Eric Snow wrote: > >> Anyone know the story behind the lower-case names for the >> non-exception built-in types (like list and type)? ?I am guessing that >> they were originally factory functions that, at some point, graduated >> to full types; and the names were kept lower-case for backward >> compatibility. > > Exactly. > > [steve at sylar ~]$ python1.5 > Python 1.5.2 (#1, Apr ?1 2009, 22:55:54) ?[GCC 4.1.2 20070925 (Red Hat > 4.1.2-27)] on linux2 > Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>>> type(int) > > > >> However, if we were to consider making a change for Python 4, I am not >> sure how I feel about Int("5") over int("5"). ?Maybe it would be >> Integer("5"). >> >> Regardless, perhaps the type names are still lower-case for some other >> valid reason. ?If so, I would love to know what that is. ?Is there any >> merit to having lower-cased class names? > > > Backwards compatibility and tradition. > > Many languages have functions to convert a value into a string, integer or > float, which are usually written something like str(), int() and float(). > It would seem strange to write them as Str(), Int() and Float() in Python > just because they happen to be types. > > Maybe in Python 4000 there will be a push to rationalise the case of > built-in types. > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > From bahamutzero8825 at gmail.com Sun Oct 2 01:12:05 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sun, 02 Oct 2011 00:12:05 -0500 Subject: Is there any way to access attributes from an imported module? Message-ID: <4E87F2A5.9000204@gmail.com> I'm not sure the subject's wording is the best, but I'll try to explain. I have a main script that imports several modules and I need to be able to call methods from a class instance inside that main script from a module. Currently, functions can be defined to access the methods, but such functions can only be called via commands sent to the main script (it's an IRC bot, and commands are sent via IRC). What I want to do is call those methods without sending commands (I want to send an IRC message from an except clause). I'm not too sure which bits are relevant, and it's probably a lot of code for a post, so I'll link: Main script (DelphiBot().load() is where commands are processed): https://github.com/sthrs/Beacon/blob/501ab1ffef83aa13613edb5985ad9a4570245a85/main.py The module I'm working on with examples of both functions that use commands and functions that don't: https://github.com/sthrs/Beacon/blob/501ab1ffef83aa13613edb5985ad9a4570245a85/modules/lastfm.py I have developer access to the repo, so modifying the main script is not an issue (I realize there is a very good possibility this will require changing the way the bot handles loading commands). A push in the right direction would be greatly appreciated, as I'm quite stumped. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 From steve+comp.lang.python at pearwood.info Sun Oct 2 02:55:13 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 02 Oct 2011 17:55:13 +1100 Subject: Is there any way to access attributes from an imported module? References: Message-ID: <4e880adc$0$29997$c3e8da3$5496439d@news.astraweb.com> Andrew Berg wrote: > I'm not sure the subject's wording is the best, but I'll try to explain. > I have a main script that imports several modules and I need to be able > to call methods from a class instance inside that main script from a > module. Currently, functions can be defined to access the methods, but > such functions can only be called via commands sent to the main script > (it's an IRC bot, and commands are sent via IRC). What I want to do is > call those methods without sending commands (I want to send an IRC > message from an except clause). Have I missed something? Why can't you just import the module and call the methods like you would for any other module and class? import module instance = module.Some_Class() result = instance.method(some, arguments, may, be, needed) -- Steven From raycores at gmail.com Sun Oct 2 03:26:23 2011 From: raycores at gmail.com (Lynn Oliver) Date: Sun, 2 Oct 2011 00:26:23 -0700 Subject: question on installing python 2.7.2 and tcl 8.5.10 on WinXP Message-ID: <0831907A-F8EB-4CC2-97A9-307671C8B3DA@gmail.com> Hello, I'm having problems building tcl/tk and python on Windows XP so that both are installed correctly. 1. ActivePython 2.7.2.5 works fine on my system but may be implicated in recent R6034 runtime errors from users. 2. Python.org 2.7.2 msi binaries install fine, but produce a "tcl wasn't installed correctly" runtime error from pyinstaller builds. 3. I built Python.org 2.7.2 sources using MSVC++ 2008 Express with a lot of manual work for the subprocess wrappers. The buildbot tools, which should more or less automate that process, did not work for me. 4. I can build tcl/tk 8.5.10 using MinGW/Msys. 5. When I built the tkinter component, I placed the build of tcl/tk where it was expected by the build scripts, and VC++ reported that the build was successful. However, if I start python.exe from the build directory, I can't import Tkinter (or tkinter). I feel like I must be missing some basic understanding of how and where things are installed; having completed the builds I still don't know how to install the resulting files into the correct directories. Any suggestions? Thanks for your help, Lynn -------------- next part -------------- An HTML attachment was scrubbed... URL: From bahamutzero8825 at gmail.com Sun Oct 2 04:01:20 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sun, 02 Oct 2011 03:01:20 -0500 Subject: Is there any way to access attributes from an imported module? In-Reply-To: <4e880adc$0$29997$c3e8da3$5496439d@news.astraweb.com> References: <4e880adc$0$29997$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E881A50.8060303@gmail.com> On 2011.10.02 01:55 AM, Steven D'Aprano wrote: > Have I missed something? Why can't you just import the module and call the > methods like you would for any other module and class? > > import module > instance = module.Some_Class() > result = instance.method(some, arguments, may, be, needed) I need to affect the instance created in the main script; creating a new instance would be pointless (and AFAICT would result in the interpreter hitting a recursion limit since the module is imported during creation of the instance). -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 From bahamutzero8825 at gmail.com Sun Oct 2 04:42:24 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sun, 02 Oct 2011 03:42:24 -0500 Subject: Is there any way to access attributes from an imported module? In-Reply-To: <4E880E87.5070507@islandtraining.com> References: <4E87F2A5.9000204@gmail.com> <4E880E87.5070507@islandtraining.com> Message-ID: <4E8823F0.8080102@gmail.com> On 2011.10.02 02:11 AM, Gary Herron wrote: > You may be able to do the simplest thing: If a module wants to call > something form the main module (or main script as you call it) just try > importing that main script and call whatever it is you want. This > results in a circular set of imports, but Python can often deal with > those without trouble. (Not always, so circular imports are best > avoided in general, but .. try it and see.) It doesn't work. I get an AttributeError any time I try to access the class instance from the sub-module. Even moving the load() call outside __init__() doesn't change this. > If there is code in the main script (module) that needs to be called > form elsewhere, take it out of the main module and put it in a separate > module. Then import that new module both in the main script, and the > various sub-modules. This is cleaner than the circular imports in the > previous solution. I need to affect a specific instance which imports the sub-modules. I worded the subject line wrong (and I've no clue how to word it now). This is quite hard to explain, and I don't think it's easy to understand without really examining the code (I don't even fully understand it). More ideas are certainly welcome, but I think I'll have to ask the developer (who has only been somewhat active lately). -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 From steve+comp.lang.python at pearwood.info Sun Oct 2 04:50:07 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 02 Oct 2011 19:50:07 +1100 Subject: Is there any way to access attributes from an imported module? References: <4e880adc$0$29997$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e8825c0$0$29992$c3e8da3$5496439d@news.astraweb.com> Andrew Berg wrote: > On 2011.10.02 01:55 AM, Steven D'Aprano wrote: >> Have I missed something? Why can't you just import the module and call >> the methods like you would for any other module and class? >> >> import module >> instance = module.Some_Class() >> result = instance.method(some, arguments, may, be, needed) > > I need to affect the instance created in the main script; Then call the methods on the instance created in the main script. I'm still failing to see your problem. -- Steven From tartley at tartley.com Sun Oct 2 05:10:16 2011 From: tartley at tartley.com (Jonathan Hartley) Date: Sun, 2 Oct 2011 02:10:16 -0700 (PDT) Subject: executing arbitrary statements In-Reply-To: References: Message-ID: <12122472.2101.1317546616537.JavaMail.geo-discussion-forums@yqma37> On Saturday, October 1, 2011 8:06:43 AM UTC+1, Chris Rebert wrote: > On Fri, Sep 30, 2011 at 11:31 PM, Jason Swails wrote: > > I'm probably missing something pretty obvious, but I was wondering if there > > was a way of executing an arbitrary line of code somehow (such as a line of > > code based on user-input).? There's the obvious use of "eval" that will > > evaluate a function call, but that doesn't allow all things. > > > Because write is a function eval works fine for it.? But since print isn't > > (2.7), it throws a syntax error.? Likewise, variable assignments aren't > > allowed either as they are also not functions and lack a return value: > > > Use the `exec` statement, which is capable of executing statements (as > opposed to just expressions): > http://docs.python.org/reference/simple_stmts.html#the-exec-statement > > > What I'm more or less looking to do is present a (limited) form of an > > interpreter inside the application I'm writing for the advanced user. > > > > I'm also interested to hear if this is a particularly bad idea for any > > reason, > > It's potentially rather hacky and ad-hoc to effectively directly > inject arbitrary statements at certain points in your code. > > Assuming you were to trust the user-provided code, callbacks/hooks or > plugin modules are typically much cleaner ways to integrate custom > code from the user. > > Depending on your particular use case, the `cmd` module might also be > a workable alternative: > http://docs.python.org/library/cmd.html > > > and if there are security issues involved with allowing users to > > execute their own code inside my program (keeping in mind that some people > > may "donate" their scripts to others that may run them as black boxes). > > It is *very much* a security issue! > > > Is > > it enough to disallow import statements, thereby not giving direct access to > > the sys and os modules? > > Not by a long shot! There are a bunch of known tricks that exploit > introspection to circumvent such restrictions. > Secure execution of untrusted Python code is a difficult problem. Some > have accomplished it to a degree, but typically only by modifying the > interpreter itself or imposing relatively onerous restrictions on the > untrusted code. > > > I know more or less what I want to do, but I'd also > > appreciate any experienced input/advice/suggestions. > > I additionally came across this in researching my reply: > http://pypi.python.org/pypi/RestrictedPython/ > Apparently the speed of execution leaves something to be desired, but > the package /supposedly/ works well otherwise. > > Cheers, > Chris > -- > http://rebertia.com I (and many others) entirely avoid using 'eval' in all my code for many years, based on the security concerns that Chris rightly highlights. It's worth noting though, that RaymondH's talks last year on some valid uses of 'eval' and 'exec' have opened my eyes to it somewhat. In summary, while it's dangerous to execute user-submitted code, there are no security risks associated with executing code generated by your own program. It takes a while to see how this might be useful, if (like me) you're not used to thinking about it. Raymond's premier example was his implementation of namedtuple: (see http://hg.python.org/cpython/file/default/Lib/collections/__init__.py) This defines a string, the contents of which is a class definition, with some string formatting markers in it. These are replaced with known values on invocation of the namedtuple factory function, which then exec's the class-definition string and returns the resulting new type. This results in an implementation that is both simpler and faster than trying to simply write a general-purpose class that does at runtime all the things that 'namedtuple' does. From tartley at tartley.com Sun Oct 2 05:10:16 2011 From: tartley at tartley.com (Jonathan Hartley) Date: Sun, 2 Oct 2011 02:10:16 -0700 (PDT) Subject: executing arbitrary statements In-Reply-To: References: Message-ID: <12122472.2101.1317546616537.JavaMail.geo-discussion-forums@yqma37> On Saturday, October 1, 2011 8:06:43 AM UTC+1, Chris Rebert wrote: > On Fri, Sep 30, 2011 at 11:31 PM, Jason Swails wrote: > > I'm probably missing something pretty obvious, but I was wondering if there > > was a way of executing an arbitrary line of code somehow (such as a line of > > code based on user-input).? There's the obvious use of "eval" that will > > evaluate a function call, but that doesn't allow all things. > > > Because write is a function eval works fine for it.? But since print isn't > > (2.7), it throws a syntax error.? Likewise, variable assignments aren't > > allowed either as they are also not functions and lack a return value: > > > Use the `exec` statement, which is capable of executing statements (as > opposed to just expressions): > http://docs.python.org/reference/simple_stmts.html#the-exec-statement > > > What I'm more or less looking to do is present a (limited) form of an > > interpreter inside the application I'm writing for the advanced user. > > > > I'm also interested to hear if this is a particularly bad idea for any > > reason, > > It's potentially rather hacky and ad-hoc to effectively directly > inject arbitrary statements at certain points in your code. > > Assuming you were to trust the user-provided code, callbacks/hooks or > plugin modules are typically much cleaner ways to integrate custom > code from the user. > > Depending on your particular use case, the `cmd` module might also be > a workable alternative: > http://docs.python.org/library/cmd.html > > > and if there are security issues involved with allowing users to > > execute their own code inside my program (keeping in mind that some people > > may "donate" their scripts to others that may run them as black boxes). > > It is *very much* a security issue! > > > Is > > it enough to disallow import statements, thereby not giving direct access to > > the sys and os modules? > > Not by a long shot! There are a bunch of known tricks that exploit > introspection to circumvent such restrictions. > Secure execution of untrusted Python code is a difficult problem. Some > have accomplished it to a degree, but typically only by modifying the > interpreter itself or imposing relatively onerous restrictions on the > untrusted code. > > > I know more or less what I want to do, but I'd also > > appreciate any experienced input/advice/suggestions. > > I additionally came across this in researching my reply: > http://pypi.python.org/pypi/RestrictedPython/ > Apparently the speed of execution leaves something to be desired, but > the package /supposedly/ works well otherwise. > > Cheers, > Chris > -- > http://rebertia.com I (and many others) entirely avoid using 'eval' in all my code for many years, based on the security concerns that Chris rightly highlights. It's worth noting though, that RaymondH's talks last year on some valid uses of 'eval' and 'exec' have opened my eyes to it somewhat. In summary, while it's dangerous to execute user-submitted code, there are no security risks associated with executing code generated by your own program. It takes a while to see how this might be useful, if (like me) you're not used to thinking about it. Raymond's premier example was his implementation of namedtuple: (see http://hg.python.org/cpython/file/default/Lib/collections/__init__.py) This defines a string, the contents of which is a class definition, with some string formatting markers in it. These are replaced with known values on invocation of the namedtuple factory function, which then exec's the class-definition string and returns the resulting new type. This results in an implementation that is both simpler and faster than trying to simply write a general-purpose class that does at runtime all the things that 'namedtuple' does. From steve+comp.lang.python at pearwood.info Sun Oct 2 10:11:04 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 03 Oct 2011 01:11:04 +1100 Subject: executing arbitrary statements References: Message-ID: <4e8870f9$0$29979$c3e8da3$5496439d@news.astraweb.com> Jonathan Hartley wrote: > I (and many others) entirely avoid using 'eval' in all my code for many > years, based on the security concerns that Chris rightly highlights. It's > worth noting though, that RaymondH's talks last year on some valid uses of > 'eval' and 'exec' have opened my eyes to it somewhat. In summary, while > it's dangerous to execute user-submitted code, there are no security risks > associated with executing code generated by your own program. That's not strictly true. If you look at the code for namedtuple, you will see that Raymond actually spends significant effort to sanitise the input to namedtuple. Right at the top of the class is this comment: # Parse and validate the field names. Validation serves two purposes, # generating informative error messages and preventing template injection attacks. So even something like namedtuple needs to take care of security risks. In a more general sense, "security" does not necessarily mean security against outsiders. Sometimes the threat you're defending from is an insider, or even yourself: for example, there are various utility programs designed to prevent you from emailing while drunk (I know people who should use them!), *many* security protocols designed to prevent a single rogue member of an organisation from doing harm (e.g. it takes at least two people to launch nuclear warheads), etc. This is why (for example) on Linux, the rm command defaults to interactive use when given as root. If you've ever typed rm -r * in the wrong directory (especially the root directory) you'll understand that sometimes the worst threat is yourself. -- Steven From rustompmody at gmail.com Sun Oct 2 11:03:07 2011 From: rustompmody at gmail.com (rusi) Date: Sun, 2 Oct 2011 08:03:07 -0700 (PDT) Subject: Chaos Theory [was Re: Benefit and belief] References: <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Oct 2, 8:03?am, Steven D'Aprano wrote: > By the way, who removed the OT label from the subject line? Please don't > unless it actually comes back on topic. > > DevPlayer wrote: > > I still assert that contradiction is caused by narrow perspective. > > There's no doubt that some *apparent* contradictions are caused by lack of > correct information. But: > > N is an even number; > N (the same N, for avoidance of doubt) is an odd number > > is still a contradiction, no matter how you look at it. DevPlayer is probably talking of 'synthetic/a posteriori' statements You're changing it to 'analytic/a priori' (like the OT subject line ) (see http://en.wikipedia.org/wiki/Analytic%E2%80%93synthetic_distinction#Kant ) From marko.loparic at gmail.com Sun Oct 2 13:36:30 2011 From: marko.loparic at gmail.com (markolopa) Date: Sun, 2 Oct 2011 10:36:30 -0700 (PDT) Subject: Replacing spreadsheets by Python and the browser Message-ID: <307ff168-fba6-4017-8ecb-a758b32c14b2@g23g2000vbz.googlegroups.com> Hello, Could you please recommend me a Python tool that could help me to get rid of the messy information and scripts I have in spreadsheets? Spreadsheets are great for having simple things done quickly. But as the needs grow their limitations can be quite frustrating. I would like to use the browser to edit information that for the moment I store in spreadsheets. I believe that the perfect tool for me would be that a combination a table editing tool and a tree navigation tool. I would like to navigate in a tree, expanding and collapsing nodes. The leaf nodes would then be tables with some editable columns. A good table editing tool (without the tree navigation) would already be very helpful. Examples of information I would store in such a tree/table system (which are now in spreasheets): - My dvd, avi collection: The tree would be the directory tree of the file system where I store my movies. For each directory containing the avis or the dvds there would be a table with one movie by row and several editable columns: the file name, the genre, the year, whether I have seen it or not, comments, etc. . The same thing for mp3. - My family budget. The tree would be the account tree, the rows in the table would be the deposits and withdrwals. This is actually my most important need. I don't find gnucash flexible enough for my needs. Beancount (http://furius.ca/beancount/) has a great html output, but I would like to use the browser also for input. I am very comfortable with Python, but I don't know much about web framewords and javascript interfaces. I am ready to learn anything that could help me to do the desired tasks quickly, without having to code a web application from scratch. Is javascript the way to go? In this case is there a Python lib can I use on the server side? Could a tool like django be helpful? Pyjamas? Both a single machine or a client-server architecture are fine for me. Thanks a lot in advance for all suggestion, Marko From rustompmody at gmail.com Sun Oct 2 13:48:35 2011 From: rustompmody at gmail.com (rusi) Date: Sun, 2 Oct 2011 10:48:35 -0700 (PDT) Subject: Replacing spreadsheets by Python and the browser References: <307ff168-fba6-4017-8ecb-a758b32c14b2@g23g2000vbz.googlegroups.com> Message-ID: <310597fc-3654-4eb1-a0a1-436554b421ae@q25g2000vbx.googlegroups.com> On Oct 2, 10:36?pm, markolopa wrote: > Hello, > > Could you please recommend me a Python tool that could help me to get > rid of the messy information and scripts I have in spreadsheets? > > Spreadsheets are great for having simple things done quickly. But as > the needs grow their limitations can be quite frustrating. I would > like to use the browser to edit information that for the moment I > store in spreadsheets. > > I believe that the perfect tool for me would be that a combination a > table editing tool and a tree navigation tool. I would like to > navigate in a tree, expanding and collapsing nodes. The leaf nodes > would then be tables with some editable columns. > > A good table editing tool (without the tree navigation) would already > be very helpful. > > Examples of information I would store in such a tree/table system > (which are now in spreasheets): > - My dvd, avi collection: The tree would be the directory tree of the > file system where I store my movies. For each directory containing the > avis or the dvds there would be a table with one movie by row and > several editable columns: the file name, the genre, the year, whether > I have seen it or not, comments, etc. > . The same thing for mp3. > - My family budget. The tree would be the account tree, the rows in > the table would be the deposits and withdrwals. This is actually my > most important need. I don't find gnucash flexible enough for my > needs. ?Beancount (http://furius.ca/beancount/) has a great html > output, but I would like to use the browser also for input. > > I am very comfortable with Python, but I don't know much about web > framewords and javascript interfaces. I am ready to learn anything > that could help me to do the desired tasks quickly, without having to > code a web application from scratch. Is javascript the way to go? In > this case is there a Python lib can I use on the server side? Could a > tool like django be helpful? Pyjamas? Both a single machine or a > client-server architecture are fine for me. > > Thanks a lot in advance for all suggestion, > Marko May not be what you are asking for but you may want to look at orgmode: http://orgmode.org/ From andrea.crotti.0 at gmail.com Sun Oct 2 13:51:25 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Sun, 02 Oct 2011 18:51:25 +0100 Subject: Replacing spreadsheets by Python and the browser In-Reply-To: <307ff168-fba6-4017-8ecb-a758b32c14b2@g23g2000vbz.googlegroups.com> References: <307ff168-fba6-4017-8ecb-a758b32c14b2@g23g2000vbz.googlegroups.com> Message-ID: <4E88A49D.2040704@gmail.com> On 10/02/2011 06:36 PM, markolopa wrote: > Hello, > > Could you please recommend me a Python tool that could help me to get > rid of the messy information and scripts I have in spreadsheets? > > Spreadsheets are great for having simple things done quickly. But as > the needs grow their limitations can be quite frustrating. I would > like to use the browser to edit information that for the moment I > store in spreadsheets. > > I believe that the perfect tool for me would be that a combination a > table editing tool and a tree navigation tool. I would like to > navigate in a tree, expanding and collapsing nodes. The leaf nodes > would then be tables with some editable columns. > > A good table editing tool (without the tree navigation) would already > be very helpful. > > Examples of information I would store in such a tree/table system > (which are now in spreasheets): > - My dvd, avi collection: The tree would be the directory tree of the > file system where I store my movies. For each directory containing the > avis or the dvds there would be a table with one movie by row and > several editable columns: the file name, the genre, the year, whether > I have seen it or not, comments, etc. > . The same thing for mp3. > - My family budget. The tree would be the account tree, the rows in > the table would be the deposits and withdrwals. This is actually my > most important need. I don't find gnucash flexible enough for my > needs. Beancount (http://furius.ca/beancount/) has a great html > output, but I would like to use the browser also for input. > > I am very comfortable with Python, but I don't know much about web > framewords and javascript interfaces. I am ready to learn anything > that could help me to do the desired tasks quickly, without having to > code a web application from scratch. Is javascript the way to go? In > this case is there a Python lib can I use on the server side? Could a > tool like django be helpful? Pyjamas? Both a single machine or a > client-server architecture are fine for me. > > Thanks a lot in advance for all suggestion, > Marko Well my answer is not really python-related, but one tool that really changed my life is orgmode http://orgmode.org/ It does almost everything you ask and a 1000 other things. If you want to go with a python project, in general you should probably need a lot of javascript to have something which is nice and easy to use, and yes something like django would work. From yasar11732 at gmail.com Sun Oct 2 14:22:56 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Sun, 2 Oct 2011 21:22:56 +0300 Subject: Adding new keywords to Python interpreter Message-ID: Hi people, Nowadays, I am trying to explore python source. I added a new keyword, essentially doing same thing as 'continue' keyword to the interpreter, mostly by following instructions in PEP 306. If anyone interested here is the video about how I did it: http://www.youtube.com/watch?v=Ww7BeIdUbUI notes in video are in Turkish, but you don't require the notes much, as they don't mention any crucial point. By the way, I am not saying this is the best, or even right way to do it. I am just sharing what I have done. Have a nice day :) -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From rantingrick at gmail.com Sun Oct 2 15:01:18 2011 From: rantingrick at gmail.com (rantingrick) Date: Sun, 2 Oct 2011 12:01:18 -0700 (PDT) Subject: Replacing spreadsheets by Python and the browser References: <307ff168-fba6-4017-8ecb-a758b32c14b2@g23g2000vbz.googlegroups.com> Message-ID: <8b7a28d7-d826-4e02-bb68-5cae6a0db6d1@i28g2000yqn.googlegroups.com> On Oct 2, 12:36?pm, markolopa wrote: > Examples of information I would store in such a tree/table system > (which are now in spreasheets): > - My dvd, avi collection: The tree would be the directory tree of the > file system where I store my movies. For each directory containing the > avis or the dvds there would be a table with one movie by row and > several editable columns: the file name, the genre, the year, whether > I have seen it or not, comments, etc. > . The same thing for mp3. > - My family budget. The tree would be the account tree, the rows in > the table would be the deposits and withdrwals. This is actually my > most important need. I don't find gnucash flexible enough for my > needs. ?Beancount (http://furius.ca/beancount/) has a great html > output, but I would like to use the browser also for input. Is there any reason why you could not use the advanced widgets in WxPython? You never said whether this MUST BE a web application. If GUI is okay then check out wxListCtrl and wxTreeCtrl. All you need to do is write a little control code and voila. http://www.wxpython.org/onlinedocs.php From python at bdurham.com Sun Oct 2 15:38:43 2011 From: python at bdurham.com (python at bdurham.com) Date: Sun, 02 Oct 2011 15:38:43 -0400 Subject: Replacing spreadsheets by Python and the browser In-Reply-To: References: <307ff168-fba6-4017-8ecb-a758b32c14b2@g23g2000vbz.googlegroups.com> Message-ID: <1317584323.23992.140258150165505@webmail.messagingengine.com> Check out ResolverOne http://www.resolversystems.com Malcolm From andrea.gavana at gmail.com Sun Oct 2 17:29:24 2011 From: andrea.gavana at gmail.com (Andrea Gavana) Date: Mon, 3 Oct 2011 00:29:24 +0300 Subject: Change import order with *.pth files Message-ID: Hi All, my apologies if this is a dumb question, but I couldn't find a solution - possibly because I am not sure how to state my problem in a short sentence. Let's say I am using a package called "blah", and this package is already installed on site-packages (and I need it to be there) with a name "blah-1.2-win". In the site-packages folder, there is a pth file called "blah.pth" which contains this line: blah-1.2-win To redirect Python to the correct folder when I type "import blah". Anyway, now I am developing another version of this package and it's called "blah-2.0-win", and it sits on my computer into a different folder (not on site-packages, on an entire different drive in reality). How can I tell Python *not* to use the version inside site-packages but to use the other one in my development folder (without touching the pth file in site-packages, of course)? I have tried fiddling with sys.path and to create a local (in my development folder) pth file, to no avail. I hope I have been able to explain my problem clearly... This is on Windows, Python 2.5 to 2.7. Thank you in advance for your suggestions. Andrea. "Imagination Is The Only Weapon In The War Against Reality." http://xoomer.alice.it/infinity77/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Sun Oct 2 17:43:44 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 02 Oct 2011 21:43:44 GMT Subject: [OT] Re: Chaos Theory [was Re: Benefit and belief] References: <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e88db0f$0$29981$c3e8da3$5496439d@news.astraweb.com> On Sun, 02 Oct 2011 08:03:07 -0700, rusi wrote: > On Oct 2, 8:03?am, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: >> By the way, who removed the OT label from the subject line? Please >> don't unless it actually comes back on topic. >> >> DevPlayer wrote: >> > I still assert that contradiction is caused by narrow perspective. >> >> There's no doubt that some *apparent* contradictions are caused by lack >> of correct information. But: >> >> N is an even number; >> N (the same N, for avoidance of doubt) is an odd number >> >> is still a contradiction, no matter how you look at it. > > DevPlayer is probably talking of 'synthetic/a posteriori' statements > You're changing it to 'analytic/a priori' (like the OT subject line > ) > (see > http://en.wikipedia.org/wiki/Analytic%E2%80%93synthetic_distinction#Kant > ) An interesting link. I knew the Objectivists were nuts, but I really didn't appreciate quite how nuts they were until I read Leonard Peikoff's criticism of Kant. Not that I necessary agree with Kant, but the Objectivist argument basically boils down to "We would like empirical knowledge to be 100% certain, but Kant demonstrates that it isn't. Therefore he must be wrong." Or to put it another way: "I reject your reality and substitute my own." But in any case, no, I am not merely talking about analytic/a priori statements. Here's a synthetic/a priori version: (a) The sum of odd numbers between 6 and 20 equals 91. (b) The sum of odd numbers between 6 and 20 equals 93. and here's a synthetic/a posteriori version: (c) During the 1936 Olympic Games, the leader of the host nation had a full beard. (d) During the 1936 Olympic Games, the leader of the host nation did not have a full beard. Unlike Kant, I don't think that analytic/a posteriori is contradictory. Here is an example: (e) Combustion is caused by a chemical reaction between an oxidant and some other reagent. (f) Combustion is caused by the release of phlogiston from materials. In all cases, we can be sure that the contradiction between the pair of statements are genuine contradictions and not mere apparent contradictions caused by "narrow perspective" or incomplete or erroneous knowledge. -- Steven From andrea.crotti.0 at gmail.com Sun Oct 2 17:57:23 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Sun, 02 Oct 2011 22:57:23 +0100 Subject: Change import order with *.pth files In-Reply-To: References: Message-ID: <4E88DE43.1040607@gmail.com> On 10/02/2011 10:29 PM, Andrea Gavana wrote: > Hi All, > > my apologies if this is a dumb question, but I couldn't find a > solution - possibly because I am not sure how to state my problem in > a short sentence. > > Let's say I am using a package called "blah", and this package is > already installed on site-packages (and I need it to be there) with a > name "blah-1.2-win". In the site-packages folder, there is a pth file > called "blah.pth" which contains this line: > > blah-1.2-win > > To redirect Python to the correct folder when I type "import blah". > Anyway, now I am developing another version of this package and it's > called "blah-2.0-win", and it sits on my computer into a different > folder (not on site-packages, on an entire different drive in > reality). How can I tell Python *not* to use the version inside > site-packages but to use the other one in my development folder > (without touching the pth file in site-packages, of course)? > > I have tried fiddling with sys.path and to create a local (in my > development folder) pth file, to no avail. I hope I have been able to > explain my problem clearly... This is on Windows, Python 2.5 to 2.7. > > Thank you in advance for your suggestions. > > Andrea. Well messing up with the pth file is not a very good idea in general, since it's thought to be manipulated by distutils, not by hand. The best way to solve your problem is to use virtualenv or something similar, check it out... From kw at codebykevin.com Sun Oct 2 18:02:05 2011 From: kw at codebykevin.com (Kevin Walzer) Date: Sun, 02 Oct 2011 18:02:05 -0400 Subject: getattr and method name Message-ID: I'm seeing a very odd error in an application I'm developing using Python 2.7.2, on Mac OS 10.7. This application uses a wrapper method to look up other method names via getattr and then call those methods. I have not previously had an issue with this name, but for some reason this functionality no longer works as expected. Here is the relevant code: #run command with root privileges def runCommand(self, cmd, *args): try: functionstring = args[2] callfunction = getattr(self, functionstring.split('.')[1]) self.passtext = self.tk.call('authorize::getAuthPassword') callfunction() except: try: print cmd functionstring = cmd.split()[2] callfunction = getattr(self, functionstring.split('.')[1]) self.passtext = self.tk.call('authorize::getAuthPassword') callfunction() except: raise I use this approach to call the method named in the "cmd" parameter because I also have to look up a password name that is returned by an underlying Tk package that I use in my application (that's the reason for the 'self.tk.call'). What is happening is when I use the "callfunction()" call, instead of the method name being called, a string like this is being invoked: > The "scanPackages" method (just to use it as an example) uses Popen to call an underlying system tool on the OS. However, when invoked via callfunction(), the 'bound method...' string is passed to the OS instead as a command! As a result, I get this output from the pipe: /bin/sh: bound: No such file or directory I am not sure what in my application is causing this kind of breakage, as earlier versions of the app ran fine with similar code on earlier versions on the OS. Is this the correct way to structure this kind of functionality, or am I better off structuring it some other way? --Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From steveo at syslang.net Sun Oct 2 18:12:03 2011 From: steveo at syslang.net (Steven W. Orr) Date: Sun, 02 Oct 2011 18:12:03 -0400 Subject: Advise on using logging.getLogger needed. Message-ID: <4E88E1B3.6080009@syslang.net> I hope I don't sound like I'm ranting :-( I have created a module (called xlogging) which sets up logging the way I want it. I found out that if I set up my logger without a name, then it gets applied to every logger that is referenced by every module that ever gets imported. The problem is that I must call xlogging.getLogger or logging.getLogger in all other modules using the name of the root logger, and I don't know what that name is. I want the name of the root logger to be the name of the running program, so in my setup, I say pname = sys.argv[0] try: rslash = pname.rindex('/') except ValueError: pass else: pname = pname[rslash + 1:] try: dot_py = pname.rindex('.py') except ValueError: pass else: pname = pname[0:dot_py] and then I say logger = logging.getLogger(pname) My problem is that I just want the modules that I write, to be able to get the named root logger and still be able to refer to possible sub-loggers. So, let's say I run program foo. At some point in my mail setup, I set the configuration for the foo logger. I'd like my xlogging module to supply a getLogger function such that if I don't supply any arguments, it will return the logger that would normally be returned by logging.getLogger(pname). Also, part of the reason I'm confused is because foo calls m1 and m2 and they want to say logger = xlogging.getLogger(MaybeWithAnArg?) at the top of their code. This means that the import statement for m1 and m2 are getting the calls to getLogger executed before I get the chance to set things up. I am running 2.6, so I don't have access to logging.getChild, but I'm not clear that I even want that. My modules are used by multiple programs. Does this mean that I should simply use __name__ all the time? (That seems inelegant, no?) If I'm making sense, is there a way to do this? -- Time flies like the wind. Fruit flies like a banana. Stranger things have .0. happened but none stranger than this. Does your driver's license say Organ ..0 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000 individuals! What if this weren't a hypothetical question? steveo at syslang.net From emekamicro at gmail.com Sun Oct 2 18:15:09 2011 From: emekamicro at gmail.com (Emeka) Date: Mon, 3 Oct 2011 00:15:09 +0200 Subject: TK + MVC In-Reply-To: <9eq19cFmb2U1@mid.individual.net> References: <9eq19cFmb2U1@mid.individual.net> Message-ID: Greg, Do you have an example where the Controller is connected? Regards, EMeka On Sun, Oct 2, 2011 at 4:40 AM, Gregory Ewing wrote: > Alexander Kapps wrote: > > But I think a simple (and quick 'n' dirty) Tk MVC example can look like >> this: >> > > The Controller doesn't seem to add any value in that example. > You might as well connect the Model and Views directly to > each other. > > -- > Greg > -- > http://mail.python.org/**mailman/listinfo/python-list > -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Oct 2 18:34:44 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 Oct 2011 15:34:44 -0700 Subject: getattr and method name In-Reply-To: References: Message-ID: On Sun, Oct 2, 2011 at 3:02 PM, Kevin Walzer wrote: > I'm seeing a very odd error in an application I'm developing using Python > 2.7.2, on Mac OS 10.7. > > This application uses a wrapper method to look up other method names via > getattr and then call those methods. I have not previously had an issue with > this name, but for some reason this functionality no longer works as > expected. > > Here is the relevant code: > > ? ?#run command with root privileges > ? ?def runCommand(self, cmd, *args): > ? ? ? ?try: > ? ? ? ? ? ?functionstring = args[2] > ? ? ? ? ? ?callfunction = getattr(self, functionstring.split('.')[1]) > ? ? ? ? ? ?self.passtext = self.tk.call('authorize::getAuthPassword') > ? ? ? ? ? ?callfunction() > ? ? ? ?except: > ? ? ? ? ? ?try: > ? ? ? ? ? ? ? ?print cmd > ? ? ? ? ? ? ? ?functionstring = cmd.split()[2] > ? ? ? ? ? ? ? ?callfunction = getattr(self, functionstring.split('.')[1]) > ? ? ? ? ? ? ? ?self.passtext = self.tk.call('authorize::getAuthPassword') > ? ? ? ? ? ? ? ?callfunction() > ? ? ? ? ? ?except: > ? ? ? ? ? ? ? ?raise > > I use this approach to call the method named in the "cmd" parameter because > I also have to look up a password name that is returned by an underlying Tk > package that I use in my application (that's the reason for the > 'self.tk.call'). What is happening is when I use the "callfunction()" call, > instead of the method name being called, a string like this is being > invoked: > > instance at 0x101b232d8>> Er, your terminology seems kinda funky. Do you mean to say that repr(callfunction) results in that string (which is normal and expected), or that the return value from callfunction() is that string (which would be rather bizarre)? I would presume the former. [One does not call/invoke a string; strings aren't callable.] > The "scanPackages" method (just to use it as an example) uses Popen to call > an underlying system tool on the OS. However, when invoked via > callfunction(), the 'bound method...' string is passed to the OS instead as > a command! As a result, I get this output from the pipe: > > /bin/sh: bound: No such file or directory Either you've elided some important part of the code from your fragment above, or the problem would seem to lie in scanPackages() [presumably its Popen() call is screwy]. Please post the code for scanPackages(), and (if applicable) the full code for runCommand(). Cheers, Chris -- http://rebertia.com From tjreedy at udel.edu Sun Oct 2 18:55:46 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 02 Oct 2011 18:55:46 -0400 Subject: getattr and method name In-Reply-To: References: Message-ID: On 10/2/2011 6:02 PM, Kevin Walzer wrote: > I'm seeing a very odd error in an application I'm developing using > Python 2.7.2, on Mac OS 10.7. > > This application uses a wrapper method to look up other method names via > getattr and then call those methods. I have not previously had an issue > with this name, but for some reason this functionality no longer works > as expected. > > Here is the relevant code: > > #run command with root privileges > def runCommand(self, cmd, *args): > try: > functionstring = args[2] > callfunction = getattr(self, functionstring.split('.')[1]) > self.passtext = self.tk.call('authorize::getAuthPassword') > callfunction() > except: > try: > print cmd > functionstring = cmd.split()[2] > callfunction = getattr(self, functionstring.split('.')[1]) > self.passtext = self.tk.call('authorize::getAuthPassword') > callfunction() > except: > raise > > I use this approach to call the method named in the "cmd" parameter > because I also have to look up a password name that is returned by an > underlying Tk package that I use in my application (that's the reason > for the 'self.tk.call'). What is happening is when I use the > "callfunction()" call, instead of the method name being called, a string > like this is being invoked: > > <__main__.phynchronicityApp instance at 0x101b232d8>> > > The "scanPackages" method (just to use it as an example) uses Popen to > call an underlying system tool on the OS. However, when invoked via > callfunction(), the 'bound method...' string is passed to the OS instead > as a command! As a result, I get this output from the pipe: > > /bin/sh: bound: No such file or directory > > I am not sure what in my application is causing this kind of breakage, > as earlier versions of the app ran fine with similar code on earlier > versions on the OS. Is this the correct way to structure this kind of > functionality, or am I better off structuring it some other way? I do not know of any 2.7 changes that would affect such code. Perhaps you changed something in the method being invoked (not shown) . You did not specify whether you have the problem in the first or second try block. I would start with printing the type and value of some to all of the variables. -- Terry Jan Reedy From alex.kapps at web.de Sun Oct 2 19:13:48 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Mon, 03 Oct 2011 01:13:48 +0200 Subject: TK + MVC In-Reply-To: <9eq19cFmb2U1@mid.individual.net> References: <9eq19cFmb2U1@mid.individual.net> Message-ID: <4E88F02C.10405@web.de> On 02.10.2011 04:40, Gregory Ewing wrote: > Alexander Kapps wrote: > >> But I think a simple (and quick 'n' dirty) Tk MVC example can look >> like this: > > The Controller doesn't seem to add any value in that example. > You might as well connect the Model and Views directly to > each other. > Sure, in that simple example the Controller is just there to show a complete MVC pattern with all three parts. There are often examples where the View is actually both, the View and the Controller. That's why I said that I'm not sure if I really understand the MVC pattern. There are so many different versions, sometimes strict and sometimes less strict, and I think what's the real problem with my example is, whether it is really correct to not connect the Model and the View directly, but to let the Controller "mediate" between both. From alex.kapps at web.de Sun Oct 2 19:14:35 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Mon, 03 Oct 2011 01:14:35 +0200 Subject: TK + MVC In-Reply-To: References: <9eq19cFmb2U1@mid.individual.net> Message-ID: <4E88F05B.3090801@web.de> On 03.10.2011 00:15, Emeka wrote: > Greg, > > Do you have an example where the Controller is connected? What do you mean? In my example, the Controller *is* connected (to both the View and the Model.) From steve+comp.lang.python at pearwood.info Sun Oct 2 19:21:32 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 02 Oct 2011 23:21:32 GMT Subject: getattr and method name References: Message-ID: <4e88f1fc$0$29981$c3e8da3$5496439d@news.astraweb.com> On Sun, 02 Oct 2011 18:02:05 -0400, Kevin Walzer wrote: > I'm seeing a very odd error in an application I'm developing using > Python 2.7.2, on Mac OS 10.7. > > This application uses a wrapper method to look up other method names via > getattr and then call those methods. I have not previously had an issue > with this name, but for some reason this functionality no longer works > as expected. > > Here is the relevant code: > > #run command with root privileges > def runCommand(self, cmd, *args): > try: > functionstring = args[2] > callfunction = getattr(self, functionstring.split('.')[1]) > self.passtext = self.tk.call('authorize::getAuthPassword') > callfunction() > except: Bare excepts should almost never be used. I'd say they certainly shouldn't be used like this: you can mask coding bugs, user KeyboardInterrupts, and other things which shouldn't be masked. It also obscures the intent of the code. As far as I can see, it appears that this method expects to be called like this: instance.runCommand(cmd, some, arbitrary, number, of, extra, args) In this case, the method tries to authenticate and then execute some command based on "number" (but ignoring all other arguments, including cmd); if ANY failure occurs at all, including too few arguments, missing dot in the argument, or failed authentication(?), then try again using "cmd" instead. I don't understand the intent of this code. > try: > print cmd > functionstring = cmd.split()[2] > callfunction = getattr(self, > functionstring.split('.')[1]) > self.passtext = self.tk.call( > 'authorize::getAuthPassword') > callfunction() > except: > raise This try block is completely unnecessary. What's the point of catching an exception only to immediately raise it again? > I use this approach to call the method named in the "cmd" parameter > because I also have to look up a password name that is returned by an > underlying Tk package that I use in my application (that's the reason > for the 'self.tk.call'). What's a password name? Generally passwords don't have names themselves. Do you mean a user or account name? > What is happening is when I use the > "callfunction()" call, instead of the method name being called, a string > like this is being invoked: > > <__main__.phynchronicityApp instance at 0x101b232d8>> Are you sure that's meant to be a string? It appears to be an actual bound method. What makes you think it is a string? Where is that output coming from? My *guess* is that this is the output of the "print cmd" line. If so, that tells you nothing about the type of cmd. It does however tell you that you need to look at what is calling the runCommand method. Why is it being called with a method as the command? What should it be called with? Given that you call cmd.split()[2], I would expect that cmd should be a string with at least three words. Taking a wild guess, perhaps you should call cmd to get a string which then gets split into pieces to get the name of the system tool you are expecting: > The "scanPackages" method (just to use it as an example) uses Popen to > call an underlying system tool on the OS. However, when invoked via > callfunction(), the 'bound method...' string is passed to the OS instead > as a command! As a result, I get this output from the pipe: > > /bin/sh: bound: No such file or directory Or possibly the error is in callfunction. What does it do? > I am not sure what in my application is causing this kind of breakage, > as earlier versions of the app ran fine with similar code on earlier > versions on the OS. Is this the correct way to structure this kind of > functionality, or am I better off structuring it some other way? Frankly, it looks like a mess. But I don't understand your intention well enough to make any recommendations. -- Steven From rhodri at wildebst.demon.co.uk Sun Oct 2 20:04:21 2011 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Mon, 03 Oct 2011 01:04:21 +0100 Subject: Is there any way to access attributes from an imported module? References: Message-ID: On Sun, 02 Oct 2011 06:12:05 +0100, Andrew Berg wrote: > I'm not sure the subject's wording is the best, but I'll try to explain. > I have a main script that imports several modules and I need to be able > to call methods from a class instance inside that main script from a > module. Do you mean that one of the imported modules wishes to use an instance created in the main script? If that's the case, you're going to have to pass the instance to the module somehow, since the module knows nothing of what if anything has imported it. -- Rhodri James *-* Wildebeest Herder to the Masses From kw at codebykevin.com Sun Oct 2 20:24:34 2011 From: kw at codebykevin.com (Kevin Walzer) Date: Sun, 02 Oct 2011 20:24:34 -0400 Subject: getattr and method name In-Reply-To: References: Message-ID: Turns out the error was a typo in the actual method being called...*faceinhands* Sorry for the noise. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From gherron at islandtraining.com Sun Oct 2 21:13:07 2011 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 02 Oct 2011 18:13:07 -0700 Subject: getattr and method name In-Reply-To: References: Message-ID: <4E890C23.8030904@islandtraining.com> On 10/02/2011 05:24 PM, Kevin Walzer wrote: > Turns out the error was a typo in the actual method being > called...*faceinhands* > > Sorry for the noise. > But this is a great example of why you should not use a naked except clause. As stated, your code will execute the except clause for *any* kind of an error, not just the exception you envisioned when you wrote it. If you had written the except clause to catch just the exceptions you were interested in, then the exception int a called function would have come through that code as in un-handled exception, instead of being caught and essentially ignored. Gary Herron From rustompmody at gmail.com Sun Oct 2 22:08:15 2011 From: rustompmody at gmail.com (rusi) Date: Sun, 2 Oct 2011 19:08:15 -0700 (PDT) Subject: Change import order with *.pth files References: Message-ID: <3b5dd4e2-8e47-4b11-b0f9-af91f942ec58@n15g2000vbn.googlegroups.com> On 10/02/2011 10:29 PM, Andrea Gavana wrote: > Hi All, > ? ? my apologies if this is a dumb question, but I couldn't find a > solution ?- possibly because I am not sure how to state my problem in > a short sentence. I think this (and such) are important questions and I too await answers. It seems that these questions are poorly dealt with in the python docs probably because the docs try hard to be generic wrt OS and this is an area where such 'genericity' confuses more than it helps. From roy at panix.com Sun Oct 2 22:12:40 2011 From: roy at panix.com (Roy Smith) Date: Sun, 02 Oct 2011 22:12:40 -0400 Subject: getattr and method name References: Message-ID: In article , Gary Herron wrote: > On 10/02/2011 05:24 PM, Kevin Walzer wrote: > > Turns out the error was a typo in the actual method being > > called...*faceinhands* > > > > Sorry for the noise. > > > > But this is a great example of why you should not use a naked except > clause. As stated, your code will execute the except clause for *any* > kind of an error, not just the exception you envisioned when you wrote > it. If you had written the except clause to catch just the exceptions > you were interested in, then the exception int a called function would > have come through that code as in un-handled exception, instead of being > caught and essentially ignored. And, along those same lines, a couple of bits of generic exception advice... 1) Create specific exceptions to describe specific problems. FooPackageSocketBindError sure beats IOError when it comes to trying to figure out what went wrong. 2) As much as possible, keep your try blocks short. In the original example, we've got: try: functionstring = args[2] callfunction = getattr(self, functionstring.split('.')[1]) self.passtext = self.tk.call('authorize::getAuthPassword') callfunction() If we caught an IndexError, we would not know if it came from the args[2], or the getattr(...)[1], or possibly even from something deep down within callfunction(). From bahamutzero8825 at gmail.com Sun Oct 2 22:21:41 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sun, 02 Oct 2011 21:21:41 -0500 Subject: Is there any way to access attributes from an imported module? In-Reply-To: <4E880E87.5070507@islandtraining.com> References: <4E87F2A5.9000204@gmail.com> <4E880E87.5070507@islandtraining.com> Message-ID: <4E891C35.6070003@gmail.com> I found a way to do it, albeit a very hackish one. Since the class instance already catches exceptions from the modules it imports, I can make a custom exception (in a common area for both it and the submodules to import) for it to catch and have it call its own methods there based on information stored in the exception. I'm eventually going to redesign it to be cleaner and more obvious, but for now, this is a nice quick-and-dirty solution. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 From phlip2005 at gmail.com Sun Oct 2 22:27:52 2011 From: phlip2005 at gmail.com (Phlip) Date: Sun, 2 Oct 2011 19:27:52 -0700 (PDT) Subject: timedelta is squicking me out Message-ID: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> has anyone invented a system like R*by's ActiveSupport's 5.years.ago, 42.minutes.since ? (Yes, I'm aware the notation will be different!) -- Phlip http://zeekland.zeroplayer.com/ From clp2 at rebertia.com Sun Oct 2 22:41:23 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 Oct 2011 19:41:23 -0700 Subject: timedelta is squicking me out In-Reply-To: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> Message-ID: On Sun, Oct 2, 2011 at 7:27 PM, Phlip wrote: > has anyone invented a system like R*by's ActiveSupport's 5.years.ago, > 42.minutes.since ? > > (Yes, I'm aware the notation will be different!) If something involves Python and nontrivial chronology, then mxDateTime is the go-to library. And indeed, it has a RelativeDateTime type: http://www.egenix.com/products/python/mxBase/mxDateTime/doc/#_Toc293683810 Cheers, Chris -- http://rebertia.com From steve+comp.lang.python at pearwood.info Mon Oct 3 00:37:43 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 03 Oct 2011 04:37:43 GMT Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> Message-ID: <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> On Fri, 30 Sep 2011 21:09:54 +0100, Nobody wrote: > On Thu, 29 Sep 2011 11:53:12 +0200, Alain Ketterlin wrote: > >>> I have a Python script which I would like to test without a tty >>> attached to the process. I could run it as a cron job, but is there an >>> easier way? [...] > I suspect that the OP just wants e.g.: > > script.py &>/dev/null <&- > > which will redirect stdout and stderr to /dev/null and close stdin. No, that's not what I wanted. I ended up just running the script as a cron job. It was a one-off (well, twice actually, since the first time demonstrated a bug in my code) test of some code that tries to determine the size of the current terminal. I wanted to ensure that it would do the right thing when run without a tty, such as from a cron job. Thanks to everyone who replied. -- Steven From greg.ewing at canterbury.ac.nz Mon Oct 3 00:59:14 2011 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Mon, 03 Oct 2011 17:59:14 +1300 Subject: TK + MVC In-Reply-To: References: <9eq19cFmb2U1@mid.individual.net> Message-ID: <4E894122.5060907@canterbury.ac.nz> Emeka wrote: > Greg, > > Do you have an example where the Controller is connected? No, in fact I've never really felt the need for anything called a Controller in the GUI stuff I've done. I just have Models and Views. Models hold the data, and Views display it and handle input. If you come across a case where a third object seems justified, then by all means use one. But don't feel obliged to include one just because it's part of some official pattern or other. -- Greg From hansmu at xs4all.nl Mon Oct 3 01:39:58 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Mon, 03 Oct 2011 07:39:58 +0200 Subject: Python without a tty In-Reply-To: <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e894aae$0$2450$e4fe514c@news2.news.xs4all.nl> On 3/10/11 06:37:43, Steven D'Aprano wrote: > On Fri, 30 Sep 2011 21:09:54 +0100, Nobody wrote: > >> On Thu, 29 Sep 2011 11:53:12 +0200, Alain Ketterlin wrote: >> >>>> I have a Python script which I would like to test without a tty >>>> attached to the process. I could run it as a cron job, but is there an >>>> easier way? > [...] >> I suspect that the OP just wants e.g.: >> >> script.py&>/dev/null<&- >> >> which will redirect stdout and stderr to /dev/null and close stdin. > > > No, that's not what I wanted. > > I ended up just running the script as a cron job. It was a one-off (well, > twice actually, since the first time demonstrated a bug in my code) test > of some code that tries to determine the size of the current terminal. I > wanted to ensure that it would do the right thing when run without a tty, > such as from a cron job. In that case, the "at" command would have been the answer. It is a bit like cron, but meant for one-off jobs. You might have received more useful answers if you'd mentioned you goals earlier. -- HansM From airween at gmail.com Mon Oct 3 02:10:57 2011 From: airween at gmail.com (=?utf-8?B?SGVnZWTDvHMs?= Ervin) Date: Mon, 3 Oct 2011 08:10:57 +0200 Subject: Python without a tty In-Reply-To: <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20111003061054.GA2530@arxnet.hu> hello, On Mon, Oct 03, 2011 at 04:37:43AM +0000, Steven D'Aprano wrote: > > I wanted to ensure that it would do the right thing when run without a tty, > such as from a cron job. If you fork() your process, then it will also loose the tty... import os import sys try: pid = os.fork() if pid > 0: sys.exit(0) except OSError, e: sys.exit(1) os.chdir("/") os.setsid() os.umask(0) a. From r32813 at freescale.com Mon Oct 3 02:45:25 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Mon, 3 Oct 2011 06:45:25 +0000 Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str In-Reply-To: References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> Message-ID: <02EA6D704E30CE499C5071776509A925F5BABD@039-SN1MPN1-003.039d.mgd.msft.net> Hello guys, I am migrating my application from python 1.5.2 to 2.7.1. I encountered an error when I run some commands (I put in debug statement however, not able to trace down to which line of code that cause it to generate a lot of messages in one second until my hard disk space is full. The error log I got in my log file is as below:- Oct 3 14:12:41 ('Encountered exception while processing from', (0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), , TypeError('exceptions must be old-style classes or derived from BaseException, not str',)) Does it mean in newer python I need to migrate all my Exception to non-string based exception type? That's should be a lot of changes. :p Regards, Wah Meng From hansmu at xs4all.nl Mon Oct 3 03:28:27 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Mon, 03 Oct 2011 09:28:27 +0200 Subject: Python without a tty In-Reply-To: References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e89641b$0$2536$e4fe514c@news2.news.xs4all.nl> On 3/10/11 08:10:57, Heged?s, Ervin wrote: > hello, > > On Mon, Oct 03, 2011 at 04:37:43AM +0000, Steven D'Aprano wrote: >> >> I wanted to ensure that it would do the right thing when run without a tty, >> such as from a cron job. > > If you fork() your process, then it will also loose the tty... Errhm, I suggest you check again. This cannot be true. > import os > import sys > > > try: > pid = os.fork() > if pid> 0: > sys.exit(0) > except OSError, e: > sys.exit(1) > > os.chdir("/") > os.setsid() > os.umask(0) It is os.setsid() that makes you lose the tty. Hope this helps, -- HansM From tartley at tartley.com Mon Oct 3 03:40:41 2011 From: tartley at tartley.com (Jonathan Hartley) Date: Mon, 3 Oct 2011 00:40:41 -0700 (PDT) Subject: executing arbitrary statements In-Reply-To: <4e8870f9$0$29979$c3e8da3$5496439d@news.astraweb.com> References: <4e8870f9$0$29979$c3e8da3$5496439d@news.astraweb.com> Message-ID: <11779918.2105.1317627641162.JavaMail.geo-discussion-forums@yqbr29> Fair points Steven. Thanks for further refining my initial refinement. :-) From steve+comp.lang.python at pearwood.info Mon Oct 3 03:44:00 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 03 Oct 2011 07:44:00 GMT Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> Message-ID: <4e8967c0$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 03 Oct 2011 06:45:25 +0000, Wong Wah Meng-R32813 wrote: > Does it mean in newer python I need to migrate all my Exception to > non-string based exception type? That's should be a lot of changes. :p Yes. Python 1.5 is very old. It's over 11 years old. You might find it easier to first migrate to Python 2.5, where string exceptions are still legal and only generate a warning, and then migrate to 2.7. Good luck! -- Steven From clp2 at rebertia.com Mon Oct 3 03:45:34 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 Oct 2011 00:45:34 -0700 Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str In-Reply-To: <02EA6D704E30CE499C5071776509A925F5BABD@039-SN1MPN1-003.039d.mgd.msft.net> References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> <02EA6D704E30CE499C5071776509A925F5BABD@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: On Sun, Oct 2, 2011 at 11:45 PM, Wong Wah Meng-R32813 wrote: > Hello guys, > > I am migrating my application from python 1.5.2 to 2.7.1. I encountered an error when I run some commands (I put in debug statement however, not able to trace down to which line of code that cause it to generate a lot of messages in one second until my hard disk space is full. The error log I got in my log file is as below:- > > Oct ?3 14:12:41 ?('Encountered exception while processing from', (0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), , TypeError('exceptions must be old-style classes or derived from BaseException, not str',)) > > Does it mean in newer python I need to migrate all my Exception to non-string based exception type? Correct. You can no longer do merely `raise "Some error message"`. You should instead raise an exception instance of the appropriate type; e.g. `raise ValueError("foo must be positive")`. It's advisable to read the NEWS / "What's New" documents for the intervening versions so you can learn what else has changed. > That's should be a lot of changes. :p To be fair, v1.5.2 is practically ancient at this point. It's over a decade old! And 2 *major* versions behind what's current. In a pinch, you could always write a script to mechanically change `raise "..."` to `raise StandardError("...")` [or some other fairly generic exception type]. Cheers, Chris From r32813 at freescale.com Mon Oct 3 03:51:52 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Mon, 3 Oct 2011 07:51:52 +0000 Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str In-Reply-To: References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> <02EA6D704E30CE499C5071776509A925F5BABD@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <02EA6D704E30CE499C5071776509A925F5BB2D@039-SN1MPN1-003.039d.mgd.msft.net> Noted. No choice then, I will convert all my raise statement to use the exception instance. Thanks! Regards, Wah Meng -----Original Message----- From: chris at rebertia.com [mailto:chris at rebertia.com] On Behalf Of Chris Rebert Sent: Monday, October 03, 2011 3:46 PM To: Wong Wah Meng-R32813 Cc: python-list at python.org Subject: Re: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str On Sun, Oct 2, 2011 at 11:45 PM, Wong Wah Meng-R32813 wrote: > Hello guys, > > I am migrating my application from python 1.5.2 to 2.7.1. I encountered an error when I run some commands (I put in debug statement however, not able to trace down to which line of code that cause it to generate a lot of messages in one second until my hard disk space is full. The error log I got in my log file is as below:- > > Oct ?3 14:12:41 ?('Encountered exception while processing from', (0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), , TypeError('exceptions must be old-style classes or derived from BaseException, not str',)) > > Does it mean in newer python I need to migrate all my Exception to non-string based exception type? Correct. You can no longer do merely `raise "Some error message"`. You should instead raise an exception instance of the appropriate type; e.g. `raise ValueError("foo must be positive")`. It's advisable to read the NEWS / "What's New" documents for the intervening versions so you can learn what else has changed. > That's should be a lot of changes. :p To be fair, v1.5.2 is practically ancient at this point. It's over a decade old! And 2 *major* versions behind what's current. In a pinch, you could always write a script to mechanically change `raise "..."` to `raise StandardError("...")` [or some other fairly generic exception type]. Cheers, Chris From airween at gmail.com Mon Oct 3 03:56:55 2011 From: airween at gmail.com (=?utf-8?B?SGVnZWTDvHMs?= Ervin) Date: Mon, 3 Oct 2011 09:56:55 +0200 Subject: Python without a tty In-Reply-To: <4e89641b$0$2536$e4fe514c@news2.news.xs4all.nl> References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> <4e89641b$0$2536$e4fe514c@news2.news.xs4all.nl> Message-ID: <20111003075653.GA4589@arxnet.hu> hello, On Mon, Oct 03, 2011 at 09:28:27AM +0200, Hans Mulder wrote: > On 3/10/11 08:10:57, Heged?s, Ervin wrote: > > > >If you fork() your process, then it will also loose the tty... > > Errhm, I suggest you check again. This cannot be true. > > >os.setsid() > > It is os.setsid() that makes you lose the tty. well, thank you, I confused Python fork() and glibc daemon() - as I know that detach the terminal - I'm really sorry. a. From r32813 at freescale.com Mon Oct 3 04:07:08 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Mon, 3 Oct 2011 08:07:08 +0000 Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str In-Reply-To: <4e8967c0$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> <4e8967c0$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <02EA6D704E30CE499C5071776509A925F5BB81@039-SN1MPN1-003.039d.mgd.msft.net> I see. Thanks for the tips. If I run out of time I shall consider only using 2.5. Regards, Wah Meng -----Original Message----- From: python-list-bounces+wahmeng=freescale.com at python.org [mailto:python-list-bounces+wahmeng=freescale.com at python.org] On Behalf Of Steven D'Aprano Sent: Monday, October 03, 2011 3:44 PM To: python-list at python.org Subject: Re: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str On Mon, 03 Oct 2011 06:45:25 +0000, Wong Wah Meng-R32813 wrote: > Does it mean in newer python I need to migrate all my Exception to > non-string based exception type? That's should be a lot of changes. :p Yes. Python 1.5 is very old. It's over 11 years old. You might find it easier to first migrate to Python 2.5, where string exceptions are still legal and only generate a warning, and then migrate to 2.7. Good luck! -- Steven -- http://mail.python.org/mailman/listinfo/python-list From adam at rybnik.pl Mon Oct 3 04:12:03 2011 From: adam at rybnik.pl (Adam Przybyla) Date: Mon, 3 Oct 2011 08:12:03 +0000 (UTC) Subject: Need A script to open a excel file and extract the data using autofilter References: <4f3ec474-dd9f-4585-8f3c-41323d79b8de@z19g2000vby.googlegroups.com> Message-ID: Prakash wrote: > Need A script to open a excel file and extract the data using > autofilter and write it in a new sheet or new file like I have to > select all rows in which all the columns contain pass as status ... try this: http://www.python-excel.org/ Regards Adam Przybyla From gagsl-py2 at yahoo.com.ar Mon Oct 3 04:14:20 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Oct 2011 05:14:20 -0300 Subject: Change import order with *.pth files References: Message-ID: En Sun, 02 Oct 2011 18:29:24 -0300, Andrea Gavana escribi?: > Let's say I am using a package called "blah", and this package is already > installed on site-packages (and I need it to be there) with a name > "blah-1.2-win". In the site-packages folder, there is a pth file called > "blah.pth" which contains this line: > > blah-1.2-win > > To redirect Python to the correct folder when I type "import blah". > Anyway, > now I am developing another version of this package and it's called > "blah-2.0-win", and it sits on my computer into a different folder (not > on > site-packages, on an entire different drive in reality). How can I tell > Python *not* to use the version inside site-packages but to use the other > one in my development folder (without touching the pth file in > site-packages, of course)? From Python 2.6 on, there is a per user site-packages directory, which is searched before the global one. See: http://docs.python.org/whatsnew/2.6.html#pep-370-per-user-site-packages-directory You could put your developing version on that directory. In Python 2.5 and earlier, if you have to PREPEND a directory to sys.path, you may set the PYTHONPATH environment variable, or edit the site.py standard module. This may be fine in your development environment, but I would never do that in production. -- Gabriel Genellina From greg.ewing at canterbury.ac.nz Mon Oct 3 04:51:19 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 03 Oct 2011 21:51:19 +1300 Subject: TK + MVC In-Reply-To: References: <9eq19cFmb2U1@mid.individual.net> Message-ID: <9etbcaF1mkU1@mid.individual.net> Alexander Kapps wrote: > Sure, in that simple example the Controller is just there to show a > complete MVC pattern with all three parts. There are often examples > where the View is actually both, the View and the Controller. I think what I'm really trying to say is that this example is *poor* at illustrating the supposed MVC pattern, because it gives no clue as to why one might want to use a Controller. > That's why I said that I'm not sure if I really understand the MVC > pattern. There are so many different versions, sometimes strict and > sometimes less strict, and I think what's the real problem with my > example is, whether it is really correct to not connect the Model and > the View directly, but to let the Controller "mediate" between both. I don't blame you for being confused. Different people seem to have different ideas about what the "C" in "MVC" means. As far as I can tell, in the original Smalltalk concept of MVC, the View handled output and the Controller handled input. In Apple's Cocoa tutorials, the Controller seems to be something that sits between the View and the Model with a somewhat ill-defined role. Then there are web frameworks that call themselves "MVC" with their own strange twists on what the terms mean. One possible role for a Controller-like object would be where the View is not a single widget, but some collection of widgets that cooperate to provide a user interface. In that case, the Controller could be something that creates and assembles the relevant widgets, and provides whatever glue code is needed to make them work together. I suspect that this is what Apple mean by a Controller in Cocoa. I've certainly created this kind of structure, but I tend not to use a separate object for it. Instead I create a subclass of Window (Toplevel in Tk terms), or some other container widget, to serve as both the coordinating object and a container for all the parts. I don't think of it as a Controller, but simply as a compound View that happens to be made up of several objects. So I don't think there's any single "correct" way to put a "C" into "MVC", or even necessarily a need to put one in at all. To my mind, the important things about the concept of model-view separation are: * The Model holds the data and provides a common interface for Views to access and change it. * Multiple Views, and different kinds of View, can be attached to a Model through its common interface. * There is some mechanism for a Model to broadcast an "I've changed" message to all its attached Views. Whether the Views attach to the Model directly or through some intermediate object is not really important. And when there is an intermediate object, whether you call it a Controller or regard it as simply another kind of View is just a matter of perspective. -- Greg From greg.ewing at canterbury.ac.nz Mon Oct 3 04:59:54 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 03 Oct 2011 21:59:54 +1300 Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str In-Reply-To: References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> Message-ID: <9etbscF5mgU1@mid.individual.net> Wong Wah Meng-R32813 wrote: > I am migrating my application from python 1.5.2 to 2.7.1. > Does it mean in newer python I need to migrate all my Exception to > non-string based exception type? That's should be a lot of changes. :p 'Fraid so. You are leaping quite a lot of versions at once, and string exceptions have been considered passe for a *long* time. They may already have been deprecated in 1.5, I'm not sure. Note that in Python 3 the condition is even stricter -- old style classes are gone, and exceptions must derive from BaseException or some other existing exception type. So you'd best do that now for the sake of easing migration to Python 3 in the future. -- Greg From greg.ewing at canterbury.ac.nz Mon Oct 3 05:04:26 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 03 Oct 2011 22:04:26 +1300 Subject: Python without a tty In-Reply-To: References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9etc4tF825U1@mid.individual.net> Heged?s wrote: > If you fork() your process, then it will also loose the tty... Um, no, fork() doesn't do that, as far as I know. > os.setsid() *This* is what's losing the tty. According to the Fine Man Page: DESCRIPTION The setsid function creates a new session. The calling process is the session leader of the new session, is the process group leader of a new process group and has no controlling terminal. ^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- Greg From electronicswebthaya at gmail.com Mon Oct 3 06:08:17 2011 From: electronicswebthaya at gmail.com (deepika) Date: Mon, 3 Oct 2011 03:08:17 -0700 (PDT) Subject: http://www.electronicswebworld.com/ Message-ID: http://www.electronicswebworld.com/ online jobs for u http://www.tamilwebworld.com/ From chris at simplistix.co.uk Mon Oct 3 06:11:56 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 03 Oct 2011 11:11:56 +0100 Subject: packages, modules and double imports - oh my! Message-ID: <4E898A6C.4040909@simplistix.co.uk> Hi All, The attached package gives that smallest possible example of problems I'm hitting with some SQLAlchemy declarative classes. In short, I want to be able to do: python -m pack.module and have if the __name__=='__main__' block spit out the SQL to create the tables necessary for the modules in that class... So, using the attached package to demonstrate, the first problem I get is: cwithers at cwlin:~> python -m pack.module Traceback (most recent call last): File "/usr/lib64/python2.6/runpy.py", line 121, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib64/python2.6/runpy.py", line 34, in _run_code exec code in run_globals File "/home/cwithers/pack/module.py", line 3, in class MyClass(object): File "pack/__init__.py", line 7, in __init__ raise Exception('%r registered twice' % self.__name__) Exception: 'MyClass' registered twice Looks like I have a pack.module.MyClass and a __main__.MyClass, which feels like a bug to me... Ho hum, lets try something different: cwithers at cwlin:~> python pack/module.py Traceback (most recent call last): File "pack/module.py", line 1, in from pack import MyMeta ImportError: No module named pack Meh, okay, so only the path containing the script being run ends up on PYTHONPATH, okay, so: cwithers at cwlin:~> PYTHONPATH=. python pack/module.py Traceback (most recent call last): File "pack/module.py", line 3, in class MyClass(object): File "pack/__init__.py", line 7, in __init__ raise Exception('%r registered twice' % self.__name__) Exception: 'MyClass' registered twice ...back to square one :-( cwithers at cwlin:~> python -m pack /usr/bin/python: pack is a package and cannot be directly executed That's annoying, why isn't pack/__init__.py's __name__=='__main__' block executed? cwithers at cwlin:~> python pack /usr/bin/python: can't find '__main__.py' in 'pack' Wha? First I've ever heard of __main__.py... where's that documented? Anyway: cwithers at cwlin:~> python pack/__init__.py Traceback (most recent call last): File "pack/__init__.py", line 10, in from pack.module import MyClass ImportError: No module named pack.module Oh, right, we're back here..., so lets try: cwithers at cwlin:~> PYTHONPATH=. python pack/__init__.py {'MyClass': } {} wtf? why aren't these the same registry object?! Any help appreciated... Chris -------------- next part -------------- A non-text attachment was scrubbed... Name: pack.tgz Type: application/x-compressed-tar Size: 426 bytes Desc: not available URL: From clp2 at rebertia.com Mon Oct 3 06:22:32 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 Oct 2011 03:22:32 -0700 Subject: packages, modules and double imports - oh my! In-Reply-To: <4E898A6C.4040909@simplistix.co.uk> References: <4E898A6C.4040909@simplistix.co.uk> Message-ID: On Mon, Oct 3, 2011 at 3:11 AM, Chris Withers wrote: > Hi All, > > The attached package gives that smallest possible example of problems I'm > hitting with some SQLAlchemy declarative classes. > > In short, I want to be able to do: > > python -m pack.module and have if the __name__=='__main__' block spit out > the SQL to create the tables necessary for the modules in that class... > cwithers at cwlin:~> python -m pack > /usr/bin/python: pack is a package and cannot be directly executed > > That's annoying, why isn't pack/__init__.py's __name__=='__main__' block > executed? > > cwithers at cwlin:~> python pack > /usr/bin/python: can't find '__main__.py' in 'pack' > > Wha? First I've ever heard of __main__.py... where's that documented? http://docs.python.org/library/runpy.html : "The runpy module['s] main use is to implement the -m command line switch" "If the supplied module name refers to a package rather than a normal module, then that package is imported and the __main__ submodule within that package is then executed and the resulting module globals dictionary returned." (`runpy` having appeared in your first Traceback. Definitely seems like some explicit cross-references should be added to the docs.) Cheers, Chris From rajashree.thorat16 at gmail.com Mon Oct 3 08:00:25 2011 From: rajashree.thorat16 at gmail.com (Rajashree Thorat) Date: Mon, 3 Oct 2011 17:30:25 +0530 Subject: Problem regarding command line completion Message-ID: Hi All, Please can anyone help me in resolving following problem. import cmd class CmdLineApp(cmd.Cmd): def do_grep(self, line): print line option = ["--ignore-case", "--invert-match","--word-regexp","--line-regexp"] def complete_grep(self, text, line, begidx, endidx): return [i for i in CmdLineApp.option if i.startswith(text)] interpreter = CmdLineApp() interpreter.cmdloop() In above program I want to do command line completion (or tab completion). If the elements of option list starts with special character such as '-', '@', '#', '--' , then it is giving me output like (Cmd) grep grep (Cmd) grep ------ instead of (Cmd) grep -- --ignore-case --invert-match --word-regexp --line-regexp How I can handle this special characters? Thanks & Regards Rajshree Thorat -------------- next part -------------- An HTML attachment was scrubbed... URL: From awilliam at whitemice.org Mon Oct 3 08:02:19 2011 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Mon, 03 Oct 2011 08:02:19 -0400 Subject: parse xml In-Reply-To: References: Message-ID: <20111003080219.Horde.ms_VVJeICrNOiaRLGCllO1A@aleph.wmmi.net> Quoting ???? <1248283536 at qq.com>: > please click the > http://www.secinfo.com/d14qfp.q9j.htm > then ,click the following: > 44: XML IDEA: Condensed Consolidating Statements of Income XML > 5.11M (Details)--R158 > there is the citigroup's annual financial report --statements of > income,xml file. > how can i get a table of statements of income in python ? Read the document with etree, and either iterate over it or grab the required values with xpath. from lxml import etree doc = etree.parse(self.rfile) result = doc.xpath(self._xpath, namespaces=doc.getroot().nsmap) From rantingrick at gmail.com Mon Oct 3 08:25:19 2011 From: rantingrick at gmail.com (rantingrick) Date: Mon, 3 Oct 2011 05:25:19 -0700 (PDT) Subject: lower-case names for builtin types References: Message-ID: <29076d4a-7575-4989-a922-e824c5781ee6@z8g2000yqb.googlegroups.com> On Oct 1, 10:41?pm, Eric Snow wrote: > Anyone know the story behind the lower-case names for the > non-exception built-in types (like list and type)? ?I am guessing that > they were originally factory functions that, at some point, graduated > to full types; and the names were kept lower-case for backward > compatibility. Or it could be that they wanted to hoard all the good generic variable names! > However, if we were to consider making a change for Python 4, I am not > sure how I feel about Int("5") over int("5"). ?Maybe it would be > Integer("5"). Yes! Some folks get all huffy about this subject because they get SO attached to built in functions. What's so weird about calling a function that THEN calls a constructor as opposed to just calling the constructor directly? Seems like unnecessary overhead to me. From roy at panix.com Mon Oct 3 08:59:07 2011 From: roy at panix.com (Roy Smith) Date: Mon, 03 Oct 2011 08:59:07 -0400 Subject: timedelta is squicking me out References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> Message-ID: In article , Chris Rebert wrote: > If something involves Python and nontrivial chronology, then > mxDateTime is the go-to library. And indeed, it has a RelativeDateTime > type: > http://www.egenix.com/products/python/mxBase/mxDateTime/doc/#_Toc293683810 We've been using http://labix.org/python-dateutil, which is pretty good. I've never used mxDateTime, so I don't know how the two compare head-to-head. From redcat at streemit.net Mon Oct 3 09:51:52 2011 From: redcat at streemit.net (Redcat) Date: 3 Oct 2011 13:51:52 GMT Subject: To start a simple server References: <06b7fcdc-8615-4980-8d42-f212033ee5c8@dk6g2000vbb.googlegroups.com> Message-ID: <9etsvnF1kdU9@mid.individual.net> Are you running web.py on your computer, or is it running for example on a hosting company's computer? If it's not on your computer you have your port 8080 traffic blocked the hosting company's firewall. On Sun, 02 Oct 2011 20:59:40 -0700, sillyou su wrote: > i am learning webpy and I am following the tutorial ?http://webpy.org/ > docs/0.3/tutorial? . > > But when i installed mysql , i found problem. > > Here is the code: > #===============================================# import web > > urls=("/.","index") > > app=web.application(urls,globals()) > > class index: > def GET(self): > return 'hello world' > > if __name__=='__main__': > app.run() > #===============================================# > > And here is error information? > #===============================================# http://0.0.0.0:8080/ > > Traceback (most recent call last): > File "C:\Users\su\Desktop\code.py", line 18, in app.run() > File "C:\Python27\lib\site-packages\web\application.py", line 311, in > run > return wsgi.runwsgi(self.wsgifunc(*middleware)) File > "C:\Python27\lib\site-packages\web\wsgi.py", line 54, in runwsgi return > httpserver.runsimple(func, validip(listget(sys.argv, 1, ''))) File > "C:\Python27\lib\site-packages\web\httpserver.py", line 148, in > runsimple > server.start() > File "C:\Python27\lib\site-packages\web\wsgiserver\__init__.py", line > 1753, in start > raise socket.error(msg) > error: No socket could be created > #===============================================# > A service occupy port 8080. So i stop the service. > The program did run, but another problem came out. > #===============================================# > > the program is not running. In the browser? > ============================================ This webpage is not > available > The webpage at http://0.0.0.0:8080/ might be temporarily down or it may > have moved permanently to a new web address. Error 108 > (net::ERR_ADDRESS_INVALID): Unknown error. > > ============================================ > > now the program is running. In the browser? > ============================================ This webpage is not > available > The webpage at http://0.0.0.0:8080/ might be temporarily down or it may > have moved permanently to a new web address. Error 108 > (net::ERR_ADDRESS_INVALID): Unknown error. > ============================================ Nothing difference . > > I can't describe the problem very well in English. So I post all > information here . > > Thank you for any tips. From wilson.amit at gmail.com Mon Oct 3 11:03:18 2011 From: wilson.amit at gmail.com (amit) Date: Mon, 3 Oct 2011 08:03:18 -0700 (PDT) Subject: BaseHTTPServer ThreadMixIn not working Message-ID: Hi everyone, I am really stuck in a very simple problem and wanted to know if you could take some time to check it out - My code is simple. Using BaseHTTPServer and ThreadInMix I want to run a python script (Script1.py) for every request made simultaneously. My code-> from subprocess import PIPE, Popen from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler import time def simple_script(self): print 'simple_script' s = Popen('C:/Python27/python C:/Script1.py 5', shell=True, stdout=PIPE, stderr=PIPE) out, err = s.communicate() print out, err self.wfile.write(out) class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.end_headers() self.wfile.write('{0}\n'.format(time.asctime())) simple_script(self) return class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): pass if __name__ == '__main__': server = ThreadedHTTPServer(('', 8080), Handler) print 'Starting server, use to stop' server.serve_forever() """ # C:/Script1.py import time, sys s = time.time() while True: if time.time() - s > int(sys.argv[1]): break else: time.sleep(1) print time.asctime() """ If I open multiple tabs/pages in Chrome/Firefox/IE and give URL: http://localhost:8080, the pages wait for previous page? This does not imply threading? Any help? Thanks From jeanmichel at sequans.com Mon Oct 3 11:12:44 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 03 Oct 2011 17:12:44 +0200 Subject: Advise on using logging.getLogger needed. In-Reply-To: <4E88E1B3.6080009@syslang.net> References: <4E88E1B3.6080009@syslang.net> Message-ID: <4E89D0EC.8020900@sequans.com> Steven W. Orr wrote: > I hope I don't sound like I'm ranting :-( > > I have created a module (called xlogging) which sets up logging the way I want > it. I found out that if I set up my logger without a name, then it gets > applied to every logger that is referenced by every module that ever gets > imported. > > The problem is that I must call xlogging.getLogger or logging.getLogger in all > other modules using the name of the root logger, and I don't know what that > name is. > > I want the name of the root logger to be the name of the running program, so > in my setup, I say > > pname = sys.argv[0] > try: > rslash = pname.rindex('/') > except ValueError: > pass > else: > pname = pname[rslash + 1:] > > try: > dot_py = pname.rindex('.py') > except ValueError: > pass > else: > pname = pname[0:dot_py] > > This is also written pname, _ = os.path.splitext(os.path.basename(sys.argv[0])) > and then I say > > logger = logging.getLogger(pname) > > My problem is that I just want the modules that I write, to be able to get the > named root logger and still be able to refer to possible sub-loggers. > > So, let's say I run program foo. At some point in my mail setup, I set the > configuration for the foo logger. I'd like my xlogging module to supply a > getLogger function such that if I don't supply any arguments, it will return > the logger that would normally be returned by logging.getLogger(pname). > > Also, part of the reason I'm confused is because foo calls m1 and m2 and they > want to say > > logger = xlogging.getLogger(MaybeWithAnArg?) > > at the top of their code. This means that the import statement for m1 and m2 > are getting the calls to getLogger executed before I get the chance to set > things up. > > I am running 2.6, so I don't have access to logging.getChild, but I'm not > clear that I even want that. > > My modules are used by multiple programs. Does this mean that I should simply > use __name__ all the time? (That seems inelegant, no?) > > If I'm making sense, is there a way to do this? > > > To be honest, I'm not sure I've understood exactly what you're trying to do, but I have the feeling you're just trying to the usual stuff with the wrong method. I would advise to drop your xlogging module, it just add some confusion. Maybe you'll be able to add it later on. * in libraries/modules, you never configure any logger. The configuration of the logger is let to the main program. -> only instanciate a logger, something like logger = logging.getLogger(__name__) Then use it, you don't care about what becomes of the logs, it's up to the program using the module to decide * From the main program, you can create a logger for your application, but you still configure the root logger, only the root logger will grab the log event from other modules. m1 module file: import logging _logger=logging.getLogger(__name__) def func(): _logger.debug('foo') myApp file: import m1 import logging _logger = logging.getLogger('MyApp') def run(): _logger.info('bar') m1.func() if __name__=='__main__': # here you configure the logs by configuring the *root* logger rootLogger = logging.getLogger() # no name => root logger rootLogger.handlers = [] # clean up the current configuration rootLogger.addHandler(logging.StreamHandler()) rootLogger.handlers[-1].setFormatter(logging.Formatter('%(name)s - %(levelname)s:%(message)s')) rootLogger.setLevel(level=logging.DEBUG) run() you should get something like MyApp - INFO:bar m1 - DEBUG:foo Hope it helps, JM From chris at simplistix.co.uk Mon Oct 3 11:25:53 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 03 Oct 2011 16:25:53 +0100 Subject: packages, modules and double imports - oh my! In-Reply-To: References: <4E898A6C.4040909@simplistix.co.uk> Message-ID: <4E89D401.3060407@simplistix.co.uk> On 03/10/2011 11:22, Chris Rebert wrote: > http://docs.python.org/library/runpy.html : > "The runpy module['s] main use is to implement the -m command line switch" > "If the supplied module name refers to a package rather than a normal > module, then that package is imported and the __main__ submodule > within that package is then executed and the resulting module globals > dictionary returned." Interesting, but doesn't help with the bizarre double-exec of module.py when it happens to be __main__... cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From rantingrick at gmail.com Mon Oct 3 11:54:04 2011 From: rantingrick at gmail.com (rantingrick) Date: Mon, 3 Oct 2011 08:54:04 -0700 (PDT) Subject: Chaos Theory [was Re: Benefit and belief] References: <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> <4e88db0f$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Oct 2, 4:43?pm, Steven D'Aprano wrote: > In all cases, we can be sure that the contradiction between the pair of > statements are genuine contradictions and not mere apparent > contradictions caused by "narrow perspective" or incomplete or erroneous > knowledge. Observer: Why is it that Clark Kent and Superman are never in the same place at the same time? ComicFanboy: Because Clark Kent IS Kal-El's secret identity duh! PuesdoWiseObserver: Wait a minute fanboy, they ARE in the same place at the same time since Clark Kent IS really Superman. Ha, i'm smart. TrueWiseObserver: Wrong pseudo. Superman will ALWAYS be superman even if he wears a dress and stilettos. Clark Kent is just an assumed identity of Superman. From SokolischSpeaks at moonbat.com Mon Oct 3 11:56:27 2011 From: SokolischSpeaks at moonbat.com (Gary Sokolisch) Date: Mon, 3 Oct 2011 11:56:27 -0400 Subject: Who Is Gary Sokolich? 1405 Message-ID: <107i3o920tscl$.xvt9vfbi86md.dlg@40tude.net> 1405 W Gary Sokolich 801 Kings Road Newport Beach, CA 92663-5715 (949) 650-5379 http://web.archive.org/web/20080821231423/http://www.tbpe.state.tx.us/da/da022808.htm TEXAS BOARD OF PROFESSIONAL ENGINEERS February 28, 2008 Board Meeting Disciplinary Actions W. Gary Sokolich , Newport Beach, California ? File B-29812 - It was alleged that Dr. Sokolich unlawfully offered or attempted to practice engineering in Texas (...) Dr. Sokolich chose to end the proceedings by signing a Consent Order that was accepted by the Board to cease and desist from representing himself as an ?Engineer? in Texas, from any and all representations that he can offer or perform engineering services and from the actual practice of engineering in Texas (...) Dr. Sokolich was also assessed a $1,360.00 administrative penalty. _______________ http://articles.latimes.com/1988-04-14/local/me-1922_1_ucla-researcher A former UCLA physiologist has agreed to provide copies of his research to the school to settle a lawsuit the university filed against him in 1985, lawyers in the case said. (...) The University of California Board of Regents filed a $620,000 lawsuit against Sokolich, accusing him of taking research on the hearing capabilities of animals in June, 1982. Sokolich was dismissed by UCLA (...). (...) From aivar.annamaa at gmail.com Mon Oct 3 12:21:56 2011 From: aivar.annamaa at gmail.com (Aivar Annamaa) Date: Mon, 3 Oct 2011 19:21:56 +0300 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) Message-ID: Hi! I'm looking for a trick or hidden feature to make Python 3 automatically call a "main" function but without programmers writing `if __name__ == "__main__": ...` I found rejected PEP 299, but i thought that maybe there's something new already. Here's why I want such a thing: I'm teaching introductory programming course with Python. I've seen that global variables attract beginners like honey attracts bees and this makes teaching function parameters harder. When students learn functions, they usually write their function definitions and function applications in the same scope -- in top-level of the module (don't know the correct term for it). This has the downside, that any variable introduced in top-level is automatically visible in function definitions and I have hard time convincing students not to use those variables in functions directly. I've been thinking that it might be better for teaching if all program code would be in functions. This would make "Hello World" a bit more difficult, but would help teaching the "real thing" ie. functions. best regards, Aivar -------------- next part -------------- An HTML attachment was scrubbed... URL: From alec.taylor6 at gmail.com Mon Oct 3 12:26:30 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 4 Oct 2011 03:26:30 +1100 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: Message-ID: Make something with http://metapython.org/ ? On Tue, Oct 4, 2011 at 3:21 AM, Aivar Annamaa wrote: > Hi! > > I'm looking for a trick or hidden feature to make Python 3 automatically > call a "main" function but without programmers writing `if __name__ == > "__main__": ...` > > I found rejected PEP 299, but i thought that maybe there's something new > already. > > Here's why I want such a thing: > I'm teaching introductory programming course with Python. I've seen that > global variables attract beginners like honey attracts bees and this makes > teaching function parameters harder. When students learn functions, they > usually write their function definitions and function applications in the > same scope -- in top-level of the module (don't know the correct term for > it). This has the downside, that any variable introduced in top-level is > automatically visible in function definitions and I have hard time > convincing students not to use those variables in functions directly. > > I've been thinking that it might be better for teaching if all program code > would be in functions. This would make "Hello World" a bit more difficult, > but would help teaching the "real thing" ie. functions. > > best regards, > Aivar > > -- > http://mail.python.org/mailman/listinfo/python-list > > From rosuav at gmail.com Mon Oct 3 12:27:41 2011 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Oct 2011 03:27:41 +1100 Subject: Chaos Theory [was Re: Benefit and belief] In-Reply-To: References: <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> <4e88db0f$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Oct 4, 2011 at 2:54 AM, rantingrick wrote: > Observer: Why is it that Clark Kent and Superman are never in the same > place at the same time? > ComicFanboy: Because Clark Kent IS Kal-El's secret identity duh! > PuesdoWiseObserver: Wait a minute fanboy, they ARE in the same place > at the same time since Clark Kent IS really Superman. Ha, i'm smart. > TrueWiseObserver: Wrong pseudo. Superman will ALWAYS be superman even > if he wears a dress and stilettos. Clark Kent is just an assumed > identity of Superman. ComicBookGeek: Actually, they have been seen together, on several occasions - thanks to stand-ins, dummies, or even super-speed and changing faster than the human eye can see. PhysicsExpert: Super-speed wouldn't work, the acceleration required to achieve it would burn up his surroundings! Your point? Chris Angelico PS. I did the arithmetic once on how much force Superman would have to exert on his surroundings in order to be seen in two places at once. It was like those calculations on Santa and the number of joules of energy the lead reindeer would be copping. From emekamicro at gmail.com Mon Oct 3 12:47:38 2011 From: emekamicro at gmail.com (Emeka) Date: Mon, 3 Oct 2011 17:47:38 +0100 Subject: TK + MVC In-Reply-To: <4E88F05B.3090801@web.de> References: <9eq19cFmb2U1@mid.individual.net> <4E88F05B.3090801@web.de> Message-ID: Alex, The question was not meant for you. I was responding to Greg's comment. Regards, Emeka On Mon, Oct 3, 2011 at 12:14 AM, Alexander Kapps wrote: > On 03.10.2011 00:15, Emeka wrote: > >> Greg, >> >> Do you have an example where the Controller is connected? >> > > What do you mean? In my example, the Controller *is* connected (to both the > View and the Model.) > -- > http://mail.python.org/**mailman/listinfo/python-list > -- *Satajanus Nig. Ltd * -------------- next part -------------- An HTML attachment was scrubbed... URL: From sillyousu at gmail.com Mon Oct 3 13:05:15 2011 From: sillyousu at gmail.com (sillyou su) Date: Mon, 3 Oct 2011 10:05:15 -0700 (PDT) Subject: To start a simple server References: <06b7fcdc-8615-4980-8d42-f212033ee5c8@dk6g2000vbb.googlegroups.com> <9etsvnF1kdU9@mid.individual.net> Message-ID: <4be53ff4-d534-4a4c-85ae-d1cc10813829@i33g2000yqm.googlegroups.com> I am running web.py on my computer From redcat at streemit.net Mon Oct 3 13:41:32 2011 From: redcat at streemit.net (Redcat) Date: 3 Oct 2011 17:41:32 GMT Subject: To start a simple server References: <06b7fcdc-8615-4980-8d42-f212033ee5c8@dk6g2000vbb.googlegroups.com> <9etsvnF1kdU9@mid.individual.net> <4be53ff4-d534-4a4c-85ae-d1cc10813829@i33g2000yqm.googlegroups.com> Message-ID: <9euaecF1kdU13@mid.individual.net> On Mon, 03 Oct 2011 10:05:15 -0700, sillyou su wrote: > I am running web.py on my computer Does "netstat -nat | grep 8080" show anything listening on port 8080? (I'm assuming here that you're running on a Linux box) From amelia at catfolks.net Mon Oct 3 14:15:16 2011 From: amelia at catfolks.net (Amelia T Cat) Date: 3 Oct 2011 18:15:16 GMT Subject: To start a simple server References: <06b7fcdc-8615-4980-8d42-f212033ee5c8@dk6g2000vbb.googlegroups.com> <9etsvnF1kdU9@mid.individual.net> Message-ID: <9eucdkF1kdU14@mid.individual.net> On Mon, 03 Oct 2011 10:09:59 -0700, sillyou su wrote: > ??? > > I should use 127.0.0.1 instance of 0.0.0.0 Theoretically either one should be fine. If you use 127.0.0.1 it will only expose the service to your local machine. If you use 0.0.0.0 ut will expose the service to other computers on the same network as the one running the service. From __peter__ at web.de Mon Oct 3 14:31:01 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 03 Oct 2011 20:31:01 +0200 Subject: Problem regarding command line completion References: Message-ID: Rajashree Thorat wrote: > Please can anyone help me in resolving following problem. > > import cmd > class CmdLineApp(cmd.Cmd): > > def do_grep(self, line): > print line > > option = ["--ignore-case", > "--invert-match","--word-regexp","--line-regexp"] > def complete_grep(self, text, line, begidx, endidx): > return [i for i in CmdLineApp.option if > i.startswith(text)] > > interpreter = CmdLineApp() > interpreter.cmdloop() > > In above program I want to do command line completion (or tab completion). > If the elements of option list starts with special character such as > '-', '@', '#', '--' , then it is giving me output like > > (Cmd) grep > grep > (Cmd) grep ------ > > instead of > > (Cmd) grep -- > --ignore-case --invert-match --word-regexp --line-regexp > > How I can handle this special characters? Try removing them from readline's set of delimiters with import readline delims = readline.get_completer_delims() my_delims = "".join(set(delims) - set("-@#")) readline.set_completer_delims(my_delims) From iurisilvio at gmail.com Mon Oct 3 14:39:12 2011 From: iurisilvio at gmail.com (Iuri) Date: Mon, 3 Oct 2011 15:39:12 -0300 Subject: To start a simple server In-Reply-To: <9eucdkF1kdU14@mid.individual.net> References: <06b7fcdc-8615-4980-8d42-f212033ee5c8@dk6g2000vbb.googlegroups.com> <9etsvnF1kdU9@mid.individual.net> <9eucdkF1kdU14@mid.individual.net> Message-ID: Something is running in your port 8080. Change the port and try again. On Mon, Oct 3, 2011 at 3:15 PM, Amelia T Cat wrote: > On Mon, 03 Oct 2011 10:09:59 -0700, sillyou su wrote: > > > ??? > > > > I should use 127.0.0.1 instance of 0.0.0.0 > > Theoretically either one should be fine. If you use 127.0.0.1 it will > only expose the service to your local machine. If you use 0.0.0.0 ut will > expose the service to other computers on the same network as the one > running the service. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Mon Oct 3 14:54:26 2011 From: davea at ieee.org (Dave Angel) Date: Mon, 03 Oct 2011 14:54:26 -0400 Subject: packages, modules and double imports - oh my! In-Reply-To: <4E89D401.3060407@simplistix.co.uk> References: <4E898A6C.4040909@simplistix.co.uk> <4E89D401.3060407@simplistix.co.uk> Message-ID: <4E8A04E2.1000201@ieee.org> On 01/-10/-28163 02:59 PM, Chris Withers wrote: > On 03/10/2011 11:22, Chris Rebert wrote: >> http://docs.python.org/library/runpy.html : >> "The runpy module['s] main use is to implement the -m command line >> switch" >> "If the supplied module name refers to a package rather than a normal >> module, then that package is imported and the __main__ submodule >> within that package is then executed and the resulting module globals >> dictionary returned." > > Interesting, but doesn't help with the bizarre double-exec of > module.py when it happens to be __main__... > > cheers, > > Chris > Sounds to me like you have a circular dependency. It's never a good idea, and especially if you have a circular dependency on the script itself, it'll get loaded twice. Once it comes in as __main__, and the other time by its filename. So redesign the module to eliminate the circulars. If a.py imports b.py, then b.py should not import a.py, directly or indirectly. You are lucky you got an explicit error; We've seen other people get very obscure bugs when two instances of some module variables were in existence. DaveA From davea at ieee.org Mon Oct 3 15:14:13 2011 From: davea at ieee.org (Dave Angel) Date: Mon, 03 Oct 2011 15:14:13 -0400 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: Message-ID: <4E8A0985.2010007@ieee.org> On 01/-10/-28163 02:59 PM, Aivar Annamaa wrote: > Hi! > > I'm looking for a trick or hidden feature to make Python 3 automatically > call a "main" function but without programmers writing `if __name__ == > "__main__": ...` > > I found rejected PEP 299, but i thought that maybe there's something new > already. > > Here's why I want such a thing: > I'm teaching introductory programming course with Python. I've seen that > global variables attract beginners like honey attracts bees and this makes > teaching function parameters harder. When students learn functions, they > usually write their function definitions and function applications in the > same scope -- in top-level of the module (don't know the correct term for > it). This has the downside, that any variable introduced in top-level is > automatically visible in function definitions and I have hard time > convincing students not to use those variables in functions directly. > > I've been thinking that it might be better for teaching if all program code > would be in functions. This would make "Hello World" a bit more difficult, > but would help teaching the "real thing" ie. functions. > > best regards, > Aivar > It's not clear if you're asking for a new fork of the language, or just wanting to keep people from bad habits. Like it or not, there are plenty of globals already there, one of them being __name__ . All the built-ins are effectively global, and so is any function they define at top-level. Likewise any top-level class, and any symbols imported with import or with from/import. So I consider it impractical for the language to do something that self-discipline is required for. Is it explaining the if statement that's the problem? If so, you could have them do an unconditional main(sys.argv) at the bottom of their file, and not bother putting an if statement in front of it. Then when you get to user-written modules, you could introduce the if __name__ and explain its need. DaveA From ian.g.kelly at gmail.com Mon Oct 3 15:37:56 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 3 Oct 2011 13:37:56 -0600 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: <4E8A0985.2010007@ieee.org> References: <4E8A0985.2010007@ieee.org> Message-ID: On Mon, Oct 3, 2011 at 1:14 PM, Dave Angel wrote: > Is it explaining the if statement that's the problem? ?If so, you could have > them do an unconditional main(sys.argv) at the bottom of their file, and not > bother putting an if statement in front of it. ?Then when you get to > user-written modules, you could introduce the if __name__ and explain its > need. It's not a good idea to teach bad habits they'll just have to unlearn later on. Especially since they might not be paying attention when you talk about if __name__ and how to do it right. I would suggest giving them the whole if __name__ block as boilerplate and telling them they're not allowed to alter it. Then in a later class, explain its purpose. From galyle at gmail.com Mon Oct 3 15:55:37 2011 From: galyle at gmail.com (galyle) Date: Mon, 3 Oct 2011 12:55:37 -0700 (PDT) Subject: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus Message-ID: Hello, I'm trying to build a menu which provides suggestions to a user based on input to an entry. I have done something like this before using Tcl/Tk, so I expected that it would work without much difficulty with Tkinter. I was wrong. The problem I have is that, as soon as the menu is posted, it appears to take the keyboard focus until the user either selects an option or clicks an area outside of the menu. The behavior I would like is for keyboard input to go to the entry, and for the menu to update based on that input. I have tried different bindings (both to the entry and menu) and I have tried different focus/grab combinations (even force_focus and grab_set_global to the entry) when the menu is posted, but nothing seems to work. Are there any suggestions on how to get the behavior I'm seeking? The following code demonstrates the issue I'm having: import Tkinter class demo: def __init__(self, parent): self._entry = Tkinter.Entry(width = 60) self._suggestions = Tkinter.Menu(parent, tearoff = 0, takefocus = 0) self._entry.pack(padx = 20, pady = 20) self._entry.bind('', self._suggest_text, add = '+') def _suggest_text(self, event): curr = self._entry.get() + repr(event.char)[1] x = self._entry.winfo_rootx() y = self._entry.winfo_rooty() y += self._entry.winfo_height() try: self._suggestions.delete(0, 'end') self._suggestions.add_command(label = curr + '_1') self._suggestions.add_command(label = curr + '_2') self._suggestions.add_command(label = curr + '_3') self._suggestions.add_command(label = curr + '_4') self._suggestions.post(x, y) finally: self._suggestions.grab_release() if __name__ == '__main__': root = Tkinter.Tk() root.title('A Problem') demo(root) root.mainloop() From rantingrick at gmail.com Mon Oct 3 16:10:15 2011 From: rantingrick at gmail.com (rantingrick) Date: Mon, 3 Oct 2011 13:10:15 -0700 (PDT) Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: Message-ID: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> On Oct 3, 2:14?pm, Dave Angel wrote: > Like it or not, there are plenty of globals already there, one of them > being __name__ . ?All the built-ins are effectively global, and so > ? is any function they define at top-level. I keep wondering if that was another PyWart? I believe (and hindsight is 20-20) that all the built-in modules should have been protected by a top-level namespace. Something succicent, something like "py"... from py.archive import zipfile, tarfile from py.gui import Tkinter from py.markup import HTMLParser ...and voila, no more clashes with user defined modules! >?Likewise any top-level > class, and any symbols imported with import or with from/import. ?So I > consider it impractical for the language to do something that > self-discipline is required for. Also for scoping. py> count = 0 py> def foo(): ... global.count += 1 py> print count 1 Why? Well because many times i find myself wondering if this or that variable is local or global -- and when i say "global" i am speaking of module scope! The "global" cures the ill. From pulsarpietro at gmail.com Mon Oct 3 16:24:21 2011 From: pulsarpietro at gmail.com (pedr0) Date: Mon, 3 Oct 2011 13:24:21 -0700 (PDT) Subject: HTTP Persistent connection Message-ID: <25371269.3648.1317673461242.JavaMail.geo-discussion-forums@yqnv12> Hi at all, I have some problem with the httplib module, I would like have an HTTP persistent connection but when run this code : #first request http_connection = httplib.HTTPConnection(host) http_connection.request(method,url,headers=headers) response = http_connection.getresponse() #second request It works using two different socket, I can see that using wireshark, each request use two different source port. I am using Python 2.6.1, some can suggest me how solve problem ? Thanks in advance. \pedr0 From pulsarpietro at gmail.com Mon Oct 3 16:39:17 2011 From: pulsarpietro at gmail.com (pedr0) Date: Mon, 3 Oct 2011 13:39:17 -0700 (PDT) Subject: HTTP Persistent connection In-Reply-To: <25371269.3648.1317673461242.JavaMail.geo-discussion-forums@yqnv12> References: <25371269.3648.1317673461242.JavaMail.geo-discussion-forums@yqnv12> Message-ID: <27527508.4070.1317674357487.JavaMail.geo-discussion-forums@yqnk41> I forget to insert second request. host = "www.higuys.net" #first request http_connection = httplib.HTTPConnection(host) http_connection.request(method,url_first,headers=headers) response = http_connection.getresponse() #second request http_connection = httplib.HTTPConnection(host) http_connection.request(method,url_second,headers=headers) response = http_connection.getresponse() From rantingrick at gmail.com Mon Oct 3 16:40:01 2011 From: rantingrick at gmail.com (rantingrick) Date: Mon, 3 Oct 2011 13:40:01 -0700 (PDT) Subject: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus References: Message-ID: <9256d59e-efae-4bf0-8de9-56e5ac3c1ab2@j31g2000vbl.googlegroups.com> On Oct 3, 2:55?pm, galyle wrote: > Hello, I'm trying to build a menu which provides suggestions to a user > based on input to an entry. ?I have done something like this before > using Tcl/Tk, so I expected that it would work without much difficulty > with Tkinter. ?I was wrong. Why not just use the Tix.ComboBox instead? I believe it's editable. From gordon at panix.com Mon Oct 3 16:51:43 2011 From: gordon at panix.com (John Gordon) Date: Mon, 3 Oct 2011 20:51:43 +0000 (UTC) Subject: HTTP Persistent connection References: <25371269.3648.1317673461242.JavaMail.geo-discussion-forums@yqnv12> <27527508.4070.1317674357487.JavaMail.geo-discussion-forums@yqnk41> Message-ID: In <27527508.4070.1317674357487.JavaMail.geo-discussion-forums at yqnk41> pedr0 writes: > I forget to insert second request. > host = "www.higuys.net" > #first request > http_connection = httplib.HTTPConnection(host) > http_connection.request(method,url_first,headers=headers) > response = http_connection.getresponse() > #second request > http_connection = httplib.HTTPConnection(host) > http_connection.request(method,url_second,headers=headers) > response = http_connection.getresponse() I haven't used httplib much so maybe this is a dumb question, but if you want to reuse the same connection, why are you declaring two separate HTTPConnection objects? Wouldn't you want to reuse the same object? -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From rantingrick at gmail.com Mon Oct 3 16:55:44 2011 From: rantingrick at gmail.com (rantingrick) Date: Mon, 3 Oct 2011 13:55:44 -0700 (PDT) Subject: Chaos Theory [was Re: Benefit and belief] References: <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> <4e88db0f$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8b72b54c-c33a-454b-8b4f-f599a63ab111@j19g2000vbn.googlegroups.com> On Oct 3, 11:27?am, Chris Angelico wrote: > PhysicsExpert: Super-speed wouldn't work, the acceleration required to > achieve it would burn up his surroundings! For some definition of "super-speed" i suppose. Since we're bouncing around the "relatives" here we need to consider this one also -> Super Speed to a tortoise will be super-slow, say for example, compared to the air-speed velocity of an unladen swallow. > Your point? Reductio ad Absurdum From pulsarpietro at gmail.com Mon Oct 3 17:12:58 2011 From: pulsarpietro at gmail.com (pedr0) Date: Mon, 3 Oct 2011 14:12:58 -0700 (PDT) Subject: HTTP Persistent connection In-Reply-To: References: <25371269.3648.1317673461242.JavaMail.geo-discussion-forums@yqnv12> <27527508.4070.1317674357487.JavaMail.geo-discussion-forums@yqnk41> Message-ID: <906183.4513.1317676378727.JavaMail.geo-discussion-forums@yqgn17> Because I am a newbye!!! Thanks a lot for your answer! From ed at leafe.com Mon Oct 3 17:21:34 2011 From: ed at leafe.com (Ed Leafe) Date: Mon, 3 Oct 2011 16:21:34 -0500 Subject: Hello, and request for help with 'dynamic grids' In-Reply-To: <4E64CFAB.70804@fossworkflowguides.com> References: <4E645BA6.4070500@fossworkflowguides.com> <1315229031.32028.140258137504765@webmail.messagingengine.com> <4E64CFAB.70804@fossworkflowguides.com> Message-ID: <2EE49CA6-EB6F-4D51-90F3-3CB6317872D5@leafe.com> On Sep 5, 2011, at 8:33 AM, Simon Cropper wrote: > Dabo is a great product. Spoke extensively with Ed Leafe and Paul McNett. Unfortunately the framework is not 'dynamic'. If you have an fixed database and tables it can quite quickly create a basic data entry setup and menu. Looks great when it runs. The problem is creating the window and grid on the fly. Sorry, someone just pointed me to this message. Of course we can build a window and grid on the fly: the command is: form, grid = dabo.ui.browse() ...where is a data set, or any object with a getDataSet() method, such as a bizobj or a cursor. I demonstrated this at my session at PyCon 2007: http://www.youtube.com/watch?v=y8G8AefXDo8&t=3m6s If you don't want to do this in a separate window, you can call the grid's buildFromDataSet() method directly. This command has a ton of optional parameters to control just how you would like the grid to appear. -- Ed Leafe From greg.ewing at canterbury.ac.nz Mon Oct 3 17:50:25 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 04 Oct 2011 10:50:25 +1300 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: <4E8A0985.2010007@ieee.org> Message-ID: <9eup13F72aU1@mid.individual.net> Ian Kelly wrote: > I would suggest giving them the whole if __name__ block as boilerplate > and telling them they're not allowed to alter it. I would suggest not showing them "if __name__" at all; instead encourage them to do this: def main(): ... ... main() You only need "if __name__ == '__main__'" if you want a .py file that can be used as either a module or a main program. Most of the time you *don't* need that. I consider it advanced usage that beginners shouldn't be confused with. -- Greg From anikom15 at gmail.com Mon Oct 3 18:01:24 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Mon, 3 Oct 2011 15:01:24 -0700 Subject: overloading operators for a function object In-Reply-To: References: Message-ID: <20111003220124.GA20084@Smoke> On Fri, Sep 30, 2011 at 09:50:42PM -0700, Fletcher Johnson wrote: > Is it possible to overload operators for a function? > > For instance I would like to do something roughly like... > > def func_maker(): > def func(): pass > > def __eq__(other): > if other == "check": return True > return False > > func.__eq__ = __eq__ > return func > > newfunc = func_maker() > newfunc == "check" #true > newfunc == "no" #false I'm curious as to what you're going to use this for. From davea at ieee.org Mon Oct 3 18:22:35 2011 From: davea at ieee.org (Dave Angel) Date: Mon, 03 Oct 2011 18:22:35 -0400 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> Message-ID: <4E8A35AB.5020601@ieee.org> On 01/-10/-28163 02:59 PM, rantingrick wrote: > On Oct 3, 2:14 pm, Dave Angel wrote: > >> Like it or not, there are plenty of globals already there, one of them >> being __name__ . All the built-ins are effectively global, and so >> is any function they define at top-level. > I keep wondering if that was another PyWart? I believe (and hindsight > is 20-20) that all the built-in modules There's only one __builtins__ module, which is implicitly loaded, and contains tons of things which are effectively global, such as open, float, filter, sorted, etc. > should have been protected by > a top-level namespace. Something succicent, something like "py"... > > from py.archive import zipfile, tarfile > from py.gui import Tkinter > from py.markup import HTMLParser > > ...and voila, no more clashes with user defined modules! > Gee, you just described a package. So why not say that the stdlib should have been done as a package of modules ? I don't know if I agree or not, just trying to keep things level. >> Likewise any top-level >> class, and any symbols imported with import or with from/import. So I >> consider it impractical for the language to do something that >> self-discipline is required for. > Also for scoping. > > py> count = > py> def foo(): > ... global.count += > py> print count > 1 > > Why? Well because many times i find myself wondering if this or that > variable is local or global -- and when i say "global" i am speaking > of module scope! The "global" cures the ill. > DaveA From rhodri at wildebst.demon.co.uk Mon Oct 3 18:34:54 2011 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Mon, 03 Oct 2011 23:34:54 +0100 Subject: Is there any way to access attributes from an imported module? References: <4E87F2A5.9000204@gmail.com> <4E880E87.5070507@islandtraining.com> Message-ID: On Mon, 03 Oct 2011 03:21:41 +0100, Andrew Berg wrote: > I found a way to do it, albeit a very hackish one. Since the class > instance already catches exceptions from the modules it imports, I can > make a custom exception (in a common area for both it and the submodules > to import) for it to catch and have it call its own methods there based > on information stored in the exception. I'm eventually going to redesign > it to be cleaner and more obvious, but for now, this is a nice > quick-and-dirty solution. OK, I give up. I cannot construct a mental model of what's going on that doesn't grievously abuse at least one of the terms you are using. Could you post some illustrative code snippets, please? -- Rhodri James *-* Wildebeest Herder to the Masses From ian.g.kelly at gmail.com Mon Oct 3 18:41:08 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 3 Oct 2011 16:41:08 -0600 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> Message-ID: On Mon, Oct 3, 2011 at 2:10 PM, rantingrick wrote: > Also for scoping. > > py> count = 0 > py> def foo(): > ... ? ? global.count += 1 > py> print count > 1 > > Why? Well because many times i find myself wondering if this or that > variable is local or global -- and when i say "global" i am speaking > of module scope! The "global" cures the ill. def add_from_input(num_lines): total = global.sum(global.int(global.input()) for i in global.range(num_lines)) global.print("The total is", total) Yes, that's much better. From gelonida at gmail.com Mon Oct 3 18:51:48 2011 From: gelonida at gmail.com (Gelonida N) Date: Tue, 04 Oct 2011 00:51:48 +0200 Subject: Advise on using logging.getLogger needed. In-Reply-To: <4E88E1B3.6080009@syslang.net> References: <4E88E1B3.6080009@syslang.net> Message-ID: On 10/03/2011 12:12 AM, Steven W. Orr wrote: > I hope I don't sound like I'm ranting :-( > > I have created a module (called xlogging) which sets up logging the way I want > it. I found out that if I set up my logger without a name, then it gets > applied to every logger that is referenced by every module that ever gets > imported. > > The problem is that I must call xlogging.getLogger or logging.getLogger in all > other modules using the name of the root logger, and I don't know what that > name is. > . . . . > > My modules are used by multiple programs. Does this mean that I should simply > use __name__ all the time? (That seems inelegant, no?) > > If I'm making sense, is there a way to do this? > > My impression is, that you try to use logging in a rather unconventional way. What you should normally do: Only your main script should configure the logging. If you want to do logging already during the import phase, then make sure, that you configure logging importing any module, that wants to log during the import phase. All other modules should only have following lines import logging log = logging.getLogger('name') # normally unique name for each module if you have groups of modules, that belong together, then choose hierarchical names for example 'gui.mainwindow' 'gui.subwindow' or similiar So if xlogging.py is the module, that sets up logging the way you want, then you should import it ONLY in your main script. or perhaps in a 'if __name__ == '__main__' section for anything, that you might want to run stand alone you can configure obtain (and thus configure) the root logger with rootlogger = logging.getLogger() your module can also configure other loggers and configure them. gui_logger = logging.getlogger('gui') configuring this logger will affect the configuration of all loggers named 'gui' or 'gui.somethingelse' You might want to look at the python doc to see how you could configure logging via a config file http://docs.python.org/release/2.6/library/logging.html#configuring-logging or you can look at: http://antonym.org/2005/03/a-real-python-logging-example.html From galyle at gmail.com Mon Oct 3 19:24:11 2011 From: galyle at gmail.com (galyle) Date: Mon, 3 Oct 2011 16:24:11 -0700 (PDT) Subject: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus References: <9256d59e-efae-4bf0-8de9-56e5ac3c1ab2@j31g2000vbl.googlegroups.com> Message-ID: <7c5a214d-effb-41cc-aefb-ba301581e1ae@i23g2000yqm.googlegroups.com> On Oct 3, 2:40?pm, rantingrick wrote: > On Oct 3, 2:55?pm, galyle wrote: > > > Hello, I'm trying to build a menu which provides suggestions to a user > > based on input to an entry. ?I have done something like this before > > using Tcl/Tk, so I expected that it would work without much difficulty > > with Tkinter. ?I was wrong. > > Why not just use the Tix.ComboBox instead? I believe it's editable. Thanks for the suggestion. I tried using a Pmw.ComboBox, but I've run into essentially the same problem. If I bring up the selection list on a keypress, then the selection takes the focus and further input no longer goes to the entry of the ComboBox. However, if I set the focus to the entry after bringing up the selection list, I can at least continue inputting to the entry, even though the selection list menu gets placed behind the entry. This is not desirable behavior, but at least it is closer. Any idea how to bring the menu to the forefront without the entry losing focus? The following demo demonstrates the issue: import Tkinter import Pmw class demo: def __init__(self, parent): self._search_bar = Pmw.ComboBox(parent, label_text = 'Register Mnemonic', labelpos = 'w', entry_width = 60) self._search_bar.pack(padx = 20, pady = 20) self._search_bar._entryfield.component('entry').bind('', self._suggest_text, add = '+') def _suggest_text(self, event): curr = self._search_bar._entryfield.getvalue() + repr(event.char)[1] self._search_bar._list.setlist([curr + '_0', curr + '_1', curr + '_2']) self._search_bar._postList(event) self._search_bar._entryfield.component('entry').focus_set() print curr if __name__ == '__main__': root = Tkinter.Tk() root.title('A Problem') demo(root) root.mainloop() From rosuav at gmail.com Mon Oct 3 20:07:24 2011 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 4 Oct 2011 11:07:24 +1100 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> Message-ID: On Tue, Oct 4, 2011 at 9:41 AM, Ian Kelly wrote: > def add_from_input(num_lines): > ? ?total = global.sum(global.int(global.input()) for i in > global.range(num_lines)) > ? ?global.print("The total is", total) That's pretty unfair to the globals. def add_from_input(param.num_lines): local.total = global.sum(global.int(global.input()) for tinyscope.i in global.range(param.num_lines)) global.print("The total is", local.total) FTFY. ChrisA From nobody at nowhere.com Mon Oct 3 20:08:10 2011 From: nobody at nowhere.com (Nobody) Date: Tue, 04 Oct 2011 01:08:10 +0100 Subject: Python without a tty References: <4e84388c$0$29965$c3e8da3$5496439d@news.astraweb.com> <87bou3wu7r.fsf@dpt-info.u-strasbg.fr> <4e893c17$0$29981$c3e8da3$5496439d@news.astraweb.com> <9etc4tF825U1@mid.individual.net> Message-ID: On Mon, 03 Oct 2011 22:04:26 +1300, Gregory Ewing wrote: >> os.setsid() > > *This* is what's losing the tty. According to the Fine Man Page: > > DESCRIPTION > The setsid function creates a new session. The calling process is the > session leader of the new session, is the process group leader of a new > process group and has no controlling terminal. > ^^^^^^^^^^^^^^^^^^^^^^^^^^^ The above description is incomplete. This version has more detail: DESCRIPTION setsid() creates a new session if the calling process is not a process group leader. The calling process is the leader of the new session, the process group leader of the new process group, and has no control- ling tty. The process group ID and session ID of the calling process are set to the PID of the calling process. The calling process will be the only process in this new process group and in this new session. The key point is "... if the calling process is not a process group leader". The easiest way to achieve this condition is to fork(). This ensures that the child process won't be a process group leader unless it explicitly makes itself one with setpgid() or setpgrp(). A process launched from a shell typically /will/ be a process group leader unless it's part of a pipeline (the shell creates a new process group for each pipeline; one of the processes in that group will be its leader). setsid() will fail with EPERM if the calling process is a process group leader. From roy at panix.com Mon Oct 3 20:22:01 2011 From: roy at panix.com (Roy Smith) Date: Mon, 03 Oct 2011 20:22:01 -0400 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <4E8A0985.2010007@ieee.org> Message-ID: In article , Ian Kelly wrote: > It's not a good idea to teach bad habits they'll just have to unlearn > later on. Absolutely correct. People who teach teachers how to teach call this the Law of Primacy (http://en.wikipedia.org/wiki/Principles_of_learning#Primacy), and (despite a lot of the religious psychobabble that comes with the territory) it really is true. Much better to just say, "put this stuff at the end of your file and don't worry about it for now" then to teach people the wrong way to do things. At some point, you'll get up to talking about modules and/or the magic double-underscore namespace. Then you'll have the opportunity to double back and explain what it means. From rustompmody at gmail.com Mon Oct 3 23:00:55 2011 From: rustompmody at gmail.com (rusi) Date: Mon, 3 Oct 2011 20:00:55 -0700 (PDT) Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> <02EA6D704E30CE499C5071776509A925F5BABD@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: On Oct 3, 12:45?pm, Chris Rebert wrote: > On Sun, Oct 2, 2011 at 11:45 PM, Wong Wah Meng-R32813 > > wrote: > > Hello guys, > > > I am migrating my application from python 1.5.2 to 2.7.1. I encountered an error when I run some commands (I put in debug statement however, not able to trace down to which line of code that cause it to generate a lot of messages in one second until my hard disk space is full. The error log I got in my log file is as below:- > > > Oct ?3 14:12:41 ?('Encountered exception while processing from', (0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'), , TypeError('exceptions must be old-style classes or derived from BaseException, not str',)) > > > Does it mean in newer python I need to migrate all my Exception to non-string based exception type? > > Correct. You can no longer do merely `raise "Some error message"`. You > should instead raise an exception instance of the appropriate type; > e.g. `raise ValueError("foo must be positive")`. > It's advisable to read the NEWS / "What's New" documents for the > intervening versions so you can learn what else has changed. > > > That's should be a lot of changes. :p > > To be fair, v1.5.2 is practically ancient at this point. It's over a > decade old! And 2 *major* versions behind what's current. > In a pinch, you could always write a script to mechanically change > `raise "..."` to `raise StandardError("...")` [or some other fairly > generic exception type]. > > Cheers, > Chris I wonder whether 2to3 could help directly or else have a hook to do this semi-automatically? NOTE: I am not advocating going straight to python 3, just using (parts of) the 2to3 'fixes' to aid migration. From sillyousu at gmail.com Mon Oct 3 23:42:14 2011 From: sillyousu at gmail.com (sillyou su) Date: Mon, 3 Oct 2011 20:42:14 -0700 (PDT) Subject: To start a simple server References: <06b7fcdc-8615-4980-8d42-f212033ee5c8@dk6g2000vbb.googlegroups.com> <9etsvnF1kdU9@mid.individual.net> <9eucdkF1kdU14@mid.individual.net> Message-ID: <7bceb2ea-676c-4dc7-9531-905ed1d14eb4@m5g2000vbe.googlegroups.com> On Oct 4, 2:15?am, Amelia T Cat wrote: > On Mon, 03 Oct 2011 10:09:59 -0700, sillyou su wrote: > > ??? > > > I should use 127.0.0.1 instance of ?0.0.0.0 > > Theoretically either one should be fine. If you use 127.0.0.1 it will > only expose the service to your local machine. If you use 0.0.0.0 ut will > expose the service to other computers on the same network as the one > running the service. Yes. Thank you. I run service on my computer. So I should use localhost to launch the service. From wuwei23 at gmail.com Tue Oct 4 00:27:12 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Oct 2011 21:27:12 -0700 (PDT) Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> Message-ID: <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> rantingrick wrote: > Why? Well because many times i find myself wondering if this or that > variable is local or global -- and when i say "global" i am speaking > of module scope! The "global" cures the ill. Given your stated propensity for huge code blocks not chunked into functions, I'm not surprised you lose track of what is global, what is nonlocal etc. This is another clear advantage of small functions: you can view it all at once. For the rest of us, a variable is global if its referenced but not defined in a specific scope. There's no need for such verbose hand-holding. I'd say the wart is in your design practice rather than the language itself. From wuwei23 at gmail.com Tue Oct 4 00:35:16 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Oct 2011 21:35:16 -0700 (PDT) Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: Message-ID: <74e9b784-7de4-4306-a747-bff85b1a1181@fx14g2000vbb.googlegroups.com> Sorry for hijacking Alec's response but I didn't see the OP. > Aivar Annamaa wrote: > > I'm looking for a trick or hidden feature to make Python 3 automatically > > call a "main" function but without programmers writing `if __name__ == > > "__main__": ...` One direct way is to call it from the command line: python -c "import mymodule; mymodule.main()" After your students have had to use that verbose form for a while, they'll be more than happy to add the boilerplate themselves to the end of their modules :) From wuwei23 at gmail.com Tue Oct 4 00:43:34 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Oct 2011 21:43:34 -0700 (PDT) Subject: Chaos Theory [was Re: Benefit and belief] References: <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> <4e88db0f$0$29981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <2675a628-e3a5-41a0-a9e2-2dc0803444de@t16g2000yqm.googlegroups.com> rantingrick wrote: > TrueWiseObserver: Wrong pseudo. Superman will ALWAYS be superman even > if he wears a dress and stilettos. Clark Kent is just an assumed > identity of Superman. Actually, he identifies with Clark Kent, Superman is the secret identity. You're thinking of Batman, for whom Bruce Wayne is the mask. From schesis at gmail.com Tue Oct 4 01:04:49 2011 From: schesis at gmail.com (Zero Piraeus) Date: Tue, 4 Oct 2011 01:04:49 -0400 Subject: Chaos Theory [was Re: Benefit and belief] In-Reply-To: <2675a628-e3a5-41a0-a9e2-2dc0803444de@t16g2000yqm.googlegroups.com> References: <4e83c65d$0$29997$c3e8da3$5496439d@news.astraweb.com> <87zkho2glb.fsf@benfinney.id.au> <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> <4e88db0f$0$29981$c3e8da3$5496439d@news.astraweb.com> <2675a628-e3a5-41a0-a9e2-2dc0803444de@t16g2000yqm.googlegroups.com> Message-ID: : On 4 October 2011 00:43, alex23 wrote: > rantingrick wrote: >> Clark Kent is just an assumed identity of Superman. > > Actually, he identifies with Clark Kent, Superman is the secret > identity. > > You're thinking of Batman, for whom Bruce Wayne is the mask. A dissenting view [and a Kill Bill spoiler, of sorts]: http://www.youtube.com/watch?v=PdWF7kd1tNo -[]z. From me+list/python at ixokai.io Tue Oct 4 02:24:27 2011 From: me+list/python at ixokai.io (Stephen Hansen) Date: Mon, 03 Oct 2011 23:24:27 -0700 Subject: Suggested coding style In-Reply-To: <27620bc4-edd2-473e-809f-18f17b426b4f@db5g2000vbb.googlegroups.com> References: <27620bc4-edd2-473e-809f-18f17b426b4f@db5g2000vbb.googlegroups.com> Message-ID: <4E8AA69B.303@ixokai.io> On 9/30/11 6:54 AM, rantingrick wrote: > a misplaced and rarely used functionality of the stdlib. Have you tried putting "\.zfill\(" and selecting Python in google.com/codesearch? It seems to have quite a few users, among only openly available code. Considering there is a much larger body of code that isn't openly available, its not hard to extrapolate from the search. (Then again, the Python Community is made up of only people on this list! Everyone knows that.) Sure, you can use format strings, but that is a significantly more complicated thing to do. It may not be /common/, but is not at all unusual for one to have in a string a number that they want to line up numerically with zeros. You may not have had to do it a lot. But, golly, you are not a representative sample of the world. Your code, your projects, the things you have done, are not a representative sample of all the Python code, projects, and things people have done with Python out there. The "zfill" may not be a super wonderful function, used by many in most places. But its there, its simple, its clear what it does. Removing it means that anyone who wants to do what it did, now have to learn a fairly complex mini-language, even if perhaps that is the only time they will /ever/ need to use said language. That's a burden which is just, frankly, silly. Its nice that the format mini-language is powerful. But its nice that there are also simple, clear, direct primitives people can use to accomplish simple, fairly common needs. -- Stephen Hansen ... Also: Ixokai ... Mail: me+list/python (AT) ixokai (DOT) io ... Blog: http://meh.ixokai.io/ -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 487 bytes Desc: OpenPGP digital signature URL: From wuwei23 at gmail.com Tue Oct 4 02:25:56 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Oct 2011 23:25:56 -0700 (PDT) Subject: Chaos Theory [was Re: Benefit and belief] References: <20110929220132.GD2715@benfinney.id.au> <4E84FD75.5050907@stoneleaf.us> <284c7599-8c20-4535-9e23-f08b01760ba1@i33g2000yqm.googlegroups.com> <6720eaad-029c-48e2-bacf-318bc716b712@z12g2000yqz.googlegroups.com> <4e87d470$0$29973$c3e8da3$5496439d@news.astraweb.com> <4e88db0f$0$29981$c3e8da3$5496439d@news.astraweb.com> <2675a628-e3a5-41a0-a9e2-2dc0803444de@t16g2000yqm.googlegroups.com> Message-ID: <8433efdb-55ef-4e40-bbf6-4fc508bdc1b0@j1g2000yqj.googlegroups.com> Zero Piraeus wrote: > A dissenting view [and a Kill Bill spoiler, of sorts]: > > http://www.youtube.com/watch?v=PdWF7kd1tNo A fun diatribe, sure, but still an outsider view that is in direct conflict with how the characters are actually portrayed. From masood.524 at gmail.com Tue Oct 4 02:39:15 2011 From: masood.524 at gmail.com (masood shaik) Date: Mon, 3 Oct 2011 23:39:15 -0700 (PDT) Subject: how to call java methods in python Message-ID: Hi I am trying to import java method in python. But i am getting the following error. error: ImportError: No module named Calculator Calculator is the name of the class written in java. I am trying to access the methods of that class. Please help me. From wuwei23 at gmail.com Tue Oct 4 02:52:15 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Oct 2011 23:52:15 -0700 (PDT) Subject: how to call java methods in python References: Message-ID: On Oct 4, 4:39?pm, masood shaik wrote: > Please help me. Please help us help you. You've given us nothing but an error message. (Which seems to indicate that you're trying 'import Calculator'...) What are you using to call Java methods in Python? Can you provide a small example of code that demonstrates the problem? From lucaberto at libero.it Tue Oct 4 02:58:15 2011 From: lucaberto at libero.it (luca72) Date: Mon, 3 Oct 2011 23:58:15 -0700 (PDT) Subject: open html page for parsing Message-ID: Hello i have a simple question: up to now if i have to parse a page i do as follow: import urllib site = urllib.urlopen('http://www.blabla.ooo') list_a = site.readline() site.close() __and then i make my work__ Now i have the site that is open by an html file like this: insert the password; ;
this is in a file called example.html how can i open it with urllib From lucaberto at libero.it Tue Oct 4 03:00:45 2011 From: lucaberto at libero.it (luca72) Date: Tue, 4 Oct 2011 00:00:45 -0700 (PDT) Subject: urllib and parsing Message-ID: Hello i have a simple question: up to now if i have to parse a page i do as follow: import urllib site = urllib.urlopen('http://www.blabla.ooo') list_a = site.readline() site.close() __and then i make my work__ Now i have the site that is open by an html file like this: insert the password; ;
this is in a file called example.html how can i open it with urllib, please note i don't have to parse this file, but i have to parse the site where he point. From masood.524 at gmail.com Tue Oct 4 03:14:49 2011 From: masood.524 at gmail.com (masood shaik) Date: Tue, 4 Oct 2011 00:14:49 -0700 (PDT) Subject: how to call java methods in python References: Message-ID: <33a61c6f-508a-48f0-97dc-d51099199c30@z12g2000yqz.googlegroups.com> Hi I am trying out my hand on accessing java methods in python. here is my piece of code.. Calculator.java --------------- public class Calculator { public Calculator(){ } public double calculateTip(double cost, double tipPercentage){ return cost * tipPercentage; } public double calculateTax(double cost, double taxPercentage){ return cost * taxPercentage; } } javaInPython.py --------------- import Calculator class javaInPython(Calculator): def __init__(self): pass def calculateTotal(self, cost, tip, tax): return cost + self.calculateTip(tip,tax) + self.calculateTax(tax,tip) if __name__ == "__main__": calc = javaInPython() cost = 23.75 tip = .15 tax = .07 print "Starting Cost: ", cost print "Tip Percentage: ", tip print "Tax Percentage: ", tax Now i am trying to access the calculateTip() and its showing import error. It works fine when i am running it with jython but why its not happening in python. Please do help me. On Oct 4, 11:52?am, alex23 wrote: > On Oct 4, 4:39?pm, masood shaik wrote: > > > Please help me. > > Please help us help you. You've given us nothing but an error message. > (Which seems to indicate that you're trying 'import Calculator'...) > > What are you using to call Java methods in Python? > > Can you provide a small example of code that demonstrates the problem? From clp2 at rebertia.com Tue Oct 4 03:22:31 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 Oct 2011 00:22:31 -0700 Subject: open html page for parsing In-Reply-To: References: Message-ID: On Mon, Oct 3, 2011 at 11:58 PM, luca72 wrote: > Hello i have a simple question: > up to now if i have to parse a page i do as follow: > import urllib > site = urllib.urlopen('http://www.blabla.ooo') > list_a = site.readline() > site.close() > __and then i make my work__ > > Now i have the site that is open by an html file like this: > ? ? ? ? ? ? ? ? > insert the password > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?; > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?; > ? ? ? ? ? ? ? ? ? ? ? ? > ? ? ? ? ? ? ? ?
> > > > > > this is in a file called example.html > > how can i open it with urllib Assuming you meant "How do I submit the form in example.html and get the resulting response page?", use urllib.urlencode() to encode the form's key-value pairs, and then pass the encoded result as the `data` argument to urllib.urlopen(). Or use something like Selenium (http://seleniumhq.org/ ), mechanize (http://wwwsearch.sourceforge.net/mechanize/ ), or Scrapy (http://scrapy.org/ ) that emulates/drives a web browser and lets you fill out forms programatically. Cheers, Chris -- http://rebertia.com From r32813 at freescale.com Tue Oct 4 03:51:06 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Tue, 4 Oct 2011 07:51:06 +0000 Subject: Is exec() also not used in python 2.7.1 anymore? Message-ID: <02EA6D704E30CE499C5071776509A925F5C2ED@039-SN1MPN1-003.039d.mgd.msft.net> In migrating my application from python 1.5.2 to 2.7.1, one of my modules breaks when I import it. Here is the line where it breaks. Can I have a quick check if this built-in function still supported in python 2.7.1 and if so, what ought to be changed here? Thanks in advance for replying. exec('def %s(self, *args, **kw): pass'%methodStrName) SyntaxError: unqualified exec is not allowed in function '_exposeMethods' it contains a nested function with free variables Regards, Wah Meng -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Tue Oct 4 04:16:43 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 Oct 2011 01:16:43 -0700 Subject: how to call java methods in python In-Reply-To: <33a61c6f-508a-48f0-97dc-d51099199c30@z12g2000yqz.googlegroups.com> References: <33a61c6f-508a-48f0-97dc-d51099199c30@z12g2000yqz.googlegroups.com> Message-ID: On Tue, Oct 4, 2011 at 12:14 AM, masood shaik wrote: > Hi > ?I am trying out my hand on accessing java methods in python. here is > my piece of code.. > > Calculator.java > --------------- > public class Calculator { > > ? ?public Calculator(){ > > ? ?} > > ? ?public double calculateTip(double cost, double tipPercentage){ > ? ? ? ?return cost * tipPercentage; > ? ?} > > ? ?public double calculateTax(double cost, double taxPercentage){ > ? ? ? ?return cost * taxPercentage; > ? ?} > > } > > javaInPython.py > --------------- > import Calculator > > class javaInPython(Calculator): > ? ?def __init__(self): > ? ? ? ?pass > > ? ?def calculateTotal(self, cost, tip, tax): > ? ? ? ?return cost + self.calculateTip(tip,tax) + > self.calculateTax(tax,tip) > > if __name__ == "__main__": > ? ?calc = javaInPython() > ? ?cost = 23.75 > ? ?tip = .15 > ? ?tax = .07 > ? ?print "Starting Cost: ", cost > ? ?print "Tip Percentage: ", tip > ? ?print "Tax Percentage: ", tax > > Now i am trying to access the calculateTip() and its showing import > error. > It works fine when i am running it with jython but why its not > happening in python. That's because the integration functionality you're depending upon is *specific to Jython*. Unlike Jython, CPython does not include an automatic Java bridge. CPython doesn't feature Java integration; only Jython does. (N.B.: CPython is the reference implementation of Python, hosted at python.org.) Cheers, Chris From clp2 at rebertia.com Tue Oct 4 04:26:04 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 Oct 2011 01:26:04 -0700 Subject: Is exec() also not used in python 2.7.1 anymore? In-Reply-To: <02EA6D704E30CE499C5071776509A925F5C2ED@039-SN1MPN1-003.039d.mgd.msft.net> References: <02EA6D704E30CE499C5071776509A925F5C2ED@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: On Tue, Oct 4, 2011 at 12:51 AM, Wong Wah Meng-R32813 wrote: > In migrating my application from python 1.5.2 to 2.7.1, one of my modules > breaks when I import it. Here is the line where it breaks. Can I have a > quick check if this built-in function still supported in python 2.7.1 Er, `exec` is a primitive statement, not a built-in function (so, the parens around it are superfluous), but yes, it's still present in 2.7. (Ironically, exec was changed to a function in Python 3.0.) > and if > so, what ought to be changed here? Thanks in advance for replying. > > ? exec('def %s(self, *args, **kw): pass'%methodStrName) Defining a do-nothing, dynamically-named function seems kinda strange in the first place; why are you doing this? Cheers, Chris -- http://rebertia.com From __peter__ at web.de Tue Oct 4 04:40:05 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 04 Oct 2011 10:40:05 +0200 Subject: Is exec() also not used in python 2.7.1 anymore? References: <02EA6D704E30CE499C5071776509A925F5C2ED@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: Wong Wah Meng-R32813 wrote: > In migrating my application from python 1.5.2 to 2.7.1, one of my modules > breaks when I import it. Here is the line where it breaks. Can I have a > quick check if this built-in function still supported in python 2.7.1 and > if so, what ought to be changed here? Thanks in advance for replying. > > exec('def %s(self, *args, **kw): pass'%methodStrName) > SyntaxError: unqualified exec is not allowed in function '_exposeMethods' > it contains a nested function with free variables I think the message is quite explicit about the problem. You have a nested function along the lines: >>> def f(): ... exec "" ... def g(): return x ... File "", line 2 SyntaxError: unqualified exec is not allowed in function 'f' it contains a nested function with free variables With the current scoping rules x in the inner function may refer either to a local variable in f() or a global variable -- and because of the exec statement the compiler cannot determine which. Depending on your usecase a workaround may be to declare the free variable as global: >>> def f(): ... exec "" ... def g(): ... global x ... return x ... return g ... >>> x = 42 >>> f()() 42 From aivar.annamaa at gmail.com Tue Oct 4 04:43:39 2011 From: aivar.annamaa at gmail.com (Aivar Annamaa) Date: Tue, 4 Oct 2011 11:43:39 +0300 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: Message-ID: Thanks for all the comments! It seems that the best way is still just to teach students self discipline. And hope that they (for now) believe some things (eg. dangers of global variables) without seeing. Aivar -------------- next part -------------- An HTML attachment was scrubbed... URL: From masood.524 at gmail.com Tue Oct 4 05:44:41 2011 From: masood.524 at gmail.com (masood shaik) Date: Tue, 4 Oct 2011 02:44:41 -0700 (PDT) Subject: how to call java methods in python References: <33a61c6f-508a-48f0-97dc-d51099199c30@z12g2000yqz.googlegroups.com> Message-ID: <735343b1-5c1e-4831-b794-b455675c2cd5@dk6g2000vbb.googlegroups.com> On Oct 4, 1:16?pm, Chris Rebert wrote: > On Tue, Oct 4, 2011 at 12:14 AM, masood shaik wrote: > > Hi > > ?I am trying out my hand on accessing java methods in python. here is > > my piece of code.. > > > Calculator.java > > --------------- > > public class Calculator { > > > ? ?public Calculator(){ > > > ? ?} > > > ? ?public double calculateTip(double cost, double tipPercentage){ > > ? ? ? ?return cost * tipPercentage; > > ? ?} > > > ? ?public double calculateTax(double cost, double taxPercentage){ > > ? ? ? ?return cost * taxPercentage; > > ? ?} > > > } > > > javaInPython.py > > --------------- > > import Calculator > > > class javaInPython(Calculator): > > ? ?def __init__(self): > > ? ? ? ?pass > > > ? ?def calculateTotal(self, cost, tip, tax): > > ? ? ? ?return cost + self.calculateTip(tip,tax) + > > self.calculateTax(tax,tip) > > > if __name__ == "__main__": > > ? ?calc = javaInPython() > > ? ?cost = 23.75 > > ? ?tip = .15 > > ? ?tax = .07 > > ? ?print "Starting Cost: ", cost > > ? ?print "Tip Percentage: ", tip > > ? ?print "Tax Percentage: ", tax > Please help me Regarding how to create java bridge as how to call a java function from python > > Now i am trying to access the calculateTip() and its showing import > > error. > > It works fine when i am running it with jython but why its not > > happening in python. > > That's because the integration functionality you're depending upon is > *specific to Jython*. Unlike Jython, CPython does not include an > automatic Java bridge. CPython doesn't feature Java integration; only > Jython does. > > (N.B.: CPython is the reference implementation of Python, hosted at python.org.) > > Cheers, > Chris From a24061 at ducksburg.com Tue Oct 4 05:56:57 2011 From: a24061 at ducksburg.com (Adam Funk) Date: Tue, 04 Oct 2011 10:56:57 +0100 Subject: recommend a graphics library for plotting by the pixel? Message-ID: <9s1rl8xt8t.ln2@news.ducksburg.com> I'd like to create a window with a "pause" button and a large plotting area, in which I'd like to draw a polygon, detect the pixel co?rdinates of a mouse click, and then start setting the colors of pixels by (x,y) co?rdinates. (This is just for my own amusement, to play with some formulas for generating fractals using random numbers.) There seems to be a large number of different python GUI libraries, and I wonder if someone can recommend the easiests one to learn for this purpose? (The only python graphics library I've used is PyGame, which I don't think is the way to go here.) -- In the 1970s, people began receiving utility bills for -?999,999,996.32 and it became harder to sustain the myth of the infallible electronic brain. (Stob 2001) From r32813 at freescale.com Tue Oct 4 06:32:41 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Tue, 4 Oct 2011 10:32:41 +0000 Subject: Is exec() also not used in python 2.7.1 anymore? In-Reply-To: References: <02EA6D704E30CE499C5071776509A925F5C2ED@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <02EA6D704E30CE499C5071776509A925F5C3AA@039-SN1MPN1-003.039d.mgd.msft.net> Haha... yeah I reviewed the code, it is supposed to exposed some remote methods locally (RMI proxy usage). However, I am not sure why what it does is merely a pass. I commented out this code and haven't seen any negative implication. I will look into this again if I am convinced the next error I see is due to I commented out this code. Thanks! Regards, Wah Meng -----Original Message----- From: chris at rebertia.com [mailto:chris at rebertia.com] On Behalf Of Chris Rebert Sent: Tuesday, October 04, 2011 4:26 PM To: Wong Wah Meng-R32813 Cc: python-list at python.org Subject: Re: Is exec() also not used in python 2.7.1 anymore? On Tue, Oct 4, 2011 at 12:51 AM, Wong Wah Meng-R32813 wrote: > In migrating my application from python 1.5.2 to 2.7.1, one of my modules > breaks when I import it. Here is the line where it breaks. Can I have a > quick check if this built-in function still supported in python 2.7.1 Er, `exec` is a primitive statement, not a built-in function (so, the parens around it are superfluous), but yes, it's still present in 2.7. (Ironically, exec was changed to a function in Python 3.0.) > and if > so, what ought to be changed here? Thanks in advance for replying. > > ? exec('def %s(self, *args, **kw): pass'%methodStrName) Defining a do-nothing, dynamically-named function seems kinda strange in the first place; why are you doing this? Cheers, Chris -- http://rebertia.com From gandalf at shopzeus.com Tue Oct 4 06:56:12 2011 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 04 Oct 2011 12:56:12 +0200 Subject: how to call java methods in python In-Reply-To: <735343b1-5c1e-4831-b794-b455675c2cd5@dk6g2000vbb.googlegroups.com> References: <33a61c6f-508a-48f0-97dc-d51099199c30@z12g2000yqz.googlegroups.com> <735343b1-5c1e-4831-b794-b455675c2cd5@dk6g2000vbb.googlegroups.com> Message-ID: <4E8AE64C.1050101@shopzeus.com> > Please help me > > Regarding how to create java bridge as how to call a java function > from python If you want to call a Java *method* from the C python implementation, then there are many possibilities. For example, you can write your Java program as a service. The Python program can talk to it through some kind of IPC mechanism. There are lots of ways to do communication between two running processes. Lower lever would be (just an example) to open a TCP/IP server socket on the Java side, and connect to it from the Python side. Then develop your own protocol for communication. Higher level would be (just another example) to use CORBA/ORB on the Java side, and do the same from the Python side. There are dozens of libraries that can help you communicate between processes. I suggest that you look after these libraries, and select one that suits your needs. If you want to call Java methods that run inside the same process with Python then I have bad news. This won't be possible. (Or it might be, but don't worth the work...) Best, Laszlo From svaliev at gmail.com Tue Oct 4 09:50:27 2011 From: svaliev at gmail.com (Valiev Sergey) Date: Tue, 4 Oct 2011 17:50:27 +0400 Subject: syntax enhancement Message-ID: Hi, you may found this idea stupid, but nevertheless... - `[]` - used for list comprehension, - `()` - used for generators, - `[start:stop]` / `[start:stop:step]` - used for slices. The idea is to use `(start:stop)` / `(start:stop:step)` as 'lazy evaluated' slices (like itertools.islice). What do you think about it? -- Best regards, Valiev Sergey *skype:* *svaliev* *jabber:* *svaliev at gmail.com* *phone:* +7 926 233-17-64 -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrea.crotti.0 at gmail.com Tue Oct 4 10:48:46 2011 From: andrea.crotti.0 at gmail.com (andrea.crotti.0 at gmail.com) Date: Tue, 04 Oct 2011 15:48:46 +0100 Subject: eggbasket Message-ID: <87aa9gdd81.fsf@precision.i-did-not-set--mail-host-address--so-tickle-me> I'm struggling trying to get a working local pypi server. Now eggbasket apparently also supports upload, which should be nice. So I: - created a virtualenv - installed all the necessary and trying to initializing the server I get: --8<---------------cut here---------------start------------->8--- eggbasket-server --init Traceback (most recent call last): File "/home/andrea/.local/bin/eggbasket-server", line 9, in load_entry_point('EggBasket==0.6.1b', 'console_scripts', 'eggbasket-server')() File "/home/andrea/.local/lib/python2.7/site-packages/EggBasket-0.6.1b-py2.7.egg/eggbasket/commands.py", line 145, in main init_database(args) File "/home/andrea/.local/lib/python2.7/site-packages/EggBasket-0.6.1b-py2.7.egg/eggbasket/commands.py", line 76, in init_database model = get_model() File "/usr/lib/python2.7/site-packages/TurboGears-1.5-py2.7.egg/turbogears/util.py", line 241, in get_model package = __import__(package_name, {}, {}, ["model"]) File "/home/andrea/.local/lib/python2.7/site-packages/EggBasket-0.6.1b-py2.7.egg/eggbasket/model.py", line 22, in from sqlalchemy.exceptions import InvalidRequestError ImportError: No module named exceptions --8<---------------cut here---------------end--------------->8--- But funny thing is that if try to understand to see what's going on, from within "model.py" import sqlalchemy.exceptions work perfectly, but importing something inside it gives this strange error, any idea of what it could be? How is it possible that the module exists and it's actually imported, and not found when I actually try to import something from it? From alec.taylor6 at gmail.com Tue Oct 4 10:53:25 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Wed, 5 Oct 2011 01:53:25 +1100 Subject: recommend a graphics library for plotting by the pixel? In-Reply-To: <9s1rl8xt8t.ln2@news.ducksburg.com> References: <9s1rl8xt8t.ln2@news.ducksburg.com> Message-ID: Sounds like a job for Processing... On Tue, Oct 4, 2011 at 8:56 PM, Adam Funk wrote: > I'd like to create a window with a "pause" button and a large plotting > area, in which I'd like to draw a polygon, detect the pixel > co?rdinates of a mouse click, and then start setting the colors of > pixels by (x,y) co?rdinates. ?(This is just for my own amusement, to > play with some formulas for generating fractals using random numbers.) > > There seems to be a large number of different python GUI libraries, > and I wonder if someone can recommend the easiests one to learn for > this purpose? ?(The only python graphics library I've used is PyGame, > which I don't think is the way to go here.) > > > -- > In the 1970s, people began receiving utility bills for > -?999,999,996.32 and it became harder to sustain the > myth of the infallible electronic brain. ?(Stob 2001) > -- > http://mail.python.org/mailman/listinfo/python-list > From woooee at gmail.com Tue Oct 4 11:41:06 2011 From: woooee at gmail.com (woooee) Date: Tue, 4 Oct 2011 08:41:06 -0700 (PDT) Subject: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus References: <9256d59e-efae-4bf0-8de9-56e5ac3c1ab2@j31g2000vbl.googlegroups.com> <7c5a214d-effb-41cc-aefb-ba301581e1ae@i23g2000yqm.googlegroups.com> Message-ID: <4a81ac45-4a55-4684-8588-7e9ec0f1d455@k15g2000yqd.googlegroups.com> Adding focus_set seems to work for me. What do want to do differently? import Tkinter class demo: def __init__(self, parent): self._entry = Tkinter.Entry(width = 60) self._suggestions = Tkinter.Menu(parent, tearoff = 0, takefocus = 0) self._entry.pack(padx = 20, pady = 20) self._entry.bind('', self._suggest_text, add = '+') self._entry.focus_set() def _suggest_text(self, event): curr = self._entry.get() + repr(event.char)[1] x = self._entry.winfo_rootx() y = self._entry.winfo_rooty() y += self._entry.winfo_height() try: self._suggestions.delete(0, 'end') self._suggestions.add_command(label = curr + '_1') self._suggestions.add_command(label = curr + '_2') self._suggestions.add_command(label = curr + '_3') self._suggestions.add_command(label = curr + '_4') self._suggestions.post(x, y) finally: self._suggestions.grab_release() if __name__ == '__main__': root = Tkinter.Tk() root.title('A Problem') demo(root) root.mainloop() From woooee at gmail.com Tue Oct 4 11:45:10 2011 From: woooee at gmail.com (woooee) Date: Tue, 4 Oct 2011 08:45:10 -0700 (PDT) Subject: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus References: Message-ID: Sorry, I did not understand the question correctly, and so have added another focus_set for the entry after the menu's creation. You can still enter after the menu comes up, even though you can't see where you are entering. import Tkinter class demo: def __init__(self, parent): self._entry = Tkinter.Entry(width = 60) self._suggestions = Tkinter.Menu(parent, tearoff = 0, takefocus = 0) self._entry.pack(padx = 20, pady = 20) self._entry.bind('', self._suggest_text, add = '+') self._entry.focus_set() def _suggest_text(self, event): curr = self._entry.get() + repr(event.char)[1] x = self._entry.winfo_rootx() y = self._entry.winfo_rooty() y += self._entry.winfo_height() try: self._suggestions.delete(0, 'end') self._suggestions.add_command(label = curr + '_1') self._suggestions.add_command(label = curr + '_2') self._suggestions.add_command(label = curr + '_3') self._suggestions.add_command(label = curr + '_4') self._suggestions.post(x, y) finally: self._suggestions.grab_release() self._entry.focus_set() if __name__ == '__main__': root = Tkinter.Tk() root.title('A Problem') demo(root) root.mainloop() From ian.g.kelly at gmail.com Tue Oct 4 11:49:58 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 4 Oct 2011 09:49:58 -0600 Subject: recommend a graphics library for plotting by the pixel? In-Reply-To: <9s1rl8xt8t.ln2@news.ducksburg.com> References: <9s1rl8xt8t.ln2@news.ducksburg.com> Message-ID: On Tue, Oct 4, 2011 at 3:56 AM, Adam Funk wrote: > I'd like to create a window with a "pause" button and a large plotting > area, in which I'd like to draw a polygon, detect the pixel > co?rdinates of a mouse click, and then start setting the colors of > pixels by (x,y) co?rdinates. ?(This is just for my own amusement, to > play with some formulas for generating fractals using random numbers.) > > There seems to be a large number of different python GUI libraries, > and I wonder if someone can recommend the easiests one to learn for > this purpose? ?(The only python graphics library I've used is PyGame, > which I don't think is the way to go here.) You could use wxPython. You'll need to create a custom control and have it paint itself by blitting from a wx.Bitmap, which you'll draw on by using a wx.MemoryDC and then refreshing the control. I would probably just use pygame myself. I guess you're avoiding it because of the requirement for a button, but there are GUI libraries available for it, or if all you need are a couple of buttons you could easily roll your own. Stay away from the Tkinter Canvas widget. It does vector graphics, and it will be inefficient if you try to use it as a raster. Cheers, Ian From ironfroggy at gmail.com Tue Oct 4 12:17:13 2011 From: ironfroggy at gmail.com (Calvin Spealman) Date: Tue, 4 Oct 2011 12:17:13 -0400 Subject: syntax enhancement In-Reply-To: References: Message-ID: On Tue, Oct 4, 2011 at 9:50 AM, Valiev Sergey wrote: > Hi, > you may found this idea stupid, but nevertheless... > - `[]` - used for list comprehension, > - `()` - used for generators, > - `[start:stop]` / `[start:stop:step]` - used for slices. > The idea is to use `(start:stop)` / `(start:stop:step)` as 'lazy evaluated' > slices (like itertools.islice). > What do you think about it? > It simply looks too much like a function call. > -- > Best regards, > Valiev Sergey > *skype:* *svaliev* > *jabber:* *svaliev at gmail.com* > *phone:* +7 926 233-17-64 > > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy -------------- next part -------------- An HTML attachment was scrubbed... URL: From anikom15 at gmail.com Tue Oct 4 12:44:40 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Tue, 4 Oct 2011 09:44:40 -0700 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: <74e9b784-7de4-4306-a747-bff85b1a1181@fx14g2000vbb.googlegroups.com> References: <74e9b784-7de4-4306-a747-bff85b1a1181@fx14g2000vbb.googlegroups.com> Message-ID: <20111004164440.GA27367@Smoke> On Mon, Oct 03, 2011 at 09:35:16PM -0700, alex23 wrote: > Sorry for hijacking Alec's response but I didn't see the OP. > > > Aivar Annamaa wrote: > > > I'm looking for a trick or hidden feature to make Python 3 automatically > > > call a "main" function but without programmers writing `if __name__ == > > > "__main__": ...` > > One direct way is to call it from the command line: > > python -c "import mymodule; mymodule.main()" > > After your students have had to use that verbose form for a while, > they'll be more than happy to add the boilerplate themselves to the > end of their modules :) Boiler plate is silly. Let the students figure out stuff themselves. The students need to know why global variables in functions is unwieldly, not just not use them because it's cool. When I taught myself Python I quickly realized global variables were unwieldly and usually impractical after using them. From galyle at gmail.com Tue Oct 4 13:05:49 2011 From: galyle at gmail.com (galyle) Date: Tue, 4 Oct 2011 10:05:49 -0700 (PDT) Subject: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus References: Message-ID: <19357b0e-0c8f-4081-9ea5-56acc4f03731@d17g2000yqa.googlegroups.com> On Oct 4, 9:45?am, woooee wrote: > Sorry, I did not understand the question correctly, and so have added > another focus_set for the entry after the menu's creation. ?You can > still enter after the menu comes up, even though you can't see where > you are entering. > > import Tkinter > > class demo: > ? ? def __init__(self, parent): > ? ? ? ? self._entry = Tkinter.Entry(width = 60) > ? ? ? ? self._suggestions = Tkinter.Menu(parent, tearoff = 0, > takefocus = 0) > ? ? ? ? self._entry.pack(padx = 20, pady = 20) > ? ? ? ? self._entry.bind('', self._suggest_text, add = '+') > ? ? ? ? self._entry.focus_set() > > ? ? def _suggest_text(self, event): > ? ? ? ? curr = self._entry.get() + repr(event.char)[1] > ? ? ? ? x = self._entry.winfo_rootx() > ? ? ? ? y = self._entry.winfo_rooty() > ? ? ? ? y += self._entry.winfo_height() > ? ? ? ? try: > ? ? ? ? ? ? self._suggestions.delete(0, 'end') > ? ? ? ? ? ? self._suggestions.add_command(label = curr + '_1') > ? ? ? ? ? ? self._suggestions.add_command(label = curr + '_2') > ? ? ? ? ? ? self._suggestions.add_command(label = curr + '_3') > ? ? ? ? ? ? self._suggestions.add_command(label = curr + '_4') > ? ? ? ? ? ? self._suggestions.post(x, y) > ? ? ? ? finally: > ? ? ? ? ? ? self._suggestions.grab_release() > > ? ? ? ? self._entry.focus_set() > > if __name__ == '__main__': > ? ? root = Tkinter.Tk() > ? ? root.title('A Problem') > ? ? demo(root) > ? ? root.mainloop() Perhaps it is because I'm trying this on Windows, but the above code does not work for me. After the menu is posted, no further keyboard input gets directed to the entry until the menu is unposted. It looks like my best bet is to use the ComboBox suggested above. The ComboBox method is very close to working, but I've got a problem now where all focus on the app is directed to the ComboBox entry (I need to set it that way to redirect keyboard input from the popup menu), making it impossible to close the app without killing it. I've tried to return focus to the entry parent by binding the entry to and , but this has the effect of making the popup take the focus after every keystroke, which is not what I want. The (almost working) demo below should demonstrate the issue fairly well: import Tkinter import Pmw class demo: def __init__(self, parent): self._search_bar = Pmw.ComboBox(parent, label_text = 'Register Mnemonic', labelpos = 'w', entry_width = 60) self._search_bar.pack(padx = 20, pady = 20) self._search_bar._entryfield.component('entry').bind('', self._suggest_text, add = '+') def _suggest_text(self, event): curr = self._search_bar._entryfield.getvalue() curr += repr(event.char)[1] self._search_bar._list.setlist([curr + '_0', curr + '_1', curr + '_2']) self._search_bar._postList(event) self._search_bar._entryfield.component('entry').focus_set() self._search_bar._popup.lift() if __name__ == '__main__': root = Tkinter.Tk() root.title('A Problem') demo(root) root.mainloop() From chris at simplistix.co.uk Tue Oct 4 14:22:01 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 04 Oct 2011 19:22:01 +0100 Subject: TestFixtures 2.2.0 Released! Message-ID: <4E8B4EC9.5030108@simplistix.co.uk> Hi All, The TestFixtures releases keep coming, I hope someone other than me is finding these useful ;-) This release features a change to test_datetime and test_date so that they return instances of the real datetime.datetime and datetime.date classes by default. I'm hoping this will making using these mocks with other libraries such as SQLALchemy and the associated database backend libraries much easier However, if you need the old behaviour, it's still available via the new "strict" mode: http://packages.python.org/testfixtures/datetime.html#strict-dates-and-times The package is on PyPI and a full list of all the links to docs, issue trackers and the like can be found here: http://www.simplistix.co.uk/software/python/testfixtures Any questions, please do ask here or on the Simplistix open source mailing lists... cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From galyle at gmail.com Tue Oct 4 14:35:25 2011 From: galyle at gmail.com (galyle) Date: Tue, 4 Oct 2011 11:35:25 -0700 (PDT) Subject: Question: How to Prevent Tkinter Menu from Taking Keyboard Focus References: <19357b0e-0c8f-4081-9ea5-56acc4f03731@d17g2000yqa.googlegroups.com> Message-ID: <1e2853df-25db-4e6f-9de6-9a0f915f8f3b@j10g2000vbb.googlegroups.com> On Oct 4, 11:05?am, galyle wrote: > On Oct 4, 9:45?am, woooee wrote: > > > > > > > > > > > Sorry, I did not understand the question correctly, and so have added > > another focus_set for the entry after the menu's creation. ?You can > > still enter after the menu comes up, even though you can't see where > > you are entering. > > > import Tkinter > > > class demo: > > ? ? def __init__(self, parent): > > ? ? ? ? self._entry = Tkinter.Entry(width = 60) > > ? ? ? ? self._suggestions = Tkinter.Menu(parent, tearoff = 0, > > takefocus = 0) > > ? ? ? ? self._entry.pack(padx = 20, pady = 20) > > ? ? ? ? self._entry.bind('', self._suggest_text, add = '+') > > ? ? ? ? self._entry.focus_set() > > > ? ? def _suggest_text(self, event): > > ? ? ? ? curr = self._entry.get() + repr(event.char)[1] > > ? ? ? ? x = self._entry.winfo_rootx() > > ? ? ? ? y = self._entry.winfo_rooty() > > ? ? ? ? y += self._entry.winfo_height() > > ? ? ? ? try: > > ? ? ? ? ? ? self._suggestions.delete(0, 'end') > > ? ? ? ? ? ? self._suggestions.add_command(label = curr + '_1') > > ? ? ? ? ? ? self._suggestions.add_command(label = curr + '_2') > > ? ? ? ? ? ? self._suggestions.add_command(label = curr + '_3') > > ? ? ? ? ? ? self._suggestions.add_command(label = curr + '_4') > > ? ? ? ? ? ? self._suggestions.post(x, y) > > ? ? ? ? finally: > > ? ? ? ? ? ? self._suggestions.grab_release() > > > ? ? ? ? self._entry.focus_set() > > > if __name__ == '__main__': > > ? ? root = Tkinter.Tk() > > ? ? root.title('A Problem') > > ? ? demo(root) > > ? ? root.mainloop() > > Perhaps it is because I'm trying this on Windows, but the above code > does not work for me. ?After the menu is posted, no further keyboard > input gets directed to the entry until the menu is unposted. > > It looks like my best bet is to use the ComboBox suggested above. ?The > ComboBox method is very close to working, but I've got a problem now > where all focus on the app is directed to the ComboBox entry (I need > to set it that way to redirect keyboard input from the popup menu), > making it impossible to close the app without killing it. ?I've tried > to return focus to the entry parent by binding the entry to > and , but this has the effect of making the popup take the > focus after every keystroke, which is not what I want. > > The (almost working) demo below should demonstrate the issue fairly > well: > > import Tkinter > import Pmw > > class demo: > ? ? def __init__(self, parent): > ? ? ? ? self._search_bar = Pmw.ComboBox(parent, > ? ? ? ? ? ? label_text = 'Register Mnemonic', > ? ? ? ? ? ? labelpos = 'w', entry_width = 60) > ? ? ? ? self._search_bar.pack(padx = 20, pady = 20) > ? ? ? ? self._search_bar._entryfield.component('entry').bind('', > ? ? ? ? ? ? self._suggest_text, add = '+') > > ? ? def _suggest_text(self, event): > ? ? ? ? curr = self._search_bar._entryfield.getvalue() > ? ? ? ? curr += repr(event.char)[1] > ? ? ? ? self._search_bar._list.setlist([curr + '_0', curr + '_1', > ? ? ? ? ? ? curr + '_2']) > ? ? ? ? self._search_bar._postList(event) > ? ? ? ? self._search_bar._entryfield.component('entry').focus_set() > ? ? ? ? self._search_bar._popup.lift() > > if __name__ == '__main__': > ? ? root = Tkinter.Tk() > ? ? root.title('A Problem') > ? ? demo(root) > ? ? root.mainloop() Well, it required quite a bit of digging, but I finally have what I want. For those who are curious, the following demo should provide some help: import Tkinter import Pmw class demo: def __init__(self, parent): self._parent = parent self._search_bar = Pmw.ComboBox(parent, label_text = 'Register Mnemonic', labelpos = 'w', entry_width = 60) self._search_bar.pack(padx = 20, pady = 20) self._search_bar._entryfield.component('entry').bind('', self._suggest_text, add = '+') self._search_bar._entryfield.component('entry').bind('', self._remove_list, add = '+') self._search_bar._entryfield.component('entry').bind('', self._remove_list, add = '+') self._search_bar._entryfield.component('entry').bind('', self._remove_list, add = '+') self._search_bar._popup.bind('', self._remove_list, add = '+') def _suggest_text(self, event): x = self._search_bar._entryfield.winfo_rootx() y = self._search_bar._entryfield.winfo_rooty() + \ self._search_bar._entryfield.winfo_height() w = self._search_bar._entryfield.winfo_width() + \ self._search_bar._arrowBtn.winfo_width() curr = self._search_bar._entryfield.getvalue() curr += repr(event.char)[1] self._search_bar._list.setlist([curr + '_0', curr + '_1', curr + '_2']) self._search_bar._list.configure(hull_width=w) Pmw.setgeometryanddeiconify(self._search_bar._popup, '+%d+%d' % (x, y)) self._search_bar._popup.lift() def _remove_list(self, event): self._search_bar._popup.withdraw() if __name__ == '__main__': root = Tkinter.Tk() root.title('A Problem') demo(root) root.mainloop() From chris at simplistix.co.uk Tue Oct 4 14:42:06 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 04 Oct 2011 19:42:06 +0100 Subject: Need A script to open a excel file and extract the data using autofilter In-Reply-To: References: <4f3ec474-dd9f-4585-8f3c-41323d79b8de@z19g2000vby.googlegroups.com> <74fc7fc6-8d5d-40fd-b152-0ce022a78a0c@m5g2000vbe.googlegroups.com> Message-ID: <4E8B537E.9020704@simplistix.co.uk> On 01/10/2011 23:00, David Monaghan wrote: >> after opening the text.xls file i need to filter all the rows in which >> the status column is passed and copy the whole sheet to another sheet > > I don't do this often enough to have it to mind, so what I normally do is > record a Macro, convert it to VBS and then convert that to Python. Ouch! Slow, error prone and Windows only ;-) Please consider using xlrd and described on http://www.python-excel.org cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From derek at simkowiak.net Tue Oct 4 15:18:50 2011 From: derek at simkowiak.net (Derek Simkowiak) Date: Tue, 04 Oct 2011 12:18:50 -0700 Subject: recommend a graphics library for plotting by the pixel? In-Reply-To: References: <9s1rl8xt8t.ln2@news.ducksburg.com> Message-ID: <4E8B5C1A.9030909@simkowiak.net> If this is strictly for 2D pixel graphics, I recommend using PyGame (aka SDL). Why do you not think it's the way to go? It was built for this type of thing. You may also want to use PIL (Python Imaging Library) for various image manipulation tasks, but PIL doesn't handle mouse clicks and screen blitting the way PyGame does. --Derek Simkowiak http://derek.simkowiak.net On 10/04/2011 07:53 AM, Alec Taylor wrote: > Sounds like a job for Processing... > > On Tue, Oct 4, 2011 at 8:56 PM, Adam Funk wrote: >> I'd like to create a window with a "pause" button and a large plotting >> area, in which I'd like to draw a polygon, detect the pixel >> co?rdinates of a mouse click, and then start setting the colors of >> pixels by (x,y) co?rdinates. (This is just for my own amusement, to >> play with some formulas for generating fractals using random numbers.) >> >> There seems to be a large number of different python GUI libraries, >> and I wonder if someone can recommend the easiests one to learn for >> this purpose? (The only python graphics library I've used is PyGame, >> which I don't think is the way to go here.) >> >> >> -- >> In the 1970s, people began receiving utility bills for >> -?999,999,996.32 and it became harder to sustain the >> myth of the infallible electronic brain. (Stob 2001) >> -- >> http://mail.python.org/mailman/listinfo/python-list >> From miki.tebeka at gmail.com Tue Oct 4 15:34:32 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Tue, 4 Oct 2011 12:34:32 -0700 (PDT) Subject: eggbasket In-Reply-To: References: Message-ID: <3874595.317.1317756872917.JavaMail.geo-discussion-forums@prma7> > How is it possible that the module exists and it's actually imported, > and not found when I actually try to import something from it? Do you have a local file/directory that is called sqlalchemy? From miki.tebeka at gmail.com Tue Oct 4 15:34:32 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Tue, 4 Oct 2011 12:34:32 -0700 (PDT) Subject: eggbasket In-Reply-To: References: Message-ID: <3874595.317.1317756872917.JavaMail.geo-discussion-forums@prma7> > How is it possible that the module exists and it's actually imported, > and not found when I actually try to import something from it? Do you have a local file/directory that is called sqlalchemy? From pulsarpietro at gmail.com Tue Oct 4 16:08:41 2011 From: pulsarpietro at gmail.com (pedr0) Date: Tue, 4 Oct 2011 13:08:41 -0700 (PDT) Subject: HTTP ResponseNotReady Message-ID: <7336281.656.1317758921108.JavaMail.geo-discussion-forums@yqjh13> Hi at all, I don't understand why, in this piece of code, i catch the raise ResponseNotReady(self.__state) http.client.ResponseNotReady: Request-sent EVERY time I run this piece of code: #connection http_connection = http.client.HTTPConnection('www.xxx.net',80,timeout=60) #first request http_connection.request("POST", "/",params,headers=headers_) r1 = http_connection.getresponse() #second request http_connection.request("GET", "/","",headers=headers_) r2 = http_connection.getresponse() Someone can help me ? From pulsarpietro at gmail.com Tue Oct 4 16:29:30 2011 From: pulsarpietro at gmail.com (pedr0) Date: Tue, 4 Oct 2011 13:29:30 -0700 (PDT) Subject: HTTP ResponseNotReady In-Reply-To: <7336281.656.1317758921108.JavaMail.geo-discussion-forums@yqjh13> References: <7336281.656.1317758921108.JavaMail.geo-discussion-forums@yqjh13> Message-ID: <575322.1824.1317760170966.JavaMail.geo-discussion-forums@yqar15> Hi solved this problem, I have to add: #connection http_connection = http.client.HTTPConnection('www.xxx.net',80,timeout=60) #first request http_connection.request("POST", "/",params,headers=headers_) r1 = http_connection.getresponse() r1.read() // THIS ONE #second request http_connection.request("GET", "/","",headers=headers_) r2 = http_connection.getresponse() Someone know if this is a bug ? Thanks From python at mrabarnett.plus.com Tue Oct 4 16:53:48 2011 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Oct 2011 21:53:48 +0100 Subject: HTTP ResponseNotReady In-Reply-To: <575322.1824.1317760170966.JavaMail.geo-discussion-forums@yqar15> References: <7336281.656.1317758921108.JavaMail.geo-discussion-forums@yqjh13> <575322.1824.1317760170966.JavaMail.geo-discussion-forums@yqar15> Message-ID: <4E8B725C.2050501@mrabarnett.plus.com> On 04/10/2011 21:29, pedr0 wrote: > Hi solved this problem, I have to add: > > > > #connection > http_connection = http.client.HTTPConnection('www.xxx.net',80,timeout=60) > #first request > http_connection.request("POST", "/",params,headers=headers_) > r1 = http_connection.getresponse() > r1.read() // THIS ONE > #second request > http_connection.request("GET", "/","",headers=headers_) > r2 = http_connection.getresponse() > > > Someone know if this is a bug ? > It's not a bug. The documentation for "getresponse" says: """HTTPConnection.getresponse() Should be called after a request is sent to get the response from the server. Returns an HTTPResponse instance. Note Note that you must have read the whole response before you can send a new request to the server. """ The note is highlighted. From pulsarpietro at gmail.com Tue Oct 4 17:00:27 2011 From: pulsarpietro at gmail.com (pedr0) Date: Tue, 4 Oct 2011 14:00:27 -0700 (PDT) Subject: HTTP ResponseNotReady In-Reply-To: References: <7336281.656.1317758921108.JavaMail.geo-discussion-forums@yqjh13> <575322.1824.1317760170966.JavaMail.geo-discussion-forums@yqar15> Message-ID: <11222070.2131.1317762027904.JavaMail.geo-discussion-forums@yqlb4> Mumble mumble... I described bad my question I think, yes I read that, but maybe is not a correct way of working. The http request I did retrieve (every time) an empty response, when I print the read() result call the result is the same of the sample you are talking about. http://docs.python.org/py3k/library/http.client.html?highlight=http.client#http.client (2th sample) Then I have to call the read() function only for change the state of my request, for this reasons I asked for a bug open in the http.client module. From pulsarpietro at gmail.com Tue Oct 4 17:00:27 2011 From: pulsarpietro at gmail.com (pedr0) Date: Tue, 4 Oct 2011 14:00:27 -0700 (PDT) Subject: HTTP ResponseNotReady In-Reply-To: References: <7336281.656.1317758921108.JavaMail.geo-discussion-forums@yqjh13> <575322.1824.1317760170966.JavaMail.geo-discussion-forums@yqar15> Message-ID: <11222070.2131.1317762027904.JavaMail.geo-discussion-forums@yqlb4> Mumble mumble... I described bad my question I think, yes I read that, but maybe is not a correct way of working. The http request I did retrieve (every time) an empty response, when I print the read() result call the result is the same of the sample you are talking about. http://docs.python.org/py3k/library/http.client.html?highlight=http.client#http.client (2th sample) Then I have to call the read() function only for change the state of my request, for this reasons I asked for a bug open in the http.client module. From andrea.crotti.0 at gmail.com Tue Oct 4 17:08:30 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Tue, 04 Oct 2011 22:08:30 +0100 Subject: eggbasket In-Reply-To: <3874595.317.1317756872917.JavaMail.geo-discussion-forums@prma7> References: <3874595.317.1317756872917.JavaMail.geo-discussion-forums@prma7> Message-ID: <4E8B75CE.1070700@gmail.com> On 10/04/2011 08:34 PM, Miki Tebeka wrote: > Do you have a local file/directory that is called sqlalchemy? Funny thing, I have the same problem with another machine, with sqlalchemy installed system-wide instead of locally. Strange issue, maybe a problem with python 2.7/Linux? From monaghand.david at gmail.com Tue Oct 4 17:12:54 2011 From: monaghand.david at gmail.com (David Monaghan) Date: Tue, 04 Oct 2011 22:12:54 +0100 Subject: Need A script to open a excel file and extract the data using autofilter References: <4f3ec474-dd9f-4585-8f3c-41323d79b8de@z19g2000vby.googlegroups.com> <74fc7fc6-8d5d-40fd-b152-0ce022a78a0c@m5g2000vbe.googlegroups.com> Message-ID: On Tue, 04 Oct 2011 19:42:06 +0100, Chris Withers wrote: >On 01/10/2011 23:00, David Monaghan wrote: >>> after opening the text.xls file i need to filter all the rows in which >>> the status column is passed and copy the whole sheet to another sheet >> >> I don't do this often enough to have it to mind, so what I normally do is >> record a Macro, convert it to VBS and then convert that to Python. > >Ouch! Slow, error prone and Windows only ;-) > >Please consider using xlrd and described on http://www.python-excel.org All true! The reason I usually do it like that is I normally only need to do very simple things and I usually stop at the VBS stage. And I wasn't aware of xlrd - I'll give it a look. DaveM From ben+python at benfinney.id.au Tue Oct 4 17:45:55 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 05 Oct 2011 08:45:55 +1100 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <74e9b784-7de4-4306-a747-bff85b1a1181@fx14g2000vbb.googlegroups.com> Message-ID: <871uus1ld8.fsf@benfinney.id.au> Westley Mart?nez writes: > Boiler plate is silly. Let the students figure out stuff themselves. That argues directly against the Primacy effect mentioned earlier , which is demonstrated by much scientific evidence. What scientific evidence do you have to argue against it? > The students need to know why global variables in functions is > unwieldly, not just not use them because it's cool. If you say so. But why not show them the traps after *first* teaching them the recommended way to do it? > When I taught myself Python I quickly realized global variables were > unwieldly and usually impractical after using them. That's no argument at all against how to teach Python in a teacher-student relationship. -- \ ?If you have the facts on your side, pound the facts. If you | `\ have the law on your side, pound the law. If you have neither | _o__) on your side, pound the table.? ?anonymous | Ben Finney From bthate at gmail.com Tue Oct 4 19:16:09 2011 From: bthate at gmail.com (Bart Thate) Date: Tue, 4 Oct 2011 16:16:09 -0700 (PDT) Subject: GOZERBOT 0.99.0 RELEASED Message-ID: <4caa84b1-27aa-402d-9fec-042562a433dd@x16g2000yql.googlegroups.com> Hello world and everybody ! i'm pleased to announce the release of GOZERBOT 0.99.0, the first in a series of releases that are supposed to lead to a proper 1.0 release for GOZERBOT. The intention is to get a 1.0 version of GOZERBOT available for users that still use this bot, got almost 2000 download of 0.9.2 so its worth to support all those users with a release they can build on. I dont have the intention to develop GOZERBOT any further beyond that, that's what JSONBOT is all about, so keep in mind these are pure maintenance releases. 2 major changes crept into this release, namely: * no more seperate gozerplugs package, its all wrapped into 1 thing. The gozerplugs package has find its way under the gplugs directory in the main distro so no more seperate installing of plugins. * SQLAlchemy is now optional, so GOZERBOT can run on older versions of debian etc. Since this leads to less dependancies GOZERBOT is easier to install. note: there is not going to be a seperate "all" distro as those dependancies are already included. SQLAlchemy is made optional by providing plugins that use direct queries on the database, this is the default. You can change operations back to SA by setting db_driver = "alchemy" in gozerdata/ mainconfig. The intention is to release a new version of GOZERBOT every week or so, until its stable for a long period of time. When its time i'll cut of the 1.0 release ;] urls: * download tar - http://code.google.com/p/gozerbot/downloads/list * mercurial clone - "hg clone https://gozerbot.googlecode.com/hg mybot" * please report bugs at http://code.google.com/p/gozerbot/issues/entry especially if you are already running a GOZERBOT and run into problems. * path to the futire - http://jsonbot.org read the provided README for instructions on how to get the bot running. About GOZERBOT: GOZERBOT is a channel bot supporting conversations in irc channels and jabber conference rooms. It is mainly used to send notifications (RSS, nagios, etc.) and to have custom commands made for the channel. More then just a channel bot GOZERBOT aims to provide a platform for the user to program his own bot and make it into something thats usefull. This is done with a plugin structure that makes it easy to program your own plugins. GOZERBOT comes with some batteries included. From ameyer2 at yahoo.com Tue Oct 4 21:07:10 2011 From: ameyer2 at yahoo.com (Alan Meyer) Date: Tue, 04 Oct 2011 21:07:10 -0400 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: Message-ID: <4E8BADBE.2090300@yahoo.com> On 10/3/2011 12:26 PM, Alec Taylor wrote: ... > On Tue, Oct 4, 2011 at 3:21 AM, Aivar Annamaa wrote: ... >> I'm looking for a trick or hidden feature to make Python 3 automatically >> call a "main" function but without programmers writing `if __name__ == >> "__main__": ...` ... >> Here's why I want such a thing: >> I'm teaching introductory programming course with Python. I've seen that >> global variables attract beginners like honey attracts bees and this makes >> teaching function parameters harder. ... Teaching good programming practice is hard. Many programmers, not just students, take the attitude, "My code works. Who cares what it looks like?" Getting them to understand that code has to be readable, understandable, and maintainable can be very hard. I wonder if some teaching exercises would help, for example: 1. Find a program, perhaps submitted by a student in a previous class or perhaps something you write yourself, that's full of global variables. Assign the students to rewrite the program so that it has no globals at all, and to write up a comparison of the pros and cons of the global and no-global approaches. 2. Find or write a program with lots of globals. Introduce some subtle bugs into the program that have to do with global references. Assign the students to a) find and fix the bugs and b) explain how the code could have been written to prevent bugs like this from creeping in. 3. Find or write a program with a number of globals. For each global, ask the students to write an analysis comparing its usefulness and/or dangerousness. Are some of the globals worse than others? Why? 4. Find or write a program with some globals. Make up a change request from a user that will run into problems because of the globals. Assign the students to implement the change request. There are probably lots of other similar exercises one could make up. The idea is not to force students to do the right thing, but to get them to understand the differences between the better ways and the worse ways to write code. Incidentally, all of these exercises involve maintaining or re-writing existing code written by other people. Students don't usually do much of that, but when they get a real job, they find that maintenance is most of what they actually do, especially as junior programmers. Having to work in the real world of maintaining other people's code gives a student a better appreciation of the value of clean, modular, readable, documented code. Alan From ameyer2 at yahoo.com Tue Oct 4 21:09:15 2011 From: ameyer2 at yahoo.com (Alan Meyer) Date: Tue, 04 Oct 2011 21:09:15 -0400 Subject: Need A script to open a excel file and extract the data using autofilter In-Reply-To: References: <4f3ec474-dd9f-4585-8f3c-41323d79b8de@z19g2000vby.googlegroups.com> <74fc7fc6-8d5d-40fd-b152-0ce022a78a0c@m5g2000vbe.googlegroups.com> Message-ID: <4E8BAE3B.3090807@yahoo.com> On 10/4/2011 5:12 PM, David Monaghan wrote: > On Tue, 04 Oct 2011 19:42:06 +0100, Chris Withers > wrote: > >> On 01/10/2011 23:00, David Monaghan wrote: >>>> after opening the text.xls file i need to filter all the rows in which >>>> the status column is passed and copy the whole sheet to another sheet >>> >>> I don't do this often enough to have it to mind, so what I normally do is >>> record a Macro, convert it to VBS and then convert that to Python. >> >> Ouch! Slow, error prone and Windows only ;-) >> >> Please consider using xlrd and described on http://www.python-excel.org > > All true! The reason I usually do it like that is I normally only need to do > very simple things and I usually stop at the VBS stage. And I wasn't aware > of xlrd - I'll give it a look. > > DaveM I've used xlrd. It's pretty nice. Alan From ameyer2 at yahoo.com Tue Oct 4 21:22:42 2011 From: ameyer2 at yahoo.com (Alan Meyer) Date: Tue, 04 Oct 2011 21:22:42 -0400 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: <4E8BADBE.2090300@yahoo.com> References: <4E8BADBE.2090300@yahoo.com> Message-ID: <4E8BB162.5080100@yahoo.com> On 10/4/2011 9:07 PM, Alan Meyer wrote: > ... and to write up a comparison of the pros and cons of the global and > no-global approaches. ... Of course you'll need to be fair in evaluating the students comparisons. Some bright students are likely to come up with good reasons for using globals in some situations, and they might even be right. Or if they're not completely right, they might nevertheless be partly right. They should get high marks for that. You could even make up an exercise where the students are assigned to write a program that uses a global that could NOT be better implemented without globals. Then ask one or two of the authors of the better programs to defend their programs in front of the class. It's always a mistake to read student papers with preconceived, set in concrete ideas about what's right and what's wrong. Many years ago when I was teaching (philosophy, not computer science), in every class I taught there was always at least one student who taught me something I didn't know, or taught me that something I thought I knew was wrong. Alan From steve+comp.lang.python at pearwood.info Tue Oct 4 21:27:27 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 05 Oct 2011 01:27:27 GMT Subject: how to call java methods in python References: <33a61c6f-508a-48f0-97dc-d51099199c30@z12g2000yqz.googlegroups.com> Message-ID: <4e8bb27e$0$29978$c3e8da3$5496439d@news.astraweb.com> On Tue, 04 Oct 2011 00:14:49 -0700, masood shaik wrote: > Hi > I am trying out my hand on accessing java methods in python. here is > my piece of code.. [...] > Now i am trying to access the calculateTip() and its showing import > error. > It works fine when i am running it with jython but why its not happening > in python. Jython *is* Python. It is a Python implementation built on the Java virtual machine. Integrating Java with Python is a major reason for using Jython. http://www.jython.org/ You can't just import a Java library into the C implementation of Python, any more than you can just import a Python library into Java. You need an interface between them. Jython includes one such interface. The C reference implementation of Python does not. To integrate Java libraries with CPython is harder, but not impossible. I have never tried any of these, but you could try JPype, Py4J, or JCC: http://jpype.sourceforge.net/ http://py4j.sourceforge.net/index.html http://pypi.python.org/pypi/JCC/2.1 -- Steven From steve+comp.lang.python at pearwood.info Tue Oct 4 21:28:26 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 05 Oct 2011 01:28:26 GMT Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <4E8BADBE.2090300@yahoo.com> Message-ID: <4e8bb2b9$0$29978$c3e8da3$5496439d@news.astraweb.com> On Tue, 04 Oct 2011 21:07:10 -0400, Alan Meyer wrote: > Incidentally, all of these exercises involve maintaining or re-writing > existing code written by other people. Students don't usually do much > of that, but when they get a real job, they find that maintenance is > most of what they actually do, especially as junior programmers. Having > to work in the real world of maintaining other people's code gives a > student a better appreciation of the value of clean, modular, readable, > documented code. Well said that man!!! -- Steven From tjreedy at udel.edu Tue Oct 4 21:45:14 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 04 Oct 2011 21:45:14 -0400 Subject: syntax enhancement In-Reply-To: References: Message-ID: On 10/4/2011 9:50 AM, Valiev Sergey wrote: > - `[]` - used for list comprehension, > - `()` - used for generators, > - `[start:stop]` / `[start:stop:step]` - used for slices. > The idea is to use `(start:stop)` / `(start:stop:step)` as 'lazy > evaluated' slices (like itertools.islice). > What do you think about it? a(b) is already used for function calls. Making a(b:c) be something unreleated does not seem like a good idea to me. At present, a[b:c] == a[slice(b,c)]. However, a(slice(b,c)) is already a function call and could not equal a(b:c). -- Terry Jan Reedy From steve+comp.lang.python at pearwood.info Tue Oct 4 22:06:14 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 05 Oct 2011 02:06:14 GMT Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> Message-ID: <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> On Mon, 03 Oct 2011 21:27:12 -0700, alex23 wrote: > rantingrick wrote: >> Why? Well because many times i find myself wondering if this or that >> variable is local or global -- and when i say "global" i am speaking of >> module scope! The "global" cures the ill. > > Given your stated propensity for huge code blocks not chunked into > functions, I'm not surprised you lose track of what is global, what is > nonlocal etc. This is another clear advantage of small functions: you > can view it all at once. For the rest of us, a variable is global if its > referenced but not defined in a specific scope. There's no need for such > verbose hand-holding. > > I'd say the wart is in your design practice rather than the language > itself. Furthermore, rick's suggestion that all globals should be referenced using an explicit global namespace would become extraordinarily horrible in practice. Let's take a simple example from the shutil module: # From Python 2.5 shutil.py def copystat(src, dst): """Copy all stat info (mode bits, atime and mtime) from src to dst""" st = os.stat(src) mode = stat.S_IMODE(st.st_mode) if hasattr(os, 'utime'): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, 'chmod'): os.chmod(dst, mode) Under Rick's proposal, that would be written: def copystat(src, dst): """Copy all stat info (mode bits, atime and mtime) from src to dst""" st = global.os.stat(src) mode = global.stat.S_IMODE(st.st_mode) if global.hasattr(os, 'utime'): global.os.utime(dst, (st.st_atime, st.st_mtime)) if global.hasattr(os, 'chmod'): global.os.chmod(dst, mode) Imported modules are variables like any other, and as they usually exist in the global scope, so they will all need to be explicitly referenced as global. This will get tiresome very quickly, and is a cure far worse than the disease, and alone is enough to disqualify this suggestion from serious consideration. Furthermore, "globals" in Python also includes the built-ins, so every reference to built-ins like len, sum, list, int, abs, etc. will also need an explicit reference, e.g. global.len, global.sum. (The alternative would be a significantly different name-lookup strategy: instead of names being "local" vs "global or builtin", they would be "local or builtin" vs "global". This will break monkey-patching.) -- Steven From ameyer2 at yahoo.com Tue Oct 4 22:23:49 2011 From: ameyer2 at yahoo.com (Alan Meyer) Date: Tue, 04 Oct 2011 22:23:49 -0400 Subject: how to call java methods in python In-Reply-To: References: Message-ID: <4E8BBFB5.1030304@yahoo.com> On 10/4/2011 2:39 AM, masood shaik wrote: > Hi > > I am trying to import java method in python. But i am getting the > following error. > > > error: ImportError: No module named Calculator > > > Calculator is the name of the class written in java. I am trying to > access the methods of that class. > > Please help me. Masood, What you are trying to do requires a lot of understanding of advanced computer programming. I suggest you read Laszlo's response, and the links suggested by Steven. If you find those responses too hard to understand, or if you don't understand the difference between Jython and CPython, or if you don't know what CPython is, then you are "in over your head" as we say in the U.S. You are trying to do something that is too hard for you. If that is so, and if this is for a school project, I suggest you talk to the teacher about getting an easier project. Good luck. Alan From wuwei23 at gmail.com Tue Oct 4 23:20:34 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 Oct 2011 20:20:34 -0700 (PDT) Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Imported modules are variables like any other, and as they usually exist > in the global scope, so they will all need to be explicitly referenced as > global. This will get tiresome very quickly, and is a cure far worse than > the disease, and alone is enough to disqualify this suggestion from > serious consideration. But on the gripping hand, it is a clear triumph of "Explicit is better than implicit." ;) From wuwei23 at gmail.com Tue Oct 4 23:24:41 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 Oct 2011 20:24:41 -0700 (PDT) Subject: recommend a graphics library for plotting by the pixel? References: <9s1rl8xt8t.ln2@news.ducksburg.com> Message-ID: <6a4f8ef3-81d1-4e91-8cd8-8014a021a2aa@18g2000yqz.googlegroups.com> On Oct 5, 12:53?am, Alec Taylor wrote: > Sounds like a job for Processing... Don't you mean PyProcessing? :) http://code.google.com/p/pyprocessing/ From steve+comp.lang.python at pearwood.info Wed Oct 5 01:37:52 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 05 Oct 2011 05:37:52 GMT Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e8bed30$0$29978$c3e8da3$5496439d@news.astraweb.com> On Tue, 04 Oct 2011 20:20:34 -0700, alex23 wrote: > Steven D'Aprano wrote: >> Imported modules are variables like any other, and as they usually >> exist in the global scope, so they will all need to be explicitly >> referenced as global. This will get tiresome very quickly, and is a >> cure far worse than the disease, and alone is enough to disqualify this >> suggestion from serious consideration. > > But on the gripping hand, it is a clear triumph of "Explicit is better > than implicit." ;) I see your wink, but explicitness is not a binary state. You can have too much explicitness. Which would you rather? import math x = math.sin(1.2345) or: import the module called 'math' into the current namespace and bind that module to the name 'math' in the current namespace bind the name 'x' in the current namespace to the return result of calling the attribute named 'sin' in the object currently bound to the name 'math' in the current namespace using the float literal 1.2345 as the argument I'm thinking that the second version might get a bit annoying after a little while, no matter what the Zen says. Besides, based on the Zen, should we also write this? local.x = global.math.sin(1.2345) -- Steven From gagsl-py2 at yahoo.com.ar Wed Oct 5 02:08:20 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 Oct 2011 03:08:20 -0300 Subject: BaseHTTPServer ThreadMixIn not working References: Message-ID: En Mon, 03 Oct 2011 12:03:18 -0300, amit escribi?: > I am really stuck in a very simple problem and wanted to know if you > could take some time to check it out - > > My code is simple. Using BaseHTTPServer and ThreadInMix I want to run > a python script (Script1.py) for every request made simultaneously. > [...] > > If I open multiple tabs/pages in Chrome/Firefox/IE and give URL: > http://localhost:8080, the pages wait for previous page? This does not > imply threading? Any help? Thanks Your code is fine, and Python behaves correctly. The browser is queuing all similar requests when it sees they all refer to the same URI. Had the first response contained an Expires: header in the future, there would be no need to ask again for the same object; the ETag: and Last-Modified: headers may play a role too. So, only after the first response is completely read, Chrome/Firefox/IE sees it is invalid and knows she cannot re-use the received body and has to issue the second request and waits again and ... Try with different URLs for each request: http://localhost:8080/a http://localhost:8080/b http://localhost:8080/c and you'll see they all are processed in parallel. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Wed Oct 5 02:27:08 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 05 Oct 2011 03:27:08 -0300 Subject: Is exec() also not used in python 2.7.1 anymore? References: <02EA6D704E30CE499C5071776509A925F5C2ED@039-SN1MPN1-003.039d.mgd.msft.net> <02EA6D704E30CE499C5071776509A925F5C3AA@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: En Tue, 04 Oct 2011 07:32:41 -0300, Wong Wah Meng-R32813 escribi?: > Haha... yeah I reviewed the code, it is supposed to exposed some remote > methods locally (RMI proxy usage). However, I am not sure why what it > does is merely a pass. > > I commented out this code and haven't seen any negative implication. I > will look into this again if I am convinced the next error I see is due > to I commented out this code. >> exec('def %s(self, *args, **kw): pass'%methodStrName) In case you convince yourself that defining this dynamic but empty function is really needed, you can avoid exec this way: def some_function(...) ... # instead of exec('def ...' % methodStrName) def empty_function(self, *args, **kw): pass empty_function.func_name = methodStrName ... # presumably methodStrName is referred somehow in # the remaining code block, or perhaps locals(); # modify accordingly -- Gabriel Genellina From greg.ewing at canterbury.ac.nz Wed Oct 5 02:43:57 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 05 Oct 2011 19:43:57 +1300 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9f2clfF437U1@mid.individual.net> alex23 wrote: > But on the gripping hand, it is a clear triumph of "Explicit is better > than implicit." ;) I think we may have found the long-lost 20th principle of the Zen: "If it results in eye-bleedingly horrible code, it might be a bad idea." -- Greg From rosuav at gmail.com Wed Oct 5 03:01:39 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 5 Oct 2011 18:01:39 +1100 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: <4E8BB162.5080100@yahoo.com> References: <4E8BADBE.2090300@yahoo.com> <4E8BB162.5080100@yahoo.com> Message-ID: On Wed, Oct 5, 2011 at 12:22 PM, Alan Meyer wrote: > Of course you'll need to be fair in evaluating the students comparisons. > ?Some bright students are likely to come up with good reasons for using > globals in some situations, and they might even be right. ?Or if they're not > completely right, they might nevertheless be partly right. ?They should get > high marks for that. > Definitely. There's always a right time to do the wrong thing, just as much as there's a wrong time to do the right thing. Even the much-maligned goto has its place. ChrisA From r32813 at freescale.com Wed Oct 5 03:43:57 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Wed, 5 Oct 2011 07:43:57 +0000 Subject: ImportError: No module named _sha256 Message-ID: <02EA6D704E30CE499C5071776509A925F5C810@039-SN1MPN1-003.039d.mgd.msft.net> Hello there, In migrating my application from python 1.5.2 to 2.7.1, I encountered an issue modules which utilizes _sha256 cannot be loaded. This includes hashlib, random and tempfile. I think this should be related to the build of my python 64-bit on HP11.31 using HP-UX compiler. I have tried including the header files of openSSL and library of openSSL during the build however the binary generated still unable to load those modules. Can anyone advise? $ python Python 2.7.1 (r271:86832, Sep 30 2011, 17:07:25) [C] on hp-ux11 Type "help", "copyright", "credits" or "license" for more information. >>> import hashlib Traceback (most recent call last): File "", line 1, in File "/home/r32813/genesis/GEN_DEV_271/Enablers/Python/lib/python2.7/hashlib.py", line 136, in globals()[__func_name] = __get_hash(__func_name) File "/home/r32813/genesis/GEN_DEV_271/Enablers/Python/lib/python2.7/hashlib.py", line 74, in __get_builtin_constructor import _sha256 ImportError: No module named _sha256 >>> Regards, Wah Meng -------------- next part -------------- An HTML attachment was scrubbed... URL: From 5960761 at gmail.com Wed Oct 5 05:02:44 2011 From: 5960761 at gmail.com (Daniel) Date: Wed, 05 Oct 2011 12:02:44 +0300 Subject: issue with pexpect Message-ID: <1317805364.3169.5.camel@laptop.bulsat.com> Hello, For about week i am experiencing a problem with pexpect that's why i hope you can help me :). Following is my code which tries to remove some files from the root dir and the code works on linux debian and freebsd but with no success on linux fedora .. any idea why this happen only in fedora ? #!/usr/bin/env python from __future__ import print_function import sys import pexpect import time spa=pexpect.spawn('su root') spa.expect('.*') print(spa.after) spa.sendline('abc') spa.expect('.*') print(spa.after) spa.sendline('rm -rf /root/py/pe*') spa.expect('.*') print(spa.after) spa.close() this is the output in Fedora linux it looks that the script can't authenticate as root python]$ ./sk64.py Password: rm -rf /root/py/pe* i appreciate any help thanks in advance From ben+python at benfinney.id.au Wed Oct 5 07:44:34 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 05 Oct 2011 22:44:34 +1100 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> <4e8bed30$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87wrcjzmql.fsf@benfinney.id.au> Steven D'Aprano writes: > import the module called 'math' into the current namespace and bind > that module to the name 'math' in the current namespace > > bind the name 'x' in the current namespace to the return result of > calling the attribute named 'sin' in the object currently bound to the > name 'math' in the current namespace using the float literal 1.2345 as > the argument This mocking is hurtful to people who identify too strongly with COBOL. I wonder whether that means it's intentionally hurtful. -- \ ?The long-term solution to mountains of waste is not more | `\ landfill sites but fewer shopping centres.? ?Clive Hamilton, | _o__) _Affluenza_, 2005 | Ben Finney From r32813 at freescale.com Wed Oct 5 07:56:08 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Wed, 5 Oct 2011 11:56:08 +0000 Subject: socket.getsockname is returning junk!! Message-ID: <02EA6D704E30CE499C5071776509A925F5C8F8@039-SN1MPN1-003.039d.mgd.msft.net> Hello guys, I am migrating my application from python 1.5.2 to 2.7.1. One of the existing code breaks. The getsockname method from socket object somehow returns me with some number which I deem as junk, rather than the listening port as I would have expected in the older python. Has anyone seen the same thing or is it due to my python is built with some corrupted library or something? $ python Python 2.7.1 (r271:86832, Oct 5 2011, 18:34:15) [C] on hp-ux11 Type "help", "copyright", "credits" or "license" for more information. >>> import socket >>> sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) >>> sock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 ) >>> sock.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1 ) >>> sock.setsockopt( socket.IPPROTO_TCP, 1, 1 ) >>> server_address=('zmy02hp3', 11111) >>> sock.bind(server_address) >>> sock.getsockname() (0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') In python 1.5.2 >>> server_address=('zmy02aix04', 11111) >>> sock.bind(server_address) >>> sock.getsockname() ('10.228.51.41', 11111) >>> Regards, Wah Meng -------------- next part -------------- An HTML attachment was scrubbed... URL: From 5960761 at gmail.com Wed Oct 5 08:32:05 2011 From: 5960761 at gmail.com (Daniel) Date: Wed, 05 Oct 2011 15:32:05 +0300 Subject: issue with pexpect Message-ID: <1317817925.2908.2.camel@laptop.bulsat.com> Hello, For about week i am experiencing a problem with pexpect that's why i hope you can help me :). Following is my code which tries to remove some files from the root dir and the code works on linux debian and freebsd but with no success on linux fedora .. any idea why this happen only in fedora ? #!/usr/bin/env python from __future__ import print_function import sys import pexpect import time spa=pexpect.spawn('su root') spa.expect('.*') print(spa.after) spa.sendline('abc') spa.expect('.*') print(spa.after) spa.sendline('rm -rf /root/py/pe*') spa.expect('.*') print(spa.after) spa.close() this is the output in Fedora linux it looks that the script can't authenticate as root python]$ ./sk64.py Password: rm -rf /root/py/pe* i appreciate any help thanks in advance From roy at panix.com Wed Oct 5 08:57:04 2011 From: roy at panix.com (Roy Smith) Date: Wed, 05 Oct 2011 08:57:04 -0400 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <4E8BADBE.2090300@yahoo.com> <4E8BB162.5080100@yahoo.com> Message-ID: In article , Chris Angelico wrote: > Definitely. There's always a right time to do the wrong thing, just as > much as there's a wrong time to do the right thing. Even the > much-maligned goto has its place. Not in python, it doesn't :-) But, yes, I agree that in languages that support it, it can be useful. When I was writing C++ for a living, I must have written a goto at least once every couple of years. From rosuav at gmail.com Wed Oct 5 09:10:26 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Oct 2011 00:10:26 +1100 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: <4E8BADBE.2090300@yahoo.com> <4E8BB162.5080100@yahoo.com> Message-ID: On Wed, Oct 5, 2011 at 11:57 PM, Roy Smith wrote: > In article , > ?Chris Angelico wrote: > >> Definitely. There's always a right time to do the wrong thing, just as >> much as there's a wrong time to do the right thing. Even the >> much-maligned goto has its place. > > Not in python, it doesn't :-) The absence from the language doesn't prove that. All it means is that, on those rare occasions when a goto would have been correct, the programmer had to make do with something else :-) How often do you see a loop structure that exists solely so someone can 'break' out of it? Or, worse, raising an exception? I haven't seen it in Python, but frequently in C or C++ code where the programmer had a fixation on avoiding gotos. ChrisA From mzaccariotto at h-umus.it Wed Oct 5 09:26:52 2011 From: mzaccariotto at h-umus.it (Mauro Zaccariotto) Date: Wed, 5 Oct 2011 06:26:52 -0700 (PDT) Subject: httplib2 download forbidden Message-ID: <43d464bd-460d-416b-a61e-d2cb385169aa@q13g2000vby.googlegroups.com> Hi! does anyone know what's happening here http://code.google.com/p/httplib2/ ? I get this: "403. That?s an error. Your client does not have permission to get URL /p/httplib2/ from this server. That?s all we know." It seems like the httplib2 googlecode project is preventing from accessing the project web page and downloading httplib2 library package. I'm in extreme need of using httplib2! thanks From a24061 at ducksburg.com Wed Oct 5 09:29:38 2011 From: a24061 at ducksburg.com (Adam Funk) Date: Wed, 05 Oct 2011 14:29:38 +0100 Subject: recommend a graphics library for plotting by the pixel? References: <9s1rl8xt8t.ln2@news.ducksburg.com> Message-ID: <2n2ul8xi9s.ln2@news.ducksburg.com> On 2011-10-04, Derek Simkowiak wrote: > If this is strictly for 2D pixel graphics, I recommend using PyGame > (aka SDL). Why do you not think it's the way to go? It was built for > this type of thing. I only know PyGame because we did an exercise in recreating the old breakout game and messing around with it at a local Python group. I was under the mistaken impression from that exercise that you have to maintain a set of all the objects on the screen and redraw them all every time through the loop that ends with pygame.display.flip() --- *but* I now see that the loop starts with these: clock.tick(tick_rate) screen.fill((0,0,0)) # comes from screen = pygame.display.set_mode((screen_width,screen_height)) # before the loop and that I was then deleting hit bricks, calculating the new positions of the balls, and then redrawing everything that was left on the secondary screen because things were moving around and disappearing. I guess if I don't clear the screen at the beginning of the loop but just blit pixels onto it, when I call display.flip(), it will add the new blittings to what was already there? If that's true, this will be much easier than I thought. The only buttons I have in mind are "pause", "step", "go", and "quit", and I can just as easily do those with keypresses. From faucheuses at gmail.com Wed Oct 5 09:33:51 2011 From: faucheuses at gmail.com (faucheuse) Date: Wed, 5 Oct 2011 06:33:51 -0700 (PDT) Subject: A tuple in order to pass returned values ? Message-ID: <9dfbc534-25a1-403f-b382-9d6ce011789b@z8g2000yqb.googlegroups.com> Hi, (new to python and first message here \o/) I was wondering something : when you do : return value1, value2, value3 It returns a tuple. So if I want to pass these value to a function, the function have to look like : def function(self,(value1, value2, value3)) #self because i'm working with classes I tried it, and it works perfectly, but I was wondering if it's a good choice to do so, if there is a problem by coding like that. So my question is : Is there a problem doig so ? From faucheuses at gmail.com Wed Oct 5 09:37:05 2011 From: faucheuses at gmail.com (faucheuse) Date: Wed, 5 Oct 2011 06:37:05 -0700 (PDT) Subject: A tuple in order to pass returned values ? Message-ID: Hi, (new to python and first message here \o/) I was wondering something : when you do : return value1, value2, value3 It returns a tuple. So if I want to pass these value to a function, the function have to look like : def function(self,(value1, value2, value3)) #self because i'm working with classes I tried it, and it works perfectly, but I was wondering if it's a good choice to do so, if there is a problem by coding like that. So my question is : Is there a problem doig so ? From 5960761 at gmail.com Wed Oct 5 09:46:24 2011 From: 5960761 at gmail.com (Daniel) Date: Wed, 05 Oct 2011 16:46:24 +0300 Subject: issue with pexpect In-Reply-To: References: <1317805364.3169.5.camel@laptop.bulsat.com> Message-ID: <1317822384.2908.8.camel@laptop.bulsat.com> there is no such implementation in fedora you can su as a root .. i can su from regular user to root with no problems the problem come when i use the pexpect module On Wed, 2011-10-05 at 14:47 +0200, Nizamov Shawkat wrote: > 2011/10/5 Daniel <5960761 at gmail.com>: > > Hello, > > For about week i am experiencing a problem with pexpect that's why i > > hope you can help me :). > > Following is my code which tries to remove some files from the root dir > > and the code works on linux debian and freebsd but with no success on > > linux fedora .. any idea why this happen only in fedora ? > > > > #!/usr/bin/env python > > from __future__ import print_function > > import sys > > import pexpect > > import time > > > > spa=pexpect.spawn('su root') > > spa.expect('.*') > > print(spa.after) > > spa.sendline('abc') > > spa.expect('.*') > > print(spa.after) > > spa.sendline('rm -rf /root/py/pe*') > > spa.expect('.*') > > print(spa.after) > > spa.close() > > > > > > this is the output in Fedora linux it looks that the script can't > > authenticate as root > > > > Hi! > > The problem may be that root user is disabled. This was introduced in > Ubuntu long ago and I believe that later this was also accepted in > Fedora. That means that you simply can not "su" to root, no matter > what password you supply. This is the way how your OS operates and is > not connected in any way to python or pexpect. Therefore, either use > sudo (generally recommended) or enable root user (insecure!). > > Hope it helps, > S.Nizamov From andrea.crotti.0 at gmail.com Wed Oct 5 10:11:12 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Wed, 05 Oct 2011 15:11:12 +0100 Subject: eggbasket In-Reply-To: <4E8B75CE.1070700@gmail.com> References: <3874595.317.1317756872917.JavaMail.geo-discussion-forums@prma7> <4E8B75CE.1070700@gmail.com> Message-ID: <4E8C6580.5020809@gmail.com> Well it was easy, apparently sqlalchemy.exceptions doesn't exist but sqlalchemy.exc does, and that's the correct one, maybe a version problem... I get another problem right after File "/home/andrea/PSI_refactor/test_local_pypi/lib/python2.7/site-packages/EggBasket-0.6.1b-py2.7.egg/eggbasket/commands.py", line 82, in init_database model.User.query().filter_by(user_name=u'admin').one() TypeError: 'Query' object is not callable so I might try chishop or anything else... Actually do I really need to have a local pypi server to be able to use easy_install? If I have a whole directory full of directory eggs isn't there any way to use that? From ulrich.eckhardt at dominalaser.com Wed Oct 5 10:31:03 2011 From: ulrich.eckhardt at dominalaser.com (Ulrich Eckhardt) Date: Wed, 05 Oct 2011 16:31:03 +0200 Subject: A tuple in order to pass returned values ? In-Reply-To: <9dfbc534-25a1-403f-b382-9d6ce011789b@z8g2000yqb.googlegroups.com> References: <9dfbc534-25a1-403f-b382-9d6ce011789b@z8g2000yqb.googlegroups.com> Message-ID: <7a6ul8-djv.ln1@satorlaser.homedns.org> Am 05.10.2011 15:33, schrieb faucheuse: > I was wondering something : > when you do : return value1, value2, value3 > It returns a tuple. Right. > So if I want to pass these value to a function, the function have to > look like : > def function(self,(value1, value2, value3)) [...] No, you don't have to, but you can: # example functions def fni(): return 1, 2 def fno(v1, v2): pass # store result in a tuple and unpack tuple for function call t = fni() fno(*fni) # store results in individual values v1, v2 = fni() fno(v1, v2) Note that the first variant can be written in a single line, too. A completely different alternative is passing a tuple to the function as a single parameter. You can then access the elements using normal tuple indexing. That said, I don't see a problem with your syntax, except that it's a bit unusual. Welcome to Python! Uli From rvince99 at gmail.com Wed Oct 5 10:34:19 2011 From: rvince99 at gmail.com (RVince) Date: Wed, 5 Oct 2011 07:34:19 -0700 (PDT) Subject: Writing file out to another machine Message-ID: <0d795922-d946-480d-8f41-95656e56fa86@g23g2000vbz.googlegroups.com> I have a project whereby I need it to write out a file to a different server (that the originating server has write access to). So, say I need to write out from myserver1, where my app is running, onto, say S:/IT/tmp how can I specify/do this? Thanks, RVince From ddandd at gmail.com Wed Oct 5 10:53:56 2011 From: ddandd at gmail.com (Daniel Dorani) Date: Wed, 5 Oct 2011 07:53:56 -0700 (PDT) Subject: A tuple in order to pass returned values ? In-Reply-To: <9dfbc534-25a1-403f-b382-9d6ce011789b@z8g2000yqb.googlegroups.com> References: <9dfbc534-25a1-403f-b382-9d6ce011789b@z8g2000yqb.googlegroups.com> Message-ID: <14537227.998.1317826436383.JavaMail.geo-discussion-forums@yqnk41> this feature has been removed in python3 in accordance to the PEP 3113 (http://www.python.org/dev/peps/pep-3113/), you should consider using the * operator http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists . From 5960761 at gmail.com Wed Oct 5 11:05:50 2011 From: 5960761 at gmail.com (Daniel) Date: Wed, 05 Oct 2011 18:05:50 +0300 Subject: issue with pexpect In-Reply-To: References: <1317805364.3169.5.camel@laptop.bulsat.com> Message-ID: <1317827150.2908.13.camel@laptop.bulsat.com> Okey i figure it out how to do the job in fedora i added slight delay before sending each command either by the delaybeforesend attribute or by the time module ;) cheers On Wed, 2011-10-05 at 14:47 +0200, Nizamov Shawkat wrote: > 2011/10/5 Daniel <5960761 at gmail.com>: > > Hello, > > For about week i am experiencing a problem with pexpect that's why i > > hope you can help me :). > > Following is my code which tries to remove some files from the root dir > > and the code works on linux debian and freebsd but with no success on > > linux fedora .. any idea why this happen only in fedora ? > > > > #!/usr/bin/env python > > from __future__ import print_function > > import sys > > import pexpect > > import time > > > > spa=pexpect.spawn('su root') > > spa.expect('.*') > > print(spa.after) > > spa.sendline('abc') > > spa.expect('.*') > > print(spa.after) > > spa.sendline('rm -rf /root/py/pe*') > > spa.expect('.*') > > print(spa.after) > > spa.close() > > > > > > this is the output in Fedora linux it looks that the script can't > > authenticate as root > > > > Hi! > > The problem may be that root user is disabled. This was introduced in > Ubuntu long ago and I believe that later this was also accepted in > Fedora. That means that you simply can not "su" to root, no matter > what password you supply. This is the way how your OS operates and is > not connected in any way to python or pexpect. Therefore, either use > sudo (generally recommended) or enable root user (insecure!). > > Hope it helps, > S.Nizamov From faucheuses at gmail.com Wed Oct 5 11:18:07 2011 From: faucheuses at gmail.com (faucheuse) Date: Wed, 5 Oct 2011 08:18:07 -0700 (PDT) Subject: A tuple in order to pass returned values ? References: <9dfbc534-25a1-403f-b382-9d6ce011789b@z8g2000yqb.googlegroups.com> <14537227.998.1317826436383.JavaMail.geo-discussion-forums@yqnk41> Message-ID: Thanks for the answer. From davea at ieee.org Wed Oct 5 11:19:21 2011 From: davea at ieee.org (Dave Angel) Date: Wed, 05 Oct 2011 11:19:21 -0400 Subject: A tuple in order to pass returned values ? In-Reply-To: <9dfbc534-25a1-403f-b382-9d6ce011789b@z8g2000yqb.googlegroups.com> References: <9dfbc534-25a1-403f-b382-9d6ce011789b@z8g2000yqb.googlegroups.com> Message-ID: <4E8C7579.7060207@ieee.org> On 01/-10/-28163 02:59 PM, faucheuse wrote: > Hi, (new to python and first message here \o/) > > I was wondering something : > when you do : return value1, value2, value3 > It returns a tuple. > > So if I want to pass these value to a function, the function have to > look like : > def function(self,(value1, value2, value3)) #self because i'm working > with classes > > I tried it, and it works perfectly, but I was wondering if it's a good > choice to do so, if there is a problem by coding like that. > > So my question is : Is there a problem doig so ? > In the abstract, no. There's no relationship between the two, except they happen to use the same name in their respective local namespaces. In practice, I wouldn't do it. If the three values really comprise one "thing" then it makes sense for a function to expect a single thing, and that thing needs a name. So I'd define the function as def function(self, mything): interesting, useful, related = mything ... work on them But it's certainly possible that the writer of the first function really had three independent things to return, and if the second method is expecting those same three independent things, he should define the method as: def function(self, this, that, theother): Python does have magic syntax to make this sort of thing easier to work with, using * and **. But I seldom use them unless forced to by meta-concerns, such as passing unknown arguments through one method to a method of a superclass. DaveA From gordon at panix.com Wed Oct 5 11:41:44 2011 From: gordon at panix.com (John Gordon) Date: Wed, 5 Oct 2011 15:41:44 +0000 (UTC) Subject: Writing file out to another machine References: <0d795922-d946-480d-8f41-95656e56fa86@g23g2000vbz.googlegroups.com> Message-ID: In <0d795922-d946-480d-8f41-95656e56fa86 at g23g2000vbz.googlegroups.com> RVince writes: > I have a project whereby I need it to write out a file to a different > server (that the originating server has write access to). So, say I > need to write out from myserver1, where my app is running, onto, say > S:/IT/tmp how can I specify/do this? Thanks, RVince scp file host:/some/location -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From anikom15 at gmail.com Wed Oct 5 12:37:06 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 5 Oct 2011 09:37:06 -0700 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20111005163705.GA29662@Smoke> On Tue, Oct 04, 2011 at 08:20:34PM -0700, alex23 wrote: > Steven D'Aprano wrote: > > Imported modules are variables like any other, and as they usually exist > > in the global scope, so they will all need to be explicitly referenced as > > global. This will get tiresome very quickly, and is a cure far worse than > > the disease, and alone is enough to disqualify this suggestion from > > serious consideration. > > But on the gripping hand, it is a clear triumph of "Explicit is better > than implicit." ;) > Simple is better than complex. Readability counts. From anikom15 at gmail.com Wed Oct 5 12:39:34 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 5 Oct 2011 09:39:34 -0700 Subject: recommend a graphics library for plotting by the pixel? In-Reply-To: <2n2ul8xi9s.ln2@news.ducksburg.com> References: <9s1rl8xt8t.ln2@news.ducksburg.com> <2n2ul8xi9s.ln2@news.ducksburg.com> Message-ID: <20111005163934.GB29662@Smoke> On Wed, Oct 05, 2011 at 02:29:38PM +0100, Adam Funk wrote: > On 2011-10-04, Derek Simkowiak wrote: > > > If this is strictly for 2D pixel graphics, I recommend using PyGame > > (aka SDL). Why do you not think it's the way to go? It was built for > > this type of thing. > > I only know PyGame because we did an exercise in recreating the old > breakout game and messing around with it at a local Python group. > > I was under the mistaken impression from that exercise that you have > to maintain a set of all the objects on the screen and redraw them all > every time through the loop that ends with pygame.display.flip() --- > *but* I now see that the loop starts with these: > > clock.tick(tick_rate) > screen.fill((0,0,0)) > # comes from screen = pygame.display.set_mode((screen_width,screen_height)) > # before the loop > > and that I was then deleting hit bricks, calculating the new positions > of the balls, and then redrawing everything that was left on the > secondary screen because things were moving around and disappearing. > > I guess if I don't clear the screen at the beginning of the loop but > just blit pixels onto it, when I call display.flip(), it will add the > new blittings to what was already there? If that's true, this will be > much easier than I thought. > > The only buttons I have in mind are "pause", "step", "go", and "quit", > and I can just as easily do those with keypresses. Yep. Blitting is replacing the old colors with new colors. It doesn't replace colors unless you tell it to. From s.maggiolo at gmail.com Wed Oct 5 12:55:53 2011 From: s.maggiolo at gmail.com (Stefano Maggiolo) Date: Wed, 5 Oct 2011 18:55:53 +0200 Subject: Convenient filtering in for cycles Message-ID: Dear all, I would like to know if there is a (more) convenient way of doing this structure: ===(1)=== for x in l: if P(x): do_stuff(x) ====== Let's say that my dream syntax would be ===(2)=== for x in l if P(x): do_stuff(x) ====== as if it was the second part of a list comprehension. But sadly it is not in the language. Obvious alternatives are ===(3)=== for x in (x for x in l if P(x)): do_stuff(x) ====== ===(4)=== for x in l: if not P(x): continue do_stuff(x) ====== ===(5)=== [do_stuff(x) for x in l if P(x)] ====== As I see it, every syntax-valid solution has its drawbacks: (1) adds an indentation level; (3) adds an unnatural repetition of variable names and "for"; (4) has the "masked goto" continue (even if it is quite easy to understand what happens); (5) is good but not usable when do_stuff is what it usually is, that is a list of instructions. Is there some better and valid construction I missed? If not, is there a reason why (2) is not in the language? Pardon my boldness, but I am asking this because there are two invalid construct that I keep writing when I don't pay attention: one is (2), and the other is list comprehensions as in ===(6)=== for x in (x in l if P(x)): do_stuff(x) ====== which accidentally would be a better solution than (1), (3), (4), (5), though not as good as (2). Thank you for your attention, Stefano Maggiolo From ian.g.kelly at gmail.com Wed Oct 5 13:24:51 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 5 Oct 2011 11:24:51 -0600 Subject: Convenient filtering in for cycles In-Reply-To: References: Message-ID: On Wed, Oct 5, 2011 at 10:55 AM, Stefano Maggiolo wrote: > Dear all, > > I would like to know if there is a (more) convenient way of doing this > structure: > > ===(1)=== > for x in l: > ? ?if P(x): > ? ? ? ?do_stuff(x) > ====== > > Let's say that my dream syntax would be > > ===(2)=== > for x in l if P(x): > ? ?do_stuff(x) > ====== for x in filter(P, l): do_stuff(x) This works nicely if P is a function but can be a bit unwieldy if you want to use an arbitrary expression, since you would need to put it in a lambda. > Is there some better and valid construction I missed? If not, is there > a reason why (2) is not in the language? I guess because, as you helpfully enumerated, there are already plenty of options for iterating with a condition. Syntax isn't added without a strong reason, and avoiding an extra line or an extra indentation level isn't enough. Cheers, Ian From ian.g.kelly at gmail.com Wed Oct 5 13:39:57 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 5 Oct 2011 11:39:57 -0600 Subject: Convenient filtering in for cycles In-Reply-To: References: Message-ID: On Wed, Oct 5, 2011 at 11:24 AM, Ian Kelly wrote: >> Is there some better and valid construction I missed? If not, is there >> a reason why (2) is not in the language? > > I guess because, as you helpfully enumerated, there are already plenty > of options for iterating with a condition. ?Syntax isn't added without > a strong reason, and avoiding an extra line or an extra indentation > level isn't enough. Also, see these older threads: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ef807313aa47efc/4f4269a7b566cb87 http://groups.google.com/group/python-ideas/browse_thread/thread/87eee156ac2c3a24/61621e7779b5b255 http://groups.google.com/group/python-ideas/browse_thread/thread/e2d076fe35ece873/862674672b4de683 Cheers, Ian From s.maggiolo at gmail.com Wed Oct 5 14:05:00 2011 From: s.maggiolo at gmail.com (Stefano Maggiolo) Date: Wed, 5 Oct 2011 20:05:00 +0200 Subject: Convenient filtering in for cycles In-Reply-To: References: Message-ID: Dear Ian, thank you for you kind response. I was pretty confident the issue had already been discussed, but I was unable to look it up. I suppose your "filter" syntax is the best given the options (I always forget about map and filter...) and definitely I see that the work needed to add such a feature is hardly worth the convenience. Still, I think it is sad that generators/list comprehensions and for cycles do not share the same syntax. Unfortunately, this example from one of your links convinces that anyway it is too late: (x for x in (l1 if c else l2)) # valid (x for x in l1 if c else l2) # SyntaxError for x in l1 if c else l2 # valid Cheers, Stefano From python.list at tim.thechases.com Wed Oct 5 14:31:41 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 05 Oct 2011 13:31:41 -0500 Subject: syntax enhancement In-Reply-To: References: Message-ID: <4E8CA28D.8060104@tim.thechases.com> On 10/04/11 20:45, Terry Reedy wrote: > On 10/4/2011 9:50 AM, Valiev Sergey wrote: > >> - `[]` - used for list comprehension, >> - `()` - used for generators, >> - `[start:stop]` / `[start:stop:step]` - used for slices. >> The idea is to use `(start:stop)` / `(start:stop:step)` as 'lazy >> evaluated' slices (like itertools.islice). >> What do you think about it? > > a(b) is already used for function calls. Making a(b:c) be something > unreleated does not seem like a good idea to me. At present, a[b:c] == > a[slice(b,c)]. However, a(slice(b,c)) is already a function call and > could not equal a(b:c). I'm very -1 on the initial proposal with parens, but I wouldn't object to generators growing a method (__getitem__?) to do slices via itertools, something like gen = (a for a in iterator if test(a)) for thing in gen[4::2]: do_something(thing) acting something like gen = (a for a in iterator if test(a)) for thing in itertools.islice(gen, start=4, step=2): do_something(thing) -tkc From tjreedy at udel.edu Wed Oct 5 16:09:14 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 05 Oct 2011 16:09:14 -0400 Subject: syntax enhancement In-Reply-To: <4E8CA28D.8060104@tim.thechases.com> References: <4E8CA28D.8060104@tim.thechases.com> Message-ID: On 10/5/2011 2:31 PM, Tim Chase wrote: > On 10/04/11 20:45, Terry Reedy wrote: >> On 10/4/2011 9:50 AM, Valiev Sergey wrote: >> >>> - `[]` - used for list comprehension, >>> - `()` - used for generators, >>> - `[start:stop]` / `[start:stop:step]` - used for slices. >>> The idea is to use `(start:stop)` / `(start:stop:step)` as 'lazy >>> evaluated' slices (like itertools.islice). >>> What do you think about it? >> >> a(b) is already used for function calls. Making a(b:c) be something >> unreleated does not seem like a good idea to me. At present, a[b:c] == >> a[slice(b,c)]. However, a(slice(b,c)) is already a function call and >> could not equal a(b:c). > > I'm very -1 on the initial proposal with parens, but I wouldn't object > to generators growing a method (__getitem__?) to do slices via > itertools, something like > > gen = (a for a in iterator if test(a)) > for thing in gen[4::2]: > do_something(thing) > > acting something like > > gen = (a for a in iterator if test(a)) > for thing in itertools.islice(gen, start=4, step=2): 'end' arg is required > do_something(thing) islice(gen,4,None,2) is 11 more characters than gen[4::2] If you start with 'from itertools import islice as sl', then each use is 7 more chars. In the normal case with an 'end' arg, the difference would be 4 chars less: sl(gen,4,100,2) # 3 extra chars to type ;=) gen[4:100:2] This would complicate the language and make generators more different from other iterators without adding new functionality -- Terry Jan Reedy From tjreedy at udel.edu Wed Oct 5 16:11:18 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 05 Oct 2011 16:11:18 -0400 Subject: Writing file out to another machine In-Reply-To: <0d795922-d946-480d-8f41-95656e56fa86@g23g2000vbz.googlegroups.com> References: <0d795922-d946-480d-8f41-95656e56fa86@g23g2000vbz.googlegroups.com> Message-ID: On 10/5/2011 10:34 AM, RVince wrote: > I have a project whereby I need it to write out a file to a different > server (that the originating server has write access to). So, say I > need to write out from myserver1, where my app is running, onto, say > S:/IT/tmp how can I specify/do this? Thanks, RVince open('S:/IT/tmp','w') ?? -- Terry Jan Reedy From gordon at panix.com Wed Oct 5 17:22:37 2011 From: gordon at panix.com (John Gordon) Date: Wed, 5 Oct 2011 21:22:37 +0000 (UTC) Subject: Writing file out to another machine References: <0d795922-d946-480d-8f41-95656e56fa86@g23g2000vbz.googlegroups.com> Message-ID: In Terry Reedy writes: > On 10/5/2011 10:34 AM, RVince wrote: > > I have a project whereby I need it to write out a file to a different > > server (that the originating server has write access to). So, say I > > need to write out from myserver1, where my app is running, onto, say > > S:/IT/tmp how can I specify/do this? Thanks, RVince > open('S:/IT/tmp','w') ?? I assume he intended "S:" to indicate a remote server. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From anikom15 at gmail.com Wed Oct 5 17:28:22 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 5 Oct 2011 14:28:22 -0700 Subject: syntax enhancement In-Reply-To: <4E8CA28D.8060104@tim.thechases.com> References: <4E8CA28D.8060104@tim.thechases.com> Message-ID: <20111005212822.GA30294@Smoke> On Wed, Oct 05, 2011 at 01:31:41PM -0500, Tim Chase wrote: > On 10/04/11 20:45, Terry Reedy wrote: > >On 10/4/2011 9:50 AM, Valiev Sergey wrote: > > > >>- `[]` - used for list comprehension, > >>- `()` - used for generators, > >>- `[start:stop]` / `[start:stop:step]` - used for slices. > >>The idea is to use `(start:stop)` / `(start:stop:step)` as 'lazy > >>evaluated' slices (like itertools.islice). > >>What do you think about it? > > > >a(b) is already used for function calls. Making a(b:c) be something > >unreleated does not seem like a good idea to me. At present, a[b:c] == > >a[slice(b,c)]. However, a(slice(b,c)) is already a function call and > >could not equal a(b:c). > > I'm very -1 on the initial proposal with parens, but I wouldn't > object to generators growing a method (__getitem__?) to do slices > via itertools, something like > > gen = (a for a in iterator if test(a)) > for thing in gen[4::2]: > do_something(thing) > > acting something like > > gen = (a for a in iterator if test(a)) > for thing in itertools.islice(gen, start=4, step=2): > do_something(thing) > > -tkc > > > > Wait, how would this work fundamentally? A list can be sliced because all the values are there. A generator does not have all its value at once (it generates each value as requested). I don't like change so I look at these kinds of suggestions with lots of scrutiny and biased criticism. From rosuav at gmail.com Wed Oct 5 17:31:28 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Oct 2011 08:31:28 +1100 Subject: Writing file out to another machine In-Reply-To: References: <0d795922-d946-480d-8f41-95656e56fa86@g23g2000vbz.googlegroups.com> Message-ID: On Thu, Oct 6, 2011 at 8:22 AM, John Gordon wrote: > I assume he intended "S:" to indicate a remote server. > The most obvious understanding of it is a drive letter (ie Windows box). But if not, more clarification is needed. ChrisA From ian.g.kelly at gmail.com Wed Oct 5 17:46:15 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 5 Oct 2011 15:46:15 -0600 Subject: syntax enhancement In-Reply-To: <20111005212822.GA30294@Smoke> References: <4E8CA28D.8060104@tim.thechases.com> <20111005212822.GA30294@Smoke> Message-ID: On Wed, Oct 5, 2011 at 3:28 PM, Westley Mart?nez wrote: > Wait, how would this work fundamentally? ?A list can be sliced because > all the values are there. ?A generator does not have all its value at > once (it generates each value as requested). ?I don't like change so I > look at these kinds of suggestions with lots of scrutiny and biased > criticism. Like islice, it would return an iterator that lazily pulls values from the generator as they are requested, discarding unneeded values as necessary. From gregor.hochschild at googlemail.com Wed Oct 5 19:35:59 2011 From: gregor.hochschild at googlemail.com (Greg) Date: Wed, 5 Oct 2011 16:35:59 -0700 (PDT) Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file Message-ID: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> Hi, I am having some encoding problems when I first parse stuff from a non-english website using BeautifulSoup and then write the results to a txt file. I have the text both as a normal (text) and as a unicode string (utext): print repr(text) 'Branie zak\xc2\xb3adnik\xc3\xb3w' print repr(utext) u'Branie zak\xb3adnik\xf3w' print text or print utext (fileSoup.prettify() also shows 'wrong' symbols): Branie zak?adnik?w Now I am trying to save this to a file but I never get the encoding right. Here is what I tried (+ lot's of different things with encode, decode...): outFile=open(filePath,"w") outFile.write(text) outFile.close() outFile=codecs.open( filePath, "w", "UTF8" ) outFile.write(utext) outFile.close() Thanks!! From tjreedy at udel.edu Wed Oct 5 21:36:34 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 05 Oct 2011 21:36:34 -0400 Subject: Writing file out to another machine In-Reply-To: References: <0d795922-d946-480d-8f41-95656e56fa86@g23g2000vbz.googlegroups.com> Message-ID: On 10/5/2011 5:31 PM, Chris Angelico wrote: > On Thu, Oct 6, 2011 at 8:22 AM, John Gordon wrote: >> I assume he intended "S:" to indicate a remote server. >> > > The most obvious understanding of it is a drive letter (ie Windows > box). More exactly, a remote server filesystem 'mounted' (not sure of the Windows' term) as a local drive. I am pretty sure I have read of this being done. > But if not, more clarification is needed. Definitely. -- Terry Jan Reedy From steve+comp.lang.python at pearwood.info Wed Oct 5 21:55:51 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 06 Oct 2011 01:55:51 GMT Subject: syntax enhancement References: Message-ID: <4e8d0aa7$0$29978$c3e8da3$5496439d@news.astraweb.com> On Wed, 05 Oct 2011 13:31:41 -0500, Tim Chase wrote: > I'm very -1 on the initial proposal with parens, but I wouldn't object > to generators growing a method (__getitem__?) to do slices via > itertools, something like > > gen = (a for a in iterator if test(a)) > for thing in gen[4::2]: > do_something(thing) > > acting something like > > gen = (a for a in iterator if test(a)) > for thing in itertools.islice(gen, start=4, step=2): > do_something(thing) The problem is that adding slicing to iterators is that it requires ALL iterators to support slicing, whether appropriate or not, and regardless of the implementation. Just use islice. Not everything needs to be a built-in. -- Steven From steve+comp.lang.python at pearwood.info Wed Oct 5 22:08:46 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 06 Oct 2011 02:08:46 GMT Subject: Convenient filtering in for cycles References: Message-ID: <4e8d0dae$0$29978$c3e8da3$5496439d@news.astraweb.com> On Wed, 05 Oct 2011 18:55:53 +0200, Stefano Maggiolo wrote: > Dear all, > > I would like to know if there is a (more) convenient way of doing this > structure: > > ===(1)=== > for x in l: > if P(x): > do_stuff(x) > ====== That seems pretty convenient to me. It's simple, obvious and readable. > Let's say that my dream syntax would be > > ===(2)=== > for x in l if P(x): > do_stuff(x) > ====== That is exactly the same as #1 above, except it takes one extra line (trivial) and one extra indent level (almost always trivial). So what's the problem with #1? If you have so many indent levels that one more level causes you grief, then consider that Nature's way of telling you that you have too much code in one chunk and that you should refactor some of it into functions. > as if it was the second part of a list comprehension. But sadly it is > not in the language. Obvious alternatives are > > ===(3)=== > for x in (x for x in l if P(x)): > do_stuff(x) > ====== A hard to read mess. Best avoided. > ===(4)=== > for x in l: > if not P(x): > continue > do_stuff(x) > ====== Saves an indent level, otherwise virtually identical to #1. > ===(5)=== > [do_stuff(x) for x in l if P(x)] > ====== Only appropriate if you care about the return results of do_stuff. If you are using a list comprehension solely for the side-effects, don't. > As I see it, every syntax-valid solution has its drawbacks: (1) adds an > indentation level; This shouldn't be a drawback. This should be an advantage. It's an extra indentation level because it represents a block of code. > (3) adds an unnatural repetition of variable names and "for"; (4) has > the "masked goto" continue (even if it is quite easy to understand what > happens); While it is true that "goto is harmful", it is possible to take the hatred of goto to ridiculous levels. Calling a function is a "masked goto". For-loops and while loops are "masked gotos". That doesn't make them bad things. There is nothing inherently wrong with continue and break for flow control, although of course you can write bad code with any construct. > (5) is good but not usable when do_stuff is what it usually is, that is > a list of instructions. > > Is there some better and valid construction I missed? If not, is there a > reason why (2) is not in the language? Because it complicates the language for very little benefit. That makes the language harder to learn and read and the compiler harder to maintain. Unless there is a concrete gain from the feature, why bother? -- Steven From wuwei23 at gmail.com Wed Oct 5 23:34:35 2011 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Oct 2011 20:34:35 -0700 (PDT) Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> <4e8bed30$0$29978$c3e8da3$5496439d@news.astraweb.com> <87wrcjzmql.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > This mocking is hurtful to people who identify too strongly with COBOL. > I wonder whether that means it's intentionally hurtful. Far, _far_ less hurtful than COBOL itself... From wuwei23 at gmail.com Wed Oct 5 23:36:25 2011 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Oct 2011 20:36:25 -0700 (PDT) Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <4E8BADBE.2090300@yahoo.com> <4E8BB162.5080100@yahoo.com> Message-ID: On Oct 5, 11:10?pm, Chris Angelico wrote: > The absence from the language doesn't prove that. All it means is > that, on those rare occasions when a goto would have been correct, the > programmer had to make do with something else :-) Like the goto module? :) http://entrian.com/goto/ From steve+comp.lang.python at pearwood.info Wed Oct 5 23:40:14 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 06 Oct 2011 03:40:14 GMT Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> Message-ID: <4e8d231e$0$29978$c3e8da3$5496439d@news.astraweb.com> On Wed, 05 Oct 2011 16:35:59 -0700, Greg wrote: > Hi, I am having some encoding problems when I first parse stuff from a > non-english website using BeautifulSoup and then write the results to a > txt file. If you haven't already read this, you should do so: http://www.joelonsoftware.com/articles/Unicode.html > I have the text both as a normal (text) and as a unicode string (utext): > print repr(text) > 'Branie zak\xc2\xb3adnik\xc3\xb3w' This is pretty much meaningless, because we don't know how you got the text and what it actually is. You're showing us a bunch of bytes, with no clue as to whether they are the right bytes or not. Considering that your Unicode text is also incorrect, I would say it is *not* right and your description of the problem is 100% backwards: the problem is not *writing* the text, but *reading* the bytes and decoding it. You should do something like this: (1) Inspect the web page to find out what encoding is actually used. (2) If the web page doesn't know what encoding it uses, or if it uses bits and pieces of different encodings, then the source is broken and you shouldn't expect much better results. You could try guessing, but you should expect mojibake in your results. http://en.wikipedia.org/wiki/Mojibake (3) Decode the web page into Unicode text, using the correct encoding. (4) Do all your processing in Unicode, not bytes. (5) Encode the text into bytes using UTF-8 encoding. (6) Write the bytes to a file. [...] > Now I am trying to save this to a file but I never get the encoding > right. Here is what I tried (+ lot's of different things with encode, > decode...): > outFile=codecs.open( filePath, "w", "UTF8" ) > outFile.write(utext) > outFile.close() That's the correct approach, but it won't help you if utext contains the wrong characters in the first place. The critical step is taking the bytes in the web page and turning them into text. How are you generating utext? -- Steven From wuwei23 at gmail.com Wed Oct 5 23:42:18 2011 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Oct 2011 20:42:18 -0700 (PDT) Subject: Convenient filtering in for cycles References: Message-ID: On Oct 6, 2:55?am, Stefano Maggiolo wrote: > I would like to know if there is a (more) convenient way of doing this > structure: > > ===(1)=== > for x in l: > ? ? if P(x): > ? ? ? ? do_stuff(x) > ====== map(do_stuff, filter(P, l)) From cs at zip.com.au Wed Oct 5 23:44:33 2011 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 6 Oct 2011 14:44:33 +1100 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> Message-ID: <20111006034433.GA23530@cskk.homeip.net> On 03Oct2011 13:10, rantingrick wrote: | Also for scoping. | | py> count = 0 | py> def foo(): | ... global.count += 1 | py> print count | 1 | | Why? Well because many times i find myself wondering if this or that | variable is local or global -- and when i say "global" i am speaking | of module scope! The "global" cures the ill. I must admit I rarely have this concern. My own module globals are almost entirely CONSTANT type names. (Excluding function and class names.) What's the common ambifuity case for you? -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Generally, these things are dreadful, but I saw a clip the other night on tv of someone who had built a scorpion costume for their spaniel, complete with legs and a stinger. It was quite impressive. Made me want to run out and buy a dog and a some foam rubber. - David Farley From alec.taylor6 at gmail.com Thu Oct 6 00:02:50 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Thu, 6 Oct 2011 15:02:50 +1100 Subject: recommend a graphics library for plotting by the pixel? In-Reply-To: <6a4f8ef3-81d1-4e91-8cd8-8014a021a2aa@18g2000yqz.googlegroups.com> References: <9s1rl8xt8t.ln2@news.ducksburg.com> <6a4f8ef3-81d1-4e91-8cd8-8014a021a2aa@18g2000yqz.googlegroups.com> Message-ID: Hehe, sure, why not? :P On Wed, Oct 5, 2011 at 2:24 PM, alex23 wrote: > On Oct 5, 12:53?am, Alec Taylor wrote: >> Sounds like a job for Processing... > > Don't you mean PyProcessing? :) > > http://code.google.com/p/pyprocessing/ > -- > http://mail.python.org/mailman/listinfo/python-list > From anikom15 at gmail.com Thu Oct 6 00:26:49 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 5 Oct 2011 21:26:49 -0700 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: <20111006034433.GA23530@cskk.homeip.net> References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <20111006034433.GA23530@cskk.homeip.net> Message-ID: <20111006042648.GA31575@Smoke> On Thu, Oct 06, 2011 at 02:44:33PM +1100, Cameron Simpson wrote: > On 03Oct2011 13:10, rantingrick wrote: > | Also for scoping. > | > | py> count = 0 > | py> def foo(): > | ... global.count += 1 > | py> print count > | 1 > | > | Why? Well because many times i find myself wondering if this or that > | variable is local or global -- and when i say "global" i am speaking > | of module scope! The "global" cures the ill. > > I must admit I rarely have this concern. My own module globals are > almost entirely CONSTANT type names. (Excluding function and class > names.) > > What's the common ambifuity case for you? I never have this concern either. Python's functions and classes are powerful enough to avoid globals entirely. In C I have a few sometimes and in Fortran and the like they're everywhere. Global variables are POWERFUL and USEFUL but there's a certain paradigm that goes with them, and Python works better with an object-oriented w/ functional elements approach. From gregor.hochschild at googlemail.com Thu Oct 6 00:39:17 2011 From: gregor.hochschild at googlemail.com (Greg) Date: Wed, 5 Oct 2011 21:39:17 -0700 (PDT) Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> <4e8d231e$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4aeb76e9-511f-4a46-94c7-bf2ab84877df@z12g2000yqz.googlegroups.com> Brilliant! It worked. Thanks! Here is the final code for those who are struggling with similar problems: ## open and decode file # In this case, the encoding comes from the charset argument in a meta tag # e.g. fileObj = open(filePath,"r").read() fileContent = fileObj.decode("iso-8859-2") fileSoup = BeautifulSoup(fileContent) ## Do some BeautifulSoup magic and preserve unicode, presume result is saved in 'text' ## ## write extracted text to file f = open(outFilePath, 'w') f.write(text.encode('utf-8')) f.close() On Oct 5, 11:40?pm, Steven D'Aprano wrote: > On Wed, 05 Oct 2011 16:35:59 -0700, Greg wrote: > > Hi, I am having some encoding problems when I first parse stuff from a > > non-english website using BeautifulSoup and then write the results to a > > txt file. > > If you haven't already read this, you should do so: > > http://www.joelonsoftware.com/articles/Unicode.html > > > I have the text both as a normal (text) and as a unicode string (utext): > > print repr(text) > > 'Branie zak\xc2\xb3adnik\xc3\xb3w' > > This is pretty much meaningless, because we don't know how you got the > text and what it actually is. You're showing us a bunch of bytes, with no > clue as to whether they are the right bytes or not. Considering that your > Unicode text is also incorrect, I would say it is *not* right and your > description of the problem is 100% backwards: the problem is not > *writing* the text, but *reading* the bytes and decoding it. > > You should do something like this: > > (1) Inspect the web page to find out what encoding is actually used. > > (2) If the web page doesn't know what encoding it uses, or if it uses > bits and pieces of different encodings, then the source is broken and you > shouldn't expect much better results. You could try guessing, but you > should expect mojibake in your results. > > http://en.wikipedia.org/wiki/Mojibake > > (3) Decode the web page into Unicode text, using the correct encoding. > > (4) Do all your processing in Unicode, not bytes. > > (5) Encode the text into bytes using UTF-8 encoding. > > (6) Write the bytes to a file. > > [...] > > > Now I am trying to save this to a file but I never get the encoding > > right. Here is what I tried (+ lot's of different things with encode, > > decode...): > > outFile=codecs.open( filePath, "w", "UTF8" ) > > outFile.write(utext) > > outFile.close() > > That's the correct approach, but it won't help you if utext contains the > wrong characters in the first place. The critical step is taking the > bytes in the web page and turning them into text. > > How are you generating utext? > > -- > Steven From rosuav at gmail.com Thu Oct 6 00:58:24 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Oct 2011 15:58:24 +1100 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: <4E8BADBE.2090300@yahoo.com> <4E8BB162.5080100@yahoo.com> Message-ID: On Thu, Oct 6, 2011 at 2:36 PM, alex23 wrote: > On Oct 5, 11:10?pm, Chris Angelico wrote: >> The absence from the language doesn't prove that. All it means is >> that, on those rare occasions when a goto would have been correct, the >> programmer had to make do with something else :-) > > Like the goto module? :) > > http://entrian.com/goto/ Yes. That module is extremely valuable and needs to be brought into the main trunk. Rick, can this go on your Python 4000 list? ChrisA From rosuav at gmail.com Thu Oct 6 01:00:31 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Oct 2011 16:00:31 +1100 Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file In-Reply-To: <4aeb76e9-511f-4a46-94c7-bf2ab84877df@z12g2000yqz.googlegroups.com> References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> <4e8d231e$0$29978$c3e8da3$5496439d@news.astraweb.com> <4aeb76e9-511f-4a46-94c7-bf2ab84877df@z12g2000yqz.googlegroups.com> Message-ID: On Thu, Oct 6, 2011 at 3:39 PM, Greg wrote: > Brilliant! It worked. Thanks! > > Here is the final code for those who are struggling with similar > problems: > > ## open and decode file > # In this case, the encoding comes from the charset argument in a meta > tag > # e.g. > fileContent = fileObj.decode("iso-8859-2") > f.write(text.encode('utf-8')) In other words, when you decode correctly into Unicode and encode correctly onto the disk, it works! This is why encodings are so important :) ChrisA From sajuptpm at gmail.com Thu Oct 6 01:01:56 2011 From: sajuptpm at gmail.com (sajuptpm) Date: Wed, 5 Oct 2011 22:01:56 -0700 (PDT) Subject: selenium pyvirtualdisplay script on remote server Message-ID: <9e56fd9f-87ab-4164-af26-83f3efce5d84@b6g2000vbz.googlegroups.com> Hi Friends, Here the isuue is i can't find the "li" element. that is because that element is out of display, so i adjust scroll bar or do focus around that area to get that element via find_element_by_id("loc_opt") I already tested with scroll bar and focus and its working fine in my laptop. But when i run this script on Remote Server, it can't find that element.?????? Note: Here i am using pyvirtualdisplay, Xvfb and Xephyr, because server don't have Xserver. Its also working fine with pyvirtualdisplay in my laptop. but the issue is in Remote Server. Has anyone faced this problem before ? Please suggest a solution. class Search: def __init__(self): """ """ self.display = Display(visible=0, size=(800, 600)) self.display.start() self.url ='http://www.google.com' self.search_url = None self.driver = webdriver().Firefox() def search(self, search_query, search_location=None): """ """ if search_query: self.search_url = "%s/search?q=%s" %(self.url, search_query) print "\nURL : ", self.search_url self.driver.get(self.search_url) self.submit_search() #self.driver.execute_script("window.scrollBy(0,200)") self.driver.execute_script("document.getElementById('tbpi').focus();") more_search_tools_link = self.driver.find_element_by_id("tbpi") more_search_tools_link.click() self.driver.execute_script("window.scrollBy(0,200)") loc_li = self.driver.find_element_by_id("loc_opt") From hansmeetschool at gmail.com Thu Oct 6 01:45:42 2011 From: hansmeetschool at gmail.com (Hansmeet Singh) Date: Wed, 5 Oct 2011 22:45:42 -0700 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: <4E8BADBE.2090300@yahoo.com> <4E8BB162.5080100@yahoo.com> Message-ID: REMEMBER STEVE On Wed, Oct 5, 2011 at 9:58 PM, Chris Angelico wrote: > On Thu, Oct 6, 2011 at 2:36 PM, alex23 wrote: > > On Oct 5, 11:10 pm, Chris Angelico wrote: > >> The absence from the language doesn't prove that. All it means is > >> that, on those rare occasions when a goto would have been correct, the > >> programmer had to make do with something else :-) > > > > Like the goto module? :) > > > > http://entrian.com/goto/ > > Yes. That module is extremely valuable and needs to be brought into > the main trunk. Rick, can this go on your Python 4000 list? > > ChrisA > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Thu Oct 6 03:05:01 2011 From: timr at probo.com (Tim Roberts) Date: Thu, 06 Oct 2011 00:05:01 -0700 Subject: urllib and parsing References: Message-ID: luca72 wrote: > >Hello i have a simple question: >up to now if i have to parse a page i do as follow: >... >Now i have the site that is open by an html file like this: >... >how can i open it with urllib, please note i don't have to parse this >file, but i have to parse the site where he point. Well, you can use htmllib to parse the HTML, look for the "form" tag, and extract the "action" verb. Or, if you really just want this one site, you can use urllib2 to provide POST parameters: import urllib import urllib2 url = 'http://lalal.hhdik/' values = {'password' : 'password', 'Entra' : 'Entra' } data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read() -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From timr at probo.com Thu Oct 6 03:05:42 2011 From: timr at probo.com (Tim Roberts) Date: Thu, 06 Oct 2011 00:05:42 -0700 Subject: httplib2 download forbidden References: <43d464bd-460d-416b-a61e-d2cb385169aa@q13g2000vby.googlegroups.com> Message-ID: Mauro Zaccariotto wrote: > >Hi! does anyone know what's happening here http://code.google.com/p/httplib2/ >? I get this: >"403. That?s an error. >Your client does not have permission to get URL /p/httplib2/ from this >server. That?s all we know." It's working for me. Do you have some kind of proxy in the way? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ladasky at my-deja.com Thu Oct 6 04:00:09 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 6 Oct 2011 01:00:09 -0700 (PDT) Subject: Simplest way to resize an image-like array References: <9b0b8951-bfc2-4047-8b4e-1ee0af20af27@q24g2000vby.googlegroups.com> Message-ID: On Oct 1, 2:22?am, John Ladasky wrote: > On Sep 30, 1:51?pm, Jon Clements wrote: > > > Is something like > >http://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresi... > > any use? > > There we go! ?That's the kind of method I was seeking. ?I didn't think > to look outside of scipy.interpolate. ?Thanks, Jon. Oh, grumble, scipy.misc.imresize bumps the array down to an 8-bit integer array. I need to do some arithmetic with the arrays, and it needs to be more precise than 8 bits. So I may have to rewrite the function to yield a 16-bit integer at least. From mzaccariotto at h-umus.it Thu Oct 6 04:36:19 2011 From: mzaccariotto at h-umus.it (Mauro Zaccariotto) Date: Thu, 6 Oct 2011 01:36:19 -0700 (PDT) Subject: httplib2 download forbidden References: <43d464bd-460d-416b-a61e-d2cb385169aa@q13g2000vby.googlegroups.com> Message-ID: <2e19f37e-de88-483c-8bad-660ccfcf2ec0@k15g2000yqd.googlegroups.com> On 6 Ott, 09:05, Tim Roberts wrote: > Mauro Zaccariotto wrote: > > >Hi! does anyone know what's happening herehttp://code.google.com/p/httplib2/ > >? I get this: > >"403. That s an error. > >Your client does not have permission to get URL /p/httplib2/ from this > >server. That s all we know." > > It's working for me. ?Do you have some kind of proxy in the way? > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. No, but today it's working again. O__o thank you anyway From ulrich.eckhardt at dominalaser.com Thu Oct 6 05:29:21 2011 From: ulrich.eckhardt at dominalaser.com (Ulrich Eckhardt) Date: Thu, 06 Oct 2011 11:29:21 +0200 Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file In-Reply-To: <4e8d231e$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> <4e8d231e$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 06.10.2011 05:40, schrieb Steven D'Aprano: > (4) Do all your processing in Unicode, not bytes. > > (5) Encode the text into bytes using UTF-8 encoding. > > (6) Write the bytes to a file. Just wondering, why do you split the latter two parts? I would have used codecs.open() to open the file and define the encoding in a single step. Is there a downside to this approach? Otherwise, I can only confirm that your overall approach is the easiest way to get correct results. Uli From shanghaizheng2010 at gmail.com Thu Oct 6 07:31:21 2011 From: shanghaizheng2010 at gmail.com (fashion fans) Date: Thu, 6 Oct 2011 04:31:21 -0700 (PDT) Subject: The hyper fused upper part of Nike Air Max displays the humanity Message-ID: <2c1890e6-56fe-4882-9fc6-e9d12925823e@z8g2000yqb.googlegroups.com> The hyper fused upper part of Nike Air Max displays the humanity of the designer because of its lightweight, breathability and a feeling of plusher fitness. The mesh inner collar, and the soft springy cushion http://www.outlet-nike-air-max.com/inside can protect the feet against most possible injures. Besides the rubber materials around the translucent perimeter displays a particular appearance of the shoes, which is a love of most women, especially those who pursuit to be in fashion. Meanwhile the rubber material is a guaranty of the durability and traction, which is fully the practice. With the {2}{/2}dynamic colors of Women?s Nike Air Max 2011, you will soon experience the vitality of sports when you are dressed in such a pair of classic nice cheap Nike running shoes, because it can not only create a healthy condition for feet, but also can restore the original active in the shortest time. What?s more, the Nike Air Max 2011 will not cause any exacerbation if you once were injured in feet. http://www.outlet-nike-air-max.com/ From rosuav at gmail.com Thu Oct 6 07:34:12 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 6 Oct 2011 22:34:12 +1100 Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file In-Reply-To: References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> <4e8d231e$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Oct 6, 2011 at 8:29 PM, Ulrich Eckhardt wrote: > Just wondering, why do you split the latter two parts? I would have used > codecs.open() to open the file and define the encoding in a single step. Is > there a downside to this approach? > Those two steps still happen, even if you achieve them in a single function call. What Steven described is language- and library- independent. ChrisA From davea at ieee.org Thu Oct 6 09:14:21 2011 From: davea at ieee.org (Dave Angel) Date: Thu, 06 Oct 2011 09:14:21 -0400 Subject: Writing file out to another machine In-Reply-To: References: <0d795922-d946-480d-8f41-95656e56fa86@g23g2000vbz.googlegroups.com> Message-ID: <4E8DA9AD.1090108@ieee.org> On 01/-10/-28163 02:59 PM, Dennis Lee Bieber wrote: > On Wed, 05 Oct 2011 21:36:34 -0400, Terry Reedy > declaimed the following in gmane.comp.python.general: > >> On 10/5/2011 5:31 PM, Chris Angelico wrote: >>> On Thu, Oct 6, 2011 at 8:22 AM, John Gordon wrote: >>>> I assume he intended "S:" to indicate a remote server. >>>> >>> The most obvious understanding of it is a drive letter (ie Windows >>> box). >> More exactly, a remote server filesystem 'mounted' (not sure of the >> Windows' term) as a local drive. I am pretty sure I have read of this >> being done. >> > "My Computer" > > "Map Network Drive" > > So I suspect you could refer to it as a "mapped" filesystem. Or you could refer to it as a 'net use' drive, since that's the commandline way to mount it on Windoze. DaveA From dreyemi at gmail.com Thu Oct 6 09:34:28 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Thu, 6 Oct 2011 14:34:28 +0100 Subject: Implementing Python-OAuth2 Message-ID: Hello friends, I'm working on a pretty large application that I will like to use oauth2 on as an authentication and authorization mechanism. I understand fairly the technology and I have written my own implementation before I stumbled on python-oauth2. I need advise on leveraging python-oauth2 api for creating consumer key, creating consumer secret, access token and token secret. Regards -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From ed at leafe.com Thu Oct 6 10:31:34 2011 From: ed at leafe.com (Ed Leafe) Date: Thu, 6 Oct 2011 09:31:34 -0500 Subject: Dabo 0.9.4 Released! Message-ID: Yes, it's been over a year, but today we're finally releasing Dabo 0.9.4! What can I say? While we've been actively developing Dabo all along, and committing improvements and fixes regularly, we don't seem to get around to doing releases as often as we should. Since Dabo has a Web Update feature that lets developers receive regular updates between releases, most people are fairly current, but creating a new release will help newcomers to Dabo get up to speed quicker. The changes won't be too big for most current users of the framework, but compared to the 0.9.3 release, lots has been fixed and improved! Full release notes are at: http://svn.dabodev.com/dabo/tags/dabo-0.9.4/ChangeLog ...but here are just a few of the major changes since 0.9.3: - better handling of edge cases in bizobj relations - addition of support in bizobjs for many-to-many relationships - improved efficiency in detecting changed records - added the dDatePicker control - added the option of vertical text for grid headers - integrated a code editor into the command window You can grab the latest version, as always, from http://dabodev.com/download -- Ed Leafe From nt_mahmood at yahoo.com Thu Oct 6 11:27:51 2011 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Thu, 6 Oct 2011 08:27:51 -0700 (PDT) Subject: passing multiple string to a command line option Message-ID: <1317914871.44539.YahooMailNeo@web111719.mail.gq1.yahoo.com> Dear developers, Suppose I have this list in command line options: ... -b b1,b2,b3 Here is what I wrote: parser = optparse.OptionParser() # Benchmark options parser.add_option("-b", "--benchmark", default="", help="The benchmark to be loaded.") process = [] benchmarks = options.benchmark.split(',') for bench_name in benchmarks: ??? process.append(bench_name) ??? At this stage, I want to bind each process to something: np = 2 for i in xrange(np): ??? ... ??? system.cpu[i].workload = process[i] however I get this error: ? File "configs/example/cmp.py", line 81, in ??? system.cpu[i].workload = process[i] ? File "/home/mahmood/gem5/src/python/m5/SimObject.py", line 627, in __setattr__ ??? value = param.convert(value) ? File "/home/mahmood/gem5/src/python/m5/params.py", line 236, in convert ??? tmp_list = [ ParamDesc.convert(self, value) ] ? File "/home/mahmood/gem5/src/python/m5/params.py", line 159, in convert ??? return self.ptype(value) TypeError: __init__() takes exactly 1 argument (2 given) Error setting param TmpClass.workload to bzip2_chicken params.py is part of the simulator and I didn't wrote that. My question is what is the simplest way to fix that? Or is there any better idea than what I did in order to parse such command line option? ?thanks // Naderan *Mahmood; From jeanmichel at sequans.com Thu Oct 6 11:28:20 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 06 Oct 2011 17:28:20 +0200 Subject: A tuple in order to pass returned values ? In-Reply-To: References: Message-ID: <4E8DC914.6020906@sequans.com> faucheuse wrote: > Hi, (new to python and first message here \o/) > > I was wondering something : > when you do : return value1, value2, value3 > It returns a tuple. > > So if I want to pass these value to a function, the function have to > look like : > def function(self,(value1, value2, value3)) #self because i'm working > with classes > > I tried it, and it works perfectly, but I was wondering if it's a good > choice to do so, if there is a problem by coding like that. > > So my question is : Is there a problem doig so ? > There is no problem with that but ppl will usually write something like: def function(self, a3Tuple): v1, v2 ,v3 = a3Tuple In a general manner, ppl will tend to use the minimum arguments required. However, do not pack values into tuple if they are not related. A better thing to do would be to use objects instead of tuples, tuples can serve as lazy structures for small application/script, they can become harmful in more complexe applications, especialy when used in public interfaces. JM From alain.leufroy at logilab.fr Thu Oct 6 11:34:08 2011 From: alain.leufroy at logilab.fr (Alain Leufroy) Date: Thu, 6 Oct 2011 17:34:08 +0200 (CEST) Subject: ANN: hgview 1.4.0 - Mercurial log navigator Message-ID: Announcing HgView 1.4.0 ======================= HgView home page: http://www.logilab.org/project/hgview Tarball: http://ftp.logilab.org/pub/hgview/hgview-1.4.0.tar.gz Hg repository: http://www.logilab.org/src/hgview About this release ================== Text mode inside make it into hgview 1.4.0! This release introduces a *new text based* user interface thanks to the urwid library (http://excess.org/urwid ) This interface includes the following features: * display the revision graph (with working directory as a node, and basic support for the mq), * display the files affected by a selected changeset (with basic support for the bfiles), * display diffs (with syntax highlighting thanks to pygments), * automatically refresh the displayed revision graph when the repository is being modified, * easy key-based navigation in revisions' history of a repo (same as the GUI), * a command system for special actions (see help) To use it type : ``hgview --interface curses`` (or configure it permanently in your config file) There are also some bugfixes. About HgView ============ hgview is a simple tool aiming at visually navigate in a Mercurial (hg) repository history. It is written in Python with quick and efficient key-based navigation in mind, trying to be fast enough for big repositories. --$ python-projects mailing list http://lists.logilab.org/mailman/listinfo/python-projects From jgaynor at ncsa.illinois.edu Thu Oct 6 12:15:52 2011 From: jgaynor at ncsa.illinois.edu (Jeff Gaynor) Date: Thu, 06 Oct 2011 11:15:52 -0500 Subject: Implementing Python-OAuth2 In-Reply-To: References: Message-ID: <4E8DD438.20207@ncsa.illinois.edu> On 10/06/2011 08:34 AM, Kayode Odeyemi wrote: > Hello friends, > > I'm working on a pretty large application that I will like to use > oauth2 on as an authentication and authorization mechanism. > > I understand fairly the technology and I have written my own > implementation before I stumbled on python-oauth2. > > I need advise on leveraging python-oauth2 api for creating consumer > key, creating consumer secret, access token and token secret. > This works well, but be advised that the original python oauth library had some serious issues, so was redone as python-oauth2. What is confusing is that it refers to OAuth version 1.0a, not the upcoming OAuth version 2.0, so make sure you read the right spec before using it, since they are very different indeed. There are *no* usable OAuth version 2..0 implementation in any language (usually Java comes first) that I know of, so you will get to role your own, which is hard. There are a few beta-level versions E.g. Twitter) but these are special cased to the author's needs. The spec itself is not quite ready either and since it has changed quite substantially in the last year, I suspect that everyone is waiting to see it settle to a steady state. Jeff From tjreedy at udel.edu Thu Oct 6 13:18:10 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 06 Oct 2011 13:18:10 -0400 Subject: passing multiple string to a command line option In-Reply-To: <1317914871.44539.YahooMailNeo@web111719.mail.gq1.yahoo.com> References: <1317914871.44539.YahooMailNeo@web111719.mail.gq1.yahoo.com> Message-ID: On 10/6/2011 11:27 AM, Mahmood Naderan wrote: > Dear developers, > Suppose I have this list in command line options: > ... -b b1,b2,b3 > > Here is what I wrote: > parser = optparse.OptionParser() If you are starting a new project, consider using argparse, which has superceded optparse. > # Benchmark options > parser.add_option("-b", "--benchmark", default="", help="The benchmark to be loaded.") > process = [] > benchmarks = options.benchmark.split(',') > for bench_name in benchmarks: > process.append(bench_name) > > At this stage, I want to bind each process to something: > np = 2 > for i in xrange(np): > ... > system.cpu[i].workload = process[i] > > however I get this error: > > File "configs/example/cmp.py", line 81, in > system.cpu[i].workload = process[i] > File "/home/mahmood/gem5/src/python/m5/SimObject.py", line 627, in __setattr__ > value = param.convert(value) > File "/home/mahmood/gem5/src/python/m5/params.py", line 236, in convert > tmp_list = [ ParamDesc.convert(self, value) ] > File "/home/mahmood/gem5/src/python/m5/params.py", line 159, in convert > return self.ptype(value) > TypeError: __init__() takes exactly 1 argument (2 given) > Error setting param TmpClass.workload to bzip2_chicken > > params.py is part of the simulator and I didn't wrote that. > > My question is what is the simplest way to fix that? > Or is there any better idea than what I did in order to parse such command line option? > > thanks > > // Naderan *Mahmood; -- Terry Jan Reedy From ndbecker2 at gmail.com Thu Oct 6 13:18:19 2011 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 06 Oct 2011 13:18:19 -0400 Subject: Dabo 0.9.4 Released! References: Message-ID: Ed Leafe wrote: > Yes, it's been over a year, but today we're finally releasing Dabo 0.9.4! > > What can I say? While we've been actively developing Dabo all along, and > committing improvements and fixes regularly, we don't seem to get around to > doing releases as often as we should. Since Dabo has a Web Update feature that > lets developers receive regular updates between releases, most people are > fairly current, but creating a new release will help newcomers to Dabo get up > to speed quicker. > > The changes won't be too big for most current users of the framework, but > compared to the 0.9.3 release, lots has been fixed and improved! Full release > notes are at: http://svn.dabodev.com/dabo/tags/dabo-0.9.4/ChangeLog > > ...but here are just a few of the major changes since 0.9.3: > > - better handling of edge cases in bizobj relations > - addition of support in bizobjs for many-to-many relationships > - improved efficiency in detecting changed records > - added the dDatePicker control > - added the option of vertical text for grid headers > - integrated a code editor into the command window > > You can grab the latest version, as always, from http://dabodev.com/download > > > > -- Ed Leafe What is it? From miki.tebeka at gmail.com Thu Oct 6 13:24:12 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 6 Oct 2011 10:24:12 -0700 (PDT) Subject: L.A. user group? Message-ID: <9383115.2083.1317921852552.JavaMail.geo-discussion-forums@prma7> Greetings, Is there an L.A. Python user group out there? Thanks, -- Miki From wxjmfauth at gmail.com Thu Oct 6 13:41:57 2011 From: wxjmfauth at gmail.com (jmfauth) Date: Thu, 6 Oct 2011 10:41:57 -0700 (PDT) Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> <4e8d231e$0$29978$c3e8da3$5496439d@news.astraweb.com> <4aeb76e9-511f-4a46-94c7-bf2ab84877df@z12g2000yqz.googlegroups.com> Message-ID: <2f816797-7ecc-4c97-8488-8e8f1ffc5b65@t16g2000yqm.googlegroups.com> On 6 oct, 06:39, Greg wrote: > Brilliant! It worked. Thanks! > > Here is the final code for those who are struggling with similar > problems: > > ## open and decode file > # In this case, the encoding comes from the charset argument in a meta > tag > # e.g. > fileObj = open(filePath,"r").read() > fileContent = fileObj.decode("iso-8859-2") > fileSoup = BeautifulSoup(fileContent) > > ## Do some BeautifulSoup magic and preserve unicode, presume result is > saved in 'text' ## > > ## write extracted text to file > f = open(outFilePath, 'w') > f.write(text.encode('utf-8')) > f.close() > or (Python2/Python3) >>> import io >>> with io.open('abc.txt', 'r', encoding='iso-8859-2') as f: ... r = f.read() ... >>> repr(r) u'a\nb\nc\n' >>> with io.open('def.txt', 'w', encoding='utf-8-sig') as f: ... t = f.write(r) ... >>> f.closed True jmf From fzadrozny at appcelerator.com Thu Oct 6 14:03:54 2011 From: fzadrozny at appcelerator.com (Fabio Zadrozny) Date: Thu, 6 Oct 2011 15:03:54 -0300 Subject: PyDev 2.2.3 Released Message-ID: Hi All, PyDev 2.2.3 has been released Details on PyDev: http://pydev.org Details on its development: http://pydev.blogspot.com Release Highlights: ------------------------------- * Performance improvements * Major: Fixed critical issue when dealing with zip files. * Added option to create method whenever a field would be created in quick fixes (and vice-versa), to properly deal with functional programming styles. * Fixed issue where PyDev was changing the image from another plugin in the Project Explorer (i.e.: removing error decorations from JSP). * Fixed issue: if the django models was opened in PyDev, the 'objects' object was not found in the code analysis. * Test runner no longer leaves exception visible. * Fixed issue on Py3: Relative imports are only relative if they have a leading dot (otherwise it always goes to the absolute). * Default is now set to create project with the projects itself as the source folder. * Handling deletion of .class files. * Fixed issue where loading class InterpreterInfo in AdditionalSystemInterpreterInfo.getPersistingFolder ended up raising a BundleStatusException in the initialization. * Fixed some code formatting issues What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python, Jython and IronPython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer Appcelerator http://appcelerator.com/ Aptana http://aptana.com/ PyDev - Python Development Environment for Eclipse http://pydev.org http://pydev.blogspot.com From brian.curtin at gmail.com Thu Oct 6 14:24:34 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Thu, 6 Oct 2011 13:24:34 -0500 Subject: L.A. user group? In-Reply-To: <9383115.2083.1317921852552.JavaMail.geo-discussion-forums@prma7> References: <9383115.2083.1317921852552.JavaMail.geo-discussion-forums@prma7> Message-ID: On Thu, Oct 6, 2011 at 12:24, Miki Tebeka wrote: > Greetings, > > Is there an L.A. Python user group out there? http://socal-piggies.org might work for you. They recently had a meeting in Santa Monica, and I believe many of the members are LA based. From miki.tebeka at gmail.com Thu Oct 6 14:25:08 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 6 Oct 2011 11:25:08 -0700 (PDT) Subject: passing multiple string to a command line option In-Reply-To: References: Message-ID: <22850959.1256.1317925508336.JavaMail.geo-discussion-forums@prcs9> As far as I see, the problem is not in the command line but in system.cpu[i].workload = process[i] call tree. Without seeing the code of SimObject and params I can't tell much more. From miki.tebeka at gmail.com Thu Oct 6 14:25:08 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 6 Oct 2011 11:25:08 -0700 (PDT) Subject: passing multiple string to a command line option In-Reply-To: References: Message-ID: <22850959.1256.1317925508336.JavaMail.geo-discussion-forums@prcs9> As far as I see, the problem is not in the command line but in system.cpu[i].workload = process[i] call tree. Without seeing the code of SimObject and params I can't tell much more. From thudfoo at gmail.com Thu Oct 6 15:22:06 2011 From: thudfoo at gmail.com (xDog Walker) Date: Thu, 6 Oct 2011 12:22:06 -0700 Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file In-Reply-To: <2f816797-7ecc-4c97-8488-8e8f1ffc5b65@t16g2000yqm.googlegroups.com> References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> <4aeb76e9-511f-4a46-94c7-bf2ab84877df@z12g2000yqz.googlegroups.com> <2f816797-7ecc-4c97-8488-8e8f1ffc5b65@t16g2000yqm.googlegroups.com> Message-ID: <201110061222.07161.thudfoo@gmail.com> On Thursday 2011 October 06 10:41, jmfauth wrote: > or ?(Python2/Python3) > > >>> import io > >>> with io.open('abc.txt', 'r', encoding='iso-8859-2') as f: > > ... ? ? r = f.read() > ... > > >>> repr(r) > > u'a\nb\nc\n' > > >>> with io.open('def.txt', 'w', encoding='utf-8-sig') as f: > > ... ? ? t = f.write(r) > ... > > >>> f.closed > > True > > jmf What is this io of which you speak? -- I have seen the future and I am not in it. From gordon at panix.com Thu Oct 6 15:29:51 2011 From: gordon at panix.com (John Gordon) Date: Thu, 6 Oct 2011 19:29:51 +0000 (UTC) Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> <4aeb76e9-511f-4a46-94c7-bf2ab84877df@z12g2000yqz.googlegroups.com> <2f816797-7ecc-4c97-8488-8e8f1ffc5b65@t16g2000yqm.googlegroups.com> Message-ID: In xDog Walker writes: > What is this io of which you speak? It was introduced in Python 2.6. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From nt_mahmood at yahoo.com Thu Oct 6 15:51:58 2011 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Thu, 6 Oct 2011 12:51:58 -0700 (PDT) Subject: passing multiple string to a command line option In-Reply-To: <22850959.1256.1317925508336.JavaMail.geo-discussion-forums@prcs9> References: <22850959.1256.1317925508336.JavaMail.geo-discussion-forums@prcs9> Message-ID: <1317930718.65743.YahooMailNeo@web111724.mail.gq1.yahoo.com> >Without seeing the code of SimObject and params I can't tell much more. >? ? File "/home/mahmood/gem5/src/python/m5/params.py", line 159, in convert >? ? ? return self.ptype(value) following is part of params.py and I marked line 159. I didn't wrote this code so changing this may cause problem with other files. If there is an alternative for doing such thing "passing multiple strings to command line option", it is? much better. ?# Regular parameter description. class ParamDesc(object): ??? file_ext = 'ptype' ??? def __init__(self, ptype_str, ptype, *args, **kwargs): ??????? self.ptype_str = ptype_str ??????? # remember ptype only if it is provided ??????? if ptype != None: ??????????? self.ptype = ptype ??????? if args: ??????????? if len(args) == 1: ??????????????? self.desc = args[0] ??????????? elif len(args) == 2: ??????????????? self.default = args[0] ??????????????? self.desc = args[1] ??????????? else: ??????????????? raise TypeError, 'too many arguments' ??????? if kwargs.has_key('desc'): ??????????? assert(not hasattr(self, 'desc')) ??????????? self.desc = kwargs['desc'] ??????????? del kwargs['desc'] ??????? if kwargs.has_key('default'): ??????????? assert(not hasattr(self, 'default')) ??????????? self.default = kwargs['default'] ??????????? del kwargs['default'] ??????? if kwargs: ??????????? raise TypeError, 'extra unknown kwargs %s' % kwargs ??????? if not hasattr(self, 'desc'): ??????????? raise TypeError, 'desc attribute missing' ??? def __getattr__(self, attr): ??????? if attr == 'ptype': ??????????? ptype = SimObject.allClasses[self.ptype_str] ??????????? assert isSimObjectClass(ptype) ??????????? self.ptype = ptype ??????????? return ptype ??????? raise AttributeError, "'%s' object has no attribute '%s'" % \ ????????????? (type(self).__name__, attr) ??? def convert(self, value): ??????? if isinstance(value, proxy.BaseProxy): ??????????? value.set_param_desc(self) ??????????? return value ??????? if not hasattr(self, 'ptype') and isNullPointer(value): ??????????? # deferred evaluation of SimObject; continue to defer if ??????????? # we're just assigning a null pointer ??????????? return value ??????? if isinstance(value, self.ptype): ??????????? return value ??????? if isNullPointer(value) and isSimObjectClass(self.ptype): ??????????? return value ??????? return self.ptype(value)???????????? # LINE 159 ??? def cxx_predecls(self, code): ??????? self.ptype.cxx_predecls(code) ??? def swig_predecls(self, code): ??????? self.ptype.swig_predecls(code) ??? def cxx_decl(self, code): ??????? code('${{self.ptype.cxx_type}} ${{self.name}};') // Naderan *Mahmood; ----- Original Message ----- From: Miki Tebeka To: comp.lang.python at googlegroups.com Cc: python mailing list ; Mahmood Naderan Sent: Thursday, October 6, 2011 9:55 PM Subject: Re: passing multiple string to a command line option As far as I see, the problem is not in the command line but in? ? system.cpu[i].workload = process[i] call tree. Without seeing the code of SimObject and params I can't tell much more. From Joshua.R.English at gmail.com Thu Oct 6 21:14:26 2011 From: Joshua.R.English at gmail.com (Josh English) Date: Thu, 6 Oct 2011 18:14:26 -0700 (PDT) Subject: Deleting files on a shared server Message-ID: <24959174.190.1317950066875.JavaMail.geo-discussion-forums@prho12> This is a follow-up to some questions I posted a month or two ago. I have two programs running on various Windows XP boxes, sharing several resource files on a Windows 2003 server. It's a mapped drive on the workstations to a shared folder. I am using a locking utility that works by creating ".lock" files in the shared folder and deleting those files when the program is done with them. To delete the files, I am using os.unlink. One lock file refuses to disappear, even though I have code at both application startup and shutdown (on the OnInit and OnExit methods to the wxPython Application object) that hunts down .lock files and deletes them. Is there a better command than os.unlink to delete a file on Windows 2003 server? Josh From steve+comp.lang.python at pearwood.info Thu Oct 6 22:02:26 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 07 Oct 2011 13:02:26 +1100 Subject: A tuple in order to pass returned values ? References: Message-ID: <4e8e5db3$0$29967$c3e8da3$5496439d@news.astraweb.com> Jean-Michel Pichavant wrote: > In a general manner, ppl will tend to use the minimum arguments > required. However, do not pack values into tuple if they are not related. How would you return multiple values if not in a tuple? Tuples are *the* mechanism for returning multiple values in Python. If you're doing something else, you're wasting your time. > A better thing to do would be to use objects instead of tuples, tuples > can serve as lazy structures for small application/script, they can > become harmful in more complexe applications, especialy when used in > public interfaces. First off, tuples *are* objects, like everything else in Python. If you are creating custom classes *just* to hold state, instead of using a tuple, you are wasting time. Instead of this: class Record: def __init__(self, x, y, z): self.x = x self.y = y self.z = z result = Record(1, 2, 3) Just use a tuple or a namedtuple: the work is already done for you, you have a well-written, fast, rich data structure ready to use. For two or three items, or for short-lived results that only get used once, an ordinary tuple is fine, but otherwise a namedtuple is much better: from collections import namedtuple result = namedtuple('Record', 'x y z')(1, 2, 3) -- Steven From steve+comp.lang.python at pearwood.info Thu Oct 6 23:04:57 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 07 Oct 2011 14:04:57 +1100 Subject: Deleting files on a shared server References: <24959174.190.1317950066875.JavaMail.geo-discussion-forums@prho12> Message-ID: <4e8e6c5a$0$30002$c3e8da3$5496439d@news.astraweb.com> Josh English wrote: > This is a follow-up to some questions I posted a month or two ago. I have > two programs running on various Windows XP boxes, sharing several resource > files on a Windows 2003 server. It's a mapped drive on the workstations to > a shared folder. > > I am using a locking utility that works by creating ".lock" files in the > shared folder and deleting those files when the program is done with them. > > To delete the files, I am using os.unlink. How and when? If you are deleting the files using a __del__ handler in an instance, it is quick possible that it is never being run, or not being run when you think it is. For file locking, you should consider using a portable solution like this one: http://code.activestate.com/recipes/65203-portalocker-cross-platform-posixnt-api-for-flock-s/ > One lock file refuses to disappear, even though I have code at both > application startup and shutdown (on the OnInit and OnExit methods to the > wxPython Application object) that hunts down .lock files and deletes them. Perhaps the file is open and so can't be deleted under Windows. Are you getting an exception when you try to unlink the file? If so, what does it say? > Is there a better command than os.unlink to delete a file on Windows 2003 > server? No. os.unlink is a wrapper around your system's unlink command -- if it can't delete the file, you can't delete the file. -- Steven From miki.tebeka at gmail.com Thu Oct 6 23:05:30 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 6 Oct 2011 20:05:30 -0700 (PDT) Subject: L.A. user group? In-Reply-To: References: <9383115.2083.1317921852552.JavaMail.geo-discussion-forums@prma7> Message-ID: <2719923.311.1317956730911.JavaMail.geo-discussion-forums@prfp13> Thanks! From miki.tebeka at gmail.com Thu Oct 6 23:05:30 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 6 Oct 2011 20:05:30 -0700 (PDT) Subject: L.A. user group? In-Reply-To: References: <9383115.2083.1317921852552.JavaMail.geo-discussion-forums@prma7> Message-ID: <2719923.311.1317956730911.JavaMail.geo-discussion-forums@prfp13> Thanks! From wuwei23 at gmail.com Thu Oct 6 23:10:56 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 6 Oct 2011 20:10:56 -0700 (PDT) Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> <4e8bed30$0$29978$c3e8da3$5496439d@news.astraweb.com> <87wrcjzmql.fsf@benfinney.id.au> Message-ID: <65fb52c4-0b30-43c7-a9f4-153d18d72ed4@hd1g2000vbb.googlegroups.com> Dennis Lee Bieber wrote: > ? ? ? ? While I wouldn't want to write an FFT in COBOL, one can't deny that > laying out fixed width reports and moving blocks of decimal data between > record layouts is quite easy in COBOL. Well, sure, but there's still plenty of pain in the verbosity :) From Joshua.R.English at gmail.com Fri Oct 7 01:08:19 2011 From: Joshua.R.English at gmail.com (Josh English) Date: Thu, 6 Oct 2011 22:08:19 -0700 (PDT) Subject: Deleting files on a shared server In-Reply-To: <24959174.190.1317950066875.JavaMail.geo-discussion-forums@prho12> References: <24959174.190.1317950066875.JavaMail.geo-discussion-forums@prho12> Message-ID: <27274396.452.1317964099801.JavaMail.geo-discussion-forums@prib32> The problem shows up when the application starts. It tries to read the file but the lock mechanism times out because the file is still around after the last time the application ran. It's a wxPython program. The code to unlink the .lock files is run in the wxApp.OnInit method (before any code to open these resources) and in the wxApp.OnExit method. I know both of these methods are being called. The locking mechanism I am using can be found at http://www.evanfosmark.com/2009/01/cross-platform-file-locking-support-in-python/ The clearing code is: import os import fnmatch files = fnmatch.filter(os.listdir(self.Options.DataDir), "*.lock") for f in files: os.unlink(os.path.abspath(os.path.join(self.Options.DataDir, f))) The Options object has a property called DataDir. MMM... Now that I sit down to test abso-frikkin'-lutely that this code does what I want it to do, it appears not to do this at all. The files list I build doesn't work and returns an empty list. I may have found a workaround using glob. Now my face is red. From masood.524 at gmail.com Fri Oct 7 01:18:04 2011 From: masood.524 at gmail.com (masood shaik) Date: Thu, 6 Oct 2011 22:18:04 -0700 (PDT) Subject: database connection Message-ID: <618adb1f-73b4-4372-9ad4-4b2f8c312601@h10g2000yqd.googlegroups.com> Hi can u please tell me how we can connect to database without changing the permission of db file using sqlite3 From rustompmody at gmail.com Fri Oct 7 01:40:35 2011 From: rustompmody at gmail.com (rusi) Date: Thu, 6 Oct 2011 22:40:35 -0700 (PDT) Subject: PyDev 2.2.3 Released References: Message-ID: On Oct 6, 11:03?pm, Fabio Zadrozny wrote: > Hi All, > > PyDev 2.2.3 has been released > > Details on PyDev:http://pydev.org > Details on its development:http://pydev.blogspot.com On my debian box I get: $ /opt/Aptana\ Studio\ 3/AptanaStudio3 HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught TypeError: Object [object Event],, has no method 'toJSON',javascript::1) HandleConsoleMessage(Uncaught ReferenceError: loadPortal is not defined,http://content.aptana.com/aptana/my_aptana/? content=start&id=83fef29f-0f3d-40db-8b9a-0f417b84cd8c&v=3.0.0.1316445268&ts=1317965412438&fg=f8f8f8&p=O&bg=141414&ch=edeceb: 59) HandleConsoleMessage(AJS.Confluence: run binder components,http:// wiki.appcelerator.org/s/en/2159/26/58/_/download/superbatch/js/ batch.js:436) HandleConsoleMessage(Dropdown width override occurred,http:// wiki.appcelerator.org/s/en/2159/26/58/_/download/superbatch/js/ batch.js:436) HandleConsoleMessage(Dropdown width override occurred,http:// wiki.appcelerator.org/s/en/2159/26/58/_/download/superbatch/js/ batch.js:436) HandleConsoleMessage(Drag and Drop: requesting translation,http:// wiki.appcelerator.org/s/en/2159/26/58/_/download/superbatch/js/ batch.js:436) HandleConsoleMessage(DragAndDropUtils: computed cache URL: /s/en/ 2159/26/1.0.16/_/plugins/drag-and-drop/i18n.action?locale=en_GB,http:// wiki.appcelerator.org/s/en/2159/26/58/_/download/superbatch/js/ batch.js:436) HandleConsoleMessage(Overriding default quick search,http:// wiki.appcelerator.org/s/en/2159/26/58/_/download/superbatch/js/ batch.js:436) HandleConsoleMessage(Applying doc-theme quick search,http:// wiki.appcelerator.org/s/en/2159/26/58/_/download/superbatch/js/ batch.js:436) HandleConsoleMessage(confluence-keyboard-shortcuts initialising,http:// wiki.appcelerator.org/s/en/2159/26/58/_/download/superbatch/js/ batch.js:436) [1007/110047:ERROR:base/native_library_linux.cc(28)] dlopen failed when trying to open /opt/jre1.6.0_20/lib/i386/libnpjp2.so: /opt/ jre1.6.0_20/lib/i386/libnpjp2.so: undefined symbol: __gxx_personality_v0 Job found still running after platform shutdown. Jobs should be canceled by the plugin that scheduled them during shutdown: com.aptana.usage.StudioAnalytics$1 From selahattin_ay at msn.com Fri Oct 7 02:23:57 2011 From: selahattin_ay at msn.com (selahattin ay) Date: Fri, 7 Oct 2011 06:23:57 +0000 Subject: sending ftp file list to mail??? Message-ID: hi all. I want to get my ftp list and send the list to my mail adress... my codes are from ftplib import FTP import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMETextbaglanti = FTP("ftp.guncelyorum.org") baglanti.login("******", "*******") print baglanti.dir() posta = MIMEMultipart()def posta_olustur(): posta['Subject']=konu posta['From']=gmail_kullanici posta['To']=kime posta.attach(MIMEText(baglanti.retrlines("LIST"))) <------ what can I do for here def posta_gonder(): smtpserver = smtplib.SMTP("smtp.gmail.com",587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo smtpserver.login(gmail_kullanici, gmail_sifre) print "baglanti saglandi" smtpserver.sendmail(gmail_kullanici, kime, posta.as_string()) print "Posta Gonderildi" smtpserver.close() # mail to kime = raw_input("Kime gonderecesiniz?: ") # gmail user namegmail_kullanici = raw_input("gmail kullanici adiniz: ") #gmail passgmail_sifre = raw_input("Gmail sifreniz: ") #subjectkonu = raw_input ("Posta Konusu: ") posta_olustur() posta_gonder() -------------- next part -------------- An HTML attachment was scrubbed... URL: From lucaberto at libero.it Fri Oct 7 03:19:35 2011 From: lucaberto at libero.it (luca72) Date: Fri, 7 Oct 2011 00:19:35 -0700 (PDT) Subject: matplotlib on osx 10.6 Message-ID: <3ba1a0ca-d959-4367-b5f8-fff283f577cf@g29g2000yqh.googlegroups.com> hello i try to install matplotlib on osx 10.6 , i have also installed freetype libpng and numpy but i get this error: BUILDING MATPLOTLIB matplotlib: 1.1.0 python: 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] platform: darwin REQUIRED DEPENDENCIES numpy: 1.2.1 freetype2: found, but unknown version (no pkg-config) * WARNING: Could not find 'freetype2' headers in any * of '.', './freetype2'. OPTIONAL BACKEND DEPENDENCIES libpng: found, but unknown version (no pkg-config) * Could not find 'libpng' headers in any of '.' Tkinter: Tkinter: 67083, Tk: 8.5, Tcl: 8.5 Gtk+: no * Building for Gtk+ requires pygtk; you must be able * to "import gtk" in your build/install environment Mac OS X native: yes Qt: no Qt4: Qt: 4.7.0, PyQt4: 4.8.2 Cairo: no OPTIONAL DATE/TIMEZONE DEPENDENCIES datetime: present, version unknown dateutil: present, version unknown pytz: matplotlib will provide adding pytz OPTIONAL USETEX DEPENDENCIES dvipng: no ghostscript: /bin/sh: gs: command not found latex: no [Edit setup.cfg to suppress the above messages] ============================================================================ pymods ['pylab'] packages ['matplotlib', 'matplotlib.backends', 'matplotlib.backends.qt4_editor', 'matplotlib.projections', 'matplotlib.testing', 'matplotlib.testing.jpl_units', 'matplotlib.tests', 'mpl_toolkits', 'mpl_toolkits.mplot3d', 'mpl_toolkits.axes_grid', 'mpl_toolkits.axes_grid1', 'mpl_toolkits.axisartist', 'matplotlib.sphinxext', 'matplotlib.tri', 'matplotlib.delaunay', 'pytz'] running build running build_py copying lib/matplotlib/mpl-data/matplotlibrc -> build/lib.macosx-10.6- universal-2.6/matplotlib/mpl-data copying lib/matplotlib/mpl-data/matplotlib.conf -> build/ lib.macosx-10.6-universal-2.6/matplotlib/mpl-data running build_ext building 'matplotlib.ft2font' extension gcc-4.2 -fno-strict-aliasing -fno-common -dynamic -DNDEBUG -g -fwrapv - Os -Wall -DENABLE_DTRACE -arch i386 -arch ppc -arch x86_64 -pipe - DPY_ARRAY_UNIQUE_SYMBOL=MPL_ARRAY_API -DPYCXX_ISO_CPP_LIB=1 -I/System/ Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/ numpy/core/include -I. -I/System/Library/Frameworks/Python.framework/ Versions/2.6/Extras/lib/python/numpy/core/include/freetype2 -I./ freetype2 -I/System/Library/Frameworks/Python.framework/Versions/2.6/ include/python2.6 -c src/ft2font.cpp -o build/temp.macosx-10.6- universal-2.6/src/ft2font.o In file included from src/ft2font.h:16, from src/ft2font.cpp:3: /usr/local/include/ft2build.h:56:38: error: freetype/config/ ftheader.h: No such file or directory In file included from src/ft2font.cpp:3: src/ft2font.h:17:10: error: #include expects "FILENAME" or src/ft2font.h:18:10: error: #include expects "FILENAME" or src/ft2font.h:19:10: error: #include expects "FILENAME" or src/ft2font.h:20:10: error: #include expects "FILENAME" or src/ft2font.h:21:10: error: #include expects "FILENAME" or In file included from src/ft2font.cpp:3: src/ft2font.h:35: error: ?FT_Bitmap? has not been declared src/ft2font.h:35: error: ?FT_Int? has not been declared src/ft2font.h:35: error: ?FT_Int? has not been declared src/ft2font.h:91: error: expected ?,? or ?...? before ?&? token src/ft2font.h:91: error: ISO C++ forbids declaration of ?FT_Face? with no type src/ft2font.h:138: error: ?FT_Face? does not name a type src/ft2font.h:139: error: ?FT_Matrix? does not name a type src/ft2font.h:140: error: ?FT_Vector? does not name a type src/ft2font.h:141: error: ?FT_Error? does not name a type src/ft2font.h:142: error: ?FT_Glyph? was not declared in this scope src/ft2font.h:142: error: template argument 1 is invalid src/ft2font.h:142: error: template argument 2 is invalid src/ft2font.h:143: error: ?FT_Vector? was not declared in this scope src/ft2font.h:143: error: template argument 1 is invalid src/ft2font.h:143: error: template argument 2 is invalid src/ft2font.h:149: error: ?FT_BBox? does not name a type src/ft2font.cpp:51: error: ?FT_Library? does not name a type src/ft2font.cpp:114: error: variable or field ?draw_bitmap? declared void src/ft2font.cpp:114: error: ?FT_Bitmap? was not declared in this scope src/ft2font.cpp:114: error: ?bitmap? was not declared in this scope src/ft2font.cpp:115: error: ?FT_Int? was not declared in this scope src/ft2font.cpp:116: error: ?FT_Int? was not declared in this scope /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/ python/numpy/core/include/numpy/__multiarray_api.h:958: warning: ?int _import_array()? defined but not used In file included from src/ft2font.h:16, from src/ft2font.cpp:3: /usr/local/include/ft2build.h:56:38: error: freetype/config/ ftheader.h: No such file or directory In file included from src/ft2font.cpp:3: src/ft2font.h:17:10: error: #include expects "FILENAME" or src/ft2font.h:18:10: error: #include expects "FILENAME" or src/ft2font.h:19:10: error: #include expects "FILENAME" or src/ft2font.h:20:10: error: #include expects "FILENAME" or src/ft2font.h:21:10: error: #include expects "FILENAME" or In file included from src/ft2font.cpp:3: src/ft2font.h:35: error: ?FT_Bitmap? has not been declared src/ft2font.h:35: error: ?FT_Int? has not been declared src/ft2font.h:35: error: ?FT_Int? has not been declared src/ft2font.h:91: error: expected ?,? or ?...? before ?&? token src/ft2font.h:91: error: ISO C++ forbids declaration of ?FT_Face? with no type src/ft2font.h:138: error: ?FT_Face? does not name a type src/ft2font.h:139: error: ?FT_Matrix? does not name a type src/ft2font.h:140: error: ?FT_Vector? does not name a type src/ft2font.h:141: error: ?FT_Error? does not name a type src/ft2font.h:142: error: ?FT_Glyph? was not declared in this scope src/ft2font.h:142: error: template argument 1 is invalid src/ft2font.h:142: error: template argument 2 is invalid src/ft2font.h:143: error: ?FT_Vector? was not declared in this scope src/ft2font.h:143: error: template argument 1 is invalid src/ft2font.h:143: error: template argument 2 is invalid src/ft2font.h:149: error: ?FT_BBox? does not name a type src/ft2font.cpp:51: error: ?FT_Library? does not name a type src/ft2font.cpp:114: error: variable or field ?draw_bitmap? declared void src/ft2font.cpp:114: error: ?FT_Bitmap? was not declared in this scope src/ft2font.cpp:114: error: ?bitmap? was not declared in this scope src/ft2font.cpp:115: error: ?FT_Int? was not declared in this scope src/ft2font.cpp:116: error: ?FT_Int? was not declared in this scope /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/ python/numpy/core/include/numpy/__multiarray_api.h:958: warning: ?int _import_array()? defined but not used In file included from src/ft2font.h:16, from src/ft2font.cpp:3: /usr/local/include/ft2build.h:56:38: error: freetype/config/ ftheader.h: No such file or directory In file included from src/ft2font.cpp:3: src/ft2font.h:17:10: error: #include expects "FILENAME" or src/ft2font.h:18:10: error: #include expects "FILENAME" or src/ft2font.h:19:10: error: #include expects "FILENAME" or src/ft2font.h:20:10: error: #include expects "FILENAME" or src/ft2font.h:21:10: error: #include expects "FILENAME" or In file included from src/ft2font.cpp:3: src/ft2font.h:35: error: ?FT_Bitmap? has not been declared src/ft2font.h:35: error: ?FT_Int? has not been declared src/ft2font.h:35: error: ?FT_Int? has not been declared src/ft2font.h:91: error: expected ?,? or ?...? before ?&? token src/ft2font.h:91: error: ISO C++ forbids declaration of ?FT_Face? with no type src/ft2font.h:138: error: ?FT_Face? does not name a type src/ft2font.h:139: error: ?FT_Matrix? does not name a type src/ft2font.h:140: error: ?FT_Vector? does not name a type src/ft2font.h:141: error: ?FT_Error? does not name a type src/ft2font.h:142: error: ?FT_Glyph? was not declared in this scope src/ft2font.h:142: error: template argument 1 is invalid src/ft2font.h:142: error: template argument 2 is invalid src/ft2font.h:143: error: ?FT_Vector? was not declared in this scope src/ft2font.h:143: error: template argument 1 is invalid src/ft2font.h:143: error: template argument 2 is invalid src/ft2font.h:149: error: ?FT_BBox? does not name a type src/ft2font.cpp:51: error: ?FT_Library? does not name a type src/ft2font.cpp:114: error: variable or field ?draw_bitmap? declared void src/ft2font.cpp:114: error: ?FT_Bitmap? was not declared in this scope src/ft2font.cpp:114: error: ?bitmap? was not declared in this scope src/ft2font.cpp:115: error: ?FT_Int? was not declared in this scope src/ft2font.cpp:116: error: ?FT_Int? was not declared in this scope /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/ python/numpy/core/include/numpy/__multiarray_api.h:958: warning: ?int _import_array()? defined but not used lipo: can't open input file: /var/folders/wA/wAdFPXZ7FC0P4R1RaKSw3k++ +TI/-Tmp-//ccFESr3g.out (No such file or directory) error: command 'gcc-4.2' failed with exit status 1 Please help me From mail at timgolden.me.uk Fri Oct 7 03:45:32 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 07 Oct 2011 08:45:32 +0100 Subject: Deleting files on a shared server In-Reply-To: <24959174.190.1317950066875.JavaMail.geo-discussion-forums@prho12> References: <24959174.190.1317950066875.JavaMail.geo-discussion-forums@prho12> Message-ID: <4E8EAE1C.1050104@timgolden.me.uk> On 07/10/2011 02:14, Josh English wrote: > This is a follow-up to some questions I posted a month or two ago. I > have two programs running on various Windows XP boxes, sharing > several resource files on a Windows 2003 server. It's a mapped drive > on the workstations to a shared folder. > > I am using a locking utility that works by creating ".lock" files in > the shared folder and deleting those files when the program is done > with them. > > To delete the files, I am using os.unlink. > > One lock file refuses to disappear, even though I have code at both > application startup and shutdown (on the OnInit and OnExit methods to > the wxPython Application object) that hunts down .lock files and > deletes them. Assuming that your code paths succeed and that the unlink actually happens, it is possible for files to continue to exist after they have been successfully deleted. This happens if another process has opened them with share-delete mode; typically this will be a virus checker or a process like the TortoiseSVN cache (or its counterparts for other VCS). The file won't actually disappear until the last handle on it is released. TJG From gagsl-py2 at yahoo.com.ar Fri Oct 7 04:16:40 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Oct 2011 05:16:40 -0300 Subject: database connection References: <618adb1f-73b4-4372-9ad4-4b2f8c312601@h10g2000yqd.googlegroups.com> Message-ID: En Fri, 07 Oct 2011 02:18:04 -0300, masood shaik escribi?: > can u please tell me how we can connect to database without changing > the permission of db file using sqlite3 The OS user who executes the Python script must have read (and write, usually) access to the database file - *any* OS user who can read the database file can connect to it. sqlite does not have internal users, and does not implement GRANT/REVOKE statements. -- Gabriel Genellina From poalman at gmail.com Fri Oct 7 04:29:29 2011 From: poalman at gmail.com (Paul) Date: Fri, 7 Oct 2011 08:29:29 +0000 (UTC) Subject: Thread handling issue Message-ID: I'm wondering what the best solution for this problem is. I've got a wxpython app, in one part a user makes some selections then opens a dialog to select where to output. At which point the app starts a thread processing their selection while they're choosing an output location, hopefully ready for when they're done. My problem is if the user doesn't select an output location and cancels the dialog to go back to the selection I want to terminate the thread to avoid the user opening and closing the output selection firing off a ton of threads. As there's no inbuilt way of killing threads I was wondering the best way to prevent this? From lucaberto at libero.it Fri Oct 7 04:32:36 2011 From: lucaberto at libero.it (luca72) Date: Fri, 7 Oct 2011 01:32:36 -0700 (PDT) Subject: matplotlib on osx 10.6 References: <3ba1a0ca-d959-4367-b5f8-fff283f577cf@g29g2000yqh.googlegroups.com> Message-ID: <72680a34-62d1-47d2-b85f-b699900b8f77@f6g2000vbm.googlegroups.com> Hello i have solved installing gfortran and pkgconfig Luca From gagsl-py2 at yahoo.com.ar Fri Oct 7 04:34:58 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Oct 2011 05:34:58 -0300 Subject: How to inspect slot wrappers arguments in Python? References: Message-ID: En Sat, 01 Oct 2011 12:13:45 -0300, julian bilcke escribi?: > I would like to get the list of parameters I need to initialize an AST > node. > > I'm trying to use the `inspect` module, however it seems I can't use it > on a > built-in (native?) class, or else I misunderstood. [...] > > >>> import inspect > >>> import ast > >>> inspect.getargspec(ast.If.__init__) > Traceback (most recent call last): > File "", line 1, in > File > "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py", > line 813, in getargspec > raise TypeError('{!r} is not a Python function'.format(func)) > TypeError: is not a > Python function > > I am wondering if there is another way to get these parameters > automatically? (ie. without compiling myself a dict) I'm afraid there is no way; this kind of introspection does not work for functions written in C. The function itself usually has a generic signature resembling (*args, **kw), and its parameters are usually unpacked calling a suitable variant of PyArg_ParseXXX. The information about the number and type of expected arguments is encoded in its 'format' parameter, and is not stored anywhere. -- Gabriel Genellina From mail at timgolden.me.uk Fri Oct 7 04:45:38 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 07 Oct 2011 09:45:38 +0100 Subject: Thread handling issue In-Reply-To: References: Message-ID: <4E8EBC32.9060000@timgolden.me.uk> On 07/10/2011 09:29, Paul wrote: > I'm wondering what the best solution for this problem is. > > I've got a wxpython app, in one part a user makes some selections then opens a > dialog to select where to output. At which point the app starts a thread > processing their selection while they're choosing an output location, hopefully > ready for when they're done. > > My problem is if the user doesn't select an output location and cancels the > dialog to go back to the selection I want to terminate the thread to avoid the > user opening and closing the output selection firing off a ton of threads. > > As there's no inbuilt way of killing threads I was wondering the best way to > prevent this? The most common approach is to have the thread monitor an event which is set if, for example, the user cancels. The thread may of course have to wait, for example, for a long-running database query to complete before it can discover that its time has been wasted :) The exact mechanism will depend on how your code is structured, what the thread is doing, and how it's passing anything back to the main thread. TJG From jyesudian at gmail.com Fri Oct 7 05:01:46 2011 From: jyesudian at gmail.com (Yesudian Rajkumar Johnkoilpillai) Date: Fri, 7 Oct 2011 14:31:46 +0530 Subject: Python selenium web driver Message-ID: Hi, I am looking into using Selenium 2.0 for launching Firefox and browse few sites. I am using Python APIs to talk to webdriver on Ubuntu 11.04. I am basically trying to follow the steps mentioned at http://pypi.python.org/pypi/selenium . When I run the program, it throws error as below. yesudian at yesudian-virtual-machine:~/Try$ sudo python five.py [sudo] password for yesudian: Traceback (most recent call last): File "five.py", line 6, in browser = webdriver.Firefox() # Get local session of firefox File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py", line 46, in __init__ self.binary, timeout), File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/extension_connection.py", line 46, in __init__ self.binary.launch_browser(self.profile) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 44, in launch_browser self._wait_until_connectable() File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 87, in _wait_until_connectable raise WebDriverException("Can't load the profile. Profile Dir : %s" % self.profile.path) selenium.common.exceptions.WebDriverException: Message: "Can't load the profile. Profile Dir : /tmp/tmpCR4CB7" I tried to launch chrome also and the same issue happens. Do you have any thoughts ? Regards Yesudian Rajkumar -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri Oct 7 05:16:48 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Oct 2011 06:16:48 -0300 Subject: sending ftp file list to mail??? References: Message-ID: En Fri, 07 Oct 2011 03:23:57 -0300, selahattin ay escribi?: > hi all. I want to get my ftp list and send the list to my mail adress... > my codes are And your problem is...? -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri Oct 7 05:28:28 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Oct 2011 06:28:28 -0300 Subject: sending ftp file list to mail??? References: Message-ID: En Fri, 07 Oct 2011 03:23:57 -0300, selahattin ay escribi?: > hi all. I want to get my ftp list and send the list to my mail adress... > my codes are > baglanti = FTP("ftp.guncelyorum.org") > baglanti.login("******", "*******") > print baglanti.dir() > posta = MIMEMultipart() > def posta_olustur(): > posta['Subject']=konu > posta['From']=gmail_kullanici > posta['To']=kime > posta.attach(MIMEText(baglanti.retrlines("LIST"))) <------ what > can I do for here Ah, I didn't notice that part. MIMEText expects a string. retrlines, by default, outputs to stdout, isn't very useful. Try this: def posta_olustur(): ... lines = [] baglanti.retrlines("LIST", lines.append) text = '\n'.join(lines) posta.attach(MIMEText(text)) -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri Oct 7 05:37:12 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 07 Oct 2011 06:37:12 -0300 Subject: socket.getsockname is returning junk!! References: <02EA6D704E30CE499C5071776509A925F5C8F8@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: En Wed, 05 Oct 2011 08:56:08 -0300, Wong Wah Meng-R32813 escribi?: > I am migrating my application from python 1.5.2 to 2.7.1. One of the > existing code breaks. The getsockname method from socket object somehow > returns me with some number which I deem as junk, rather than the > listening port as I would have expected in the older python. Has anyone > seen the same thing or is it due to my python is built with some > corrupted library or something? > > > $ python > Python 2.7.1 (r271:86832, Oct 5 2011, 18:34:15) [C] on hp-ux11 > Type "help", "copyright", "credits" or "license" for more information. >>>> import socket >>>> sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) >>>> sock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 ) >>>> sock.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1 ) >>>> sock.setsockopt( socket.IPPROTO_TCP, 1, 1 ) >>>> server_address=('zmy02hp3', 11111) >>>> sock.bind(server_address) >>>> sock.getsockname() > (0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') > > In python 1.5.2 >>>> server_address=('zmy02aix04', 11111) >>>> sock.bind(server_address) >>>> sock.getsockname() > ('10.228.51.41', 11111) I'd say it's a problem with the _socket module; did the unit tests flag anything when you built Python? On Windows, Python 2.7.1: >>> server_address=('lepton', 11111) >>> sock.bind(server_address) >>> sock.getsockname() ('127.0.0.1', 11111) -- Gabriel Genellina From jeanmichel at sequans.com Fri Oct 7 05:43:30 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 07 Oct 2011 11:43:30 +0200 Subject: A tuple in order to pass returned values ? In-Reply-To: <4e8e5db3$0$29967$c3e8da3$5496439d@news.astraweb.com> References: <4e8e5db3$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E8EC9C2.1080306@sequans.com> Steven D'Aprano wrote: > Jean-Michel Pichavant wrote: > > >> In a general manner, ppl will tend to use the minimum arguments >> required. However, do not pack values into tuple if they are not related. >> > > How would you return multiple values if not in a tuple? > > Tuples are *the* mechanism for returning multiple values in Python. If > you're doing something else, you're wasting your time. > > > >> A better thing to do would be to use objects instead of tuples, tuples >> can serve as lazy structures for small application/script, they can >> become harmful in more complexe applications, especialy when used in >> public interfaces. >> > > First off, tuples *are* objects, like everything else in Python. > > If you are creating custom classes *just* to hold state, instead of using a > tuple, you are wasting time. Instead of this: > > class Record: > def __init__(self, x, y, z): > self.x = x > self.y = y > self.z = z > > result = Record(1, 2, 3) > > Just use a tuple or a namedtuple: the work is already done for you, you have > a well-written, fast, rich data structure ready to use. For two or three > items, or for short-lived results that only get used once, an ordinary > tuple is fine, but otherwise a namedtuple is much better: > > from collections import namedtuple > result = namedtuple('Record', 'x y z')(1, 2, 3) > > I don't have access to namedtuple, working with python 2.5 It sounds to me that namedtuple exactly tries to fix what I dislike in tuples : undocumented packing of unrelated data. However, I'm not sure it fixes the main issue: unpacking. Unpacking prevents you from adding any additional fields to your 'tuple' without breaking any line of code that was unpacking the tuple (to oppose to accessing an object attribute). And it did annoy me a lot when improving applications. Now I'm using tuples only in small applications, and try to avoid unpacking as much as possible. namedtuple sounds great (if you don't use unpacking :o) ), too bad it is available only from python 2.6. JM From r32813 at freescale.com Fri Oct 7 05:48:58 2011 From: r32813 at freescale.com (Wong Wah Meng-R32813) Date: Fri, 7 Oct 2011 09:48:58 +0000 Subject: socket.getsockname is returning junk!! In-Reply-To: References: <02EA6D704E30CE499C5071776509A925F5C8F8@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <02EA6D704E30CE499C5071776509A925F5D440@039-SN1MPN1-003.039d.mgd.msft.net> Thanks. Someone pointed out that this could be due to a corrupted build, which I revisited the process. I included -lxnet in the linking process of the build, and this problem is resolved. The -lxnet was stated in README file for HP-UX Itanium build, which I somehow dropped it out in the middle of the process and wasn't aware it was essential as excluding it cost me the junk I was seeing. Problem solved!! Thanks a lot for reverting. :) Regards, Wah Meng -----Original Message----- From: python-list-bounces+wahmeng=freescale.com at python.org [mailto:python-list-bounces+wahmeng=freescale.com at python.org] On Behalf Of Gabriel Genellina Sent: Friday, October 07, 2011 5:37 PM To: python-list at python.org Subject: Re: socket.getsockname is returning junk!! En Wed, 05 Oct 2011 08:56:08 -0300, Wong Wah Meng-R32813 escribi?: > I am migrating my application from python 1.5.2 to 2.7.1. One of the > existing code breaks. The getsockname method from socket object somehow > returns me with some number which I deem as junk, rather than the > listening port as I would have expected in the older python. Has anyone > seen the same thing or is it due to my python is built with some > corrupted library or something? > > > $ python > Python 2.7.1 (r271:86832, Oct 5 2011, 18:34:15) [C] on hp-ux11 > Type "help", "copyright", "credits" or "license" for more information. >>>> import socket >>>> sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) >>>> sock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 ) >>>> sock.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1 ) >>>> sock.setsockopt( socket.IPPROTO_TCP, 1, 1 ) >>>> server_address=('zmy02hp3', 11111) >>>> sock.bind(server_address) >>>> sock.getsockname() > (0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') > > In python 1.5.2 >>>> server_address=('zmy02aix04', 11111) >>>> sock.bind(server_address) >>>> sock.getsockname() > ('10.228.51.41', 11111) I'd say it's a problem with the _socket module; did the unit tests flag anything when you built Python? On Windows, Python 2.7.1: >>> server_address=('lepton', 11111) >>> sock.bind(server_address) >>> sock.getsockname() ('127.0.0.1', 11111) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list From poalman at gmail.com Fri Oct 7 06:15:05 2011 From: poalman at gmail.com (Paul) Date: Fri, 7 Oct 2011 10:15:05 +0000 (UTC) Subject: Thread handling issue References: <4E8EBC32.9060000@timgolden.me.uk> Message-ID: Tim Golden timgolden.me.uk> writes: > > On 07/10/2011 09:29, Paul wrote: > > I'm wondering what the best solution for this problem is. > > > > I've got a wxpython app, in one part a user makes some selections then opens a > > dialog to select where to output. At which point the app starts a thread > > processing their selection while they're choosing an output location, hopefully > > ready for when they're done. > > > > My problem is if the user doesn't select an output location and cancels the > > dialog to go back to the selection I want to terminate the thread to avoid the > > user opening and closing the output selection firing off a ton of threads. > > > > As there's no inbuilt way of killing threads I was wondering the best way to > > prevent this? > > The most common approach is to have the thread monitor an event which is > set if, for example, the user cancels. The thread may of course have to > wait, for example, for a long-running database query to complete before > it can discover that its time has been wasted :) > > The exact mechanism will depend on how your code is structured, > what the thread is doing, and how it's passing anything back > to the main thread. > > TJG > My first thought was to use a flag but wouldn't the new thread see the cancel flag and stop as well? I could set it back but then any other threads might have been busy and not seen it while the flag was on. The thread goes through the selection and does a few quick server calls for each one building up a data file. I guess as the server calls are quite fast the thread would be able to check flags quite often unless it's getting time-outs or something. The threads don't pass anything back they're passed a reference to a data object which is constructed before the thread starts. The thread makes updates to the data object and sets a complete attribute flag in the object before finishing. From cs at zip.com.au Fri Oct 7 06:24:29 2011 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 7 Oct 2011 21:24:29 +1100 Subject: A tuple in order to pass returned values ? In-Reply-To: <4E8EC9C2.1080306@sequans.com> References: <4E8EC9C2.1080306@sequans.com> Message-ID: <20111007102429.GA15713@cskk.homeip.net> On 07Oct2011 11:43, Jean-Michel Pichavant wrote: | namedtuple sounds great (if you don't use unpacking :o) ), too bad | it is available only from python 2.6. It is easy enough to roll your own. Here's some example code with several flaws (it claims tuplehood, but is actually a list; it is not immutable; it takes a list of field names instead of a space separated string as namedtuple does) and isn't very tested. But feel free to take it and adapt it: def NamedTupleClassFactory(*fields): ''' Construct classes for named tuples a bit like the named tuples coming in Python 2.6/3.0. NamedTupleClassFactory('a','b','c') returns a subclass of "list" whose instances have properties .a, .b and .c as references to elements 0, 1 and 2 respectively. ''' class NamedTuple(list): for i in range(len(fields)): f=fields[i] exec('def getx(self): return self[%d]' % i) exec('def setx(self,value): self[%d]=value' % i) exec('%s=property(getx,setx)' % f) return NamedTuple def NamedTuple(fields,iter=()): ''' Return a named tuple with the specified fields. Useful for one-off tuples/lists. ''' return NamedTupleClassFactory(*fields)(iter) More old code:-( I can see I need to go back to that and make it cleaner. Surely I can get rid of the exec(0s at least:-) Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Hacker: One who accidentally destroys. Wizard: One who recovers afterwards. From __peter__ at web.de Fri Oct 7 06:42:02 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Oct 2011 12:42:02 +0200 Subject: A tuple in order to pass returned values ? References: <4E8EC9C2.1080306@sequans.com> <20111007102429.GA15713@cskk.homeip.net> Message-ID: Cameron Simpson wrote: > On 07Oct2011 11:43, Jean-Michel Pichavant wrote: > | namedtuple sounds great (if you don't use unpacking :o) ), too bad > | it is available only from python 2.6. > > It is easy enough to roll your own. Or use Raymond Hettinger's implementation: http://code.activestate.com/recipes/500261-named-tuples/ From python.list at tim.thechases.com Fri Oct 7 07:46:46 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 07 Oct 2011 06:46:46 -0500 Subject: Testing properties that are date-related Message-ID: <4E8EE6A6.2010208@tim.thechases.com> Are there best practices for testing dates that are properties which take the current date into consideration? I have something like class Foo: def _get_year_range(self): return (self._min_year, self._max_year) def _set_year_range(self, year): if isinstance(year, tuple): _min, _max = map(window_date, year) if _min > _max: _min, _max = _max, _min else: # a raw int _min = _max = window_date(year) self._min_year, self._max_year = _min, _max year_range = property( fget=_get_year_range, fget=_get_year_range, ) The problem is that the behavior of the window_date function depends on the current date (the function makes a guess about adding the century if the year was <100). It *does* take an "around" parameter that defaults to the current date. So for pure testing of the window_date() function, I can hard-code some date where I know what the expected values should be. However if I want to write a test-harness for my property, I have no way (AFAIK) to pass in this fixed date to _set_year_range() so that the success/failure of my tests doesn't depend on the day I run them: class TestFoo: def test_year_range(self): around = date(2011,1,1) f = Foo() f.year_range = (97, 84) self.assertEqual(f.year_range, (1984, 1997)) Any suggestions/tips/hints? Thanks, -tkc From __peter__ at web.de Fri Oct 7 08:38:03 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 07 Oct 2011 14:38:03 +0200 Subject: Testing properties that are date-related References: <4E8EE6A6.2010208@tim.thechases.com> Message-ID: Tim Chase wrote: > Are there best practices for testing dates that are properties > which take the current date into consideration? I have something > like > > class Foo: > def _get_year_range(self): > return (self._min_year, self._max_year) > def _set_year_range(self, year): > if isinstance(year, tuple): > _min, _max = map(window_date, year) > if _min > _max: _min, _max = _max, _min > else: # a raw int > _min = _max = window_date(year) > self._min_year, self._max_year = _min, _max > year_range = property( > fget=_get_year_range, > fget=_get_year_range, > ) > > The problem is that the behavior of the window_date function > depends on the current date (the function makes a guess about > adding the century if the year was <100). It *does* take an > "around" parameter that defaults to the current date. So for > pure testing of the window_date() function, I can hard-code some > date where I know what the expected values should be. > > However if I want to write a test-harness for my property, I have > no way (AFAIK) to pass in this fixed date to _set_year_range() so > that the success/failure of my tests doesn't depend on the day I > run them: > > class TestFoo: > def test_year_range(self): > around = date(2011,1,1) > f = Foo() > f.year_range = (97, 84) > self.assertEqual(f.year_range, (1984, 1997)) > > Any suggestions/tips/hints? Thanks, Temporarily replace the window_date() function with something that you can control completely. Assuming Foo and window_date are defined in foo.py: # untested import foo class TestFoo: def setUp(self): foo.window_date = functools.partial(foo.window_date, around=date(2011, 1, 1)) def tearDown(self): foo.window_date = foo.window_date.func def test_year_range(self): f = Foo() f.year_range = (97, 84) self.assertEqual(f.year_range, (1984, 1997)) See also http://www.voidspace.org.uk/python/mock/ From python.list at tim.thechases.com Fri Oct 7 09:41:18 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 07 Oct 2011 08:41:18 -0500 Subject: Testing properties that are date-related In-Reply-To: References: <4E8EE6A6.2010208@tim.thechases.com> Message-ID: <4E8F017E.8050403@tim.thechases.com> On 10/07/11 07:38, Peter Otten wrote: >> Are there best practices for testing dates that are properties >> which take the current date into consideration >> >> The problem is that the behavior of the window_date function >> depends on the current date (the function makes a guess about >> adding the century if the year was<100). It *does* take an >> "around" parameter that defaults to the current date. So for >> pure testing of the window_date() function, I can hard-code some >> date where I know what the expected values should be. >> >> However if I want to write a test-harness for my property, I have >> no way (AFAIK) to pass in this fixed date to _set_year_range() so >> that the success/failure of my tests doesn't depend on the day I >> run them > > Temporarily replace the window_date() function with something that you can > control completely. Assuming Foo and window_date are defined in foo.py: > > # untested > import foo > > class TestFoo: > def setUp(self): > foo.window_date = functools.partial(foo.window_date, > around=date(2011, 1, 1)) > def tearDown(self): > foo.window_date = foo.window_date.func > def test_year_range(self): > f = Foo() > f.year_range = (97, 84) > self.assertEqual(f.year_range, (1984, 1997)) I had to twiddle my class code a bit to make sure it referenced module.window_date() everywhere instead of just a raw window_date() (originally pulled in via "from module import window_date") so that it picked up the new function, but otherwise it worked like a charm. (there was also the matter of some function properties that were used for an undetailed parameter to allow for suggesting that the window_date bias backwards, forwards or around the current date, but a little hackery took care of that too, just copying the germane properties from the saved function object to the result of the partial() call) Thanks! -tkc From miki.tebeka at gmail.com Fri Oct 7 10:11:39 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 7 Oct 2011 07:11:39 -0700 (PDT) Subject: passing multiple string to a command line option In-Reply-To: References: <22850959.1256.1317925508336.JavaMail.geo-discussion-forums@prcs9> Message-ID: <22831825.757.1317996699182.JavaMail.geo-discussion-forums@prma7> Seems like self.ptype is a type that has __init__ with no arguments (other than self). You can add "print type(self.ptype)" as first line of "convert" to see what type it is (or place a breakpoint there). From miki.tebeka at gmail.com Fri Oct 7 10:11:39 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 7 Oct 2011 07:11:39 -0700 (PDT) Subject: passing multiple string to a command line option In-Reply-To: References: <22850959.1256.1317925508336.JavaMail.geo-discussion-forums@prcs9> Message-ID: <22831825.757.1317996699182.JavaMail.geo-discussion-forums@prma7> Seems like self.ptype is a type that has __init__ with no arguments (other than self). You can add "print type(self.ptype)" as first line of "convert" to see what type it is (or place a breakpoint there). From ethan at stoneleaf.us Fri Oct 7 10:45:49 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 07 Oct 2011 07:45:49 -0700 Subject: Testing properties that are date-related In-Reply-To: <4E8F017E.8050403@tim.thechases.com> References: <4E8EE6A6.2010208@tim.thechases.com> <4E8F017E.8050403@tim.thechases.com> Message-ID: <4E8F109D.4040604@stoneleaf.us> Tim Chase wrote: > On 10/07/11 07:38, Peter Otten wrote: >>> Are there best practices for testing dates that are properties >>> which take the current date into consideration >>> >>> The problem is that the behavior of the window_date function >>> depends on the current date (the function makes a guess about >>> adding the century if the year was<100). It *does* take an >>> "around" parameter that defaults to the current date. So for >>> pure testing of the window_date() function, I can hard-code some >>> date where I know what the expected values should be. >>> >>> However if I want to write a test-harness for my property, I have >>> no way (AFAIK) to pass in this fixed date to _set_year_range() so >>> that the success/failure of my tests doesn't depend on the day I >>> run them >> >> Temporarily replace the window_date() function with something that you >> can >> control completely. Assuming Foo and window_date are defined in foo.py: >> >> # untested >> import foo >> >> class TestFoo: >> def setUp(self): >> foo.window_date = functools.partial(foo.window_date, >> around=date(2011, 1, 1)) >> def tearDown(self): >> foo.window_date = foo.window_date.func >> def test_year_range(self): >> f = Foo() >> f.year_range = (97, 84) >> self.assertEqual(f.year_range, (1984, 1997)) > > I had to twiddle my class code a bit to make sure it referenced > module.window_date() everywhere instead of just a raw window_date() > (originally pulled in via "from module import window_date") so that it > picked up the new function, but otherwise it worked like a charm. Another option is injection: import foo def window_date(...): ... foo.window_date = window_date ~Ethan~ From mail at timgolden.me.uk Fri Oct 7 10:56:54 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 07 Oct 2011 15:56:54 +0100 Subject: Thread handling issue In-Reply-To: References: <4E8EBC32.9060000@timgolden.me.uk> Message-ID: <4E8F1336.3070907@timgolden.me.uk> On 07/10/2011 11:15, Paul wrote: > My first thought was to use a flag but wouldn't the new thread see the cancel > flag and stop as well? I could set it back but then any other threads might have > been busy and not seen it while the flag was on. > > The thread goes through the selection and does a few quick server calls for each > one building up a data file. I guess as the server calls are quite fast the > thread would be able to check flags quite often unless it's getting time-outs or > something. > > The threads don't pass anything back they're passed a reference to a data object > which is constructed before the thread starts. The thread makes updates to the > data object and sets a complete attribute flag in the object before finishing. Well a lot depends on how you're doing things. (ie "It Depends"). You could generate an event for each thread so a second thread started while the first was running down wouldn't cause confusion. It's not clear whether the data object is common to all threads -- in which case you need to make sure you're locking etc. -- or is a new instance for each thread. I did try a couple of passes at a code-sketch, but there are too many unknowns to do justice to it. Basically, have the thread poll an event as it moves through. Have the UI set the event and join to the existing thread (ie wait for it to finish) and then fire off a new one. Or -- if the data items are independent -- fire off the new one regardless and let the old one die when it sees its event, assuming that the data object it's populating is disposable. TJG From python.list at tim.thechases.com Fri Oct 7 12:28:55 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 07 Oct 2011 11:28:55 -0500 Subject: Testing properties that are date-related In-Reply-To: <4E8F109D.4040604@stoneleaf.us> References: <4E8EE6A6.2010208@tim.thechases.com> <4E8F017E.8050403@tim.thechases.com> <4E8F109D.4040604@stoneleaf.us> Message-ID: <4E8F28C7.3070502@tim.thechases.com> On 10/07/11 09:45, Ethan Furman wrote: > Tim Chase wrote: >> On 10/07/11 07:38, Peter Otten wrote: >>> def setUp(self): >>> foo.window_date = functools.partial(foo.window_date, >>> around=date(2011, 1, 1)) >> >> it worked like a charm. > > Another option is injection: > > import foo > > def window_date(...): > ... > > foo.window_date = window_date The problem is that I *want* the functionality of the existing window_date() because that's part of what's being tested. Peter's suggestion of injection to the module namespace via functools.partial() to specify the missing parameter was the tip I needed to be able to write tests that exercised things properly without overly invasive changes to the code. But thanks for your idea. -tkc From nt_mahmood at yahoo.com Fri Oct 7 12:52:16 2011 From: nt_mahmood at yahoo.com (Mahmood Naderan) Date: Fri, 7 Oct 2011 09:52:16 -0700 (PDT) Subject: passing multiple string to a command line option In-Reply-To: <22831825.757.1317996699182.JavaMail.geo-discussion-forums@prma7> References: <22850959.1256.1317925508336.JavaMail.geo-discussion-forums@prcs9> <22831825.757.1317996699182.JavaMail.geo-discussion-forums@prma7> Message-ID: <1318006336.7951.YahooMailNeo@web111711.mail.gq1.yahoo.com> That print command generated a lot of errors. Since that error in my first post is related to the python code in simulator, I emailed them and consulted for help. Seems that it is going to be fixed.... Thanks for your kindness :) ? // Naderan *Mahmood; ----- Original Message ----- From: Miki Tebeka To: comp.lang.python at googlegroups.com Cc: python mailing list ; Miki Tebeka ; Mahmood Naderan Sent: Friday, October 7, 2011 5:41 PM Subject: Re: passing multiple string to a command line option Seems like self.ptype is a type that has __init__ with no arguments (other than self). You can add "print type(self.ptype)" as first line of "convert" to see what type it is (or place a breakpoint there). From redcat at streemit.net Fri Oct 7 12:56:33 2011 From: redcat at streemit.net (Redcat) Date: 7 Oct 2011 16:56:33 GMT Subject: help References: Message-ID: <9f8pa1Fsh8U3@mid.individual.net> On Fri, 07 Oct 2011 15:59:55 +0000, X1 wrote: > I have this program that fails: > > $ vapt > Traceback (most recent call last): > File "/usr/local/bin/vapt", line 3, in > from vapt import vapt > File "/usr/lib/python2.6/site-packages/vapt/__init__.py", line 11, in > > __import__(name, glob, loc, []) > File "/usr/lib/python2.6/site-packages/vapt/cadview.py", line 13, in > > import OpenGL.Tk as gltk > ImportError: No module named Tk > > > can you help me? > This is on fedora The OpenGL.Tk module is looking for the Tk module and not finding it. Install the Tk module. Try "sudo easy_install Tk". From dreyemi at gmail.com Fri Oct 7 13:16:59 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Fri, 7 Oct 2011 18:16:59 +0100 Subject: unsupported operand type(s) for pow(): 'unicode', 'long', 'long': Pycrypto Message-ID: Hello everyone, I'm writing a fairly large app which uses Oauth (python-oauth2). I am trying to generate a public/private key pair on user supplied parameters (whitespaced-delimited strings basically). When trying to encrypt the key, I'm getting the "unsupported operand type(s) for pow(): 'unicode', 'long', 'long'" >From Interactive shell, the program worked successfully. My question is do I have to make the user supplied data of a non-unicode string to make this work? Thanks -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Fri Oct 7 14:23:16 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 7 Oct 2011 12:23:16 -0600 Subject: unsupported operand type(s) for pow(): 'unicode', 'long', 'long': Pycrypto In-Reply-To: References: Message-ID: On Fri, Oct 7, 2011 at 11:16 AM, Kayode Odeyemi wrote: > Hello everyone, > > I'm writing a fairly large app which uses Oauth (python-oauth2). I am trying > to generate a > public/private key pair on user supplied parameters (whitespaced-delimited > strings basically). > > When trying to encrypt the key, I'm getting the "unsupported operand type(s) > for pow(): 'unicode', 'long', 'long'" > > From Interactive shell, the program worked successfully. > > My question is do I have to make the user supplied data of a non-unicode > string to make this work? Please include the traceback and the snippet of code where you make the call that is failing. Without that, it is not at all clear exactly what you are doing, especially since python-oauth2 does not seem to provide any encryption API. Cheers, Ian From redcat at streemit.net Fri Oct 7 14:45:52 2011 From: redcat at streemit.net (Redcat) Date: 7 Oct 2011 18:45:52 GMT Subject: help References: <9f8pa1Fsh8U3@mid.individual.net> Message-ID: <9f8vmvFsh8U5@mid.individual.net> > Thanks, > I have the Tk module installed, but the program still fails. Probably it > is a problem of path? That would be my guess - that the Tk module is installed somewhere other than where OpenGL.Tk is looking for it. From dreyemi at gmail.com Fri Oct 7 14:54:31 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Fri, 7 Oct 2011 19:54:31 +0100 Subject: unsupported operand type(s) for pow(): 'unicode', 'long', 'long': Pycrypto In-Reply-To: References: Message-ID: On Fri, Oct 7, 2011 at 7:23 PM, Ian Kelly wrote: > On Fri, Oct 7, 2011 at 11:16 AM, Kayode Odeyemi wrote: > > Hello everyone, > > > > I'm writing a fairly large app which uses Oauth (python-oauth2). I am > trying > > to generate a > > public/private key pair on user supplied parameters > (whitespaced-delimited > > strings basically). > > > > When trying to encrypt the key, I'm getting the "unsupported operand > type(s) > > for pow(): 'unicode', 'long', 'long'" > > > > From Interactive shell, the program worked successfully. > > > > My question is do I have to make the user supplied data of a non-unicode > > string to make this work? > > Please include the traceback and the snippet of code where you make > the call that is failing. Without that, it is not at all clear > exactly what you are doing, especially since python-oauth2 does not > seem to provide any encryption API. > Thanks for writing in. I had this: encrypted = public_key.encrypt(params, 16) I was able to fix it with: encrypted = public_key.encrypt(str(params), 16) pow() needs params in non-unicode. I understand python-oauth2 does not have encryption API built-in. I'm creating one before using it. -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From vinay_sajip at yahoo.co.uk Fri Oct 7 15:05:10 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 7 Oct 2011 12:05:10 -0700 (PDT) Subject: Advise on using logging.getLogger needed. References: Message-ID: <98847de7-63ee-4f4f-bfd8-e607066816db@k34g2000yqm.googlegroups.com> On Oct 2, 11:12?pm, "Steven W. Orr" wrote: > I hope I don't sound like I'm ranting :-( You don't, but neither is it absolutely clear what you're trying to achieve. BTW the term "root logger" in the logging docs refers to a logger internal to the logging package, and not to a logger that you create. For that, it's best to refer to "top level logger for my application/library". Supposing you want your top-level logger always to be the name of your main script, and you want other loggers to live below this logger. In your main script module, therefore, you do the equivalent of pname = compute_program_name(sys.argv[0]) logger = logging.getLogger(pname) # configure logging handlers, filters etc. for your application In your library modules, if you want them to live under that top-level logger, then you can do something like pname = compute_program_name(sys.argv[0]) logger = logging.getLogger('%s.%s' % pname, __name__) where you can use something other than __name__ for the logger name suffix, if you want. > My problem is that I just want the modules that I write, to be able to get the > ?named root logger and still be able to refer to possible sub-loggers. According to the scheme I describe, if you have two scripts called "foo" and "bar" which make use of a common module "baz", then events in the foo module would appear under logger "foo", and events in the baz module when run from foo would be logged under logger "foo.baz". When running "bar", events in the bar module would appear under logger "bar", whereas events in the baz module when run from bar would be logged under logger "bar.baz". This seems to be what you're asking for, but I may have misunderstood. > I am running 2.6, so I don't have access to logging.getChild, but I'm not > clear that I even want that. getChild is just a convenience method, you don't need it - you can just build the logger name as in my example above. > My modules are used by multiple programs. Does this mean that I should simply > use __name__ all the time? (That seems inelegant, no?) Actually __name__ is very elegant, as it is impervious to you moving your code around and follows the Python package hierarchy. Also, if you are using third party code (especially from various sources), using __name__ will make things unambiguous about where exactly events are being logged from. Third party code typically won't know about your top-level logger, and __name__ is the one scheme that everything can agree on - the point about logger names being that they're supposed to codify "where" in your application events occur, and the package hierarchy is the canonical representation of source locations in an application. Regards, Vinay Sajip From ramit.prasad at jpmorgan.com Fri Oct 7 15:05:27 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 7 Oct 2011 15:05:27 -0400 Subject: Thread handling issue In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F214444E2@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- From: python-list-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Paul Sent: Friday, October 07, 2011 3:29 AM To: python-list at python.org Subject: Thread handling issue I'm wondering what the best solution for this problem is. I've got a wxpython app, in one part a user makes some selections then opens a dialog to select where to output. At which point the app starts a thread processing their selection while they're choosing an output location, hopefully ready for when they're done. My problem is if the user doesn't select an output location and cancels the dialog to go back to the selection I want to terminate the thread to avoid the user opening and closing the output selection firing off a ton of threads. As there's no inbuilt way of killing threads I was wondering the best way to prevent this? -- http://mail.python.org/mailman/listinfo/python-list ============================================================================ Why not just wait until they are done with all user input and then fire threads after that? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From kurro.pipi at hotmail.com Fri Oct 7 15:29:15 2011 From: kurro.pipi at hotmail.com (txismis unzetabarrenetxeagoikolea) Date: Fri, 7 Oct 2011 12:29:15 -0700 Subject: deepcopy does not work for A subclassed list Message-ID: This is the issue I have created a mylist class by subclassing a List, added several attributes to mylist , and overrided the append method which takes into account one of the new attributes. mylist class is functional and works as I planned, but when I try to deepcopy objects from mylist I received errors because the attribute has not been copied and the override append raise an error. When I want to deepcopy one object from mylist the algorithm does not take into account the attributes I created; ergo, I have some errors from the copy module I can use pickle to dump and load objects from my subclass with no errors. Any ideas about how to make the copy module to behave as expected. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From ralf at systemexit.de Fri Oct 7 15:33:10 2011 From: ralf at systemexit.de (Ralf Schmitt) Date: Fri, 07 Oct 2011 21:33:10 +0200 Subject: [ANN] pypiserver 0.3.0 - minimal pypi server Message-ID: <87liswd2bt.fsf@myhost.localnet> Hi, I've just uploaded pypiserver 0.3.0 to the python package index. pypiserver is a minimal PyPI compatible server. It can be used to serve a set of packages and eggs to easy_install or pip. pypiserver is easy to install (i.e. just easy_install pypiserver). It doesn't have any external dependencies. http://pypi.python.org/pypi/pypiserver/ should contain enough information to easily get you started running your own PyPI server in a few minutes. The code is available on github: https://github.com/schmir/pypiserver Changes in version 0.3.0 ------------------------- - pypiserver now scans the given root directory and it's subdirectories recursively for packages. Files and directories starting with a dot are now being ignored. - /favicon.ico now returns a "404 Not Found" error - pypiserver now contains some unit tests to be run with tox -- Cheers, Ralf From frank.ruiz at gmail.com Fri Oct 7 15:39:53 2011 From: frank.ruiz at gmail.com (Frank Ruiz) Date: Fri, 7 Oct 2011 12:39:53 -0700 Subject: Memory Message-ID: Quick question, What is the best way for pulling resource information for a system running linux? Was wondering if there was a python only way. Methods I am aware of are: 1. Parsing contents of /proc 2. Running a system command like free, or dmidecode and parsing the output. Is there any other way to pull.. lets say memory information? i.e. Find how much total RAM a system has on it. Thanks you. From ed at leafe.com Fri Oct 7 16:00:41 2011 From: ed at leafe.com (Ed Leafe) Date: Fri, 7 Oct 2011 15:00:41 -0500 Subject: Dabo 0.9.4 Released! In-Reply-To: References: Message-ID: On Oct 6, 2011, at 12:18 PM, Neal Becker wrote: > What is it? Sorry, I guess I should have included that. We've been around for so long I sometimes assume that everyone knows what Dabo is. Dabo is a framework for building desktop applications. It is strongly geared toward database applications, although a database connection is completely optional. We wrap the wxPython GUI toolkit, hiding its C++ roots and presenting a more Pythonic interface for creating your UI. See more at http://dabodev.com, and feel free to ask any more questions. -- Ed Leafe From lists at cheimes.de Fri Oct 7 16:06:52 2011 From: lists at cheimes.de (Christian Heimes) Date: Fri, 07 Oct 2011 22:06:52 +0200 Subject: Memory In-Reply-To: References: Message-ID: Am 07.10.2011 21:39, schrieb Frank Ruiz: > Quick question, > > What is the best way for pulling resource information for a system > running linux? Was wondering if there was a python only way. > > Methods I am aware of are: > > 1. Parsing contents of /proc > 2. Running a system command like free, or dmidecode and parsing the output. > > Is there any other way to pull.. lets say memory information? i.e. > Find how much total RAM a system has on it. Yes, use psutil. http://code.google.com/p/psutil/ From a24061 at ducksburg.com Fri Oct 7 16:14:44 2011 From: a24061 at ducksburg.com (Adam Funk) Date: Fri, 07 Oct 2011 21:14:44 +0100 Subject: recommend a graphics library for plotting by the pixel? References: <9s1rl8xt8t.ln2@news.ducksburg.com> Message-ID: On 2011-10-04, Ian Kelly wrote: > On Tue, Oct 4, 2011 at 3:56 AM, Adam Funk wrote: >> I'd like to create a window with a "pause" button and a large plotting >> area, in which I'd like to draw a polygon, detect the pixel >> co?rdinates of a mouse click, and then start setting the colors of >> pixels by (x,y) co?rdinates. ?(This is just for my own amusement, to >> play with some formulas for generating fractals using random numbers.) >> >> There seems to be a large number of different python GUI libraries, >> and I wonder if someone can recommend the easiests one to learn for >> this purpose? ?(The only python graphics library I've used is PyGame, >> which I don't think is the way to go here.) > > You could use wxPython. You'll need to create a custom control and > have it paint itself by blitting from a wx.Bitmap, which you'll draw > on by using a wx.MemoryDC and then refreshing the control. > > I would probably just use pygame myself. I guess you're avoiding it > because of the requirement for a button, but there are GUI libraries > available for it, or if all you need are a couple of buttons you could > easily roll your own. Excellent suggestion. I got it to work, but using keypresses (pause, step, quit) instead of buttons, and a mouse event for letting the user pick the start point on the screen. -- I worry that 10 or 15 years from now, [my daughter] will come to me and say 'Daddy, where were you when they took freedom of the press away from the Internet?' [Mike Godwin] http://www.eff.org/ From a24061 at ducksburg.com Fri Oct 7 16:15:43 2011 From: a24061 at ducksburg.com (Adam Funk) Date: Fri, 07 Oct 2011 21:15:43 +0100 Subject: recommend a graphics library for plotting by the pixel? References: <9s1rl8xt8t.ln2@news.ducksburg.com> <2n2ul8xi9s.ln2@news.ducksburg.com> Message-ID: On 2011-10-05, Westley Mart?nez wrote: > On Wed, Oct 05, 2011 at 02:29:38PM +0100, Adam Funk wrote: >> I only know PyGame because we did an exercise in recreating the old >> breakout game and messing around with it at a local Python group. >> >> I was under the mistaken impression from that exercise that you have >> to maintain a set of all the objects on the screen and redraw them all >> every time through the loop that ends with pygame.display.flip() --- >> *but* I now see that the loop starts with these: >> >> clock.tick(tick_rate) >> screen.fill((0,0,0)) >> # comes from screen = pygame.display.set_mode((screen_width,screen_height)) >> # before the loop >> >> and that I was then deleting hit bricks, calculating the new positions >> of the balls, and then redrawing everything that was left on the >> secondary screen because things were moving around and disappearing. >> >> I guess if I don't clear the screen at the beginning of the loop but >> just blit pixels onto it, when I call display.flip(), it will add the >> new blittings to what was already there? If that's true, this will be >> much easier than I thought. > Yep. Blitting is replacing the old colors with new colors. It doesn't > replace colors unless you tell it to. My mistake was in sample code, running with it, & not looking at it too closely. ;-) -- Mathematiker sind wie Franzosen: Was man ihnen auch sagt, ?bersetzen sie in ihre eigene Sprache, so da? unverz?glich etwas v?llig anderes daraus wird. [Goethe] From python at mrabarnett.plus.com Fri Oct 7 16:37:00 2011 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 07 Oct 2011 21:37:00 +0100 Subject: deepcopy does not work for A subclassed list In-Reply-To: References: Message-ID: <4E8F62EC.603@mrabarnett.plus.com> On 07/10/2011 20:29, txismis unzetabarrenetxeagoikolea wrote: > This is the issue > > I have created a mylist class by subclassing a List, added several > attributes to mylIst , and overrided the append method which takes into > account one of the new attributes. > > mylist class is functional and works as I planned, but when I try to > deepcopy objects from mylist I received errors because the attribute has > not been copied and the override append raise an error. > > When I want to deepcopy one object from mylist the algorithm does not > take into account the attributes I created; ergo, I have some errors > from the copy module > > I can use pickle to dump and load objects from my subclass with no errors. > > Any ideas about how to make the copy module to behave as expected. > The documentation talks about defining a "__deepcopy__" method. From cs at zip.com.au Fri Oct 7 18:35:58 2011 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 8 Oct 2011 09:35:58 +1100 Subject: Thread handling issue In-Reply-To: References: Message-ID: <20111007223558.GA5616@cskk.homeip.net> On 07Oct2011 10:15, Paul wrote: | Tim Golden timgolden.me.uk> writes: | > On 07/10/2011 09:29, Paul wrote: | > > My problem is if the user doesn't select an output location and cancels the | > > dialog to go back to the selection I want to terminate the thread to avoid the | > > user opening and closing the output selection firing off a ton of threads. | > > | > > As there's no inbuilt way of killing threads I was wondering the best way to | > > prevent this? | > | > The most common approach is to have the thread monitor an event which is | > set if, for example, the user cancels. The thread may of course have to | > wait, for example, for a long-running database query to complete before | > it can discover that its time has been wasted :) [...] | My first thought was to use a flag but wouldn't the new thread see the cancel | flag and stop as well? I could set it back but then any other threads might have | been busy and not seen it while the flag was on. I'd be inclined to dispatch threads via a control object of some kind. You'd have a default one for your program as a whole, but when you have a circumstance such as you describe instantiate a new control object. Set the cancel flag in the control objects. Have threads poll their invoking control object. That way you can have a flag that applies to your desired set of threads. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ He's silly and he's ignorant, but he's got guts, and guts is enough. - Sgt. Hartmann From tjreedy at udel.edu Fri Oct 7 19:35:19 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 07 Oct 2011 19:35:19 -0400 Subject: deepcopy does not work for A subclassed list In-Reply-To: <4E8F62EC.603@mrabarnett.plus.com> References: <4E8F62EC.603@mrabarnett.plus.com> Message-ID: On 10/7/2011 4:37 PM, MRAB wrote: > On 07/10/2011 20:29, txismis unzetabarrenetxeagoikolea wrote: >> Any ideas about how to make the copy module to behave as expected. >> > The documentation talks about defining a "__deepcopy__" method. Specifically, in the copy module doc "In order for a class to define its own copy implementation, it can define special methods __copy__() and __deepcopy__(). The former is called to implement the shallow copy operation; no additional arguments are passed. The latter is called to implement the deep copy operation; it is passed one argument, the memo dictionary. If the __deepcopy__() implementation needs to make a deep copy of a component, it should call the deepcopy() function with the component as first argument and the memo dictionary as second argument." All the possible customization methods are discussed in Language Reference 3.3. Special method names -- Terry Jan Reedy From tjreedy at udel.edu Fri Oct 7 19:39:22 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 07 Oct 2011 19:39:22 -0400 Subject: help In-Reply-To: <9f8pa1Fsh8U3@mid.individual.net> References: <9f8pa1Fsh8U3@mid.individual.net> Message-ID: On 10/7/2011 12:56 PM, Redcat wrote: > On Fri, 07 Oct 2011 15:59:55 +0000, X1 wrote: > >> I have this program that fails: >> >> $ vapt >> Traceback (most recent call last): >> File "/usr/local/bin/vapt", line 3, in >> from vapt import vapt >> File "/usr/lib/python2.6/site-packages/vapt/__init__.py", line 11, in >> >> __import__(name, glob, loc, []) >> File "/usr/lib/python2.6/site-packages/vapt/cadview.py", line 13, in >> >> import OpenGL.Tk as gltk >> ImportError: No module named Tk >> >> >> can you help me? >> This is on fedora > > The OpenGL.Tk module is looking for the Tk module and not finding it. > Install the Tk module. Or there is no OpenGL.Tk module >>> import itertools.xxx Traceback (most recent call last): File "", line 1, in import itertools.xxx ImportError: No module named xxx > > Try "sudo easy_install Tk". -- Terry Jan Reedy From tjreedy at udel.edu Fri Oct 7 19:50:22 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 07 Oct 2011 19:50:22 -0400 Subject: unsupported operand type(s) for pow(): 'unicode', 'long', 'long': Pycrypto In-Reply-To: References: Message-ID: On 10/7/2011 2:54 PM, Kayode Odeyemi wrote: > pow() needs params in non-unicode. pow() need 2 or 3 numbers as args. The function that calls it must turn the (2.x) string into a number, either with hash() or its own hash function. That latter function probably want integers code in range(256). "pow(x, y[, z]) Return x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than pow(x, y) % z). The two-argument form pow(x, y) is equivalent to using the power operator: x**y. The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For int operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, 10**2 returns 100, but 10**-2 returns 0.01. If the second argument is negative, the third argument must be omitted. If z is present, x and y must be of integer types, and y must be non-negative. " -- Terry Jan Reedy From brandtrade08 at 126.com Fri Oct 7 22:27:50 2011 From: brandtrade08 at 126.com (jerser-2009) Date: Fri, 7 Oct 2011 19:27:50 -0700 (PDT) Subject: The hyper fused upper part of Nike Air Message-ID: <15dfd42d-dc9d-457d-90f3-8bb358982e8f@x21g2000prd.googlegroups.com> The hyper fused upper part of Nike Air Max displays the humanity of the designer because of its lightweight, breathability and a feeling of plusher fitness. The mesh inner collar, and the soft springy cushion http://www.outlet-nike-air-max.com/inside can protect the feet against most possible injures. Besides the rubber materials around the translucent perimeter displays a particular appearance of the shoes, which is a love of most women, especially those who pursuit to be in fashion. Meanwhile the rubber material is a guaranty of the durability and traction, which is fully the practice. With the {2}{/2}dynamic colors of Women?s Nike Air Max 2011, you will soon experience the vitality of sports when you are dressed in such a pair of classic nice cheap Nike running shoes, because it can not only create a healthy condition for feet, but also can restore the original active in the shortest time. What?s more, the Nike Air Max 2011 will not cause any exacerbation if you once were injured in feet. http://www.outlet-nike-air-max.com/ From gagsl-py2 at yahoo.com.ar Sat Oct 8 00:15:36 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 08 Oct 2011 01:15:36 -0300 Subject: Deleting files on a shared server References: <24959174.190.1317950066875.JavaMail.geo-discussion-forums@prho12> <4E8EAE1C.1050104@timgolden.me.uk> Message-ID: En Fri, 07 Oct 2011 04:45:32 -0300, Tim Golden escribi?: > On 07/10/2011 02:14, Josh English wrote: >> To delete the files, I am using os.unlink. >> >> One lock file refuses to disappear, even though I have code at both >> application startup and shutdown (on the OnInit and OnExit methods to >> the wxPython Application object) that hunts down .lock files and >> deletes them. > > Assuming that your code paths succeed and that the unlink actually > happens, it is possible for files to continue to exist after they > have been successfully deleted. This happens if another process > has opened them with share-delete mode; typically this will be > a virus checker or a process like the TortoiseSVN cache (or its > counterparts for other VCS). The file won't actually disappear > until the last handle on it is released. In such cases the openfiles command [1] is very useful for detecting who is holding the file open. [1] http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/openfiles.mspx -- Gabriel Genellina From k.sahithi2862 at gmail.com Sat Oct 8 00:49:19 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Fri, 7 Oct 2011 21:49:19 -0700 (PDT) Subject: TOP 15 HOT BOLLYWOOD KISSES Message-ID: <85a54345-cff4-44ec-927e-19dfd89f0980@c20g2000prc.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html SAMANTHA HOT WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html KATRINA KAIF HOT IMAGES http://hotactress-katrina.blogspot.com/2011/08/katrina-kaif-hot.html TOP 15 HOT BOLLYWOOD KISSES http://hotactress-katrina.blogspot.com/2011/08/bollywood-kisses.html KAJAL AGARWAL HOT PICS http://hotactress-katrina.blogspot.com/2011/09/kajal-agarwal.html From dreyemi at gmail.com Sat Oct 8 04:45:09 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sat, 8 Oct 2011 09:45:09 +0100 Subject: unsupported operand type(s) for pow(): 'unicode', 'long', 'long': Pycrypto In-Reply-To: References: Message-ID: On Sat, Oct 8, 2011 at 12:50 AM, Terry Reedy wrote: > That latter function probably want integers code in range(256). Yes! Non-unicode. The source reads: def _encrypt(self, m): # compute m**d (mod n) return pow(m, self.e, self.n) >From the source, it is provided as is. The arguments must have numeric types > How come it accepts str type? -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Oct 8 05:37:41 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 08 Oct 2011 11:37:41 +0200 Subject: unsupported operand type(s) for pow(): 'unicode', 'long', 'long': Pycrypto References: Message-ID: Kayode Odeyemi wrote: > On Sat, Oct 8, 2011 at 12:50 AM, Terry Reedy wrote: > >> That latter function probably want integers code in range(256). > > > Yes! Non-unicode. The source reads: > > def _encrypt(self, m): > # compute m**d (mod n) > return pow(m, self.e, self.n) > >>From the source, it is provided as is. > > The arguments must have numeric types >> > > How come it accepts str type? pow() does not accept a str. Most likely there is conversion code similar to if isinstance(m, str): m = convert_to_int(m) that precedes the _encrypt() method call and lets unicode slip through. Grepping through the PyCrypto source for isinstance indeed finds a few candidates. Example: $ find . -name \*.py | xargs grep isinstance -A5 [...] ./PublicKey/pubkey.py: if isinstance(plaintext, types.StringType): ./PublicKey/pubkey.py- plaintext=bytes_to_long(plaintext) ; wasString=1 ./PublicKey/pubkey.py: if isinstance(K, types.StringType): ./PublicKey/pubkey.py- K=bytes_to_long(K) ./PublicKey/pubkey.py- ciphertext=self._encrypt(plaintext, K) ./PublicKey/pubkey.py- if wasString: return tuple(map(long_to_bytes, ciphertext)) ./PublicKey/pubkey.py- else: return ciphertext ./PublicKey/pubkey.py- [...] From dreyemi at gmail.com Sat Oct 8 05:55:23 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Sat, 8 Oct 2011 10:55:23 +0100 Subject: unsupported operand type(s) for pow(): 'unicode', 'long', 'long': Pycrypto In-Reply-To: References: Message-ID: On Sat, Oct 8, 2011 at 10:37 AM, Peter Otten <__peter__ at web.de> wrote: > Kayode Odeyemi wrote: > > > On Sat, Oct 8, 2011 at 12:50 AM, Terry Reedy wrote: > > > >> That latter function probably want integers code in range(256). > > > > > > Yes! Non-unicode. The source reads: > > > > def _encrypt(self, m): > > # compute m**d (mod n) > > return pow(m, self.e, self.n) > > > >>From the source, it is provided as is. > > > > The arguments must have numeric types > >> > > > > How come it accepts str type? > > pow() does not accept a str. Most likely there is conversion code similar > to > > if isinstance(m, str): > m = convert_to_int(m) > Ah! I see the reason for the unsupported operand type error. It wants a str, so it can do a conversion to int. But since unicode, long etc is not allowed, shouldn't that been taken care of in _encrypt? Or is this by design? > that precedes the _encrypt() method call and lets unicode slip through. > Grepping through the PyCrypto source for isinstance indeed finds a few > candidates. Example: > > $ find . -name \*.py | xargs grep isinstance -A5 > [...] > ./PublicKey/pubkey.py: if isinstance(plaintext, types.StringType): > ./PublicKey/pubkey.py- plaintext=bytes_to_long(plaintext) ; > wasString=1 > ./PublicKey/pubkey.py: if isinstance(K, types.StringType): > ./PublicKey/pubkey.py- K=bytes_to_long(K) > ./PublicKey/pubkey.py- ciphertext=self._encrypt(plaintext, K) > ./PublicKey/pubkey.py- if wasString: return tuple(map(long_to_bytes, > ciphertext)) > ./PublicKey/pubkey.py- else: return ciphertext > ./PublicKey/pubkey.py- > [...] > > Thanks. This make things clearer > -- > http://mail.python.org/mailman/listinfo/python-list > -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From poalman at gmail.com Sat Oct 8 06:38:01 2011 From: poalman at gmail.com (Paul) Date: Sat, 8 Oct 2011 10:38:01 +0000 (UTC) Subject: Thread handling issue References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F214444E2@EMARC112VS01.exchad.jpmchase.net> Message-ID: Basically there can be quite a big job to do based on the user selection and I've pipelined it so after the user selects the output location the next job can get started so long as the first job (preparing the data) has been running for 5 or so seconds roughly. Its just a lot nicer to have this done by the time the user has selected an output folder so the main job can start instantly. Of course the user can kill the main job too and go back to the user input so I need to be able to kill the threads anyway. From candide at free.invalid Sat Oct 8 06:42:58 2011 From: candide at free.invalid (candide) Date: Sat, 08 Oct 2011 12:42:58 +0200 Subject: Usefulness of the "not in" operator Message-ID: <4e902932$0$23273$426a34cc@news.free.fr> Python provides -- the not operator, meaning logical negation -- the in operator, meaning membership On the other hand, Python provides the not in operator meaning non-membership. However, it seems we can reformulate any "not in" expression using only "not" and "in" operation. For instance >>> 'th' not in "python" False >>> not ('th' in "python") False >>> So what is the usefulness of the "not in" operator ? Recall what Zen of Python tells There should be one-- and preferably only one --obvious way to do it. From joncle at googlemail.com Sat Oct 8 06:50:00 2011 From: joncle at googlemail.com (Jon Clements) Date: Sat, 8 Oct 2011 03:50:00 -0700 (PDT) Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> Message-ID: <14fa9dc2-d4bb-4fc9-955d-ac28848d9380@n8g2000yqd.googlegroups.com> On Oct 8, 11:42?am, candide wrote: > Python provides > > ? ? ?-- the not operator, meaning logical negation > ? ? ?-- the in operator, meaning membership > > On the other hand, Python provides the not in operator meaning > non-membership. However, it seems we can reformulate any "not in" > expression using only "not" and "in" operation. For instance > > ?>>> 'th' not in "python" > False > > ?>>> not ('th' in "python") > False > ?>>> > > So what is the usefulness of the "not in" operator ? Recall what Zen of > Python tells > > There should be one-- and preferably only one --obvious way to do it. You would seriously prefer the later? Guess I'll have to start writing stuff like: 10 - 5 as 10 + -5 (as obviously the - is redundant as an operation), and 10 / 2 as int(10 * .5) or something, who needs a divide!? Jokely yours, Jon. From poalman at gmail.com Sat Oct 8 06:51:09 2011 From: poalman at gmail.com (Paul) Date: Sat, 8 Oct 2011 10:51:09 +0000 (UTC) Subject: Thread handling issue References: <4E8EBC32.9060000@timgolden.me.uk> <4E8F1336.3070907@timgolden.me.uk> Message-ID: Tim Golden timgolden.me.uk> writes: > > On 07/10/2011 11:15, Paul wrote: > > My first thought was to use a flag but wouldn't the new thread see the cancel > > flag and stop as well? I could set it back but then any other threads might have > > been busy and not seen it while the flag was on. > > > > The thread goes through the selection and does a few quick server calls for each > > one building up a data file. I guess as the server calls are quite fast the > > thread would be able to check flags quite often unless it's getting time- outs or > > something. > > > > The threads don't pass anything back they're passed a reference to a data object > > which is constructed before the thread starts. The thread makes updates to the > > data object and sets a complete attribute flag in the object before finishing. > > Well a lot depends on how you're doing things. (ie "It Depends"). You > could generate an event for each thread so a second thread started while > the first was running down wouldn't cause confusion. It's not clear > whether the data object is common to all threads -- in which case > you need to make sure you're locking etc. -- or is a new instance > for each thread. > > I did try a couple of passes at a code-sketch, but there are too > many unknowns to do justice to it. Basically, have the thread poll > an event as it moves through. Have the UI set the event and join to > the existing thread (ie wait for it to finish) and then fire off > a new one. Or -- if the data items are independent -- fire off > the new one regardless and let the old one die when it sees its > event, assuming that the data object it's populating is disposable. > > TJG Yea currently I create a new data object for each thread. I could make it a bit smarter and if the user goes back makes a change I could re-use the old data object and modify it but currently I'm not going to worry about that. I think I'll wait for the user to actually make a change after cancelling the output selection, in case they go straight back without making changes. If they make a change I think I'll try what you suggested and send off a new thread, and send an event to the previous thread. Would this mean I'd need to use wx.lib.newevent.NewCommandEvent() to get a new event for each thread I create? and I'd have to pass the second return value from that, the event binder to the thread to bind to a clean up and exit method? From stefaan.himpe at gmail.com Sat Oct 8 07:12:42 2011 From: stefaan.himpe at gmail.com (Stefaan Himpe) Date: Sat, 08 Oct 2011 13:12:42 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: <4e902932$0$23273$426a34cc@news.free.fr> References: <4e902932$0$23273$426a34cc@news.free.fr> Message-ID: > > So what is the usefulness of the "not in" operator ? Recall what Zen of > Python tells > > There should be one-- and preferably only one --obvious way to do it. the zen of python also says (amongst other things): ... Readability counts. ... Although practicality beats purity ... Best regards, Stefaan. From steve+comp.lang.python at pearwood.info Sat Oct 8 08:01:05 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 08 Oct 2011 23:01:05 +1100 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> Message-ID: <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> candide wrote: > So what is the usefulness of the "not in" operator ? Recall what Zen of > Python tells > > There should be one-- and preferably only one --obvious way to do it. And "not in" is the obvious way to do it. "If the key is not in the ignition, you won't be able to start the car." "If not the key is in the ignition, you won't be able to start the car." Who like that second one speaks? -- Steven From anssi.kaariainen at thl.fi Sat Oct 8 08:18:08 2011 From: anssi.kaariainen at thl.fi (=?iso-8859-1?Q?K=E4=E4ri=E4inen_Anssi?=) Date: Sat, 8 Oct 2011 15:18:08 +0300 Subject: PDB command <-> variable clashes Message-ID: I am currently debugging the django test cases, and there are a lot of variables names like w, q, where, condition and so on. Especially variables like w, q, c, r are really annoying. It would be cool if pdb would detect a clash and in that case ask you what to do. Nothing more annoying than stepping through the code, finally finding the problematic place and then trying to find out what c.somevar contains... I am using Python 2.6. Is there some way to do this? My googling didn't turn out anything. Or is it recommended to use something else instead of pdb? Thank you for your time, - Anssi K??ri?inen From alain at dpt-info.u-strasbg.fr Sat Oct 8 08:41:06 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sat, 08 Oct 2011 14:41:06 +0200 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> Message-ID: <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> candide writes: > Python provides > > -- the not operator, meaning logical negation > -- the in operator, meaning membership > > On the other hand, Python provides the not in operator meaning > non-membership. However, it seems we can reformulate any "not in" > expression using only "not" and "in" operation. Sure, but note that you can also reformulate != using not and ==, < using not and >=, etc. Operators like "not in" and "is not" should really be considered single tokens, even though they seem to use "not". And I think they are really convenient. -- Alain. From mwilson at the-wire.com Sat Oct 8 08:41:35 2011 From: mwilson at the-wire.com (Mel) Date: Sat, 08 Oct 2011 08:41:35 -0400 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > candide wrote: > >> So what is the usefulness of the "not in" operator ? Recall what Zen of >> Python tells >> >> There should be one-- and preferably only one --obvious way to do it. > > And "not in" is the obvious way to do it. > > > "If the key is not in the ignition, you won't be able to start the car." > > "If not the key is in the ignition, you won't be able to start the car." > > > Who like that second one speaks? :) "If the key is not in the ignition, you will be able to start the car, not." Mel. From jpiitula at ling.helsinki.fi Sat Oct 8 09:07:12 2011 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 08 Oct 2011 16:07:12 +0300 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: Mel writes: > Steven D'Aprano wrote: > > > candide wrote: > > > >> So what is the usefulness of the "not in" operator ? Recall what Zen of > >> Python tells > >> > >> There should be one-- and preferably only one --obvious way to do it. > > > > And "not in" is the obvious way to do it. > > > > > > "If the key is not in the ignition, you won't be able to start the car." > > > > "If not the key is in the ignition, you won't be able to start the car." > > > > > > Who like that second one speaks? > > :) > "If the key is not in the ignition, you will be able to start the car, not." Oh, be consistent. "If not the key is in the ignition, not you will be able to start the car." But both negations can be avoided by modus tollens. "If you are able to start the car, the key is in the ignition." And one could express "x not in s" as "(x in s) implies False" without making the "not" explicit if "implies" was in the language. (I know about <= but I also witnessed an unpleasant thread in another newsgroup where people insisted that <= should not be defined for truth values at all, and I also happen to like Python's "not in".) From roy at panix.com Sat Oct 8 09:31:10 2011 From: roy at panix.com (Roy Smith) Date: Sat, 08 Oct 2011 09:31:10 -0400 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> Message-ID: In article <87ehyn8xlp.fsf at dpt-info.u-strasbg.fr>, Alain Ketterlin wrote: > Sure, but note that you can also reformulate != using not and ==, < > using not and >=, etc. Operators like "not in" and "is not" should > really be considered single tokens, even though they seem to use "not". > And I think they are really convenient. If you want to take it one step further, all the boolean operators can be derived from nand (the dualists would insist on using nor). From candide at free.invalid Sat Oct 8 10:40:58 2011 From: candide at free.invalid (candide) Date: Sat, 08 Oct 2011 16:40:58 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> Message-ID: <4e9060fa$0$27980$426a34cc@news.free.fr> Le 08/10/2011 14:41, Alain Ketterlin a ?crit : > Operators like "not in" and "is not" should > really be considered single tokens, even though they seem to use "not". > And I think they are really convenient. I realize that I was confused by the lexical form of the "not in" operator : it is made by juxtaposing two other operators. Operators composed from two other operators exist, for instance != but the two cannot be separated, for instance 2 ! = 3 is not a valid expression. Said in another way, in Python syntax, usually a "lexically juxtaposed operator" is seen as a whole. This is not the case for an operator such as "is not" or "not in" because for example >>> 2 is not 3 is a valid statement. A notin operator or isnot operator would be less confusing (at least in my case ;) ). From candide at free.invalid Sat Oct 8 10:41:11 2011 From: candide at free.invalid (candide) Date: Sat, 08 Oct 2011 16:41:11 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: <4e902932$0$23273$426a34cc@news.free.fr> References: <4e902932$0$23273$426a34cc@news.free.fr> Message-ID: <4e906108$0$27980$426a34cc@news.free.fr> Le 08/10/2011 12:42, candide a ?crit : > >>> not ('th' in "python") > False > >>> After browsing source code, I realize that parenthesis are not necessary ("not" has higher precedence than "in"). From candide at free.invalid Sat Oct 8 10:41:43 2011 From: candide at free.invalid (candide) Date: Sat, 08 Oct 2011 16:41:43 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: <14fa9dc2-d4bb-4fc9-955d-ac28848d9380@n8g2000yqd.googlegroups.com> References: <4e902932$0$23273$426a34cc@news.free.fr> <14fa9dc2-d4bb-4fc9-955d-ac28848d9380@n8g2000yqd.googlegroups.com> Message-ID: <4e906128$0$27980$426a34cc@news.free.fr> Le 08/10/2011 12:50, Jon Clements a ?crit : > 10 - 5 as 10 + -5 (as obviously the - is redundant as an operation), > and 10 / 2 as int(10 * .5) or something, who needs a divide!? OK, I see your point but I was supposing non-membershipness seldom needed and in fact one can suppose that test membership is heavily more used than test non-membership. In fact, it seems that most Python operators have an "antonym" operator, for instance : == vs != < vs >= is vs is not + vs - etc From candide at free.invalid Sat Oct 8 10:41:51 2011 From: candide at free.invalid (candide) Date: Sat, 08 Oct 2011 16:41:51 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e90612f$0$27980$426a34cc@news.free.fr> Le 08/10/2011 14:01, Steven D'Aprano a ?crit : > And "not in" is the obvious way to do it. > > Obvious ? Not so. I performed some code mining and it appears that even good sources make use of "not (foo in bar)" expressions. ******** begin examples *************** from drpython/drPluginDialog.py ----------------------------- if not (plugin in self.parent.pluginstoremove): from numpy/f2py/crackfortran.py ------------------------------- if not (l[0] in spacedigits): from crunchy1.0alpha1/crunchy/src/plugins/vlam_editor.py ---------------------------------------------------------- if (("no_copy" in vlam) and not ("no_pre" in vlam)) or (not python_code): from Cpython/Python-3.1a1/Lib/logging/__init__.py -------------------------------------------------- if not (hdlr in self.handlers): from Cpython/Python-2.6.2/Lib/idlelib/configHandler.py ------------------------------------------------------- if not (configType in ('main','extensions','highlight','keys')): raise InvalidConfigType, 'Invalid configType specified' from pygtk-2.22.0/gtk/webkitgtk/WebKit-r93015/Source/JavaScriptCore/KeywordLookupGenerator.py --------------------------------------------------------------------------------------------- if not (key[0] in self.keys): from pypy/pypy-pypy-release-1.6/lib-python/2.7/logging/__init__.py ------------------------------------------------------------------ if not (hdlr in self.handlers): ******** end examples *************** _Many_ more examples of this type are avalaible. The obviousness of an "is not" operator is very debatable. Do you have standard functions or method such as isnotinstance, isnotsubset, isnotdir, isnotfile, isnotalpha, etc ? In my case, It took a long time to realize the existence of a "true" "not in" operator as I explain in my response to Alain. Imagine, /Dive Into Python/ book doesn't describe this operator per se and provides only one source file using it. Official Python tutorial at python.org didn't provide even one. > "If the key is not in the ignition, you won't be able to start the car." > > "If not the key is in the ignition, you won't be able to start the car." > > > Who like that second one speaks? > Depends if you are aware of negative form conjugation. From rosuav at gmail.com Sat Oct 8 10:51:03 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Oct 2011 01:51:03 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: <4e9060fa$0$27980$426a34cc@news.free.fr> References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e9060fa$0$27980$426a34cc@news.free.fr> Message-ID: On Sun, Oct 9, 2011 at 1:40 AM, candide wrote: > A notin operator or isnot operator would be less confusing (at least in my > case ;) ). > Let's replace both of them. in --> foo extant bar not in --> foo extinct bar That would solve the problem, wouldn't it? *ducking for cover* ChrisA From thorsten at thorstenkampe.de Sat Oct 8 11:13:18 2011 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 8 Oct 2011 17:13:18 +0200 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: * candide (Sat, 08 Oct 2011 16:41:11 +0200) > After browsing source code, I realize that parenthesis are not > necessary ("not" has higher precedence than "in"). Lower precedence. Thorsten From d at davea.name Sat Oct 8 11:16:54 2011 From: d at davea.name (Dave Angel) Date: Sat, 08 Oct 2011 11:16:54 -0400 Subject: Usefulness of the "not in" operator In-Reply-To: <4e906108$0$27980$426a34cc@news.free.fr> References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: <4E906966.4050600@davea.name> On 01/-10/-28163 02:59 PM, candide wrote: > Le 08/10/2011 12:42, candide a ?crit : > > >> >>> not ('th' in "python") >> False >> >>> > > > > After browsing source code, I realize that parenthesis are not > necessary ("not" has higher precedence than "in"). > You should say "... parenthesis are not necessary ("not" has LOWER precedence than "in")." -- DaveA From candide at free.invalid Sat Oct 8 11:18:23 2011 From: candide at free.invalid (candide) Date: Sat, 08 Oct 2011 17:18:23 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: <4e9069c0$0$648$426a74cc@news.free.fr> Le 08/10/2011 17:13, Thorsten Kampe a ?crit : > * candide (Sat, 08 Oct 2011 16:41:11 +0200) >> After browsing source code, I realize that parenthesis are not >> necessary ("not" has higher precedence than "in"). > > Lower precedence. > Ooops, thanks. From rosuav at gmail.com Sat Oct 8 11:20:01 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Oct 2011 02:20:01 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: <4E906966.4050600@davea.name> References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> <4E906966.4050600@davea.name> Message-ID: On Sun, Oct 9, 2011 at 2:16 AM, Dave Angel wrote: > You should say > ? ?"... parenthesis are not necessary ("not" has LOWER precedence than > "in")." > Is "are not" an operator in English, or should this be "not parentheses are necessary"? ChrisA From invalid at invalid.invalid Sat Oct 8 11:28:17 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Sat, 8 Oct 2011 15:28:17 +0000 (UTC) Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2011-10-08, Steven D'Aprano wrote: > candide wrote: > >> So what is the usefulness of the "not in" operator ? Recall what Zen of >> Python tells >> >> There should be one-- and preferably only one --obvious way to do it. > > And "not in" is the obvious way to do it. > > > "If the key is not in the ignition, you won't be able to start the car." > > "If not the key is in the ignition, you won't be able to start the car." > > > Who like that second one speaks? Yoda. -- Grant Edwards grant.b.edwards Yow! ... I don't like FRANK at SINATRA or his CHILDREN. gmail.com From nobody at nowhere.com Sat Oct 8 11:30:23 2011 From: nobody at nowhere.com (Nobody) Date: Sat, 08 Oct 2011 16:30:23 +0100 Subject: encoding problem with BeautifulSoup - problem when writing parsed text to file References: <11a143ed-7d3a-4cea-acdd-4dcee0b8ff0c@z12g2000yqz.googlegroups.com> <4e8d231e$0$29978$c3e8da3$5496439d@news.astraweb.com> <4aeb76e9-511f-4a46-94c7-bf2ab84877df@z12g2000yqz.googlegroups.com> Message-ID: On Wed, 05 Oct 2011 21:39:17 -0700, Greg wrote: > Here is the final code for those who are struggling with similar > problems: > > ## open and decode file > # In this case, the encoding comes from the charset argument in a meta > tag > # e.g. > fileObj = open(filePath,"r").read() > fileContent = fileObj.decode("iso-8859-2") > fileSoup = BeautifulSoup(fileContent) The fileObj.decode() step should be unnecessary, and is usually undesirable; Beautiful Soup should be doing the decoding itself. If you actually know the encoding (e.g. from a Content-Type header), you can specify it via the fromEncoding parameter to the BeautifulSoup constructor, e.g.: fileSoup = BeautifulSoup(fileObj.read(), fromEncoding="iso-8859-2") If you don't specify the encoding, it will be deduced from a meta tag if one is present, or a Unicode BOM, or using the chardet library if available, or using built-in heuristics, before finally falling back to Windows-1252 (which seems to be the preferred encoding of people who don't understand what an encoding is or why it needs to be specified). From candide at free.invalid Sat Oct 8 12:05:08 2011 From: candide at free.invalid (candide) Date: Sat, 08 Oct 2011 18:05:08 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: <4e9074b6$0$29120$426a74cc@news.free.fr> Le 08/10/2011 17:16, Dave Angel a ?crit : > You should say > "... parenthesis are not necessary ("not" has LOWER precedence than "in")." > I should, yes, I confess ;) In my defense, I must tell that Python document reference here : http://docs.python.org/reference/expressions.html#summary has an anti-iconic way to display the order precedence. If an operator OP1 has higher precedence than an operator OP2 , it means that, at evaluation time, you execute OP1 FIRST and operator OP2 later. So, its seems very natural to present FIRST operator with stronger precedence. So, if you iconically present this material in a tabular display, you present FIRST (ie at the top because usually we process tabular material starting on the upper part) what you need to calculate FIRST and, again, you present at the TOP the HIGHer precedence and at the BOTTOM the LOWer precedence. Documentations usually provide the table in this order (higher to lower), cf. the table in K&R book for C programing language or here for the C++ PL : http://en.cppreference.com/w/cpp/language/operator_precedence or again there for the Java PL : http://download.oracle.com/javase/tutorial/java/nutsandbolts/operators.html From steve+comp.lang.python at pearwood.info Sat Oct 8 12:08:35 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 09 Oct 2011 03:08:35 +1100 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> Message-ID: <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Roy Smith wrote: > If you want to take it one step further, all the boolean operators can > be derived from nand (the dualists would insist on using nor). Let's define the boolean values and operators using just two functions: def true(x, y): return x def false(x, y): return y That's all we need to define all of Boolean algebra. Unfortunately, it's a bit ugly in Python: >>> true So let's add a helper function to prettify the output: def pr(b): print(b(true, false).__name__) >>> pr(true) true Much nicer! Now define NAND: def Nand(a, b): return (lambda c: lambda x, y: c(y, x))(a(b, a)) and we're done. All of boolean algebra can now be derived from Nand. >>> def Not(b): ... return Nand(b, b) ... >>> pr(Not(true)) false >>> pr(Not(false)) true >>> def And(a, b): ... return Nand(Nand(a, b), Nand(a, b)) ... >>> pr(And(true, false)) false >>> pr(And(true, true)) true >>> def Or(a, b): ... return Nand(Nand(a, a), Nand(b, b)) ... >>> pr(Or(true, false)) true >>> pr(Or(false, false)) false >>> def Xor(a, b): ... return And(Nand(a, b), Or(a, b)) ... >>> pr(Xor(true, false)) true >>> pr(Xor(true, true)) false and so forth. -- Steven From steve+comp.lang.python at pearwood.info Sat Oct 8 12:18:36 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 09 Oct 2011 03:18:36 +1100 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> <4e90612f$0$27980$426a34cc@news.free.fr> Message-ID: <4e9077dd$0$29997$c3e8da3$5496439d@news.astraweb.com> candide wrote: > Le 08/10/2011 14:01, Steven D'Aprano a ?crit : > > > And "not in" is the obvious way to do it. > > Obvious ? Not so. I performed some code mining and it appears that even > good sources make use of "not (foo in bar)" expressions. All that proves is that even expert Python developers can, on occasion, write non-idiomatic Python -- or that they accept code contributed by non-expert Python developers, and don't bother adjusting trivial stylistic flaws. When I learned Pascal 20+ years ago, it took me a long time to stop writing "x not in y" and learn the non-English-like "not x in y". Then I learned Python, and it took me a while to stop writing Pascal code in Python. Bad habits take a while to disappear. (I never added superfluous semi-colons after each line though!) -- Steven From rustompmody at gmail.com Sat Oct 8 12:18:58 2011 From: rustompmody at gmail.com (rusi) Date: Sat, 8 Oct 2011 09:18:58 -0700 (PDT) Subject: help References: <9f8pa1Fsh8U3@mid.individual.net> Message-ID: On Oct 8, 2:51?pm, X1 wrote: > easy_install does not exist on Fedora. http://lmgtfy.com/?q=easy_install+fedora From rustompmody at gmail.com Sat Oct 8 12:31:59 2011 From: rustompmody at gmail.com (rusi) Date: Sat, 8 Oct 2011 09:31:59 -0700 (PDT) Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> Message-ID: On Oct 8, 6:31?pm, Roy Smith wrote: > In article <87ehyn8xlp.... at dpt-info.u-strasbg.fr>, > ?Alain Ketterlin wrote: > > > Sure, but note that you can also reformulate != using not and ==, < > > using not and >=, etc. Operators like "not in" and "is not" should > > really be considered single tokens, even though they seem to use "not". > > And I think they are really convenient. > > If you want to take it one step further, all the boolean operators can > be derived from nand (the dualists would insist on using nor). ^^^^^^^^^^^^ ???? From roy at panix.com Sat Oct 8 12:34:42 2011 From: roy at panix.com (Roy Smith) Date: Sat, 08 Oct 2011 12:34:42 -0400 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: In article <4e906108$0$27980$426a34cc at news.free.fr>, candide wrote: > After browsing source code, I realize that parenthesis are not necessary > ("not" has higher precedence than "in"). Here's my take on parenthesis: If you need to look up whether they're necessary or not, they are :-) From rosuav at gmail.com Sat Oct 8 12:43:31 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Oct 2011 03:43:31 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> Message-ID: On Sun, Oct 9, 2011 at 3:31 AM, rusi wrote: >> If you want to take it one step further, all the boolean operators can >> be derived from nand (the dualists would insist on using nor). > ? ? ? ? ? ? ? ? ? ? ? ?^^^^^^^^^^^^ > ???? > I'm not sure what you're questioning, but it's possible to derive all boolean operators from either nand or nor. Most hardware these days is built out of silicon NAND gates, but there's no reason not to do it as NOR gates. ChrisA From roy at panix.com Sat Oct 8 12:44:35 2011 From: roy at panix.com (Roy Smith) Date: Sat, 08 Oct 2011 12:44:35 -0400 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> Message-ID: In article , rusi wrote: > On Oct 8, 6:31?pm, Roy Smith wrote: > > In article <87ehyn8xlp.... at dpt-info.u-strasbg.fr>, > > ?Alain Ketterlin wrote: > > > > > Sure, but note that you can also reformulate != using not and ==, < > > > using not and >=, etc. Operators like "not in" and "is not" should > > > really be considered single tokens, even though they seem to use "not". > > > And I think they are really convenient. > > > > If you want to take it one step further, all the boolean operators can > > be derived from nand (the dualists would insist on using nor). > ^^^^^^^^^^^^ > ???? Dualist (noun): a made up word referring to wrong-thinking people who have rejected the teachings of the Prophet Nand and believe the nor is the One True Operation on which all over operations can be constructed. From g4b.org at gmail.com Sat Oct 8 15:19:40 2011 From: g4b.org at gmail.com (g4b) Date: Sat, 8 Oct 2011 12:19:40 -0700 (PDT) Subject: GUIs - A Modest Proposal In-Reply-To: <76d1$4c1c150a$4275d90a$2055@FUSE.NET> References: <6989fa9b-f642-4939-8ec9-c6e17eae42f5@y11g2000yqm.googlegroups.com> <61fe0cb7-e7a6-4f31-9a3e-5dfd2a6b8edf@j8g2000yqd.googlegroups.com> <66e22bca-17eb-43dd-b343-82278cb23cd8@x27g2000prf.googlegroups.com> <17111c68-694e-4a27-a1d2-30199ab67fe3@z13g2000prh.googlegroups.com> <76d1$4c1c150a$4275d90a$2055@FUSE.NET> Message-ID: <32365686.149.1318101580209.JavaMail.geo-discussion-forums@yqmn40> On the subject of the gui discussion mentioned here last year, which you get lead to if you read around in the pyjamas docs, I have to admit, since I know both development types (gwt, wx, qt) and (django, jquery), I have to state the fact, that pyjamas should also consider bonding with native javascript library developments. Excuse me if I accidentaly go a bit off track, but I guessed, I might bring in my thoughts (but I hope, not to get emotional responses which made this thread a bit hard to follow in the end) The interchange between fixed sized GUI applications and browsing technology as a whole could for example get very interesting for django development, if javascript operated functions would be taken over by native python. I was just looking at pyquery, a python implementation of jquery, which could easily backbone jquery itself on the python end. Now this is not pyjamas' task, but the pyjs compiler could be used, so that jquery code could be written for both languages. Since jquery DOM interfacing is way easier, and hot fixes can be made by javascript development teams, GUI elements of jquery libraries could be integrated into the application. While the functionality of the UI therefore still is GUI based in terms of fixed applications, like pyjamas desktop, concurrent efforts could take place from the so called "web-development" gui layouts. On that front, a lot of talented coders exist in younger generations, which would have the ability to develop the web frontend in closer relation to the web-designers, mainting the key issues for the world-wide-web: design, speed and small loading time. Long story short: if you could write jquery in python which actually compiles into jquery in javascript, and even runs on python itself, you could deploy widgets natively from python in django, and dont have to leave python to improve webapplications with its native strengths. You can free yourself up pretty soon from having too much problems with ui. the designer can do that. You focus on datasets, server-client-api, or you can expose one of your pyjamas widgets as jquery plugin integrating validation of data server and clientside. You can still develop a control application or other integrated software parts natively with pyjamas desktop, knowing the web uses correct code. Of course that depends on how much overhead pyjamas libraries have if you only take a piece of it out, like a richtext element or a fully bloated editor, but even then, internally you load the app anyway up front, externally the user transitions from being a human guest to being a system user only in certain occasions. Any thoughts? From jredgrave at capisco.com Sat Oct 8 16:57:09 2011 From: jredgrave at capisco.com (Jon Redgrave) Date: Sat, 8 Oct 2011 13:57:09 -0700 (PDT) Subject: PDB command <-> variable clashes References: Message-ID: <62e1b36f-7e5c-4e8e-9738-ea5e468c8332@dd6g2000vbb.googlegroups.com> On Oct 8, 1:18?pm, K??ri?inen Anssi wrote: > I am currently debugging the django test cases, and there are a lot of variables names like w, q, where, condition and so on. Especially variables like w, q, c, r are really annoying. It would be cool if pdb would detect a clash and in that case ask you what to do. Nothing more annoying than stepping through the code, finally finding the problematic place and then trying to find out what c.somevar contains... I am using Python 2.6. > > Is there some way to do this? My googling didn't turn out anything. Or is it recommended to use something else instead of pdb? > > Thank you for your time, > ?- Anssi K??ri?inen Its not perfect but I use in sitecustomize def precmd(self,l): if '.' in l: if l[:1]!='!':l='!'+l return l if l in self.curframe.f_locals: return '!'+l if l.startswith('@'): return l[1:] return l import pdb pdb.Pdb.precmd = precmd What this does is q ->variable q if it exists else quit command @q ->always quit !q ->always variable HTH Jon From timr at probo.com Sat Oct 8 18:20:44 2011 From: timr at probo.com (Tim Roberts) Date: Sat, 08 Oct 2011 15:20:44 -0700 Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> <4e8bed30$0$29978$c3e8da3$5496439d@news.astraweb.com> <87wrcjzmql.fsf@benfinney.id.au> Message-ID: Dennis Lee Bieber wrote: > > While I wouldn't want to write an FFT in COBOL, one can't deny that >laying out fixed width reports and moving blocks of decimal data between >record layouts is quite easy in COBOL. Absolutely. I've always thought the Data Section in COBOL was conceptually ahead of its time. It makes you THINK about your data structures more than, say "struct" in C. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From timr at probo.com Sat Oct 8 19:35:50 2011 From: timr at probo.com (Tim Roberts) Date: Sat, 08 Oct 2011 16:35:50 -0700 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: <7in1975qnestbd79rlfkpfd62in3hum4km@4ax.com> Roy Smith wrote: >In article <4e906108$0$27980$426a34cc at news.free.fr>, > candide wrote: > >> After browsing source code, I realize that parenthesis are not necessary >> ("not" has higher precedence than "in"). > >Here's my take on parenthesis: If you need to look up whether they're >necessary or not, they are :-) Amen. +1 -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From alex.kapps at web.de Sat Oct 8 20:17:53 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Sun, 09 Oct 2011 02:17:53 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: <7in1975qnestbd79rlfkpfd62in3hum4km@4ax.com> References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> <7in1975qnestbd79rlfkpfd62in3hum4km@4ax.com> Message-ID: <4E90E831.4090300@web.de> On 09.10.2011 01:35, Tim Roberts wrote: > Roy Smith wrote: >> In article<4e906108$0$27980$426a34cc at news.free.fr>, >> candide wrote: >> >>> After browsing source code, I realize that parenthesis are not necessary >>> ("not" has higher precedence than "in"). >> >> Here's my take on parenthesis: If you need to look up whether they're >> necessary or not, they are :-) > > Amen. +1 So LISP (Lots of Irritating Superfluous Parentheses) was right all the time and is now finally vindicated? ;-) From alex.kapps at web.de Sat Oct 8 20:25:27 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Sun, 09 Oct 2011 02:25:27 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E90E9F7.9000300@web.de> On 08.10.2011 18:08, Steven D'Aprano wrote: > Let's define the boolean values and operators using just two functions: [SNIP] Have you just explained Church booleans in an understandable language? Awesome. I still have to chew on this, but I think this is the first time where I might understand it. Thanks! Even if it's off-topic, could you add some similar explanations for Church numerals (maybe Lambda calculus it isn't too much?) From rosuav at gmail.com Sat Oct 8 21:29:45 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 9 Oct 2011 12:29:45 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: I sent this email twelve hours ago but to the wrong mailing list *blush*. Since nobody else has raised the point, I'll repost it. On Sun, Oct 9, 2011 at 12:07 AM, Jussi Piitulainen wrote: > But both negations can be avoided by modus tollens. > > "If you are able to start the car, the key is in the ignition." > But this translation implies looking at the result and ascertaining the state, which is less appropriate to a programming language. It's more like: "If you found that you were able to start the car, the key must have been in the ignition." and is thus quite inappropriate to the imperative style. A functional language MAY be able to use this style, but Python wants to have the condition and then the action. ChrisA From roy at panix.com Sat Oct 8 21:41:03 2011 From: roy at panix.com (Roy Smith) Date: Sat, 08 Oct 2011 21:41:03 -0400 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article , Chris Angelico wrote: > I sent this email twelve hours ago but to the wrong mailing list > *blush*. Since nobody else has raised the point, I'll repost it. > > On Sun, Oct 9, 2011 at 12:07 AM, Jussi Piitulainen > wrote: > > But both negations can be avoided by modus tollens. > > > > "If you are able to start the car, the key is in the ignition." > > > > But this translation implies looking at the result and ascertaining > the state, which is less appropriate to a programming language. It's > more like: > > "If you found that you were able to start the car, the key must have > been in the ignition." > > and is thus quite inappropriate to the imperative style. A functional > language MAY be able to use this style, but Python wants to have the > condition and then the action. > > ChrisA The key is in the ignition if you are able to start the car else you hot-wired it. From miki.tebeka at gmail.com Sat Oct 8 22:52:25 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Sat, 8 Oct 2011 19:52:25 -0700 (PDT) Subject: PDB command <-> variable clashes In-Reply-To: References: Message-ID: <23757466.646.1318128745524.JavaMail.geo-discussion-forums@prho12> If you want to view the variable, use the "p" (print) command. Then there is no name clash. From miki.tebeka at gmail.com Sat Oct 8 22:52:25 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Sat, 8 Oct 2011 19:52:25 -0700 (PDT) Subject: PDB command <-> variable clashes In-Reply-To: References: Message-ID: <23757466.646.1318128745524.JavaMail.geo-discussion-forums@prho12> If you want to view the variable, use the "p" (print) command. Then there is no name clash. From ericsnowcurrently at gmail.com Sun Oct 9 00:21:02 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Sat, 8 Oct 2011 22:21:02 -0600 Subject: "IX" as shorthand for "Interface" Message-ID: I'm writing a bunch of classes that have "Interface" in the name and find that the length of the subsequent names is starting to get in the way of readability (I don't really care about saving keystrokes). Is "IX" conventional enough to use in place of "Interface" in a class name? Thanks! -eric From clp2 at rebertia.com Sun Oct 9 00:31:10 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 8 Oct 2011 21:31:10 -0700 Subject: "IX" as shorthand for "Interface" In-Reply-To: References: Message-ID: On Sat, Oct 8, 2011 at 9:21 PM, Eric Snow wrote: > I'm writing a bunch of classes that have "Interface" in the name and > find that the length of the subsequent names is starting to get in the > way of readability (I don't really care about saving keystrokes). ?Is > "IX" conventional enough to use in place of "Interface" in a class > name? ?Thanks! But classes and interfaces are distinct concepts... - Chris From ericsnowcurrently at gmail.com Sun Oct 9 00:49:08 2011 From: ericsnowcurrently at gmail.com (Eric Snow) Date: Sat, 8 Oct 2011 22:49:08 -0600 Subject: "IX" as shorthand for "Interface" In-Reply-To: References: Message-ID: On Sat, Oct 8, 2011 at 10:31 PM, Chris Rebert wrote: > On Sat, Oct 8, 2011 at 9:21 PM, Eric Snow wrote: >> I'm writing a bunch of classes that have "Interface" in the name and >> find that the length of the subsequent names is starting to get in the >> way of readability (I don't really care about saving keystrokes). ?Is >> "IX" conventional enough to use in place of "Interface" in a class >> name? ?Thanks! > > But classes and interfaces are distinct concepts... > > - Chris > I saw what you did right there! Be that as it may, is "IX" a common enough abbreviation? -eric From ben+python at benfinney.id.au Sun Oct 9 01:52:56 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 09 Oct 2011 16:52:56 +1100 Subject: "IX" as shorthand for "Interface" References: Message-ID: <87aa9azp6v.fsf@benfinney.id.au> Eric Snow writes: > I'm writing a bunch of classes that have "Interface" in the name and > find that the length of the subsequent names is starting to get in the > way of readability (I don't really care about saving keystrokes). Is > "IX" conventional enough to use in place of "Interface" in a class > name? Thanks! Convention in which community? If you just mean in general programming community, I don't think ?IX? would suggest interface at all. The only common convention I've seen is the ?I? prefix: ?IFoo? to suggest ?the Foo interface?. But that's hopelessly ambiguous, and I don't recommend it. -- \ ?Sane people have an appropriate perspective on the relative | `\ importance of foodstuffs and human beings. Crazy people can't | _o__) tell the difference.? ?Paul Z. Myers, 2010-04-18 | Ben Finney From yasar11732 at gmail.com Sun Oct 9 02:30:58 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Sun, 9 Oct 2011 09:30:58 +0300 Subject: Working with spreadsheet files Message-ID: Hi, Does anyone know a good tutorial about working with Spreadsheet files (e.g. excel files) with Python. I have found xlutils, but there doesn't seem to be any documentation or tutorial about it that I could find. So, any suggestions? -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Sun Oct 9 04:09:12 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 09 Oct 2011 19:09:12 +1100 Subject: "IX" as shorthand for "Interface" References: Message-ID: <4e9156a8$0$29970$c3e8da3$5496439d@news.astraweb.com> Eric Snow wrote: > I'm writing a bunch of classes that have "Interface" in the name and > find that the length of the subsequent names is starting to get in the > way of readability (I don't really care about saving keystrokes). Is > "IX" conventional enough to use in place of "Interface" in a class > name? Thanks! I've never seen or heard of "IX" as an abbreviation for Interface. Apart from the fact that they both start with I, what is the connection? Is the fact that "IX" is pronounced Icks meant as commentary about Interfaces perhaps? -- Steven From mail at timgolden.me.uk Sun Oct 9 05:00:54 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 09 Oct 2011 10:00:54 +0100 Subject: Working with spreadsheet files In-Reply-To: References: Message-ID: <4E9162C6.80801@timgolden.me.uk> On 09/10/2011 07:30, Ya?ar Arabac? wrote: > Does anyone know a good tutorial about working with Spreadsheet files > (e.g. excel files) with Python. I have found xlutils, but there doesn't > seem to be any documentation or tutorial about it that I could find. So, > any suggestions? http://www.python-excel.org/ TJG From vishwasidthan at gmail.com Sun Oct 9 05:44:11 2011 From: vishwasidthan at gmail.com (vishwa nathan) Date: Sun, 9 Oct 2011 02:44:11 -0700 (PDT) Subject: vdfgdfg Message-ID: <81f3673d-3f4b-440e-b50d-078c9a626751@t23g2000prg.googlegroups.com> http://123maza.com/65/white725/ From mail at timgolden.me.uk Sun Oct 9 05:51:24 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 09 Oct 2011 10:51:24 +0100 Subject: Thread handling issue In-Reply-To: References: <4E8EBC32.9060000@timgolden.me.uk> <4E8F1336.3070907@timgolden.me.uk> Message-ID: <4E916E9C.3000908@timgolden.me.uk> On 08/10/2011 11:51, Paul wrote: > I think I'll wait for the user to actually make a change after cancelling the > output selection, in case they go straight back without making changes. If they > make a change I think I'll try what you suggested and send off a new thread, and > send an event to the previous thread. Would this mean I'd need to use > wx.lib.newevent.NewCommandEvent() to get a new event for each thread I create? > and I'd have to pass the second return value from that, the event binder to the > thread to bind to a clean up and exit method? I'm afraid I'm more-or-less completely unfamiliar with the wx way of doing things. You'd hopefully get useful answers from a wx-focused mailing list. (This is always the difficulty in translating between a "in theory you could do this" answer and a real-world "I've got this and that and the other " situation :) ) TJG From nobody at nowhere.com Sun Oct 9 06:12:59 2011 From: nobody at nowhere.com (Nobody) Date: Sun, 09 Oct 2011 11:12:59 +0100 Subject: "IX" as shorthand for "Interface" References: Message-ID: On Sat, 08 Oct 2011 22:21:02 -0600, Eric Snow wrote: > I'm writing a bunch of classes that have "Interface" in the name and > find that the length of the subsequent names is starting to get in the > way of readability (I don't really care about saving keystrokes). Is > "IX" conventional enough to use in place of "Interface" in a class > name? Thanks! I've only ever seen "ix" used as an abbreviation for "index". The common abbrevations for "interface" are "if" (e.g. the Linux networking headers), "iface", or the "I" prefix in Windows' COM. From python.list at tim.thechases.com Sun Oct 9 08:20:45 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 09 Oct 2011 07:20:45 -0500 Subject: DRY functions with named attributes used as default arguments Message-ID: <4E91919D.7010007@tim.thechases.com> My intent is to have a function object something like def foo(arg1, arg2=foo.DEFAULT): return int(do_stuff(arg1, arg2)) foo.SPECIAL = 42 foo.MONKEY = 31415 foo.DEFAULT = foo.SPECIAL so I can call it with either result = foo(myarg) or result = foo(myarg, foo.SPECIAL) However I can't do this because foo.DEFAULT isn't defined at the time the function is created. I'd like to avoid hard-coding things while staying DRY, so I don't like def foo(arg1, arg2=42) because the default might change due to business rule changes, I have a dangling "magic constant" and if the value of SPECIAL changes, I have to catch that it should be changed in two places. My current hack/abuse is to use __new__ in a class that can contain the information: class foo(object): SPECIAL = 42 MONKEY = 31415 DEFAULT = SPECIAL def __new__(cls, arg1, arg2=DEFAULT): return int(do_stuff(arg1, arg2)) i1 = foo("spatula") i2 = foo("tapioca", foo.MONKEY) 1) is this "icky" (a term of art ;-) 2) or is this reasonable 3) or is there a better way to do what I want? Thanks, -tkc From arnodel at gmail.com Sun Oct 9 09:19:34 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Sun, 9 Oct 2011 14:19:34 +0100 Subject: DRY functions with named attributes used as default arguments In-Reply-To: <4E91919D.7010007@tim.thechases.com> References: <4E91919D.7010007@tim.thechases.com> Message-ID: On 9 October 2011 13:20, Tim Chase wrote: > My intent is to have a function object something like > > ?def foo(arg1, arg2=foo.DEFAULT): > ? ?return int(do_stuff(arg1, arg2)) > ?foo.SPECIAL = 42 > ?foo.MONKEY = 31415 > ?foo.DEFAULT = foo.SPECIAL > > so I can call it with either > > ?result = foo(myarg) > > or > > ?result = foo(myarg, foo.SPECIAL) > > However I can't do this because foo.DEFAULT isn't defined at the time the > function is created. ?I'd like to avoid hard-coding things while staying > DRY, so I don't like > > ?def foo(arg1, arg2=42) > > because the default might change due to business rule changes, I have a > dangling "magic constant" and if the value of SPECIAL changes, I have to > catch that it should be changed in two places. > > My current hack/abuse is to use __new__ in a class that can contain the > information: > > ?class foo(object): > ? ?SPECIAL = 42 > ? ?MONKEY = 31415 > ? ?DEFAULT = SPECIAL > ? ?def __new__(cls, arg1, arg2=DEFAULT): > ? ? ?return int(do_stuff(arg1, arg2)) > > ?i1 = foo("spatula") > ?i2 = foo("tapioca", foo.MONKEY) > > 1) is this "icky" (a term of art ;-) > 2) or is this reasonable > 3) or is there a better way to do what I want? > Why do you want these argument values to be attributes of the function? Anyway, simpler than abusing classes: foo_default = 42 def foo(arg1, arg2=foo_default): ... foo.DEFAULT = foo_default del foo_default ... Or get the default at function runtime: def foo(arg1, arg2=None): if arg2 is None: arg2 = foo.DEFAULT ... foo.DEFAULT = 42 ... But I'd probably simply go for foo_DEFAULT, foo_MONKEY and foo_SPECIAL. They're also quicker (1 dict lookup instead of 2) -- Arnaud From jpc at parallelthoughts.org Sun Oct 9 09:30:42 2011 From: jpc at parallelthoughts.org (John P. Crackett) Date: Sun, 09 Oct 2011 14:30:42 +0100 Subject: Using Python xmlrpclib to build XMLRPC clients for a server with variable RPC names Message-ID: <1318167042.3120.54.camel@ptlws01.config> I need to write prototype XMLRPC clients using xmlrpclib for a server that has variable RPC names and I'd like to use Python as the prototyping tool. I've searched but can't find any relevant advice online. Any pointers would be gratefully received; details follow. The server in question constructs method names dynamically using the names of objects created by the client. Since the xmlrpclib ServerProxy object uses methods mirroring the RPC names I would need to be able to do the following: api = xmlrpclib.ServerProxy(serverURL) api.createObject("foo") api.foo.callOne() where I don't know what "foo" will actually be in advance. As an added complication, object names need to be concatenated using "-" as a separator to form compound RPC names. Following on from the example above, this could lead to: api = xmlrpclib.ServerProxy(serverURL) api. createObjects("foo", "far") api.foo-bar.callOne() Where I don't know, again, what "foo" and "bar" will actually be in advance. "foo-bar" is obviously not a valid Python method name and this is preventing me from hard-coding just to get a prototype going. Is Python + xmlrpclib usable under these circumstances? If so, a pointer in the right direction would be appreciated. Apologies if there's some glaringly obvious way of doing this that I have overlooked - I'm new to Python. Many thanks in anticipation. -- /jpc From roy at panix.com Sun Oct 9 11:02:36 2011 From: roy at panix.com (Roy Smith) Date: Sun, 09 Oct 2011 11:02:36 -0400 Subject: "IX" as shorthand for "Interface" References: Message-ID: In article , Eric Snow wrote: > I saw what you did right there! Be that as it may, is "IX" a > common enough abbreviation? I would not recognize it at first glance. If anything, I think of X as standing for experience (UI -- User Interface, UX -- User Experience). But, if it's a big package and you adopt a uniform naming convention, it shouldn't be a problem. Especially if you have some kind of README that describes what conventions you are using. Or you could use I7E :-) From __peter__ at web.de Sun Oct 9 11:19:12 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 09 Oct 2011 17:19:12 +0200 Subject: "IX" as shorthand for "Interface" References: Message-ID: Roy Smith wrote: > In article , > Eric Snow wrote: > >> I saw what you did right there! Be that as it may, is "IX" a >> common enough abbreviation? What Roy really wanted to say: I w3d n1t r7e it at f3t g4e. If a6g, I t3k of X as s6g f1r e8e (UI -- U2r I7e, UX -- U2r E8e). B1t, if it's a b1g p5e a1d y1u a3t a u5m n4g c8n, it s5n't be a p5m. E8y if y1u h2e s2e k2d of R4E t2t d7s w2t c9s y1u a1e u3g. ;) From steve+comp.lang.python at pearwood.info Sun Oct 9 11:37:57 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 10 Oct 2011 02:37:57 +1100 Subject: DRY functions with named attributes used as default arguments References: Message-ID: <4e91bfd6$0$29989$c3e8da3$5496439d@news.astraweb.com> Tim Chase wrote: > My intent is to have a function object something like > > def foo(arg1, arg2=foo.DEFAULT): > return int(do_stuff(arg1, arg2)) > foo.SPECIAL = 42 > foo.MONKEY = 31415 > foo.DEFAULT = foo.SPECIAL What's the purpose of having both foo.SPECIAL and foo.DEFAULT? You could always use a callable instance instead of a function, what C++ calls a functor (not to be confused with what Haskell calls a functor, which is completely different). class Foo: SPECIAL = 42 MONKEY = 31215 DEFAULT = SPECIAL def __call__(self, arg1, arg2=DEFAULT): ... foo = Foo() del Foo The default value of arg2 is bound at class definition time, once. If you prefer late binding instead of early binding, it is easy to put off the assignment until the function is called: def __call__(self, arg1, arg2=None): if arg2 is None: arg2 = self.DEFAULT ... If None is a legitimate data value for arg2, you can create your own sentinel: SENTINEL = object() and use that instead of None. > so I can call it with either > > result = foo(myarg) > > or > > result = foo(myarg, foo.SPECIAL) > > However I can't do this because foo.DEFAULT isn't defined at the > time the function is created. I'd like to avoid hard-coding > things while staying DRY, so I don't like > > def foo(arg1, arg2=42) > > because the default might change due to business rule changes, If the business rule changes, you have to change foo.DEFAULT anyway. So why not cut out the middle man and change the default argument in the function signature? > I > have a dangling "magic constant" and if the value of SPECIAL > changes, I have to catch that it should be changed in two places. Then put it in one place. SPECIAL = 42 def foo(arg1, arg2=SPECIAL): ... and avoid the reference to foo. > My current hack/abuse is to use __new__ in a class that can > contain the information: > > class foo(object): > SPECIAL = 42 > MONKEY = 31415 > DEFAULT = SPECIAL > def __new__(cls, arg1, arg2=DEFAULT): > return int(do_stuff(arg1, arg2)) > > i1 = foo("spatula") > i2 = foo("tapioca", foo.MONKEY) > > 1) is this "icky" (a term of art ;-) > 2) or is this reasonable Seems okay to me. A little unusual, but only a little, not "WTF is this code doing???" territory. -- Steven From edcjones at comcast.net Sun Oct 9 11:43:18 2011 From: edcjones at comcast.net (thegripper) Date: Sun, 9 Oct 2011 08:43:18 -0700 (PDT) Subject: SciPy/NumPy: read, write images using Python3 Message-ID: <9ca46882-acb1-4a23-8b6b-69539ff37d08@n15g2000vbn.googlegroups.com> In SciPy / NumPy, the primary way to read and write images is PIL. But PIL does not yet support Python3. Is there some good way to read, write, and resize images in a NumPy and Python3 environment? From edcjones at comcast.net Sun Oct 9 11:43:44 2011 From: edcjones at comcast.net (thegripper) Date: Sun, 9 Oct 2011 08:43:44 -0700 (PDT) Subject: SciPy/NumPy: read, write images using Python3 Message-ID: <0d8c568e-28a7-441b-a5b0-281d1a7b14e1@j31g2000vbl.googlegroups.com> In SciPy / NumPy, the primary way to read and write images is PIL. But PIL does not yet support Python3. Is there some good way to read, write, and resize images in a NumPy and Python3 environment? From darcy at druid.net Sun Oct 9 11:51:05 2011 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sun, 9 Oct 2011 11:51:05 -0400 Subject: "IX" as shorthand for "Interface" In-Reply-To: References: Message-ID: <20111009115105.206a492b@dilbert> On Sat, 8 Oct 2011 22:21:02 -0600 Eric Snow wrote: > I'm writing a bunch of classes that have "Interface" in the name and > find that the length of the subsequent names is starting to get in the > way of readability (I don't really care about saving keystrokes). Is > "IX" conventional enough to use in place of "Interface" in a class > name? Thanks! Here's a suggestion based on my complete ignorance of you application so take it for what it is worth. If keystrokes don't matter to you consider this. class INTERFACE: pass class Something(INTERFACE): ... It isn't in the name but the definition is clearly an "INTERFACE" (whatever that is) and you also have the option of gathering things in common to INTERFACEs in the superclass. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From albert at spenarnc.xs4all.nl Sun Oct 9 12:01:30 2011 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 09 Oct 2011 16:01:30 GMT Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> Message-ID: In article , DevPlayer wrote: >I still assert that contradiction is caused by narrow perspective. > >By that I mean: just because an objects scope may not see a certain >condition, doesn't mean that condition is non-existant. > >I also propose that just because something seems to contradict doesn't >mean it is false. Take for instance: > >Look out your window. Is it daylight or night time? You may say it is >daylight or you may say it is night time. I would disagree that only >one of those conditions are true. Both conditions are true. Always. It >is only day (or night) for YOU. But the opposite DOES in fact exist on >the other side of the world at the same time. This is a far cry from the bible stating that someone is his own grand father. Or going to great length to prove that Jezus (through Jozef) is a descendant of David. Then declaring it a dogma that Jozef has nothing to do with it. (It being ... well ... you know ...) (I have this book, it is called "the amusing bible" with all flippant and contradictory stuff pointed out by a French 1930 communist. Cartoons too. ) Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From albert at spenarnc.xs4all.nl Sun Oct 9 12:33:37 2011 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 09 Oct 2011 16:33:37 GMT Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article , Jussi Piitulainen wrote: >Mel writes: > >> Steven D'Aprano wrote: >> >> > candide wrote: >> > >> >> So what is the usefulness of the "not in" operator ? Recall what Zen of >> >> Python tells >> >> >> >> There should be one-- and preferably only one --obvious way to do it. >> > >> > And "not in" is the obvious way to do it. >> > >> > >> > "If the key is not in the ignition, you won't be able to start the car." >> > >> > "If not the key is in the ignition, you won't be able to start the car." >> > >> > >> > Who like that second one speaks? >> >> :) >> "If the key is not in the ignition, you will be able to start the car, not." > >Oh, be consistent. > >"If not the key is in the ignition, not you will be able to start the car." > >But both negations can be avoided by modus tollens. > >"If you are able to start the car, the key is in the ignition." This is not normal speach. The connotation of an if sentence is that the condition is something you have more control over than over the result. I sometime write if 0 == i : and get complaints, as if both sides of an identity are not equivalent. OTOH if i == j : and nobody cares it I wrote if j == i : > >And one could express "x not in s" as "(x in s) implies False" without >making the "not" explicit if "implies" was in the language. (I know >about <= but I also witnessed an unpleasant thread in another >newsgroup where people insisted that <= should not be defined for >truth values at all, and I also happen to like Python's "not in".) Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From clp2 at rebertia.com Sun Oct 9 14:00:01 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 9 Oct 2011 11:00:01 -0700 Subject: Using Python xmlrpclib to build XMLRPC clients for a server with variable RPC names In-Reply-To: <1318167042.3120.54.camel@ptlws01.config> References: <1318167042.3120.54.camel@ptlws01.config> Message-ID: On Sun, Oct 9, 2011 at 6:30 AM, John P. Crackett wrote: > I need to write prototype XMLRPC clients using xmlrpclib for a server > that has variable RPC names and I'd like to use Python as the > prototyping tool. ?I've searched but can't find any relevant advice > online. ?Any pointers would be gratefully received; details follow. > > The server in question constructs method names dynamically using the > names of objects created by the client. > As an added complication, object names need to be concatenated using "-" > as a separator to form compound RPC names. ?Following on from the > example above, this could lead to: > > api = xmlrpclib.ServerProxy(serverURL) > > api. createObjects("foo", "far") > > api.foo-bar.callOne() > > Where I don't know, again, what "foo" and "bar" will actually be in > advance. ?"foo-bar" is obviously not a valid Python method name and this > is preventing me from hard-coding just to get a prototype going. Try using getattr(): getattr(api, "foo-bar").callOne() For reference, getattr() satisfies the following identity: x.y === getattr(x, "y") except that getattr() does not itself enforce/require that its second argument be a valid Python identifier. Cheers, Chris -- http://rebertia.com From jpc at parallelthoughts.org Sun Oct 9 14:35:36 2011 From: jpc at parallelthoughts.org (JPC) Date: Sun, 09 Oct 2011 19:35:36 +0100 Subject: Using Python xmlrpclib to build XMLRPC clients for a server with variable RPC names In-Reply-To: References: <1318167042.3120.54.camel@ptlws01.config> Message-ID: <1318185336.8259.1.camel@ptlws01.config> That was the information I was missing many thanks. For the reference sake, a look through the source code indicates this solution; prior to your message I just didn't understand it that well. -- /jpc On Sun, 2011-10-09 at 11:00 -0700, Chris Rebert wrote: > On Sun, Oct 9, 2011 at 6:30 AM, John P. Crackett > wrote: > > I need to write prototype XMLRPC clients using xmlrpclib for a server > > that has variable RPC names and I'd like to use Python as the > > prototyping tool. I've searched but can't find any relevant advice > > online. Any pointers would be gratefully received; details follow. > > > > The server in question constructs method names dynamically using the > > names of objects created by the client. > > > As an added complication, object names need to be concatenated using "-" > > as a separator to form compound RPC names. Following on from the > > example above, this could lead to: > > > > api = xmlrpclib.ServerProxy(serverURL) > > > > api. createObjects("foo", "far") > > > > api.foo-bar.callOne() > > > > Where I don't know, again, what "foo" and "bar" will actually be in > > advance. "foo-bar" is obviously not a valid Python method name and this > > is preventing me from hard-coding just to get a prototype going. > > Try using getattr(): > getattr(api, "foo-bar").callOne() > > For reference, getattr() satisfies the following identity: > x.y === getattr(x, "y") > except that getattr() does not itself enforce/require that its second > argument be a valid Python identifier. > > Cheers, > Chris > -- > http://rebertia.com From python.list at tim.thechases.com Sun Oct 9 14:57:03 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 09 Oct 2011 13:57:03 -0500 Subject: DRY functions with named attributes used as default arguments In-Reply-To: <4e91bfd6$0$29989$c3e8da3$5496439d@news.astraweb.com> References: <4e91bfd6$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E91EE7F.9090407@tim.thechases.com> On 10/09/11 10:37, Steven D'Aprano wrote: >> My intent is to have a function object something like >> >> def foo(arg1, arg2=foo.DEFAULT): >> return int(do_stuff(arg1, arg2)) >> foo.SPECIAL = 42 >> foo.MONKEY = 31415 >> foo.DEFAULT = foo.SPECIAL > > What's the purpose of having both foo.SPECIAL and foo.DEFAULT? As you later ask... >> However I can't do this because foo.DEFAULT isn't defined at >> the time the function is created. I'd like to avoid >> hard-coding things while staying DRY, so I don't like >> >> def foo(arg1, arg2=42) >> >> because the default might change due to business rule >> changes, > > If the business rule changes, you have to change foo.DEFAULT > anyway. So why not cut out the middle man and change the > default argument in the function signature? By indirecting through DEFAULT, I can change DEFAULT to point at another behavior-tweaking option in one place ("DEFAULT = SPECIAL") rather than in multiple places. However, I can't give a very good argument for just using def foo(arg1, arg2=SPECIAL) and then, if it changes, just change *that* one location to def foo(arg1, arg2=MONKEY) because, well, Python calls them default arguments for a reason :) > class Foo: > SPECIAL = 42 > MONKEY = 31215 > DEFAULT = SPECIAL > def __call__(self, arg1, arg2=DEFAULT): > ... > > foo = Foo() > del Foo I did consider this (sorry I forgot to mention it) and it works well too. It's a little cleaner, as the magic happens in something named __call__ which is more obvious than overloading odd behavior into __new__. The instantiate-and-delete-the-class felt a little weird, and having both the class and the instance in the namespace felt weird. Granted the (ab)use of __new__ felt weird too, so neither wins by great margin. Which is part of my question: what's the least-worst way to do this? :) >> I have a dangling "magic constant" and if the value of >> SPECIAL changes, I have to catch that it should be changed >> in two places. > > Then put it in one place. > > SPECIAL = 42 > > def foo(arg1, arg2=SPECIAL): > ... > > and avoid the reference to foo. I guess part of my attempt was to keep from littering the module namespace with things that only apply to the one function (and this also applies to C-like prefixes such as FOO_SPECIAL) >> My current hack/abuse is to use __new__ in a class that can >> contain the information: >> >> class foo(object): >> SPECIAL = 42 >> MONKEY = 31415 >> DEFAULT = SPECIAL >> def __new__(cls, arg1, arg2=DEFAULT): >> return int(do_stuff(arg1, arg2)) >> >> i1 = foo("spatula") >> i2 = foo("tapioca", foo.MONKEY) >> >> 1) is this "icky" (a term of art ;-) >> 2) or is this reasonable > > Seems okay to me. A little unusual, but only a little, not > "WTF is this code doing???" territory. The code felt like it was riding the WTF-boundary, so I find your evaluation of "unusual but not WTF" encouraging. Thanks for your thoughts, -tkc From dihedral88888 at googlemail.com Sun Oct 9 16:31:56 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sun, 9 Oct 2011 13:31:56 -0700 (PDT) Subject: Is it possible to create C-style "main" function in Python? (for teaching purposes) In-Reply-To: References: <9559fe87-2f9d-439c-bd3b-94137306cf10@k15g2000yqd.googlegroups.com> <8ba21c09-2cd7-4ce0-acb5-5bd002539d42@z12g2000yqz.googlegroups.com> <4e8bbb96$0$29978$c3e8da3$5496439d@news.astraweb.com> <4e8bed30$0$29978$c3e8da3$5496439d@news.astraweb.com> <87wrcjzmql.fsf@benfinney.id.au> Message-ID: <18490275.937.1318192316512.JavaMail.geo-discussion-forums@prdw1> I do not think C is not good for functional programming, but C is hard to debug if one has to write programs to reload functional pointers and data structures that will grow in the run time for the possible cases. Thus, I love Python! From dihedral88888 at googlemail.com Sun Oct 9 16:34:27 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sun, 9 Oct 2011 13:34:27 -0700 (PDT) Subject: Thread handling issue In-Reply-To: References: Message-ID: <5016619.938.1318192467132.JavaMail.geo-discussion-forums@prdw1> TRY to get BOA with wxpython! Please check the example for the UI part in BOA. From dihedral88888 at googlemail.com Sun Oct 9 16:34:27 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sun, 9 Oct 2011 13:34:27 -0700 (PDT) Subject: Thread handling issue In-Reply-To: References: Message-ID: <5016619.938.1318192467132.JavaMail.geo-discussion-forums@prdw1> TRY to get BOA with wxpython! Please check the example for the UI part in BOA. From alahmar402 at gmail.com Sun Oct 9 16:38:30 2011 From: alahmar402 at gmail.com (cry angel) Date: Sun, 9 Oct 2011 13:38:30 -0700 (PDT) Subject: Amber riley - Mercedes Message-ID: <6b6ca45d-f102-4e17-a936-159aaca3f382@m37g2000yqc.googlegroups.com> New page for the singer Amber riley - Mercedes I wish to enter and enjoy and leave comments http://sunforsun.blogspot.com/p/amber-riley-mercedes.html From anikom15 at gmail.com Sun Oct 9 16:48:14 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Sun, 9 Oct 2011 13:48:14 -0700 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: <20111009204814.GA15277@Smoke> On Sat, Oct 08, 2011 at 12:34:42PM -0400, Roy Smith wrote: > In article <4e906108$0$27980$426a34cc at news.free.fr>, > candide wrote: > > > After browsing source code, I realize that parenthesis are not necessary > > ("not" has higher precedence than "in"). > > Here's my take on parenthesis: If you need to look up whether they're > necessary or not, they are :-) So we don't need precedence charts in the bathroom? From zaffino.p at gmail.com Sun Oct 9 16:59:11 2011 From: zaffino.p at gmail.com (Paolo Zaffino) Date: Sun, 9 Oct 2011 13:59:11 -0700 (PDT) Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows Message-ID: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Hello, I wrote a function that works on a numpy matrix and it works fine on Mac OS and GNU/Linux (I didn't test it on python 3) Now I have a problem with numpy: the same python file doesn't work on Windows (Windows xp, python 2.7 and numpy 2.6.1). I get this error: matrix=matrix.reshape(a, b, c) ValueError: total size of new array must be unchanged Why? Do anyone have an idea about this? Thank you very much. From yasar11732 at gmail.com Sun Oct 9 17:50:45 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Mon, 10 Oct 2011 00:50:45 +0300 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: I don't know about your problem, but did you compare numpy versions in windows and other platforms? You may have newer/older version in Windows. Otherwise, it looks like a platform spesific bug to me. 2011/10/9 Paolo Zaffino > Hello, > I wrote a function that works on a numpy matrix and it works fine on > Mac OS and GNU/Linux (I didn't test it on python 3) > Now I have a problem with numpy: the same python file doesn't work on > Windows (Windows xp, python 2.7 and numpy 2.6.1). > I get this error: > > matrix=matrix.reshape(a, b, c) > ValueError: total size of new array must be unchanged > > Why? Do anyone have an idea about this? > Thank you very much. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve+comp.lang.python at pearwood.info Sun Oct 9 21:14:53 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 10 Oct 2011 12:14:53 +1100 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: <4e92470d$0$29971$c3e8da3$5496439d@news.astraweb.com> Paolo Zaffino wrote: > Hello, > I wrote a function that works on a numpy matrix and it works fine on > Mac OS and GNU/Linux (I didn't test it on python 3) > Now I have a problem with numpy: the same python file doesn't work on > Windows (Windows xp, python 2.7 and numpy 2.6.1). > I get this error: > > matrix=matrix.reshape(a, b, c) > ValueError: total size of new array must be unchanged > > Why? Do anyone have an idea about this? > Thank you very much. Please give sample values for matrix, a, b and c that demonstrate the issue. What version of Python and numpy are you using on Mac and Linux? -- Steven From wuwei23 at gmail.com Mon Oct 10 00:02:40 2011 From: wuwei23 at gmail.com (alex23) Date: Sun, 9 Oct 2011 21:02:40 -0700 (PDT) Subject: A tuple in order to pass returned values ? References: <4e8e5db3$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: Jean-Michel Pichavant wrote: > However, I'm not sure it fixes the main issue: unpacking. Unpacking > prevents you from adding any additional fields to your 'tuple' without > breaking any line of code that was unpacking the tuple (to oppose to > accessing an object attribute). Generally, if it's a small, known, unlikely-to-change structure, I'd use a tuple. For anything else I'd use a class, namedtuple or bunch. However, pre-namedtuples I'd usually abstract away the field referencing with indices and lambdas: name = 0 role = 1 name_role = lambda t: (t[name], t[role]) name, role = name_role(record) etc From roy at panix.com Mon Oct 10 00:09:35 2011 From: roy at panix.com (Roy Smith) Date: Mon, 10 Oct 2011 00:09:35 -0400 Subject: A tuple in order to pass returned values ? References: <4e8e5db3$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article , alex23 wrote: > For anything else I'd use [...] bunch. Particularly useful for handing over lupins. From nobody at nowhere.com Mon Oct 10 01:35:22 2011 From: nobody at nowhere.com (Nobody) Date: Mon, 10 Oct 2011 06:35:22 +0100 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: On Sun, 09 Oct 2011 13:59:11 -0700, Paolo Zaffino wrote: > I wrote a function that works on a numpy matrix and it works fine on > Mac OS and GNU/Linux (I didn't test it on python 3) > Now I have a problem with numpy: the same python file doesn't work on > Windows (Windows xp, python 2.7 and numpy 2.6.1). > I get this error: > > matrix=matrix.reshape(a, b, c) > ValueError: total size of new array must be unchanged > > Why? What it says. The reshape()d array must have the same total number of elements as the original array. If it works on one platform and not on another, that indicates that either "matrix" has a different shape on different platforms, or a*b*c is different on different platforms. As no-one here (except you) has any idea how matrix, a, b and c are getting their values, it's impossible for us to say why they're getting different values on different platforms. From ladasky at my-deja.com Mon Oct 10 04:06:40 2011 From: ladasky at my-deja.com (John Ladasky) Date: Mon, 10 Oct 2011 01:06:40 -0700 (PDT) Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Oct 8, 5:01?am, Steven D'Aprano wrote: > Who like that second one speaks? Yoda his name is. Programs in Forth he must. From alec.taylor6 at gmail.com Mon Oct 10 08:16:55 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Mon, 10 Oct 2011 23:16:55 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Oct 9, 2011 at 3:08 AM, Steven D'Aprano wrote: > Roy Smith wrote: > >> If you want to take it one step further, all the boolean operators can >> be derived from nand (the dualists would insist on using nor). > > Let's define the boolean values and operators using just two functions: > > def true(x, y): > ? ?return x > > def false(x, y): > ? ?return y > > > That's all we need to define all of Boolean algebra. Unfortunately, it's a > bit ugly in Python: > >>>> true > > > So let's add a helper function to prettify the output: > > def pr(b): > ? ?print(b(true, false).__name__) > >>>> pr(true) > true > > Much nicer! > > > Now define NAND: > > def Nand(a, b): > ? ?return (lambda c: lambda x, y: c(y, x))(a(b, a)) > > > and we're done. All of boolean algebra can now be derived from Nand. > > >>>> def Not(b): > ... ? ? return Nand(b, b) > ... >>>> pr(Not(true)) > false >>>> pr(Not(false)) > true > > >>>> def And(a, b): > ... ? ? return Nand(Nand(a, b), Nand(a, b)) > ... >>>> pr(And(true, false)) > false >>>> pr(And(true, true)) > true > > >>>> def Or(a, b): > ... ? ? return Nand(Nand(a, a), Nand(b, b)) > ... >>>> pr(Or(true, false)) > true >>>> pr(Or(false, false)) > false > > >>>> def Xor(a, b): > ... ? ? return And(Nand(a, b), Or(a, b)) > ... >>>> pr(Xor(true, false)) > true >>>> pr(Xor(true, true)) > false > > > and so forth. > > > > -- > Steven > > -- > http://mail.python.org/mailman/listinfo/python-list > Awesome From alain at dpt-info.u-strasbg.fr Mon Oct 10 09:01:16 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Mon, 10 Oct 2011 15:01:16 +0200 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8762jx80gz.fsf@dpt-info.u-strasbg.fr> Alec Taylor writes: > On Sun, Oct 9, 2011 at 3:08 AM, Steven D'Aprano > wrote: >> def true(x, y): >> ? ?return x >> >> def false(x, y): >> ? ?return y [...] >> def Nand(a, b): >> ? ?return (lambda c: lambda x, y: c(y, x))(a(b, a)) >> >> and we're done. [...] > Awesome Yes, that's how Church defined booleans in the lambda calculus. See http://en.wikipedia.org/wiki/Church_encoding for encodings of natural numbers and lists. -- Alain. From alec.taylor6 at gmail.com Mon Oct 10 09:36:25 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 11 Oct 2011 00:36:25 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: <8762jx80gz.fsf@dpt-info.u-strasbg.fr> References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> <8762jx80gz.fsf@dpt-info.u-strasbg.fr> Message-ID: Unfortunately I don't know lambda [or for that matter, regular] calculus... On Tue, Oct 11, 2011 at 12:01 AM, Alain Ketterlin wrote: > Alec Taylor writes: > >> On Sun, Oct 9, 2011 at 3:08 AM, Steven D'Aprano >> wrote: > >>> def true(x, y): >>> ? ?return x >>> >>> def false(x, y): >>> ? ?return y > [...] >>> def Nand(a, b): >>> ? ?return (lambda c: lambda x, y: c(y, x))(a(b, a)) >>> >>> and we're done. [...] > >> Awesome > > Yes, that's how Church defined booleans in the lambda calculus. See > http://en.wikipedia.org/wiki/Church_encoding for encodings of natural > numbers and lists. > > -- Alain. > -- > http://mail.python.org/mailman/listinfo/python-list > From candide at free.invalid Mon Oct 10 09:58:01 2011 From: candide at free.invalid (candide) Date: Mon, 10 Oct 2011 15:58:01 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e92f9ea$0$13089$426a74cc@news.free.fr> Le 10/10/2011 10:06, John Ladasky a ?crit : >> Who like that second one speaks? > > Yoda his name is. Programs in Forth he must. ;) We can add to the list : -- Tarzan -- Geronimo -- don Alexandro de la Vega dying in the arms of Zorro ... From ulrich.eckhardt at dominalaser.com Mon Oct 10 09:58:43 2011 From: ulrich.eckhardt at dominalaser.com (Ulrich Eckhardt) Date: Mon, 10 Oct 2011 15:58:43 +0200 Subject: OpenGL.GLU.gluNewQuadric() segmentation fault on 64 bit systems In-Reply-To: References: Message-ID: Am 10.10.2011 14:18, schrieb X1: > has this bug been resolved? > if yes, which version on files to install? That seems to be part of PyOpenGL, so I'd check their bugtracking system. Uli From dihedral88888 at googlemail.com Mon Oct 10 11:13:15 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Mon, 10 Oct 2011 08:13:15 -0700 (PDT) Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str In-Reply-To: References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> <02EA6D704E30CE499C5071776509A925F5BABD@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <9684870.653.1318259595168.JavaMail.geo-discussion-forums@prib32> I am thinking with the power of python evolving in different versions, if a feature is not desired in the new version, then the new version could also provide some script tools, of course in python, to convert codes in old styles into new styles automatically. From dihedral88888 at googlemail.com Mon Oct 10 11:13:15 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Mon, 10 Oct 2011 08:13:15 -0700 (PDT) Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str In-Reply-To: References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> <02EA6D704E30CE499C5071776509A925F5BABD@039-SN1MPN1-003.039d.mgd.msft.net> Message-ID: <9684870.653.1318259595168.JavaMail.geo-discussion-forums@prib32> I am thinking with the power of python evolving in different versions, if a feature is not desired in the new version, then the new version could also provide some script tools, of course in python, to convert codes in old styles into new styles automatically. From nobody at nowhere.com Mon Oct 10 13:29:49 2011 From: nobody at nowhere.com (Nobody) Date: Mon, 10 Oct 2011 18:29:49 +0100 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, 09 Oct 2011 02:25:27 +0200, Alexander Kapps wrote: > Even if it's off-topic, could you add some similar explanations for > Church numerals (maybe Lambda calculus it isn't too much?) The Church numeral for N is a function of two arguments which applies its first argument N times to its second, i.e. (f^N)(x) = f(f(...(f(x))...)). IOW: def zero(f, x): return x def one(f, x): return f(x) def two(f, x): return f(f(x)) def three(f, x): return f(f(f(x))) And so on. In general: def applyN(n, f, x): for i in xrange(n): x = f(x) return x def church(n): return lambda f, x: applyN(n, f, x) seven = church(7) # this is the Church numeral for 7 > seven(lambda x: x + 1, 0) 7 > seven(lambda x: x * 2, 1) 128 > seven(lambda x: x + ".", "") '.......' From rosuav at gmail.com Mon Oct 10 13:33:43 2011 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Oct 2011 04:33:43 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Oct 11, 2011 at 4:29 AM, Nobody wrote: > > The Church numeral for N is a function of two arguments which applies its > first argument N times to its second, i.e. (f^N)(x) = f(f(...(f(x))...)). > Thanks - nice clear explanation. Appreciated. For an encore, can you give an example of where this is actually useful? It seems a pretty narrow utility. ChrisA From ian.g.kelly at gmail.com Mon Oct 10 13:55:37 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 10 Oct 2011 11:55:37 -0600 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Oct 10, 2011 at 11:33 AM, Chris Angelico wrote: > On Tue, Oct 11, 2011 at 4:29 AM, Nobody wrote: >> >> The Church numeral for N is a function of two arguments which applies its >> first argument N times to its second, i.e. (f^N)(x) = f(f(...(f(x))...)). >> > > Thanks - nice clear explanation. Appreciated. For an encore, can you > give an example of where this is actually useful? It seems a pretty > narrow utility. It's useful for writing mathematical theorems about computability with regard to the natural numbers using lambda calculus. From zaffino.p at gmail.com Mon Oct 10 14:25:03 2011 From: zaffino.p at gmail.com (Paolo Zaffino) Date: Mon, 10 Oct 2011 20:25:03 +0200 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: On Mac OS there is numpy 1.2.1, on Fedora 14 64bits numpy 1.4.1 and on Ubuntu 10.04 64bits numpy 1.3.0. On these platforms my function runs without problems. Just on Windows it doesn't works. 2011/10/9 Ya?ar Arabac? > I don't know about your problem, but did you compare numpy versions in > windows and other platforms? You may have newer/older version in Windows. > Otherwise, it looks like a platform spesific bug to me. > > 2011/10/9 Paolo Zaffino > >> Hello, >> I wrote a function that works on a numpy matrix and it works fine on >> Mac OS and GNU/Linux (I didn't test it on python 3) >> Now I have a problem with numpy: the same python file doesn't work on >> Windows (Windows xp, python 2.7 and numpy 2.6.1). >> I get this error: >> >> matrix=matrix.reshape(a, b, c) >> ValueError: total size of new array must be unchanged >> >> Why? Do anyone have an idea about this? >> Thank you very much. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > http://yasar.serveblog.net/ > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon Oct 10 15:26:35 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 Oct 2011 15:26:35 -0400 Subject: Python Migration Error: TypeError: exceptions must be old-style classes or derived from BaseException, not str In-Reply-To: <9684870.653.1318259595168.JavaMail.geo-discussion-forums@prib32> References: <57f0e31d-82e6-47a8-b5f2-22c917701a5a@p11g2000yqe.googlegroups.com> <02EA6D704E30CE499C5071776509A925F5BABD@039-SN1MPN1-003.039d.mgd.msft.net> <9684870.653.1318259595168.JavaMail.geo-discussion-forums@prib32> Message-ID: On 10/10/2011 11:13 AM, 88888 dihedral wrote: > I am thinking with the power of python evolving in different > versions, if a feature is not desired in the new version, then the > new version could also provide some script tools, of course in > python, to convert codes in old styles into new styles > automatically. That is what the 2to3 script does. It could use some updating. A 3to2 script using the same tools is available somewhere. Someone could write a 32to33 script for the few things removed in 3.3. -- Terry Jan Reedy From tjreedy at udel.edu Mon Oct 10 15:35:24 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 10 Oct 2011 15:35:24 -0400 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/10/2011 1:55 PM, Ian Kelly wrote: > On Mon, Oct 10, 2011 at 11:33 AM, Chris Angelico wrote: >> On Tue, Oct 11, 2011 at 4:29 AM, Nobody wrote: >>> >>> The Church numeral for N is a function of two arguments which applies its >>> first argument N times to its second, i.e. (f^N)(x) = f(f(...(f(x))...)). >>> >> >> Thanks - nice clear explanation. Appreciated. For an encore, can you >> give an example of where this is actually useful? It seems a pretty >> narrow utility. > > It's useful for writing mathematical theorems about computability with > regard to the natural numbers using lambda calculus. Whereas pure set theorists define counts as sets so they can work with counts within the context of pure set theory (in which everything is a set). Other mathematicians use an axiomatic definition which pretty much abstracts the common features of the set and function definitions. -- Terry Jan Reedy From galyle at gmail.com Mon Oct 10 17:57:49 2011 From: galyle at gmail.com (galyle) Date: Mon, 10 Oct 2011 14:57:49 -0700 (PDT) Subject: Question: Optional Regular Expression Grouping Message-ID: <8537a563-69d7-4bce-b192-d9427aad0a7c@i14g2000yqg.googlegroups.com> HI, I've looked through this forum, but I haven't been able to find a resolution to the problem I'm having (maybe I didn't look hard enough -- I have to believe this has come up before). The problem is this: I have a file which has 0, 2, or 3 groups that I'd like to record; however, in the case of 3 groups, the third group is correctly captured, but the first two groups get collapsed into just one group. I'm sure that I'm missing something in the way I've constructed my regular expression, but I can't figure out what's wrong. Does anyone have any suggestions? The demo below showcases the problem I'm having: import re valid_line = re.compile('^\[(\S+)\]\[(\S+)\](?:\s+|\[(\S+)\])=|\s+[\d\ [\']+.*$') line1 = "[field1][field2] = blarg" line2 = " 'a continuation of blarg'" line3 = "[field1][field2][field3] = blorg" m = valid_line.match(line1) print 'Expected: ' + m.group(1) + ', ' + m.group(2) m = valid_line.match(line2) print 'Expected: ' + str(m.group(1)) m = valid_line.match(line3) print 'Uh-oh: ' + m.group(1) + ', ' + m.group(2) From dotancohen at gmail.com Mon Oct 10 18:23:35 2011 From: dotancohen at gmail.com (Dotan Cohen) Date: Tue, 11 Oct 2011 00:23:35 +0200 Subject: Regex to match all trailing whitespace _and_ newlines. In-Reply-To: References: Message-ID: On Thu, Sep 1, 2011 at 13:30, Peter Otten <__peter__ at web.de> wrote: > Dotan Cohen wrote: > >> In the terrific Anki [1] application I am trying to remove trailing >> whitespace from form fields. This is my regex: >> [\n+\s+]$ > > My attempt: > >>>> sub = re.compile(r"\s*?(\n|$)").sub >>>> sub("", "alpha ? \nbeta ? \r\n\ngamma\n") > 'alphabetagamma' >>>> sub("", "alpha ? \nbeta ? \r\n\ngamma") > 'alphabetagamma' >>>> sub("", "alpha ? \nbeta ? \r\n\ngamma\t") > 'alphabetagamma' > Hi Peter, sorry for the _late_ reply. It turns out that Anki stores newlines internally as
, since its display model is based on HTML. Thanks, though! -- Dotan Cohen http://gibberish.co.il http://what-is-what.com From python at mrabarnett.plus.com Mon Oct 10 18:49:13 2011 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 10 Oct 2011 23:49:13 +0100 Subject: Question: Optional Regular Expression Grouping In-Reply-To: <8537a563-69d7-4bce-b192-d9427aad0a7c@i14g2000yqg.googlegroups.com> References: <8537a563-69d7-4bce-b192-d9427aad0a7c@i14g2000yqg.googlegroups.com> Message-ID: <4E937669.9060308@mrabarnett.plus.com> On 10/10/2011 22:57, galyle wrote: > HI, I've looked through this forum, but I haven't been able to find a > resolution to the problem I'm having (maybe I didn't look hard enough > -- I have to believe this has come up before). The problem is this: > I have a file which has 0, 2, or 3 groups that I'd like to record; > however, in the case of 3 groups, the third group is correctly > captured, but the first two groups get collapsed into just one group. > I'm sure that I'm missing something in the way I've constructed my > regular expression, but I can't figure out what's wrong. Does anyone > have any suggestions? > > The demo below showcases the problem I'm having: > > import re > > valid_line = re.compile('^\[(\S+)\]\[(\S+)\](?:\s+|\[(\S+)\])=|\s+[\d\ > [\']+.*$') > line1 = "[field1][field2] = blarg" > line2 = " 'a continuation of blarg'" > line3 = "[field1][field2][field3] = blorg" > > m = valid_line.match(line1) > print 'Expected: ' + m.group(1) + ', ' + m.group(2) > m = valid_line.match(line2) > print 'Expected: ' + str(m.group(1)) > m = valid_line.match(line3) > print 'Uh-oh: ' + m.group(1) + ', ' + m.group(2) Instead of "\S" I'd recommend using "[^\]]", or using a lazy repetition "\S+?". You'll also need to handle the space before the "=" in line3. valid_line = re.compile(r'^\[(\[^\]]+)\]\[(\[^\]]+)\](?:\s+|\[(\[^\]]+)\])\s*=|\s+[\d\[\']+.*$') From vlastimil.brom at gmail.com Mon Oct 10 18:59:46 2011 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Tue, 11 Oct 2011 00:59:46 +0200 Subject: Question: Optional Regular Expression Grouping In-Reply-To: <8537a563-69d7-4bce-b192-d9427aad0a7c@i14g2000yqg.googlegroups.com> References: <8537a563-69d7-4bce-b192-d9427aad0a7c@i14g2000yqg.googlegroups.com> Message-ID: 2011/10/10 galyle : > HI, I've looked through this forum, but I haven't been able to find a > resolution to the problem I'm having (maybe I didn't look hard enough > -- I have to believe this has come up before). ?The problem is this: > I have a file which has 0, 2, or 3 groups that I'd like to record; > however, in the case of 3 groups, the third group is correctly > captured, but the first two groups get collapsed into just one group. > I'm sure that I'm missing something in the way I've constructed my > regular expression, but I can't figure out what's wrong. ?Does anyone > have any suggestions? > > The demo below showcases the problem I'm having: > > import re > > valid_line = re.compile('^\[(\S+)\]\[(\S+)\](?:\s+|\[(\S+)\])=|\s+[\d\ > [\']+.*$') > line1 = "[field1][field2] = blarg" > line2 = " ? ?'a continuation of blarg'" > line3 = "[field1][field2][field3] = blorg" > > m = valid_line.match(line1) > print 'Expected: ' + m.group(1) + ', ' + m.group(2) > m = valid_line.match(line2) > print 'Expected: ' + str(m.group(1)) > m = valid_line.match(line3) > print 'Uh-oh: ' + m.group(1) + ', ' + m.group(2) > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, I believe, the space before = is causing problems (or the pattern missing it); you also need non greedy quantifiers +? to match as little as possible as opposed to the greedy default: valid_line = re.compile('^\[(\S+?)\]\[(\S+?)\](?:\s+|\[(\S+)\])\s*=|\s+[\d\[\']+.*$') or you can use word-patterns explicitely excluding the closing ], like: valid_line = re.compile('^\[([^\]]+)\]\[([^\]]+)\](?:\s+|\[([^\]]+)\])\s*=|\s+[\d\[\']+.*$') hth vbr From ian.g.kelly at gmail.com Mon Oct 10 19:03:02 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 10 Oct 2011 17:03:02 -0600 Subject: Question: Optional Regular Expression Grouping In-Reply-To: <4E937669.9060308@mrabarnett.plus.com> References: <8537a563-69d7-4bce-b192-d9427aad0a7c@i14g2000yqg.googlegroups.com> <4E937669.9060308@mrabarnett.plus.com> Message-ID: On Mon, Oct 10, 2011 at 4:49 PM, MRAB wrote: > Instead of "\S" I'd recommend using "[^\]]", or using a lazy repetition > "\S+?". Preferably the former. The core problem is that the regex matches ambiguously on the problem string. Lazy repetition doesn't remove that ambiguity; it merely attempts to make the module prefer the match that you prefer. Other notes to the OP: Always use raw strings (r'') when writing regex patterns, to make sure the backslashes are escape characters in the pattern rather than in the string literal. The '^foo|bar$' construct you're using is wonky. I think you're writing this to mean "match if the entire string is either 'foo' or 'bar'". But what that actually matches is "anything that either starts with 'foo' or ends with 'bar'". The correct way to do the former would be either '^foo$|^bar$' or '^(?:foo|bar)$'. From python at bdurham.com Mon Oct 10 19:08:37 2011 From: python at bdurham.com (python at bdurham.com) Date: Mon, 10 Oct 2011 19:08:37 -0400 Subject: Any tradeoffs or cautions in using virtualenv? Message-ID: <1318288117.32413.140258153280877@webmail.messagingengine.com> We're thinking about using virtualenv to isolate our development enivronments. Are there any tradeoffs or cautions we should consider before going this route? Are there other alternatives to virtualenv that we should consider? We are using Python 2.7 (32-bit) on Windows 7 Professional and Windows Server 2008. Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From galyle at gmail.com Mon Oct 10 19:24:13 2011 From: galyle at gmail.com (galyle) Date: Mon, 10 Oct 2011 16:24:13 -0700 (PDT) Subject: Question: Optional Regular Expression Grouping References: <8537a563-69d7-4bce-b192-d9427aad0a7c@i14g2000yqg.googlegroups.com> Message-ID: <9e526b44-c0ba-48c2-8e21-66f54856fe7c@b6g2000vbz.googlegroups.com> On Oct 10, 4:59?pm, Vlastimil Brom wrote: > 2011/10/10 galyle : > > > > > > > > > > > HI, I've looked through this forum, but I haven't been able to find a > > resolution to the problem I'm having (maybe I didn't look hard enough > > -- I have to believe this has come up before). ?The problem is this: > > I have a file which has 0, 2, or 3 groups that I'd like to record; > > however, in the case of 3 groups, the third group is correctly > > captured, but the first two groups get collapsed into just one group. > > I'm sure that I'm missing something in the way I've constructed my > > regular expression, but I can't figure out what's wrong. ?Does anyone > > have any suggestions? > > > The demo below showcases the problem I'm having: > > > import re > > > valid_line = re.compile('^\[(\S+)\]\[(\S+)\](?:\s+|\[(\S+)\])=|\s+[\d\ > > [\']+.*$') > > line1 = "[field1][field2] = blarg" > > line2 = " ? ?'a continuation of blarg'" > > line3 = "[field1][field2][field3] = blorg" > > > m = valid_line.match(line1) > > print 'Expected: ' + m.group(1) + ', ' + m.group(2) > > m = valid_line.match(line2) > > print 'Expected: ' + str(m.group(1)) > > m = valid_line.match(line3) > > print 'Uh-oh: ' + m.group(1) + ', ' + m.group(2) > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Hi, > I believe, the space before = is causing problems (or the pattern missing it); > you also need non greedy quantifiers +? to match as little as possible > as opposed to the greedy default: > > valid_line = re.compile('^\[(\S+?)\]\[(\S+?)\](?:\s+|\[(\S+)\])\s*=|\s+[\d\[\']+.*$') > > or you can use word-patterns explicitely excluding the closing ], like: > > valid_line = re.compile('^\[([^\]]+)\]\[([^\]]+)\](?:\s+|\[([^\]]+)\])\s*=|\s+[\d\[\']+. *$') > > hth > ?vbr Thanks, I had a feeling that greedy matching in my expression was causing problem. Your suggestion makes sense to me, and works quite well. From timr at probo.com Tue Oct 11 01:50:39 2011 From: timr at probo.com (Tim Roberts) Date: Mon, 10 Oct 2011 22:50:39 -0700 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: Westley Mart?nez wrote: >On Sat, Oct 08, 2011 at 12:34:42PM -0400, Roy Smith wrote: >> >> Here's my take on parenthesis: If you need to look up whether they're >> necessary or not, they are :-) > >So we don't need precedence charts in the bathroom? Yes, we do, because I'm always reading code from other people that didn't follow that rule. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steve+comp.lang.python at pearwood.info Tue Oct 11 02:44:31 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 11 Oct 2011 17:44:31 +1100 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e906108$0$27980$426a34cc@news.free.fr> Message-ID: <4e93e5cf$0$29983$c3e8da3$5496439d@news.astraweb.com> Tim Roberts wrote: > Westley Mart?nez wrote: >>On Sat, Oct 08, 2011 at 12:34:42PM -0400, Roy Smith wrote: >>> >>> Here's my take on parenthesis: If you need to look up whether they're >>> necessary or not, they are :-) >> >>So we don't need precedence charts in the bathroom? > > Yes, we do, because I'm always reading code from other people that didn't > follow that rule. No no no, they *do* follow the rule. They just have a better memory for operator precedence than you do :) -- Steven From dreyemi at gmail.com Tue Oct 11 04:16:57 2011 From: dreyemi at gmail.com (Kayode Odeyemi) Date: Tue, 11 Oct 2011 09:16:57 +0100 Subject: Implementing Python-OAuth2 In-Reply-To: <4E8DD438.20207@ncsa.illinois.edu> References: <4E8DD438.20207@ncsa.illinois.edu> Message-ID: On Thu, Oct 6, 2011 at 5:15 PM, Jeff Gaynor wrote: > On 10/06/2011 08:34 AM, Kayode Odeyemi wrote: > >> Hello friends, >> >> I'm working on a pretty large application that I will like to use oauth2 >> on as an authentication and authorization mechanism. >> >> I understand fairly the technology and I have written my own >> implementation before I stumbled on python-oauth2. >> >> I need advise on leveraging python-oauth2 api for creating consumer key, >> creating consumer secret, access token and token secret. >> >> This works well, but be advised that the original python oauth library > had some serious issues, so was redone as python-oauth2. What is confusing > is that it refers to OAuth version 1.0a, not the upcoming OAuth version 2.0, > so make sure you read the right spec before using it, since they are very > different indeed. > > There are *no* usable OAuth version 2..0 implementation in any language > (usually Java comes first) that I know of, so you will get to role your own, > which is hard. There are a few beta-level versions E.g. Twitter) but these > are special cased to the author's needs. The spec itself is not quite ready > either and since it has changed quite substantially in the last year, I > suspect that everyone is waiting to see it settle to a steady state. > > Jeff, I'm in the middle of a big confusion here and will need your help. I will like to know, can the request be signed just once and for all subsequent request made, I can use the stored nonce, signature method and token? My kind of setup is such that, I want the client app to be registered once, such that for every request to a resource, as long as the required parameters are available in the header (which would have been gotten at the initial request), access is granted. Is this a correct interpretation of Oauth? Thanks -- Odeyemi 'Kayode O. http://www.sinati.com. t: @charyorde -------------- next part -------------- An HTML attachment was scrubbed... URL: From ovidiudeac at gmail.com Tue Oct 11 04:26:03 2011 From: ovidiudeac at gmail.com (Ovidiu Deac) Date: Tue, 11 Oct 2011 11:26:03 +0300 Subject: regexp compilation error In-Reply-To: References: Message-ID: Thanks for the answer. I will give a try to pypy regex. On Fri, Sep 30, 2011 at 4:56 PM, Vlastimil Brom wrote: > 2011/9/30 Ovidiu Deac : >> This is only part of a regex taken from an old perl application which >> we are trying to understand/port to our new Python implementation. >> >> The original regex was considerably more complex and it didn't compile >> in python so I removed all the parts I could in order to isolate the >> problem such that I can ask help here. >> >> So the problem is that this regex doesn't compile. On the other hand >> I'm not really sure it should. It's an anchor on which you apply *. >> I'm not sure if this is legal. >> >> On the other hand if I remove one of the * it compiles. >> >>>>> re.compile(r"""^(?: [^y]* )*""", re.X) >> Traceback (most recent call last): >> ?File "", line 1, in >> ?File "/usr/lib/python2.6/re.py", line 190, in compile >> ? ?return _compile(pattern, flags) >> ?File "/usr/lib/python2.6/re.py", line 245, in _compile >> ? ?raise error, v # invalid expression >> sre_constants.error: nothing to repeat >>>>> re.compile(r"""^(?: [^y] )*""", re.X) >> <_sre.SRE_Pattern object at 0x7f4069cc36b0> >>>>> re.compile(r"""^(?: [^y]* )""", re.X) >> <_sre.SRE_Pattern object at 0x7f4069cc3730> >> >> Is this a bug in python regex engine? Or maybe some incompatibility with Perl? >> >> On Fri, Sep 30, 2011 at 12:29 PM, Chris Angelico wrote: >>> On Fri, Sep 30, 2011 at 7:26 PM, Ovidiu Deac wrote: >>>> $ python --version >>>> Python 2.6.6 >>> >>> Ah, I think I was misinterpreting the traceback. You do actually have >>> a useful message there; it's the same error that my Py3.2 produced: >>> >>> sre_constants.error: nothing to repeat >>> >>> I'm not sure what your regex is trying to do, but the problem seems to >>> be connected with the * at the end of the pattern. >>> >>> ChrisA >>> -- > > I believe, this is a limitation of the builtin re engine concerning > nested infinite quantifiers - (...*)* ?- in your pattern. > You can try a more powerful recent regex implementation, which appears > to handle it: > > http://pypi.python.org/pypi/regex > > using the VERBOSE flag - re.X all (unescaped) whitespace outside of > character classes is ignored, > http://docs.python.org/library/re.html#re.VERBOSE > the pattern should be equivalent to: > r"^(?:[^y]*)*" > ie. you are not actually gaining anything with double quantifier, as > there isn't anything "real" in the pattern outside [^y]* > > It appears, that you have oversimplified the pattern (if it had worked > in the original app), > however, you may simply try with > import regex as re > and see, if it helps. > > Cf: >>>> >>>> regex.findall(r"""^(?: [^y]* )*""", "a bcd e", re.X) > ['a bcd e'] >>>> re.findall(r"""^(?: [^y]* )*""", "a bcd e", re.X) > Traceback (most recent call last): > ?File "", line 1, in > ?File "re.pyc", line 177, in findall > ?File "re.pyc", line 244, in _compile > error: nothing to repeat >>>> >>>> re.findall(r"^(?:[^y]*)*", "a bcd e") > Traceback (most recent call last): > ?File "", line 1, in > ?File "re.pyc", line 177, in findall > ?File "re.pyc", line 244, in _compile > error: nothing to repeat >>>> regex.findall(r"^(?:[^y]*)*", "a bcd e") > ['a bcd e'] >>>> regex.findall(r"^[^y]*", "a bcd e") > ['a bcd e'] >>>> > > > hth, > ?vbr > -- > http://mail.python.org/mailman/listinfo/python-list > From alec.taylor6 at gmail.com Tue Oct 11 04:27:42 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 11 Oct 2011 19:27:42 +1100 Subject: Implementing Python-OAuth2 In-Reply-To: References: <4E8DD438.20207@ncsa.illinois.edu> Message-ID: Maybe use CAS instead of OAuth? https://wiki.jasig.org/display/CASC/Pycas On Tue, Oct 11, 2011 at 7:16 PM, Kayode Odeyemi wrote: > On Thu, Oct 6, 2011 at 5:15 PM, Jeff Gaynor > wrote: >> >> On 10/06/2011 08:34 AM, Kayode Odeyemi wrote: >>> >>> Hello friends, >>> >>> I'm working on a pretty large application that I will like to use oauth2 >>> on as an authentication and authorization mechanism. >>> >>> I understand fairly the technology and I have written my own >>> implementation before I stumbled on python-oauth2. >>> >>> I need advise on leveraging python-oauth2 api for creating consumer key, >>> creating consumer secret, access token and token secret. >>> >> This works well, but be advised that the original python oauth library had >> some serious issues, so was redone as python-oauth2. What is confusing is >> that it refers to OAuth version 1.0a, not the upcoming OAuth version 2.0, so >> make sure you read the right spec before using it, since they are very >> different indeed. >> >> There are *no* usable OAuth version 2..0 implementation in any language >> (usually Java comes first) that I know of, so you will get to role your own, >> which is hard. There are a few beta-level versions E.g. Twitter) but these >> are special cased to the author's needs. The spec itself is not quite ready >> either and since it has changed quite substantially in the last year, I >> suspect that everyone is waiting to see it settle to a steady state. >> > Jeff, I'm in the middle of a big confusion here and will need your help. > > I will like to know, can the request be signed just once and for all > subsequent request made, I can use the stored nonce, signature method and > token? My kind of setup is such that, I want the client app to be registered > once, such that for every request to a resource, as long as the required > parameters are available in the header (which would have been gotten at the > initial request), access is granted. > > Is this a correct interpretation of Oauth? > > Thanks > > > > -- > Odeyemi 'Kayode O. > http://www.sinati.com. t: @charyorde > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From nobody at nowhere.com Tue Oct 11 04:28:51 2011 From: nobody at nowhere.com (Nobody) Date: Tue, 11 Oct 2011 09:28:51 +0100 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, 11 Oct 2011 04:33:43 +1100, Chris Angelico wrote: >> The Church numeral for N is a function of two arguments which applies its >> first argument N times to its second, i.e. (f^N)(x) = f(f(...(f(x))...)). >> > > Thanks - nice clear explanation. Appreciated. For an encore, can you > give an example of where this is actually useful? It seems a pretty > narrow utility. It's useful insofar as it allows you to define "numbers" given nothing other than abstraction and application, which are the only operations available in the lambda calculus. The particular formulation makes it easy to define addition, which is just composition: (f^(M+N))(x) = (f^M)((f^N)(x)) I.e.: def church_add(a, b): return lambda f, x: a(f, b(f, x)) From alex.vanderspek at tno.nl Tue Oct 11 04:31:29 2011 From: alex.vanderspek at tno.nl (Alex van der Spek) Date: Tue, 11 Oct 2011 10:31:29 +0200 Subject: xml tree writing with ElementTree; prepends elements with ns0 Message-ID: <4e93fee1$0$2512$e4fe514c@news2.news.xs4all.nl> When reading a tree and writing it back to a new file all the elements are prepended with the string ns0: Why is it prepended and how can I suppress this? Thanks, Alex van der Spek From lucaberto at libero.it Tue Oct 11 04:39:39 2011 From: lucaberto at libero.it (luca72) Date: Tue, 11 Oct 2011 01:39:39 -0700 (PDT) Subject: installeventfilter Message-ID: helo i have this form how i can install the event filter: Class Form(QWidget, Ui_Form): """ Class documentation goes here. """ def __init__(self, parent = None): """ Constructor """ QWidget.__init__(self, parent) self.setupUi(self) Thanks From rosuav at gmail.com Tue Oct 11 04:46:58 2011 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 11 Oct 2011 19:46:58 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, Oct 11, 2011 at 7:28 PM, Nobody wrote: > It's useful insofar as it allows you to define "numbers" given nothing > other than abstraction and application, which are the only operations > available in the lambda calculus. > Heh. This is why mathematicians ALWAYS make use of previously-defined objects! In pure lambda calculus, constants are even more painful than in SPL[1]... ChrisA [1] http://shakespearelang.sourceforge.net/report/shakespeare/shakespeare.html#SECTION00045000000000000000 From alain at dpt-info.u-strasbg.fr Tue Oct 11 05:40:48 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Tue, 11 Oct 2011 11:40:48 +0200 Subject: xml tree writing with ElementTree; prepends elements with ns0 References: <4e93fee1$0$2512$e4fe514c@news2.news.xs4all.nl> Message-ID: <87ty7f7tnj.fsf@dpt-info.u-strasbg.fr> "Alex van der Spek" writes: > When reading a tree and writing it back to a new file all the elements are > prepended with the string ns0: That's a namespace prefix. > > Why is it prepended and how can I suppress this? See http://effbot.org/zone/element-namespaces.htm I'm not sure you can define the default namespace (i.e., avoid prefixes on element names). However, any conformant XML processor should have no problem with the output of ElementTree. If you're actually producing HTML, then you should say so when calling tostring(), by giving the appropriate value to the method argument. -- Alain. From alain at dpt-info.u-strasbg.fr Tue Oct 11 05:46:11 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Tue, 11 Oct 2011 11:46:11 +0200 Subject: xml tree writing with ElementTree; prepends elements with ns0 References: <4e93fee1$0$2512$e4fe514c@news2.news.xs4all.nl> <87ty7f7tnj.fsf@dpt-info.u-strasbg.fr> Message-ID: <87pqi37tek.fsf@dpt-info.u-strasbg.fr> Alain Ketterlin writes: > "Alex van der Spek" writes: > >> When reading a tree and writing it back to a new file all the elements are >> prepended with the string ns0: > > That's a namespace prefix. > >> >> Why is it prepended and how can I suppress this? > > See http://effbot.org/zone/element-namespaces.htm > > I'm not sure you can define the default namespace (i.e., avoid prefixes > on element names). However, any conformant XML processor should have no > problem with the output of ElementTree. Sorry, it looks like you can with ET 1.3: see http://effbot.org/zone/elementtree-13-intro.htm > If you're actually producing HTML, then you should say so when calling > tostring(), by giving the appropriate value to the method argument. > > -- Alain. From vincent.vandevyvre at swing.be Tue Oct 11 05:57:28 2011 From: vincent.vandevyvre at swing.be (Vincent Vande Vyvre) Date: Tue, 11 Oct 2011 11:57:28 +0200 Subject: installeventfilter In-Reply-To: References: Message-ID: <4E941308.6070903@swing.be> An HTML attachment was scrubbed... URL: From phil at riverbankcomputing.com Tue Oct 11 06:34:02 2011 From: phil at riverbankcomputing.com (Phil Thompson) Date: Tue, 11 Oct 2011 11:34:02 +0100 Subject: installeventfilter In-Reply-To: <4E941308.6070903@swing.be> References: <4E941308.6070903@swing.be> Message-ID: <7975e5bd1532e5dcfa0b76320eae142c@localhost> On Tue, 11 Oct 2011 11:57:28 +0200, Vincent Vande Vyvre wrote: > Le 11/10/11 10:39, luca72 a ?crit?: > helo i have this form how i can install the event filter: > Class Form(QWidget, Ui_Form): > """ > Class documentation goes here. > """ > def __init__(self, parent = None): > """ > Constructor > """ > QWidget.__init__(self, parent) > self.setupUi(self) > > Thanks > > MainWindow.eventFilter = self.event_filter > > ... > > def event_filter(self, object, event): > ??????? # example: window is resized > ??????? if event.type() == 14: > ??????????? resize() > ??????????? return True > > In your case, 'MainWindow' seems to be 'parent' Monkey patching is not a good idea. class EventFilter(QObject): def eventFilter(self, object, event): # example: window is resized if event.type() == QEvent.Resize: object.resize() return True event_filter = EventFilter() form = Form() form.installEventFilter(event_filter) Phil From ydrocourt at gmail.com Tue Oct 11 06:44:54 2011 From: ydrocourt at gmail.com (yo) Date: Tue, 11 Oct 2011 03:44:54 -0700 (PDT) Subject: python script to add a field and edit it for several shapefiles in arcgis Message-ID: dear All i m trying to write a python script supposed to create a new field in a shapefile, and then fill it with a value extracted from the name of the file... I have to do that for several hundreds of files...I am almost there it is kind of working for one file but once i put a loop in the story, then everything crashes... could anybody here offer some help ??? regards Yoann From selahattin_ay at msn.com Tue Oct 11 07:32:40 2011 From: selahattin_ay at msn.com (selahattin ay) Date: Tue, 11 Oct 2011 11:32:40 +0000 Subject: creating a code with two list Message-ID: hi all, I want to create a code with two lists like this code = ['234', '333' .............. ] liste = []a = 0 while a<999 :a+=1liste.append(a) now I want to create this sample : the first element of codes list is 234 than the all elements of liste are 1,2,3 ...... 9999 now I want to this 2341, 2342, 2343, .................... 234999 when this finishes after the second element of code begins 3331,3332, 3333, ....................333999 what can I do for this? thx ... -------------- next part -------------- An HTML attachment was scrubbed... URL: From alec.taylor6 at gmail.com Tue Oct 11 08:08:48 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 11 Oct 2011 23:08:48 +1100 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] Message-ID: Good afternoon, I'm looking for a Python library for generating SQL queries [selects, alters, inserts and commits]. I can write them by hand, but thought it would be more useful writing them in Python (i.e. client-side referential integrity checking before insert commit + test data generation) I'm running Oracle 10g and Oracle 11gR2. Do you know of a Python library which can facilitate this? Thanks for all suggestions, Alec Taylor From alec.taylor6 at gmail.com Tue Oct 11 08:11:10 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 11 Oct 2011 23:11:10 +1100 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: As you see, this way of writing constants gives you much more poetic freedom than in other programming languages. On Tue, Oct 11, 2011 at 7:46 PM, Chris Angelico wrote: > On Tue, Oct 11, 2011 at 7:28 PM, Nobody wrote: >> It's useful insofar as it allows you to define "numbers" given nothing >> other than abstraction and application, which are the only operations >> available in the lambda calculus. >> > > Heh. This is why mathematicians ALWAYS make use of previously-defined > objects! In pure lambda calculus, constants are even more painful than > in SPL[1]... > > ChrisA > [1] http://shakespearelang.sourceforge.net/report/shakespeare/shakespeare.html#SECTION00045000000000000000 > -- > http://mail.python.org/mailman/listinfo/python-list > From zaffino.p at gmail.com Tue Oct 11 09:20:36 2011 From: zaffino.p at gmail.com (Paolo Zaffino) Date: Tue, 11 Oct 2011 15:20:36 +0200 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: Nobody can help me? 2011/10/10 Paolo Zaffino > On Mac OS there is numpy 1.2.1, on Fedora 14 64bits numpy 1.4.1 and on > Ubuntu 10.04 64bits numpy 1.3.0. > On these platforms my function runs without problems. > Just on Windows it doesn't works. > > > > 2011/10/9 Ya?ar Arabac? > >> I don't know about your problem, but did you compare numpy versions in >> windows and other platforms? You may have newer/older version in Windows. >> Otherwise, it looks like a platform spesific bug to me. >> >> 2011/10/9 Paolo Zaffino >> >>> Hello, >>> I wrote a function that works on a numpy matrix and it works fine on >>> Mac OS and GNU/Linux (I didn't test it on python 3) >>> Now I have a problem with numpy: the same python file doesn't work on >>> Windows (Windows xp, python 2.7 and numpy 2.6.1). >>> I get this error: >>> >>> matrix=matrix.reshape(a, b, c) >>> ValueError: total size of new array must be unchanged >>> >>> Why? Do anyone have an idea about this? >>> Thank you very much. >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> >> >> -- >> http://yasar.serveblog.net/ >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From drobinow at gmail.com Tue Oct 11 09:34:54 2011 From: drobinow at gmail.com (David Robinow) Date: Tue, 11 Oct 2011 09:34:54 -0400 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: 2011/10/11 Paolo Zaffino : > Nobody can help me? Nope, not unless you post some code. Your problem description is too vague. From jacktradespublic at gmail.com Tue Oct 11 09:49:25 2011 From: jacktradespublic at gmail.com (Nick Zarr) Date: Tue, 11 Oct 2011 08:49:25 -0500 Subject: creating a code with two list In-Reply-To: References: Message-ID: > > liste = [] > > a = 0 > > > > while a<999 : > > a+=1 > > liste.append(a) > > I'm not sure I understand what you're trying to do here, but I don't have much time to answer right now. I just want to say there's an easier way to build a list of consecutive integers: range(1, n+1) >>> range(1, 1000) [1, 2, ..., 999] -- Nick Zarczynski Blog 4 -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Oct 11 09:56:22 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 11 Oct 2011 15:56:22 +0200 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: Paolo Zaffino wrote: > Nobody can help me? Add the lines print "a=%r, b=%r, c=%r" % (a, b, c) print "type=%s, shape=%r, size=%r" % (type(matrix), matrix.shape, matrix.size) before this one >>>> matrix = matrix.reshape(a, b, c) and tell us what it prints both on a system where it works and where it doesn't. If a, b, and c are all integers and a * b * c == matrix.size try passing a tuple: matrix = matrix.reshape((a, b, c)) # note the double parens From rosuav at gmail.com Tue Oct 11 09:59:41 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Oct 2011 00:59:41 +1100 Subject: creating a code with two list In-Reply-To: References: Message-ID: On Wed, Oct 12, 2011 at 12:49 AM, Nick Zarr wrote: >>>> range(1, 1000) > [1, 2, ..., 999] > Or for Python 3 compat: >>> list(range(1,1000)) ChrisA From yasar11732 at gmail.com Tue Oct 11 10:11:04 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Tue, 11 Oct 2011 17:11:04 +0300 Subject: Fwd: creating a code with two list In-Reply-To: References: Message-ID: your_final_list = [[str(i) + str(k) for i in range(len(liste))] for k in range(len(code))] -- http://yasar.serveblog.net/ -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From yasar11732 at gmail.com Tue Oct 11 10:18:36 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Tue, 11 Oct 2011 17:18:36 +0300 Subject: creating a code with two list In-Reply-To: References: Message-ID: And also, I should recommend you to use Turkish speaking mail groups in here: python-programcilar at googlegroups.com since your English is a little hard to comprehend. There are less people there, but, still would be more helpful for you. 11 Ekim 2011 17:11 tarihinde Ya?ar Arabac? yazd?: > > > > your_final_list = [[str(i) + str(k) for i in range(len(liste))] for k in > range(len(code))] > > > -- > http://yasar.serveblog.net/ > > > > > -- > http://yasar.serveblog.net/ > > -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From yasar11732 at gmail.com Tue Oct 11 10:34:09 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Tue, 11 Oct 2011 17:34:09 +0300 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] In-Reply-To: References: Message-ID: Are you looking for something like this? http://www.sqlalchemy.org/ 2011/10/11 Alec Taylor > Good afternoon, > > I'm looking for a Python library for generating SQL queries [selects, > alters, inserts and commits]. > > I can write them by hand, but thought it would be more useful writing > them in Python (i.e. client-side referential integrity checking before > insert commit + test data generation) > > I'm running Oracle 10g and Oracle 11gR2. Do you know of a Python > library which can facilitate this? > > Thanks for all suggestions, > > Alec Taylor > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Tue Oct 11 11:12:22 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 11 Oct 2011 10:12:22 -0500 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] In-Reply-To: References: Message-ID: <4E945CD6.3040502@tim.thechases.com> On 10/11/11 07:08, Alec Taylor wrote: > I'm looking for a Python library for generating SQL queries > [selects, alters, inserts and commits]. The popular ones are SQLObject and SQLAlchemy, both just a web-search away. Additionally, if you're working with Django, it has its own built-in ORM. -tkc From alec.taylor6 at gmail.com Tue Oct 11 11:14:15 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Wed, 12 Oct 2011 02:14:15 +1100 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] In-Reply-To: <4E945CD6.3040502@tim.thechases.com> References: <4E945CD6.3040502@tim.thechases.com> Message-ID: They look good, but I'm looking for something which can "compile" down to normal SQL code. So that I can just plug that .sql file into any environment [i.e. non-python env] On Wed, Oct 12, 2011 at 2:12 AM, Tim Chase wrote: > On 10/11/11 07:08, Alec Taylor wrote: >> >> I'm looking for a Python library for generating SQL queries >> [selects, alters, inserts and commits]. > > The popular ones are SQLObject and SQLAlchemy, both just a web-search away. > > Additionally, if you're working with Django, it has its own built-in ORM. > > -tkc > > > From awilliam at whitemice.org Tue Oct 11 11:33:46 2011 From: awilliam at whitemice.org (Adam Tauno Williams) Date: Tue, 11 Oct 2011 11:33:46 -0400 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] In-Reply-To: References: <4E945CD6.3040502@tim.thechases.com> Message-ID: <20111011113346.Horde.QM5RR5eICrNOlGHaedHkKTA@aleph.wmmi.net> Quoting Alec Taylor > They look good, but I'm looking for something which can "compile" down > to normal SQL code. > So that I can just plug that .sql file into any environment [i.e. > non-python env] SQLalchemy will happily give you statements and argument lists if that is what you want. query = db.query(Task).filter(Task.objectid==10100) print str(query) From apirker at gmail.com Tue Oct 11 12:09:29 2011 From: apirker at gmail.com (Anton Pirker) Date: Tue, 11 Oct 2011 09:09:29 -0700 (PDT) Subject: Freelance Django developer needed Message-ID: <29103438.2615.1318349369262.JavaMail.geo-discussion-forums@yqnk41> Hi! (First to everyone not into Django: sorry for the shameless job advertisement!) We are searching for a Freelance Django developer to help us out! We are: - creativesociety.com - based in Vienna, Austria - small team of 4 - pretty cool What you should have: - passion for writing beautiful code - getting things done attitude - knowledge of django, postgres, json, rest, - some knowledge of html/css - good english (talking and reading/writing documentation) What you will have to do: - develop a RESTful api that talks to a partner site - talk to the partners (humands, based in london and/or paris) to specify the api - import a LOT of data from the partner site - implement an upload and post the video files to the partner site - implement a single sign on solution so if the users are logged in on one site, are automatically logged in on the other site. - implement some html templates in django We think the project will take about 8-12 weeks, starting November 1th. If you are interested, send your CV, a "why i am the best for the job"-letter and your rates to: development [at] creativesociety [dot] com Thanks, Anton From wm at localhost.localdomain Tue Oct 11 13:02:15 2011 From: wm at localhost.localdomain (Waldek M.) Date: Tue, 11 Oct 2011 19:02:15 +0200 Subject: Freelance Django developer needed References: <29103438.2615.1318349369262.JavaMail.geo-discussion-forums@yqnk41> Message-ID: <1s95cqbh76szn.dlg@localhost.localdomain> > (First to everyone not into Django: sorry for the shameless job advertisement!) > > We are searching for a Freelance Django developer to help us out! Well, if you're sorry then why do you go on? There's a much better place to post the job offer: http://www.python.org/community/jobs/ There, you'd probably even earn credit for your posting :-) Best regards, Waldek From apirker at gmail.com Tue Oct 11 13:24:58 2011 From: apirker at gmail.com (Anton Pirker) Date: Tue, 11 Oct 2011 10:24:58 -0700 (PDT) Subject: Freelance Django developer needed In-Reply-To: <1s95cqbh76szn.dlg@localhost.localdomain> References: <29103438.2615.1318349369262.JavaMail.geo-discussion-forums@yqnk41> <1s95cqbh76szn.dlg@localhost.localdomain> Message-ID: <760129.192.1318353898238.JavaMail.geo-discussion-forums@yqnv12> Hi Waldek! On Tuesday, 11 October 2011 19:02:15 UTC+2, Waldek M. wrote: > > (First to everyone not into Django: sorry for the shameless job advertisement!) > > > Well, if you're sorry then why do you go on? > > There's a much better place to post the job offer: > http://www.python.org/community/jobs/ > > There, you'd probably even earn credit for your posting :-) Ah thanks for the pointer! Posted the job ad on the the website you mentioned. I still posted it here, so i have the most people to read my job ad. Because i want to find the best one, and i think they are not browsing job boards.. ;) greetings from vienna, Anton > > Best regards, > Waldek From warren at washresearch.com Tue Oct 11 14:16:50 2011 From: warren at washresearch.com (WR) Date: Tue, 11 Oct 2011 18:16:50 -0000 Subject: Seven Python Developers Needed $125K Message-ID: Top Global Consulting Firm in NYC needs 7 Python Developers Up to $125K depending on experience Solid knowledge of fundamental Python concepts. At least three years Python experience required. For more info email Joseph at Washresearch.com Joseph Ryan Washington Research Associates Inc (202) 408-7025 From chris at simplistix.co.uk Tue Oct 11 15:00:42 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 11 Oct 2011 20:00:42 +0100 Subject: TestFixtures 2.3.0 Released! Message-ID: <4E94925A.5020507@simplistix.co.uk> Hi All, Another TestFixtures release. This release adds warning backstops when you forget to clean up LogCapture, Replacer, TempDirectory and TestComponents instances. A replacer which didn't get its .restore() method called when it should have been caused me a lot of pain recently, so this release is here to stop others having to suffer the same ;-) The package is on PyPI and a full list of all the links to docs, issue trackers and the like can be found here: http://www.simplistix.co.uk/software/python/testfixtures Any questions, please do ask here or on the Simplistix open source mailing lists... cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From andrea.crotti.0 at gmail.com Tue Oct 11 16:15:15 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Tue, 11 Oct 2011 21:15:15 +0100 Subject: profiling big project Message-ID: <87lisrxp2k.fsf@gmail.com> Hi everyone, I am in the situation that I'll have to profile huge python programs, huge because they use many external libraries like numpy / pyqt / ETS etc etc... The applications are very slow and we wanted to understand what is actually going on. I like to use normally pycallgraph, but in this case is quite useless, because the graph would be huge, so I had the following thought, if I'm able to serialize the generate a text representation of the graph I should be then able to actually understand something. So I forked pycallgraph (https://github.com/AndreaCrotti/pycallgraph) and my idea is to create an org-mode or RST file instead of a graph, adding also links to the source code maybe. For example (in org mode) * function1 50% ** function2 25% ** function3 22% ... and so on, in RST maybe I could even use autodoc to get also the doc from the functions. Any idea / suggestions / comment? Maybe there is something like this already? From ben+python at benfinney.id.au Tue Oct 11 17:20:09 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Oct 2011 08:20:09 +1100 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] References: Message-ID: <87botnxm2e.fsf@benfinney.id.au> Alec Taylor writes: > I'm looking for a Python library for generating SQL queries [selects, > alters, inserts and commits]. SQLAlchemy is the leader in this field. It allows your code to interact with the database at different levels: you can write raw SQL, you can construct queries using a query builder, you can use an entirely-optional ORM; and they're all compatible. > I'm running Oracle 10g and Oracle 11gR2. Do you know of a Python > library which can facilitate this? Yes, . -- \ ?[W]e are still the first generation of users, and for all that | `\ we may have invented the net, we still don't really get it.? | _o__) ?Douglas Adams | Ben Finney From ben+python at benfinney.id.au Tue Oct 11 17:23:12 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Oct 2011 08:23:12 +1100 Subject: Freelance Django developer needed References: <29103438.2615.1318349369262.JavaMail.geo-discussion-forums@yqnk41> <1s95cqbh76szn.dlg@localhost.localdomain> <760129.192.1318353898238.JavaMail.geo-discussion-forums@yqnv12> Message-ID: <877h4bxlxb.fsf@benfinney.id.au> Anton Pirker writes: > I still posted it here, so i have the most people to read my job ad. That's a justification used by spammers, and it's wrong for the same reasons (this forum is inappropriate for the job posting regardless of your desires). Please don't become a spammer. -- \ ?Perchance you who pronounce my sentence are in greater fear | `\ than I who receive it.? ?Giordano Bruno, burned at the stake by | _o__) the Catholic church for the heresy of heliocentrism, 1600-02-16 | Ben Finney From kwebb at teradactyl.com Tue Oct 11 19:04:45 2011 From: kwebb at teradactyl.com (Kristen J. Webb) Date: Tue, 11 Oct 2011 17:04:45 -0600 Subject: shipping python Message-ID: <4E94CB8D.5010806@teradactyl.com> I am new to python coming from the C/shell side. We have been experimenting with some code samples and now I'm looking at some command line argument processing. I find getopt older optparse new in 2.3 argparse new in 2.7 I search around on some of my client systems and find lots of people in the 2.4 - 2.6 range. After some more digging I see that I can easy_install argparse on my development system. My question is will I be able to ship this to a customer? Can I create .pyc files so that the customer does not have to install the argparse module? If not, and I want to go back into the 2.3+ range, should I just use optparse? I guess what I am asking here is are there any guidelines/recommendations for shipping python programs to customers? Thanks in advance, Kris -- Mr. Kristen J. Webb Teradactyl LLC. PHONE: 1-505-242-1091 EMAIL: kwebb at teradactyl.com VISIT: http://www.teradactyl.com Home of the True incremental Backup System From skippy.hammond at gmail.com Tue Oct 11 21:06:59 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Wed, 12 Oct 2011 12:06:59 +1100 Subject: Implementing Python-OAuth2 In-Reply-To: References: <4E8DD438.20207@ncsa.illinois.edu> Message-ID: <4E94E833.6000705@gmail.com> On 11/10/2011 7:16 PM, Kayode Odeyemi wrote: > On Thu, Oct 6, 2011 at 5:15 PM, Jeff Gaynor > wrote: > > On 10/06/2011 08:34 AM, Kayode Odeyemi wrote: > > Hello friends, > > I'm working on a pretty large application that I will like to > use oauth2 on as an authentication and authorization mechanism. > > I understand fairly the technology and I have written my own > implementation before I stumbled on python-oauth2. > > I need advise on leveraging python-oauth2 api for creating > consumer key, creating consumer secret, access token and token > secret. > > This works well, but be advised that the original python oauth > library had some serious issues, so was redone as python-oauth2. > What is confusing is that it refers to OAuth version 1.0a, not the > upcoming OAuth version 2.0, so make sure you read the right spec > before using it, since they are very different indeed. > > There are *no* usable OAuth version 2..0 implementation in any > language (usually Java comes first) that I know of, so you will get > to role your own, which is hard. There are a few beta-level versions > E.g. Twitter) but these are special cased to the author's needs. The > spec itself is not quite ready either and since it has changed quite > substantially in the last year, I suspect that everyone is waiting > to see it settle to a steady state. > > Jeff, I'm in the middle of a big confusion here and will need your help. > > I will like to know, can the request be signed just once and for all > subsequent request made, I can use the stored nonce, signature method > and token? My kind of setup is such that, I want the client app to be > registered once, such that for every request to a resource, as long as > the required parameters are available in the header (which would have > been gotten at the initial request), access is granted. > > Is this a correct interpretation of Oauth? I believe every request must be resigned with a new nonce and new timestamp using the tokens it initially fetched during the auth step so "replay" attacks can be prevented. It might be true that some server implementations don't check the timestamp or nonce, so it *might* work for some servers if the exact same request parameters are used, but such servers are simply insecure and broken. Mark From anikom15 at gmail.com Tue Oct 11 21:08:06 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Tue, 11 Oct 2011 18:08:06 -0700 Subject: shipping python In-Reply-To: <4E94CB8D.5010806@teradactyl.com> References: <4E94CB8D.5010806@teradactyl.com> Message-ID: <20111012010806.GA27288@Smoke> On Tue, Oct 11, 2011 at 05:04:45PM -0600, Kristen J. Webb wrote: > I am new to python coming from the C/shell side. > We have been experimenting with some code > samples and now I'm looking at some command line > argument processing. I find > > getopt older > optparse new in 2.3 > argparse new in 2.7 > > I search around on some of my client systems and > find lots of people in the 2.4 - 2.6 range. > > After some more digging I see that I can > easy_install argparse on my development system. > > My question is will I be able to ship this > to a customer? Can I create .pyc files so > that the customer does not have to install the argparse > module? > > If not, and I want to go back into the 2.3+ range, > should I just use optparse? > > I guess what I am asking here is are there any > guidelines/recommendations for shipping python > programs to customers? > > Thanks in advance, > Kris If you intend for the software to run on Python <2.7 the user must have argparse installed. Python included argparse in the standard library in 2.7. Understand that getopt is analog to the getopt found in the POSIX library; optparse and argparse are designed to handle more "complex" arguments. Basically it depends on your needs. If you're concerned about portability it's very easy to deal with arguments with getopt or just sys.argv on your own. From debatem1 at gmail.com Tue Oct 11 21:29:29 2011 From: debatem1 at gmail.com (geremy condra) Date: Tue, 11 Oct 2011 18:29:29 -0700 Subject: [OT] Off-Topic Posts and Threads on the Python Mailing List In-Reply-To: References: Message-ID: On Fri, Sep 30, 2011 at 8:25 PM, Navkirat Singh wrote: > Lol you all sound like google's angry birds with their feathers ruffled by a > comment. You guys should open up another mailing list to extinguish your > virtually bruised egos. . . . Google does not produce Angry Birds. There is another mailinglist for OT conversation. Extinguishing does not help either bruises or egos. You smell like a troll. You top-posted. Your post was nonsensical, error-filled, ill-formatted, grouchy, pointless, and dumb. You've earned my contempt, and may God have mercy on your troll. Geremy Condra From steve+comp.lang.python at pearwood.info Tue Oct 11 21:31:46 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 12 Oct 2011 01:31:46 GMT Subject: shipping python References: Message-ID: <4e94ee02$0$29978$c3e8da3$5496439d@news.astraweb.com> On Tue, 11 Oct 2011 17:04:45 -0600, Kristen J. Webb wrote: > After some more digging I see that I can easy_install argparse on my > development system. > > My question is will I be able to ship this to a customer? Can I create > .pyc files so that the customer does not have to install the argparse > module? Yes, and yes. The licence of argparse is a very liberal licence, so you can just include it in your application. There's no need for the user to install it separately. You could include just the .pyc file if you insist, but I personally don't like or recommend .pyc only installations. > If not, and I want to go back into the 2.3+ range, should I just use > optparse? That depends on how complex your command line arguments are. -- Steven From wuwei23 at gmail.com Tue Oct 11 23:13:56 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 11 Oct 2011 20:13:56 -0700 (PDT) Subject: Python library for generating SQL queries [selects, alters, inserts and commits] References: <4E945CD6.3040502@tim.thechases.com> Message-ID: On Oct 12, 1:14?am, Alec Taylor wrote: > They look good, but I'm looking for something which can "compile" down > to normal SQL code. Then you're not looking hard enough. SQLAlchemy does this. From alec.taylor6 at gmail.com Wed Oct 12 00:05:03 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Wed, 12 Oct 2011 15:05:03 +1100 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] In-Reply-To: References: <4E945CD6.3040502@tim.thechases.com> Message-ID: Great, I'll learn how to use it over the next few days :] On Wed, Oct 12, 2011 at 2:13 PM, alex23 wrote: > On Oct 12, 1:14?am, Alec Taylor wrote: >> They look good, but I'm looking for something which can "compile" down >> to normal SQL code. > > Then you're not looking hard enough. SQLAlchemy does this. > > -- > http://mail.python.org/mailman/listinfo/python-list > From jackdied at gmail.com Wed Oct 12 00:07:05 2011 From: jackdied at gmail.com (Jack Diederich) Date: Wed, 12 Oct 2011 00:07:05 -0400 Subject: Implementing Python-OAuth2 In-Reply-To: <4E8DD438.20207@ncsa.illinois.edu> References: <4E8DD438.20207@ncsa.illinois.edu> Message-ID: On Thu, Oct 6, 2011 at 12:15 PM, Jeff Gaynor wrote: > On 10/06/2011 08:34 AM, Kayode Odeyemi wrote: >> I'm working on a pretty large application that I will like to use oauth2 >> on as an authentication and authorization mechanism. > > There are *no* usable OAuth version 2..0 implementation in any language > (usually Java comes first) that I know of, so you will get to role your own, > which is hard. There are a few beta-level versions E.g. Twitter) but these > are special cased to the author's needs. The spec itself is not quite ready > either and since it has changed quite substantially in the last year, I > suspect that everyone is waiting to see it settle to a steady state. I got bit hard by oauth libraries, especially because pre-OAuth2.0 someone started a forked OAuth1.0 library and named it "oauth2". Lots of forked copies of that one pollute the searches. Google has one but it is impossibly over engineered - 15,000 lines of code in a hundred files. I got frustrated and wrote one that only does 2.0 "bearer token" and has only been tested against goo.gl (the google URL shortener). But it works for me, weighs in at 200 lines of code, and only needs stdlib + json libraries. Using the official google API required me to write more than 200 lines of code, so I'm a happy camper. https://github.com/jackdied/python-foauth2 Patches-welcome-ly, -Jack NB, the name can be pronounced "faux-auth 2" or "Eff Oauth 2" at your discretion. From mdaglow at daglowconsulting.com Wed Oct 12 00:49:30 2011 From: mdaglow at daglowconsulting.com (Marta) Date: Tue, 11 Oct 2011 21:49:30 -0700 (PDT) Subject: Want to make the transition to games? Message-ID: Hi, I'm working as an onsite recruiting consultant and we are looking for top engineers who want to work with other very accomplished engineers. If you have a CS degree, strong in C++ and want to make the transition to games, please email me your resume. Cheers, Marta Daglow From christian.wutte at gmx.at Wed Oct 12 04:22:34 2011 From: christian.wutte at gmx.at (Christian Wutte) Date: Wed, 12 Oct 2011 01:22:34 -0700 (PDT) Subject: os.startfile: Why is there no arguments option? Message-ID: Hello all, as stated in the docs [1] os.startfile relies on Win32 ShellExecute(). So maybe someone can explain it to me, why there is no support for program arguments. That's quite a pity since os.startfile is the easiest way for an elevated run (with 'runas' as option) and without arguments of limited use. [1] http://docs.python.org/library/os.html?highlight=startfile#os.startfile Thanks, Christian From iamforufriends at gmail.com Wed Oct 12 05:05:36 2011 From: iamforufriends at gmail.com (hot girl) Date: Wed, 12 Oct 2011 02:05:36 -0700 (PDT) Subject: his wife need dating with other man Message-ID: his wife need dating with other man http://tinyurl.com/44s5ewx http://tinyurl.com/44s5ewx http://tinyurl.com/44s5ewx http://tinyurl.com/44s5ewx From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Wed Oct 12 05:27:48 2011 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Wed, 12 Oct 2011 11:27:48 +0200 Subject: os.startfile: Why is there no arguments option? In-Reply-To: References: Message-ID: Am 12.10.2011 10:22 schrieb Christian Wutte: > Hello all, > as stated in the docs [1] os.startfile relies on Win32 ShellExecute(). > So maybe someone can explain it to me, why there is no support for > program arguments. Because it is intended to start an arbitrary file of any type (.txt, .doc, ...) For this operations, there is no parameter support. > That's quite a pity since os.startfile is the easiest way for an > elevated run (with 'runas' as option) Obviously not. > and without arguments of limited use. So it isn't the asiest way. Have you tried os.system() and/or subprocess.Popen() resp. .call()? Thomas From ben+python at benfinney.id.au Wed Oct 12 05:41:28 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 12 Oct 2011 20:41:28 +1100 Subject: Seven Python Developers Needed $125K In-Reply-To: (WR's message of "Tue, 11 Oct 2011 18:16:50 -0000") References: Message-ID: <87mxd6wnqv.fsf@benfinney.id.au> "WR" writes: > Top Global Consulting Firm in NYC needs 7 Python Developers Please do not use this discussion forum for recruitment. Instead, use the Python Job board for that purpose. -- \ ?If the desire to kill and the opportunity to kill came always | `\ together, who would escape hanging?? ?Mark Twain, _Following | _o__) the Equator_ | Ben Finney From theller at ctypes.org Wed Oct 12 05:45:18 2011 From: theller at ctypes.org (Thomas Heller) Date: Wed, 12 Oct 2011 11:45:18 +0200 Subject: os.startfile: Why is there no arguments option? In-Reply-To: References: Message-ID: <9fl5teFavpU1@mid.individual.net> Am 12.10.2011 10:22, schrieb Christian Wutte: > Hello all, > as stated in the docs [1] os.startfile relies on Win32 ShellExecute(). > So maybe someone can explain it to me, why there is no support for > program arguments. > That's quite a pity since os.startfile is the easiest way for an > elevated run (with 'runas' as option) and without arguments of limited > use. > > [1] http://docs.python.org/library/os.html?highlight=startfile#os.startfile > > Thanks, > Christian It is trivial to call ShellExecute with ctypes. Thomas From moky.math at gmail.com Wed Oct 12 06:14:20 2011 From: moky.math at gmail.com (Laurent Claessens) Date: Wed, 12 Oct 2011 12:14:20 +0200 Subject: 1/2 evaluates to 0 Message-ID: Hi all This is well known : >>> 1/2 0 This is because the division is an "integer division". My question is : how can I evaluate 1/2 to 0.5 ? Is there some non integer division operator ? Up to now I workarounded writing float(1)/2. Is there an other way ? My Zen of python says : There should be one-- and preferably only one --obvious way to do it. and I don't believe that float(1)/2 is an "obvious way" (I'm not Dutch) Have a good afternoon Laurent From jeanmichel at sequans.com Wed Oct 12 06:24:23 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 12 Oct 2011 12:24:23 +0200 Subject: 1/2 evaluates to 0 In-Reply-To: References: Message-ID: <4E956AD7.5070309@sequans.com> Laurent Claessens wrote: > Hi all > > > This is well known : > > >>> 1/2 > 0 > > This is because the division is an "integer division". > > My question is : how can I evaluate 1/2 to 0.5 ? Is there some non > integer division operator ? > Up to now I workarounded writing float(1)/2. Is there an other way ? > > My Zen of python says : > There should be one-- and preferably only one --obvious way to do it. > > and I don't believe that float(1)/2 is an "obvious way" (I'm not Dutch) > > Have a good afternoon > Laurent Hi, 1./2 JM From enalicho at gmail.com Wed Oct 12 06:25:34 2011 From: enalicho at gmail.com (Noah Hall) Date: Wed, 12 Oct 2011 11:25:34 +0100 Subject: 1/2 evaluates to 0 In-Reply-To: References: Message-ID: On Wed, Oct 12, 2011 at 11:14 AM, Laurent Claessens wrote: > This is well known : > >>>> 1/2 > 0 > > This is because the division is an "integer division". > > My question is : how can I evaluate 1/2 to 0.5 ? Is there some non integer Include from __future__ import division on the top of your file >>> from __future__ import division >>> 1/2 0.5 From aaan at email.dk Wed Oct 12 06:27:03 2011 From: aaan at email.dk (Aage Andersen (REMOVE)) Date: Wed, 12 Oct 2011 12:27:03 +0200 Subject: 1/2 evaluates to 0 References: Message-ID: <4e956b7a$0$56792$edfadb0f@dtext02.news.tele.dk> "Laurent Claessens" skrev i en meddelelse news:j73p9s$baa$1 at news.univ-fcomte.fr... > Hi all > > > This is well known : > > >>> 1/2 > 0 > > This is because the division is an "integer division". > > My question is : how can I evaluate 1/2 to 0.5 ? Is there some non integer > division operator ? > Up to now I workarounded writing float(1)/2. Is there an other way ? what about 1.0/2 ? From paul.nospam at rudin.co.uk Wed Oct 12 06:28:51 2011 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Wed, 12 Oct 2011 11:28:51 +0100 Subject: 1/2 evaluates to 0 References: Message-ID: <87ipnuh5b0.fsf@no-fixed-abode.cable.virginmedia.net> Laurent Claessens writes: > Hi all > > > This is well known : > >>>> 1/2 > 0 > > This is because the division is an "integer division". > > My question is : how can I evaluate 1/2 to 0.5 ? Is there some non > integer division operator ? > Up to now I workarounded writing float(1)/2. Is there an other way ? from __future__ import division Or use operator.truediv Or use python 3. From rosuav at gmail.com Wed Oct 12 06:29:58 2011 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 12 Oct 2011 21:29:58 +1100 Subject: 1/2 evaluates to 0 In-Reply-To: References: Message-ID: On Wed, Oct 12, 2011 at 9:14 PM, Laurent Claessens wrote: > Hi all > > This is well known : > >>>> 1/2 > 0 Only in Python 2. > This is because the division is an "integer division". > > My question is : how can I evaluate 1/2 to 0.5 ? Is there some non integer > division operator ? 1.0/2 is floating point division, but you can also use: >>> from __future__ import division >>> 1/2 0.5 >>> 1//2 0 This is the most portable option. Stick with // for integer division and tell / to produce a float (which it will do even if the result would have fitted into an integer). Note that the __future__ directive needs to be at the top of your program. ChrisA From __peter__ at web.de Wed Oct 12 06:34:58 2011 From: __peter__ at web.de (Peter Otten) Date: Wed, 12 Oct 2011 12:34:58 +0200 Subject: 1/2 evaluates to 0 References: Message-ID: Laurent Claessens wrote: > This is well known : > > >>> 1/2 > 0 > > This is because the division is an "integer division". > > My question is : how can I evaluate 1/2 to 0.5 ? Is there some non > integer division operator ? > Up to now I workarounded writing float(1)/2. Is there an other way ? > > My Zen of python says : > There should be one-- and preferably only one --obvious way to do it. > > and I don't believe that float(1)/2 is an "obvious way" (I'm not Dutch) In Python 3 there is an obvious way: >>> 1/2 0.5 In Python 2 you can trigger that behaviour with the magic incantation >>> from __future__ import division >>> 1/2 0.5 In both cases the traditional integer division can be forced with >>> 1//2 0 From alec.taylor6 at gmail.com Wed Oct 12 07:06:08 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Wed, 12 Oct 2011 22:06:08 +1100 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] In-Reply-To: References: <4E945CD6.3040502@tim.thechases.com> Message-ID: That's why I said "over the next few days", because learning it for that last assignment would've been too much effort :P On Wed, Oct 12, 2011 at 3:45 PM, wu wei wrote: > Just don't use it for the first time in a demo and then blame me when it > fails ;) > > On Wed, Oct 12, 2011 at 2:05 PM, Alec Taylor wrote: >> >> Great, I'll learn how to use it over the next few days >> >> :] >> >> On Wed, Oct 12, 2011 at 2:13 PM, alex23 wrote: >> > On Oct 12, 1:14?am, Alec Taylor wrote: >> >> They look good, but I'm looking for something which can "compile" down >> >> to normal SQL code. >> > >> > Then you're not looking hard enough. SQLAlchemy does this. >> > >> > -- >> > http://mail.python.org/mailman/listinfo/python-list >> > > > From selahattin_ay at msn.com Wed Oct 12 07:15:26 2011 From: selahattin_ay at msn.com (selahattin ay) Date: Wed, 12 Oct 2011 11:15:26 +0000 Subject: file processing question Message-ID: hi all, I wrote these codes but the program must write the prints to a text file... code = [100, 200, 300, 400, 500] list= [] a = 0 while a < 9: a+=1 list.append(a) last_list = [[int(str(i) + str(k)) for i in code] for k in list] list2= [] b = 0 while b < 9: b+=1 list2.append(b) the thing that I want to do is, I want to create text files from 1 to 9 as in list2 1.txt, 2.txt ....9.txt like thatsample of a text file is : X:CA VERSION:2.5 P:(here will be the first value of list2 );;;; L;C: (here will be the first value of last_list ) the first sample X:CA VERSION:2.5 P: 1 ;;;; L;C: 1001 the first sample X:CA VERSION:2.5 P: 8 ;;;; L;C: 1008 can you help me about this thx for all.. -------------- next part -------------- An HTML attachment was scrubbed... URL: From installman at 189.cn Wed Oct 12 07:18:25 2011 From: installman at 189.cn (installman at 189.cn) Date: Wed, 12 Oct 2011 04:18:25 -0700 (PDT) Subject: why msvcrt.printf show the first char only? Message-ID: <88550536-6cc5-452c-8bca-ba91b175323a@l39g2000pro.googlegroups.com> from ctypes import * msvcrt = cdll.msvcrt message_string = "Hello world!\n" print(msvcrt.printf("Testing: %s", message_string)) when running in eclipse, the result is: 1 T when running in IDLE, then result is: 1 why is that? From moky.math at gmail.com Wed Oct 12 07:28:35 2011 From: moky.math at gmail.com (Laurent) Date: Wed, 12 Oct 2011 13:28:35 +0200 Subject: 1/2 evaluates to 0 In-Reply-To: References: Message-ID: <4E9579E3.9090303@gmail.com> > Include from __future__ import division on the top of your file > >>>> from __future__ import division >>>> 1/2 > 0.5 > Wohaw. This means that this behavior is going to be default in a foreseeable future ? Thanks Laurent From nobody at nowhere.com Wed Oct 12 07:34:21 2011 From: nobody at nowhere.com (Nobody) Date: Wed, 12 Oct 2011 12:34:21 +0100 Subject: 1/2 evaluates to 0 References: Message-ID: On Wed, 12 Oct 2011 13:28:35 +0200, Laurent wrote: >>>>> from __future__ import division >>>>> 1/2 >> 0.5 >> > > Wohaw. This means that this behavior is going to be default in a > foreseeable future ? It's the default in 3.x. I can't imagine it ever being the default in 2.x. From enalicho at gmail.com Wed Oct 12 07:41:05 2011 From: enalicho at gmail.com (Noah Hall) Date: Wed, 12 Oct 2011 12:41:05 +0100 Subject: 1/2 evaluates to 0 In-Reply-To: <4E9579E3.9090303@gmail.com> References: <4E9579E3.9090303@gmail.com> Message-ID: On Wed, Oct 12, 2011 at 12:28 PM, Laurent wrote: > >> Include from __future__ import division on the top of your file >> >>>>> ?from __future__ import division >>>>> ?1/2 >> >> 0.5 >> > > Wohaw. This means that this behavior is going to be default in a foreseeable > future ? Never in Python 2.x, but it already is in Python 3.x [1] [1] - http://www.python.org/dev/peps/pep-0238/ From nobody at nowhere.com Wed Oct 12 07:50:34 2011 From: nobody at nowhere.com (Nobody) Date: Wed, 12 Oct 2011 12:50:34 +0100 Subject: why msvcrt.printf show the first char only? References: <88550536-6cc5-452c-8bca-ba91b175323a@l39g2000pro.googlegroups.com> Message-ID: On Wed, 12 Oct 2011 04:18:25 -0700, installman at 189.cn wrote: > from ctypes import * > msvcrt = cdll.msvcrt > message_string = "Hello world!\n" > print(msvcrt.printf("Testing: %s", message_string)) > > when running in eclipse, the result is: > 1 > T > > when running in IDLE, then result is: > 1 > > why is that? Odd. I get 22 when running from IDLE. Also, when using the console, it actually prints the text. I suspect that stdout gets block-buffered when using an IDE. I can't see any way to get a reference to stdout, so you can't fflush() it. From steve+comp.lang.python at pearwood.info Wed Oct 12 07:56:27 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 12 Oct 2011 22:56:27 +1100 Subject: 1/2 evaluates to 0 References: Message-ID: <4e95806c$0$29986$c3e8da3$5496439d@news.astraweb.com> Nobody wrote: > On Wed, 12 Oct 2011 13:28:35 +0200, Laurent wrote: > >>>>>> from __future__ import division >>>>>> 1/2 >>> 0.5 >>> >> >> Wohaw. This means that this behavior is going to be default in a >> foreseeable future ? > > It's the default in 3.x. I can't imagine it ever being the default in 2.x. 2.7 is now in "bug-fix only" mode, so no new features, and there won't be a 2.8, so true division will never be the default in 2.x. -- Steven From christian.wutte at gmx.at Wed Oct 12 08:18:00 2011 From: christian.wutte at gmx.at (Christian Wutte) Date: Wed, 12 Oct 2011 05:18:00 -0700 (PDT) Subject: os.startfile: Why is there no arguments option? References: Message-ID: On Oct 12, 11:27?am, Thomas Rachel wrote: > Am 12.10.2011 10:22 schrieb Christian Wutte: > > > Hello all, > > as stated in the docs [1] os.startfile relies on Win32 ShellExecute(). > > So maybe someone can explain it to me, why there is no support for > > program arguments. > > Because it is intended to start an arbitrary file of any type (.txt, > .doc, ...) For this operations, there is no parameter support. > Yes, but isn't that also the case for ShellExecute()? In the MSDN page [1] for the parameters can be read: "If lpFile specifies an executable file, this parameter is a pointer to a null-terminated string that specifies the parameters to be passed to the application. The format of this string is determined by the verb that is to be invoked. If lpFile specifies a document file, lpParameters should be NULL." So the parameter should be optional for sure. > > That's quite a pity since os.startfile is the easiest way for an > > elevated run (with 'runas' as option) > > Obviously not. > > ?> and without arguments of limited use. > > So it isn't the asiest way. > > Have you tried os.system() and/or subprocess.Popen() resp. .call()? > Yes. I should have noticed, that in my case I want to make a manual elevated call. With programs that need elevated rights in the first place os.start() or subprocess.Popen(.. , shell=True) is fine. Chrisitan From christian.wutte at gmx.at Wed Oct 12 08:28:32 2011 From: christian.wutte at gmx.at (Christian Wutte) Date: Wed, 12 Oct 2011 05:28:32 -0700 (PDT) Subject: os.startfile: Why is there no arguments option? References: <9fl5teFavpU1@mid.individual.net> Message-ID: On Oct 12, 11:45?am, Thomas Heller wrote: > > It is trivial to call ShellExecute with ctypes. > Yes, but it would be easier to use os.startfile() instead of ctypes.windll.shell32.ShellExecute(), not? Further one must for sure check the MSDN page for ShellExecute for the five parameters. Then on error it is more comfortable that os.startfile already throws an WindowsError. [1] http://msdn.microsoft.com/en-us/library/windows/desktop/bb762153%28v=vs.85%29.aspx Christian From ramapraba2653 at gmail.com Wed Oct 12 08:52:44 2011 From: ramapraba2653 at gmail.com (SUPREME) Date: Wed, 12 Oct 2011 05:52:44 -0700 (PDT) Subject: HOT ACTRESSES Message-ID: <36dcd84b-9341-4d51-840a-64d9493425fa@l30g2000pro.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html From python.list at tim.thechases.com Wed Oct 12 11:33:04 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 12 Oct 2011 10:33:04 -0500 Subject: Python library for generating SQL queries [selects, alters, inserts and commits] In-Reply-To: References: <4E945CD6.3040502@tim.thechases.com> Message-ID: <4E95B330.6070903@tim.thechases.com> On 10/11/11 22:13, alex23 wrote: >> They look good, but I'm looking for something which can >> "compile" down to normal SQL code. > > Then you're not looking hard enough. SQLAlchemy does this. I'm not sure it can entirely be chalked up to not looking hard enough. Because so many keywords of what's desired are overloaded (e.g. "raw", "sql", "result", etc), it took me several passes to learn that str(query_object) did this in SQLAlchemy, and while I know there has to be SOME way to coerce it out of SQLObject, I was unable to find anything other than setting the connection-debug to True and having it print to the debugging sink. And I had the advantage of years of programming Python & SQL, and some pretty good Google-fu to guide me. For somebody coming fresh to the field, it would be easy to miss. -tkc From maxc at me.com Wed Oct 12 11:59:07 2011 From: maxc at me.com (Max Countryman) Date: Wed, 12 Oct 2011 11:59:07 -0400 Subject: Code Review: a framework for writing IRC applications or bots Message-ID: <7D6AE088-3EC7-4976-B739-A66A777E4390@me.com> Hi all, I'm still very much a learner when it comes to Python but I've been working on a little framework the past few weeks to help me in the learning process and I would like it if the more experienced members of the community could give me some advice on the design considerations and general quality of the code. The goal was to create a framework for writing IRC applications or bots. I modeled the API after Flask. It was important to me that I include a number of features: such as automatic on-the-fly reloading, threaded plugins, and the ability to reconnect to a network should the connection be lost. I'd really appreciate any feedback, tips, advice, and so forth. Please understand this isn't necessarily meant to be a utility of high value: IRC isn't exactly the most happening place after all and my main goal was to hone my skills so if your reaction is that this is essentially useless that wasn't necessarily my goal. Nonetheless I really would appreciate any kind of code review the community might be willing to provide. The project is available here: https://github.com/maxcountryman/irctk Thanks for your time! Max From andreas.perstinger at gmx.net Wed Oct 12 12:38:10 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Wed, 12 Oct 2011 18:38:10 +0200 Subject: file processing question In-Reply-To: References: Message-ID: <4E95C272.1020407@gmx.net> On 2011-10-12 13:15, selahattin ay wrote: > > hi all, I wrote these codes but the program must write the prints to a text file... > code = [100, 200, 300, 400, 500] > > > list= [] > a = 0 > while a< 9: > a+=1 > list.append(a) > last_list = [[int(str(i) + str(k)) for i in code] for k in list] > list2= [] > b = 0 > while b< 9: > b+=1 > list2.append(b) Others have already told you yesterday that you don't need while-loops: list = range(1, 10) list2 = list[:] (you probably don't need "list2" at all) > the thing that I want to do is, I want to create text files from 1 to 9 as in list2 > 1.txt, 2.txt ....9.txt like thatsample of a text file is : > > X:CA > VERSION:2.5 > P:(here will be the first value of list2 );;;; > L;C: (here will be the first value of last_list ) > > > the first sample > X:CA > VERSION:2.5 > P: 1 ;;;; > L;C: 1001 > > the first sample > > X:CA > VERSION:2.5 > P: 8 ;;;; > L;C: 1008 You want to write 9 files but last_list has 45 elements. What will happen with the rest of them? BTW: Your last_list is a list of 9 lists, each containing 5 elements ([[1001, 2001, ...], [1002, 2002, ...], ...]). Don't you really want a list of 5 lists, each containing 9 elements ([[1001, 1002, ...], [2001, 2002, ...], ...])? At least I get this impression from your samples. Bye, Andreas From yasar11732 at gmail.com Wed Oct 12 12:47:31 2011 From: yasar11732 at gmail.com (=?ISO-8859-9?Q?Ya=FEar_Arabac=FD?=) Date: Wed, 12 Oct 2011 19:47:31 +0300 Subject: file processing question In-Reply-To: <4E95C272.1020407@gmx.net> References: <4E95C272.1020407@gmx.net> Message-ID: And also, I higly recommend against using lists named list. That means overwriting builtin list object. 2011/10/12 Andreas Perstinger > On 2011-10-12 13:15, selahattin ay wrote: > >> >> hi all, I wrote these codes but the program must write the prints to a >> text file... >> code = [100, 200, 300, 400, 500] >> >> >> list= [] >> a = 0 >> while a< 9: >> a+=1 >> list.append(a) >> last_list = [[int(str(i) + str(k)) for i in code] for k in list] >> list2= [] >> b = 0 >> while b< 9: >> b+=1 >> list2.append(b) >> > > Others have already told you yesterday that you don't need while-loops: > list = range(1, 10) > list2 = list[:] > (you probably don't need "list2" at all) > > the thing that I want to do is, I want to create text files from 1 to 9 as >> in list2 >> 1.txt, 2.txt ....9.txt like thatsample of a text file is : >> >> >> X:CA >> VERSION:2.5 >> P:(here will be the first value of list2 );;;; >> L;C: (here will be the first value of last_list ) >> >> >> the first sample >> X:CA >> VERSION:2.5 >> P: 1 ;;;; >> L;C: 1001 >> >> the first sample >> >> X:CA >> VERSION:2.5 >> P: 8 ;;;; >> L;C: 1008 >> > > You want to write 9 files but last_list has 45 elements. What will happen > with the rest of them? > > BTW: Your last_list is a list of 9 lists, each containing 5 elements > ([[1001, 2001, ...], [1002, 2002, ...], ...]). Don't you really want a list > of 5 lists, each containing 9 elements ([[1001, 1002, ...], [2001, 2002, > ...], ...])? At least I get this impression from your samples. > > Bye, Andreas > -- > http://mail.python.org/**mailman/listinfo/python-list > -- http://yasar.serveblog.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Wed Oct 12 13:51:16 2011 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 12 Oct 2011 18:51:16 +0100 Subject: [Python-ideas] Implement comparison operators for range objects In-Reply-To: <4E95CF7D.6000000@pearwood.info> References: <20111012163144.GB6393@pantoffel-wg.de> <4E95CF7D.6000000@pearwood.info> Message-ID: <4E95D394.9000205@mrabarnett.plus.com> On 12/10/2011 18:33, Steven D'Aprano wrote: > Sven Marnach wrote: >> There are circumstances, for example in unit testing, when it might be >> useful to check if two range objects describe the same range. >> Currently, this can't be done using the '==' operator: >> >> >>> range(5) == range(5) >> False > [...] >> All other built-in sequence types (that is bytearray, bytes, list, >> str, and tuple) define equality by "all items of the sequence are >> equal". I think it would be both more consistent and more useful if >> range objects would pick up the same semantics. > > I can see how that would be useful and straightforward, and certainly > more useful than identity based equality. +1 > > >> When implementing '==' and '!=' for range objects, it would be natural >> to implement the other comparison operators, too (lexicographically, >> as for all other sequence types). > > I don't agree. Equality makes sense for ranges: two ranges are equal if > they have the same start, stop and step values. But order comparisons > don't have any sensible meaning: range objects are numeric ranges, > integer-valued intervals, not generic lists, and it is meaningless to > say that one range is less than or greater than another. > > Which is greater? > > range(1, 1000000, 1000) > range(1000, 10000) > > The question makes no sense, and should be treated as an error, just as > it is for complex numbers. > > -1 on adding order comparison operators. > > > > Aside: > > I'm astonished to see that range objects have a count method! What's the > purpose of that? Any value's count will either be 0 or 1, and a more > appropriate test would be `value in range`: > > >>> 17 in range(2, 30, 3) # like r.count(17) => 1 > True > >>> 18 in range(2, 30, 3) # like r.count(18) => 0 > False > In Python 2, range returns a list, and lists have a .count method. Could that be the reason? From ramit.prasad at jpmorgan.com Wed Oct 12 13:53:51 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 12 Oct 2011 13:53:51 -0400 Subject: Code Review: a framework for writing IRC applications or bots In-Reply-To: <7D6AE088-3EC7-4976-B739-A66A777E4390@me.com> References: <7D6AE088-3EC7-4976-B739-A66A777E4390@me.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F215C882F@EMARC112VS01.exchad.jpmchase.net> > It was important to me that I include a number of features: such as automatic on-the-fly reloading, If you are referring to reloading python modules (and not configuration files), I can tell you that this is a difficult feature to implement, much less do it correctly. I have experienced troubles with this in Python2 (not sure about Python3). For example: If you have two modules A and B, where B imports A. Reloading A works fine for new instances of A, but this will not automatically reload the version of A already imported by B. Note: This has been my experience with apps that try to do this, not from firsthand experience in development. Your mileage (kilometerage?) may vary. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From 1jason.whatford at gmail.com Wed Oct 12 14:27:51 2011 From: 1jason.whatford at gmail.com (J) Date: Wed, 12 Oct 2011 11:27:51 -0700 (PDT) Subject: Embedding a "frame" into a movie using python Message-ID: <18514149.192.1318444071734.JavaMail.geo-discussion-forums@vbbfh29> Hi there, I'm currently experimenting with python by putting together a little webapp running on appengine. My objective is to have the user put together some images html and embed the image as a frame into a video file (any embeddable format e.g. swf). So there are three steps: (1) Convert the html to a "frame" (2) Insert the frame into the existing movie (3) save the new movie with the frame For example, I have a film of a sunrise. I want to embed a "frame" which has a little poem about sunrises into the film much like windows movie maker and other such programs allow you to do. Is there a way I can do this with python? Cheers, J From ian.g.kelly at gmail.com Wed Oct 12 15:24:31 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 12 Oct 2011 13:24:31 -0600 Subject: [Python-ideas] Implement comparison operators for range objects In-Reply-To: <4E95D394.9000205@mrabarnett.plus.com> References: <20111012163144.GB6393@pantoffel-wg.de> <4E95CF7D.6000000@pearwood.info> <4E95D394.9000205@mrabarnett.plus.com> Message-ID: On Wed, Oct 12, 2011 at 11:51 AM, MRAB wrote: >> Aside: >> >> I'm astonished to see that range objects have a count method! What's the >> purpose of that? Any value's count will either be 0 or 1, and a more >> appropriate test would be `value in range`: >> >> ?>>> 17 in range(2, 30, 3) # like r.count(17) => 1 >> True >> ?>>> 18 in range(2, 30, 3) # like r.count(18) => 0 >> False >> > In Python 2, range returns a list, and lists have a .count method. > Could that be the reason? Python 2 xrange objects do not have a .count method. Python 3 range objects do have a .count method. The addition is curious, to say the least. From rosuav at gmail.com Wed Oct 12 16:06:45 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Oct 2011 07:06:45 +1100 Subject: Embedding a "frame" into a movie using python In-Reply-To: <18514149.192.1318444071734.JavaMail.geo-discussion-forums@vbbfh29> References: <18514149.192.1318444071734.JavaMail.geo-discussion-forums@vbbfh29> Message-ID: On Thu, Oct 13, 2011 at 5:27 AM, J <1jason.whatford at gmail.com> wrote: > My objective is to have the user put together some images html and embed the image as a frame into a video file (any embeddable format e.g. swf). So there are three steps: > SWF isn't the easiest format to work with; it's not necessarily a video, but might be a scripted object. Try working with real video formats such as avi, mpg, or ogv. You may wish to look into PiTiVi, an open source video editor; it's written in Python. I'm not sure if you can achieve what you want by simply driving PiTiVi externally, but at very least, it's worth a peek. ChrisA From pengyu.ut at gmail.com Wed Oct 12 16:42:09 2011 From: pengyu.ut at gmail.com (Peng Yu) Date: Wed, 12 Oct 2011 15:42:09 -0500 Subject: How add class name to format of the logging module? Message-ID: Hi, The following attributes does not include the class name. Is there a way to add class name to the format string? Thanks! http://docs.python.org/library/logging.html#logrecord-attributes -- Regards, Peng From zaffino.p at gmail.com Wed Oct 12 17:06:47 2011 From: zaffino.p at gmail.com (Paolo Zaffino) Date: Wed, 12 Oct 2011 23:06:47 +0200 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: I wrote a function thaht works on a 3D matrix. As first thing I have an array and I want reshape it into a 3D matrix (for further manipulations). For this reason I wrote in a row: matrix=matrix.reshape(a, b, c).T It work fine on GNU/Linux and Mac OS but not on Windows. In Windows I get this error: matrix=matrix.reshape(a, b, c).T ValueError: total size of new array must be unchanged Thank you. 2011/10/11 David Robinow > 2011/10/11 Paolo Zaffino : > > Nobody can help me? > Nope, not unless you post some code. Your problem description is too > vague. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwebb at teradactyl.com Wed Oct 12 17:10:08 2011 From: kwebb at teradactyl.com (Kristen J. Webb) Date: Wed, 12 Oct 2011 15:10:08 -0600 Subject: shipping python In-Reply-To: <4e94ee02$0$29978$c3e8da3$5496439d@news.astraweb.com> References: <4e94ee02$0$29978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E960230.9000407@teradactyl.com> I tried experimenting with .pyc files only to end up at: RuntimeError: Bad magic number in .pyc file can't run 2.5 pyc files on 2.6 :( My main motivation to use .pyc is to keep end users from changing scripts, breaking things, and then calling us. Tamper proofing may be an alternative approach if anyone has suggestions. Otherwise, trying to summarize my goals: 1. Distribute python (and other stuff) across many platforms (Linux, UNIXes, OSX, Windows) 2. Support the current 2.X version of python installed on the system 3. Take advantage of python modules that use shared OS libraries (e.g. libssl.so.whatever) 4. For linux especially, support many distributions/versions (getting openssl to work right, for example, is a tricky problem) 5. Take advantage of the latest python modules whenever possible (hence the argparse testing). I realize that I may be able to go back so far for this to make sense... 6. Provide additional product functionality through our own shared libraries (c code). I'm assuming that the customer system has python 2.X installed, otherwise they can use their favorite OS method to get it in the standard way. Looking at methods that try to package and run without python installed at all do not look appealing, anywhere from does it work, to export issues, to needing a C compiler on the client system..... Shipping .py files and support for modules like argparse for backward compatibility is what I've come up with so far. Then they have everything I need to create and install a .pyc file. (The can modify the installer .py files, but I expect this to be less of an issue and may be able to make my own simple tamper detecting for this). Can anyone suggest better strategies, or point out where this just won't work? Is distutils a good starting point? Many thanks! Kris On 10/11/11 7:31 PM, Steven D'Aprano wrote: > On Tue, 11 Oct 2011 17:04:45 -0600, Kristen J. Webb wrote: > >> After some more digging I see that I can easy_install argparse on my >> development system. >> >> My question is will I be able to ship this to a customer? Can I create >> .pyc files so that the customer does not have to install the argparse >> module? > > Yes, and yes. The licence of argparse is a very liberal licence, so you > can just include it in your application. There's no need for the user to > install it separately. > > You could include just the .pyc file if you insist, but I personally > don't like or recommend .pyc only installations. > > >> If not, and I want to go back into the 2.3+ range, should I just use >> optparse? > > That depends on how complex your command line arguments are. > > -- Mr. Kristen J. Webb Teradactyl LLC. PHONE: 1-505-242-1091 EMAIL: kwebb at teradactyl.com VISIT: http://www.teradactyl.com Home of the True incremental Backup System From rosuav at gmail.com Wed Oct 12 17:26:44 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Oct 2011 08:26:44 +1100 Subject: shipping python In-Reply-To: <4E960230.9000407@teradactyl.com> References: <4e94ee02$0$29978$c3e8da3$5496439d@news.astraweb.com> <4E960230.9000407@teradactyl.com> Message-ID: On Thu, Oct 13, 2011 at 8:10 AM, Kristen J. Webb wrote: > My main motivation to use .pyc is to keep end users from changing scripts, > breaking things, and then calling us. ?Tamper proofing may be an > alternative approach if anyone has suggestions. > I wouldn't bother; if you're worried about that, try a tamper-evident system rather than tamper-proof - for instance, MD5 checksums of everything: $ md5sum * >checksum.txt $ md5sum checksum.txt 123412341234123412341234 md5sum Save that meta-checksum and have an easy way to read it back - that way, you can be sure they haven't just rebuilt the checksum file. If that one checksum has changed, you know something else has; to find out which: $ md5sum -c --quiet checksum.txt No need to restrict what you send out that way, and you can still get a guarantee that they haven't fiddled with anything. ChrisA From vinay_sajip at yahoo.co.uk Wed Oct 12 18:03:53 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Wed, 12 Oct 2011 15:03:53 -0700 (PDT) Subject: How add class name to format of the logging module? References: Message-ID: <8cd5490c-7bb6-4e3f-829c-518c163db436@m15g2000vbk.googlegroups.com> On Oct 12, 9:42?pm, Peng Yu wrote: > Hi, > > The following attributes does not include the class name. Is there a > way to add class name to the format string? Thanks! Not in the general case without a reasonable run-time cost. Since you can find the exact line number a logging call was made from, you can always figure out the class. Regards, Vinay Sajip From andrea.crotti.0 at gmail.com Wed Oct 12 20:02:55 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Thu, 13 Oct 2011 01:02:55 +0100 Subject: shipping python In-Reply-To: <4E960230.9000407@teradactyl.com> References: <4e94ee02$0$29978$c3e8da3$5496439d@news.astraweb.com> <4E960230.9000407@teradactyl.com> Message-ID: <4E962AAF.3090109@gmail.com> On 10/12/2011 10:10 PM, Kristen J. Webb wrote: > I tried experimenting with .pyc files only to end up at: > > RuntimeError: Bad magic number in .pyc file > > can't run 2.5 pyc files on 2.6 :( > > My main motivation to use .pyc is to keep end users from changing > scripts, > breaking things, and then calling us. Tamper proofing may be an > alternative approach if anyone has suggestions. > > Otherwise, trying to summarize my goals: > > 1. Distribute python (and other stuff) across many platforms > (Linux, UNIXes, OSX, Windows) > > 2. Support the current 2.X version of python installed on the system > > 3. Take advantage of python modules that use shared OS libraries > (e.g. libssl.so.whatever) > > 4. For linux especially, support many distributions/versions > (getting openssl to work right, for example, is a tricky problem) > > 5. Take advantage of the latest python modules whenever possible > (hence the argparse testing). I realize that I may be able > to go back so far for this to make sense... > > 6. Provide additional product functionality through our own > shared libraries (c code). > > I'm assuming that the customer system has python 2.X installed, > otherwise they > can use their favorite OS method to get it in the standard way. > > Looking at methods that try to package and run without python > installed at > all do not look appealing, anywhere from does it work, to export issues, > to needing a C compiler on the client system..... > > Shipping .py files and support for modules like argparse for > backward compatibility is what I've come up with so far. > Then they have everything I need to create and install a .pyc file. > (The can modify the installer .py files, but I expect this to be > less of an issue and may be able to make my own simple tamper detecting > for this). > > Can anyone suggest better strategies, or point out where this just > won't work? > > Is distutils a good starting point? > > Many thanks! > > Kris Why do you want to use the system python and system libraries? If you want to avoid too much troubles and compatibility hell maybe give PyInstaller a try, you ship just one big executable and you're done. But apart from that setuptools is very good to know. And also the world is a funny place, but does it really happen that a customer changes the code in your python scripts, and the *complain* if it doens't work anymore?? From roy at panix.com Wed Oct 12 20:30:33 2011 From: roy at panix.com (Roy Smith) Date: Wed, 12 Oct 2011 20:30:33 -0400 Subject: shipping python References: <4e94ee02$0$29978$c3e8da3$5496439d@news.astraweb.com> <4E960230.9000407@teradactyl.com> Message-ID: In article , Andrea Crotti wrote: > And also the world is a funny place, but does it really happen that > a customer changes the code in your python scripts, and the *complain* > if it doens't work anymore?? You sound like somebody who has never had to support paying customers :-) From tim at akwebsoft.com Wed Oct 12 20:52:44 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Wed, 12 Oct 2011 16:52:44 -0800 Subject: MySQLdb on Mac Lion Message-ID: <20111013005244.GK6671@johnsons-web.com> I'm most experienced with MySQLdb on ubuntu, which is installed via apt-get or synaptic. I am setting up a mac mini with osX 10.7 (Lion). Macports makes py27-mysql 1.2.2 available, but are there any .dmg packages available? thanks -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From nad at acm.org Wed Oct 12 22:00:10 2011 From: nad at acm.org (Ned Deily) Date: Wed, 12 Oct 2011 19:00:10 -0700 Subject: MySQLdb on Mac Lion References: <20111013005244.GK6671@johnsons-web.com> Message-ID: In article <20111013005244.GK6671 at johnsons-web.com>, Tim Johnson wrote: > I'm most experienced with MySQLdb on ubuntu, which is installed via > apt-get or synaptic. > > I am setting up a mac mini with osX 10.7 (Lion). Macports makes > py27-mysql 1.2.2 available, but are there any .dmg packages > available? I strongly recommend you stick with MacPorts or Homebrew. There are too many things that can go wrong on OS X 10.6 or 10.7 if you try to install MySQL client libraries, MySQLdb, and Python from different places. IME, the binary installers for OS X provided by the MySQL are inconsistently built between versions and often need the library paths need to be tweaked. The only major drawback of using MacPorts is that it will download (and possibly build) its own version of Python but it's a small price to pay: search the archives of Stackoverflow to see how dismayingly often this topic comes up. -- Ned Deily, nad at acm.org From kwebb at teradactyl.com Wed Oct 12 22:09:38 2011 From: kwebb at teradactyl.com (Kristen J. Webb) Date: Wed, 12 Oct 2011 20:09:38 -0600 Subject: shipping python In-Reply-To: <4E962AAF.3090109@gmail.com> References: <4e94ee02$0$29978$c3e8da3$5496439d@news.astraweb.com> <4E960230.9000407@teradactyl.com> <4E962AAF.3090109@gmail.com> Message-ID: <4E964862.9090701@teradactyl.com> On 10/12/11 6:02 PM, Andrea Crotti wrote: > > Why do you want to use the system python and system libraries? It is a standard, just like glibc on linux, I'd like my code should work on the OS with minimal intrusion. > If you want to avoid too much troubles and compatibility hell maybe > give PyInstaller a try, you ship just one big executable and you're done. > But apart from that setuptools is very good to know. What about Solaris, NetBSD, FreeBSD, etc, etc. If the executable includes bits from the openssl library, what about export restrictions? I'll take a look at setuptools, thanks. > > And also the world is a funny place, but does it really happen that > a customer changes the code in your python scripts, and the *complain* > if it doens't work anymore?? > Yes, support costs with very knowledgeable clients is a very important factor. Thank you for the feedback! K -- Mr. Kristen J. Webb Teradactyl LLC. PHONE: 1-505-242-1091 EMAIL: kwebb at teradactyl.com VISIT: http://www.teradactyl.com Home of the True incremental Backup System From kwebb at teradactyl.com Wed Oct 12 22:43:06 2011 From: kwebb at teradactyl.com (Kristen J. Webb) Date: Wed, 12 Oct 2011 20:43:06 -0600 Subject: shipping python In-Reply-To: References: <4e94ee02$0$29978$c3e8da3$5496439d@news.astraweb.com> <4E960230.9000407@teradactyl.com> Message-ID: <4E96503A.7090502@teradactyl.com> On 10/12/11 3:26 PM, Chris Angelico wrote: > On Thu, Oct 13, 2011 at 8:10 AM, Kristen J. Webb wrote: >> My main motivation to use .pyc is to keep end users from changing scripts, >> breaking things, and then calling us. Tamper proofing may be an >> alternative approach if anyone has suggestions. >> > > I wouldn't bother; if you're worried about that, try a tamper-evident > system rather than tamper-proof - for instance, MD5 checksums of > everything: > > $ md5sum *>checksum.txt > $ md5sum checksum.txt > 123412341234123412341234 md5sum > > Save that meta-checksum and have an easy way to read it back - that > way, you can be sure they haven't just rebuilt the checksum file. If > that one checksum has changed, you know something else has; to find > out which: > > $ md5sum -c --quiet checksum.txt > > No need to restrict what you send out that way, and you can still get > a guarantee that they haven't fiddled with anything. > > ChrisA So you could think of the meta-checksum as a script wide version control of what is installed. Then, at key entry points, take the hit and re-generate the meta-checksum and compare. If bad, you have a major version control error, do not process further. Makes sense, so long as the user does not bother to regenerate the meta-checksum as well. Would be more extensible if in debugging, users can disable this feature. or have a tool that updates the meta-checksum so that they can run one-off code to fix problems. Oddly, this feature would make it easier to change code and still keep things running. But we could use the value in the support chain to say, "something changed, what's going on?". Thoughts? K -- Mr. Kristen J. Webb Teradactyl LLC. PHONE: 1-505-242-1091 EMAIL: kwebb at teradactyl.com VISIT: http://www.teradactyl.com Home of the True incremental Backup System From pousadas.trancoso at reservas.trancoso.ba Wed Oct 12 23:54:32 2011 From: pousadas.trancoso at reservas.trancoso.ba (pousadas trancoso reservas bahia) Date: Thu, 13 Oct 2011 03:54:32 +0000 (UTC) Subject: reservastrancoso@gmail.com Pousadas em Trancoso, reservas, agencia virtual, turismo Bahia - 75469 Message-ID: reservastrancoso at gmail.com reservastrancoso @ gmail.com (reservastrancoso at gmail.com) Pousadas em Trancoso, agencia virtual em Tancoso - Bahia. Fa?a ja sua reserva nas pousadas mais badaladas da cidade. Contato reservastrancoso @ gmail.com reservastrancoso at gmail.com (reservastrancoso at gmail.com) >S^LnssPFTXZL_TreGzKVV+k. From jpiitula at ling.helsinki.fi Thu Oct 13 04:19:16 2011 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 13 Oct 2011 11:19:16 +0300 Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <4e903b81$0$29970$c3e8da3$5496439d@news.astraweb.com> Message-ID: Chris Angelico writes: > On Sun, Oct 9, 2011 at 12:07 AM, Jussi Piitulainen wrote: > > But both negations can be avoided by modus tollens. > > > > "If you are able to start the car, the key is in the ignition." > > But this translation implies looking at the result and ascertaining > the state, which is less appropriate to a programming language. It's > more like: > > "If you found that you were able to start the car, the key must have > been in the ignition." > > and is thus quite inappropriate to the imperative style. A > functional language MAY be able to use this style, but Python wants > to have the condition and then the action. This is not in an imperative context. The context is (generalized) Boolean expressions, where there should not be any action, just expressions returning values that are combined to produce a (generalized) Boolean value. Defined order of evaluation and short-circuiting complicate the picture, but as a matter of style, I think there should not be any action part in such an expression. Usually. And "not in" is fine as far as I am concerned. From 1jason.whatford at gmail.com Thu Oct 13 04:51:36 2011 From: 1jason.whatford at gmail.com (J) Date: Thu, 13 Oct 2011 01:51:36 -0700 (PDT) Subject: Embedding a "frame" into a movie using python In-Reply-To: References: <18514149.192.1318444071734.JavaMail.geo-discussion-forums@vbbfh29> Message-ID: <11518268.545.1318495896114.JavaMail.geo-discussion-forums@vbat14> >> My objective is to have the user put together some images html and embed the image as a frame into a video file (any embeddable format e.g. swf). >SWF isn't the easiest format to work with; it's not necessarily a video, but might be a scripted object. Try working with real video formats such as avi, mpg, or ogv. >You may wish to look into PiTiVi, an open source video editor; it's written in Python. I'm not sure if you can achieve what you want by simply driving PiTiVi externally, but at very least, it's worth a peek. >ChrisA Hi Chris, thank you for your response. I am format agnostic for processing so am happy to work with avi etc., however in displaying the final film to the user I think I'd need to convert whatever I've made to swf to make it a little less downloadable. I'll check out PiTiVi - perhaps I can hack it to work on the back of appengine... Cheers, J From 1jason.whatford at gmail.com Thu Oct 13 04:51:36 2011 From: 1jason.whatford at gmail.com (J) Date: Thu, 13 Oct 2011 01:51:36 -0700 (PDT) Subject: Embedding a "frame" into a movie using python In-Reply-To: References: <18514149.192.1318444071734.JavaMail.geo-discussion-forums@vbbfh29> Message-ID: <11518268.545.1318495896114.JavaMail.geo-discussion-forums@vbat14> >> My objective is to have the user put together some images html and embed the image as a frame into a video file (any embeddable format e.g. swf). >SWF isn't the easiest format to work with; it's not necessarily a video, but might be a scripted object. Try working with real video formats such as avi, mpg, or ogv. >You may wish to look into PiTiVi, an open source video editor; it's written in Python. I'm not sure if you can achieve what you want by simply driving PiTiVi externally, but at very least, it's worth a peek. >ChrisA Hi Chris, thank you for your response. I am format agnostic for processing so am happy to work with avi etc., however in displaying the final film to the user I think I'd need to convert whatever I've made to swf to make it a little less downloadable. I'll check out PiTiVi - perhaps I can hack it to work on the back of appengine... Cheers, J From peter.mosley at talk21.com Thu Oct 13 04:52:50 2011 From: peter.mosley at talk21.com (peter) Date: Thu, 13 Oct 2011 01:52:50 -0700 (PDT) Subject: Reading screen width of a Tkinter widget. Message-ID: <2f7eee89-9be2-4405-8d92-c1545385c33f@e4g2000vbw.googlegroups.com> I recently had a problem while trying to set up a Tkinter Canvas widget as a progress bar. Everything seemed to be working, except that at 100% completion the progress bar spanned only about 75% of the canvas width. Eventually I tracked the problem down to the canvas bar 'width' property as read using w=cnvProgess['width']. It turned out the value returned was the original width of the canvas bar, and not the screen width after the canvas had been gridded using 'sticky=W+E'. Once I realised this it was not a show stopper, as I replaced the grid sticky option with a specific width instruction. But this is a bit less flexible than my original method. Is there any Tkinter command which will return the actual dimensions of a widget which has had the grid sticky option applied? Peter From candide at free.invalid Thu Oct 13 05:45:06 2011 From: candide at free.invalid (candide) Date: Thu, 13 Oct 2011 11:45:06 +0200 Subject: Opportunity missed by Python ? Message-ID: <4e96b324$0$1007$426a34cc@news.free.fr> Dart is the very new language created by Google to replace Javascript. So Python was not able to do the job? Or may be they don't know about Python at Google ;) ? From zapyon at gmx.net Thu Oct 13 05:56:58 2011 From: zapyon at gmx.net (Andreas Neudecker) Date: Thu, 13 Oct 2011 11:56:58 +0200 Subject: Opportunity missed by Python ? In-Reply-To: <4e96b324$0$1007$426a34cc@news.free.fr> References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: Am 13.10.2011 11:45, schrieb candide: > Dart is the very new language created by Google to replace Javascript. > So Python was not able to do the job? Or may be they don't know about > Python at Google ;) ? What needs to be done to make Python replace JS in Browsers/HTML? (or at least make it a viable alternative to JS) Can the Python community do this without involvment in browser development? Regards Andreas From moky.math at gmail.com Thu Oct 13 06:04:24 2011 From: moky.math at gmail.com (Laurent Claessens) Date: Thu, 13 Oct 2011 12:04:24 +0200 Subject: 1/2 evaluates to 0 In-Reply-To: <4e95806c$0$29986$c3e8da3$5496439d@news.astraweb.com> References: <4e95806c$0$29986$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E96B7A8.5050203@gmail.com> >>> Wohaw. This means that this behavior is going to be default in a >>> foreseeable future ? >> >> It's the default in 3.x. I can't imagine it ever being the default in 2.x. > > > 2.7 is now in "bug-fix only" mode, so no new features, and there won't be a > 2.8, so true division will never be the default in 2.x. Thanks all for your ansers. I'll import division from __future__ Most of what I'm using in Python is with Sage[1]. Thus I'm not about to step to 3.x :( Laurent [1] www.sagemath.org From rosuav at gmail.com Thu Oct 13 06:07:09 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Oct 2011 21:07:09 +1100 Subject: Opportunity missed by Python ? In-Reply-To: <4e96b324$0$1007$426a34cc@news.free.fr> References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: On Thu, Oct 13, 2011 at 8:45 PM, candide wrote: > Dart is the very new language created by Google to replace Javascript. > So Python was not able to do the job? Or may be they don't know about Python > at Google ;) ? > Python, as I found out to my detriment, is practically impossible to sandbox effectively. Any language that hopes to gain full traction in a browser-based environment MUST be secure against scripts gaining too much control over the browser chrome. Also, Dart is looking to support (optional) strict typing, which Python doesn't do. That's a fairly major performance enhancement. ChrisA From rosuav at gmail.com Thu Oct 13 06:09:31 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 13 Oct 2011 21:09:31 +1100 Subject: Embedding a "frame" into a movie using python In-Reply-To: <11518268.545.1318495896114.JavaMail.geo-discussion-forums@vbat14> References: <18514149.192.1318444071734.JavaMail.geo-discussion-forums@vbbfh29> <11518268.545.1318495896114.JavaMail.geo-discussion-forums@vbat14> Message-ID: On Thu, Oct 13, 2011 at 7:51 PM, J <1jason.whatford at gmail.com> wrote: > thank you for your response. I am format agnostic for processing so am happy to work with avi etc., however in displaying the final film to the user I think I'd need to convert whatever I've made to swf to make it a little less downloadable. I'll check out PiTiVi - perhaps I can hack it to work on the back of appengine... SWF is just as downloadable as any other format. I recommend doing the fewest translations you can get away with, to avoid unnecessary loss of quality. ChrisA From tjreedy at udel.edu Thu Oct 13 06:45:04 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Oct 2011 06:45:04 -0400 Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: On 10/13/2011 6:07 AM, Chris Angelico wrote: > On Thu, Oct 13, 2011 at 8:45 PM, candide wrote: >> Dart is the very new language created by Google to replace Javascript. >> So Python was not able to do the job? Or may be they don't know about Python >> at Google ;) ? >> > > Python, as I found out to my detriment, is practically impossible to > sandbox effectively. Any language that hopes to gain full traction in > a browser-based environment MUST be secure against scripts gaining too > much control over the browser chrome. I believe there was some idea of translating Dart into Javascript, which can be done with Python also (Pyjamas). > > Also, Dart is looking to support (optional) strict typing, which > Python doesn't do. That's a fairly major performance enhancement. Cython support optional typing. -- Terry Jan Reedy From clp2 at rebertia.com Thu Oct 13 07:12:14 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 13 Oct 2011 04:12:14 -0700 Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: On Thu, Oct 13, 2011 at 3:07 AM, Chris Angelico wrote: > On Thu, Oct 13, 2011 at 8:45 PM, candide wrote: >> Dart is the very new language created by Google to replace Javascript. >> So Python was not able to do the job? Or may be they don't know about Python >> at Google ;) ? >> > > Python, as I found out to my detriment, is practically impossible to > sandbox effectively. Any language that hopes to gain full traction in > a browser-based environment MUST be secure against scripts gaining too > much control over the browser chrome. > > Also, Dart is looking to support (optional) strict typing, which > Python doesn't do. That's a fairly major performance enhancement. Actually, they can't use it as much more than an optimization hint, per their own spec (see Sec 13.1 of the draft): "Static type annotations are used during static checking and when running programs in checked mode. They have no effect whatsoever in production mode. [...] A Dart implementation must provide a static checker that detects and reports exactly those situations this specification identifies as static warnings. However: ? Running the static checker on a program P is not required for compiling and running P. ? Running the static checker on a program P must not prevent successful compilation of P nor may it prevent the execution of P, regardless of whether any static warnings occur." Cheers, Chris -- http://rebertia.com From duncan.booth at invalid.invalid Thu Oct 13 07:20:21 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Oct 2011 11:20:21 GMT Subject: Opportunity missed by Python ? References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: candide wrote: > Dart is the very new language created by Google to replace Javascript. > So Python was not able to do the job? Or may be they don't know about > Python at Google ;) ? I take it you haven't actually looked at the Dart tools then? They're largely written in Python. -- Duncan Booth http://kupuguy.blogspot.com From anssi.kaariainen at thl.fi Thu Oct 13 07:25:52 2011 From: anssi.kaariainen at thl.fi (=?iso-8859-1?Q?K=E4=E4ri=E4inen_Anssi?=) Date: Thu, 13 Oct 2011 14:25:52 +0300 Subject: Dynamically altering __init__ Message-ID: Hello all, I am trying to alter the init method of a class by source to AST -> alter AST -> AST back to code -> f = types.FunctionType(code, {}, '__init__') -> mt = types.MethodType(f, None, Foo) -> Foo.__init__ = mt I have two problems, first I haven't yet figured out how to make the AST back to code, so that it will be accepted by types.FunctionType. Also, I can't make the Foo.__init__ be callable with arguments. Here is an example without using AST: class Foo(object): def __init__(self): pass src = """ def my_init_func(self, *args): print "here" """ class Foo(object): pass import parser import types st = parser.suite(src) dyn_func = parser.compilest(st) f = types.FunctionType(dyn_func, {}, '__init__') im = types.MethodType(f, None, Foo) Foo() Foo.__init__ = im Foo(1, 2, 3) The result is: TypeError: () takes no arguments (4 given). I have figured out that when I call f(), I am actually executing the src as is, not the defined function in the src. But I can't figure out how to get a reference to my_init_func. You might be wondering why I am doing this. I am trying to rewrite this: class Foo(object): attrs = ['spam', 'eggs'] def __init__(self, *args): for attname, val in izip(Foo.attrs, args): setattr(self, attname, val) into this: ... def __init__(self, *args): self.spam, self.eggs = args This is done for performance reasons. There is about 2x difference when creating 10000 objects. While it is a nice improvement, this is still mostly just for learning purposes. If you can help me it would be great. I am probably doing a lot of things wrong, but there isn't too much information available about these shorts of things. Link to example code would be perfect. - Anssi K??ri?inen From ydrocourt at gmail.com Thu Oct 13 08:00:39 2011 From: ydrocourt at gmail.com (yo) Date: Thu, 13 Oct 2011 05:00:39 -0700 (PDT) Subject: Python gp.ListFeatureClasses return only one file Message-ID: <6ef915f7-6419-41e1-bb0f-83cddad33300@f11g2000yqf.googlegroups.com> Hi All, I m using the gp.ListFeatureClasses to make a list of file in my directory (containing several hundreds of file) however when I print the variable in which the List is supposed to be stored, the print just return one file name.... does any one have an idea???? # Import system modules import sys, string, os, arcgisscripting, glob, arcpy # Create the Geoprocessor object gp = arcgisscripting.create() # define the workspace gp.Workspace = r"F:\front\shp_Files\calving_front" # list the file in the workspace try: shpList = gp.ListFeatureClasses("*.shp") shp = shpList.Next() print shp except: print arcpy.GetMessages() # allows to get error message when they happen From martin.hellwig at gmail.com Thu Oct 13 08:35:30 2011 From: martin.hellwig at gmail.com (Martin P. Hellwig) Date: Thu, 13 Oct 2011 13:35:30 +0100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) Message-ID: First of all let me say that I have no authority or knowledge of language design or multi-processing except from a user point of view, having a decade or so experience. I would like your opinion and appreciate any feedback and value any hints to documentation, procedures or related ramblings :-). I was wondering if there could be an advantage to add another control flow statement. For the purpose of this writing let's say "ooo" which stands for 'out of order'. For example; def do_something(): a = 4 b = 2 c = 1 ooo: a += 1 b += 2 c += 3 print(a, b, c) What I would expect to happen that all statements within the ooo block may be executed out of order. The block itself waits till all statements are returned before continuing. What do you think? From sigmundv at gmail.com Thu Oct 13 08:50:07 2011 From: sigmundv at gmail.com (SigmundV) Date: Thu, 13 Oct 2011 05:50:07 -0700 (PDT) Subject: 1/2 evaluates to 0 References: <4e95806c$0$29986$c3e8da3$5496439d@news.astraweb.com> <4E96B7A8.5050203@gmail.com> Message-ID: <02dcde33-1b25-4a46-8cb6-65bfccc007e8@n18g2000vbv.googlegroups.com> On Oct 13, 10:04?am, Laurent Claessens wrote: > Thanks all for your ansers. I'll import division from __future__ > Most of what I'm using in Python is with Sage[1]. Thus I'm not about to > step to 3.x :( You should get in touch with the Sage developers. In the Sage FAQ they say that "until SciPy is ported to run with Python 3.x and Cython supports Python 3.x, Sage will continue to use Python 2.x." However, both SciPy and Cython are currently compatible with Python 3.2. From the Cython FAQ: "As of 0.14, the Cython compiler runs in all Python versions from 2.3 to 3.2 inclusive." NumPy has supported Python 3 since version 1.5.0. From the release notes: "This is the first NumPy release which is compatible with Python 3." SciPy has supported Python 3 since version 0.9.0. From the release notes: "Scipy 0.9.0 is the first SciPy release to support Python 3. The only module that is not yet ported is ``scipy.weave``." So according to the Sage FAQ there is no reason why Sage shouldn't support Python 3. Sigmund From rosuav at gmail.com Thu Oct 13 09:09:13 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Oct 2011 00:09:13 +1100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: References: Message-ID: On Thu, Oct 13, 2011 at 11:35 PM, Martin P. Hellwig wrote: > What I would expect to happen that all statements within the ooo block may > be executed out > of order. The block itself waits till all statements are returned before > continuing. > In a statically-typed language such as C, this can be done by an optimizing compiler, without any hints from the programmer. But in Python, what you're looking for is either a guarantee from the programmer that none of the statements has a side effect that affects any other, or that you're prepared to wear it and have a horrendous debugging job if anyone monkey-patches your code or you do anything that makes a, b, or c into something more complex than an integer. ChrisA From andreas.perstinger at gmx.net Thu Oct 13 09:49:23 2011 From: andreas.perstinger at gmx.net (Andreas Perstinger) Date: Thu, 13 Oct 2011 15:49:23 +0200 Subject: Python gp.ListFeatureClasses return only one file In-Reply-To: <6ef915f7-6419-41e1-bb0f-83cddad33300@f11g2000yqf.googlegroups.com> References: <6ef915f7-6419-41e1-bb0f-83cddad33300@f11g2000yqf.googlegroups.com> Message-ID: <4E96EC63.1060306@gmx.net> On 2011-10-13 14:00, yo wrote: > Hi All, > I m using the gp.ListFeatureClasses to make a list of file in my > directory (containing several hundreds of file) > however when I print the variable in which the List is supposed to be > stored, the print just return one file name.... > does any one have an idea???? Depending on the version you are using, "ListFeatureClasses()" returns either a list or an enumeration object: http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=ListFeatureClasses_method You are just printing the first item. To print all, something like the following should work (assuming you are using version 9.2): shpList = gp.ListFeatureClasses("*.shp") shp = shpList.Next() while shp: print shp shp = shpList.Next() Bye, Andreas From alain at dpt-info.u-strasbg.fr Thu Oct 13 09:59:58 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Thu, 13 Oct 2011 15:59:58 +0200 Subject: Opportunity missed by Python ? References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: <87vcrtuh41.fsf@dpt-info.u-strasbg.fr> Chris Angelico writes: > On Thu, Oct 13, 2011 at 8:45 PM, candide wrote: >> Dart is the very new language created by Google to replace Javascript. >> So Python was not able to do the job? Or may be they don't know about Python >> at Google ;) ? > > Python, as I found out to my detriment, is practically impossible to > sandbox effectively. Any language that hopes to gain full traction in > a browser-based environment MUST be secure against scripts gaining too > much control over the browser chrome. A first step in that direction would be to have a specification for a python virtual machine. I guess engineers at Google know very well the limitations of Python in its current state. After all, python's inventor works there. Also, they've tried the optimization road with unladden-swallow. And failed. > Also, Dart is looking to support (optional) strict typing, which > Python doesn't do. That's a fairly major performance enhancement. I think you're absolutely right. They've already included a "better DOM". The use of typing will let them provide a very efficient standard library. I am willing to bet that Google's next step will be to provide a plugin/extension/whatever to directly execute Dart programs in the browsers. And then a JIT compiler inside the VM. And then everybody will want to move, for performance reason. All the Javascript compatibility is transitional stuff. -- Alain. From stefan_ml at behnel.de Thu Oct 13 10:13:27 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 13 Oct 2011 16:13:27 +0200 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: References: Message-ID: Martin P. Hellwig, 13.10.2011 14:35: > I was wondering if there could be an advantage to add another control flow > statement. Changes at that level must be very well justified, are often rejected for the reason of being not too complicated to write in some other form and are close to impossible to get accepted when requiring a new keyword. Also, the right place to discuss (and, more importantly, search for previous) ideas about language changes is the python-ideas mailing list. > For the purpose of this writing let's say "ooo" which stands for 'out of > order'. > > For example; > > def do_something(): > a = 4 > b = 2 > c = 1 > ooo: > a += 1 > b += 2 > c += 3 > print(a, b, c) > > What I would expect to happen that all statements within the ooo block may > be executed out > of order. The block itself waits till all statements are returned before > continuing. This looks like a rather special case. What if you need more than one statement to accomplish a single step? What if the number of parallel tasks is not fixed at coding time? I don't think there are many problems that you can solve with this feature. Also: the GIL will not allow you to take a major advantage from the parallel execution of a set of statements, as only one of the statements can use the interpreter at a time. And, on a related note: Cython has freshly gained support for parallel loops based on OpenMP, so you may be able to solve your problem with Cython instead of using plain Python. Stefan From jkn_gg at nicorp.f9.co.uk Thu Oct 13 10:33:27 2011 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Thu, 13 Oct 2011 07:33:27 -0700 (PDT) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: Message-ID: <07d3c24c-608c-4721-8fce-2b0c2a96493e@u2g2000yqc.googlegroups.com> FWIW, this looks rather like the 'PAR' construct of Occam to me. http://en.wikipedia.org/wiki/Occam_%28programming_language%29 J^n From tim at akwebsoft.com Thu Oct 13 11:22:49 2011 From: tim at akwebsoft.com (Tim Johnson) Date: Thu, 13 Oct 2011 07:22:49 -0800 Subject: MySQLdb on Mac Lion In-Reply-To: References: <20111013005244.GK6671@johnsons-web.com> Message-ID: <20111013152249.GL6671@johnsons-web.com> * Ned Deily [111012 18:12]: > In article <20111013005244.GK6671 at johnsons-web.com>, > Tim Johnson wrote: > > I'm most experienced with MySQLdb on ubuntu, which is installed via > > apt-get or synaptic. > > > > I am setting up a mac mini with osX 10.7 (Lion). Macports makes > > py27-mysql 1.2.2 available, but are there any .dmg packages > > available? > > I strongly recommend you stick with MacPorts or Homebrew. There are too > many things that can go wrong on OS X 10.6 or 10.7 if you try to install > MySQL client libraries, MySQLdb, and Python from different places. IME, > the binary installers for OS X provided by the MySQL are inconsistently > built between versions and often need the library paths need to be > tweaked. The only major drawback of using MacPorts is that it will > download (and possibly build) its own version of Python but it's a small > price to pay: search the archives of Stackoverflow to see how > dismayingly often this topic comes up. Thanks for that Ned. -- Tim tim at tee jay forty nine dot com or akwebsoft dot com http://www.akwebsoft.com From anikom15 at gmail.com Thu Oct 13 12:10:45 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 13 Oct 2011 09:10:45 -0700 Subject: Opportunity missed by Python ? In-Reply-To: <4e96b324$0$1007$426a34cc@news.free.fr> References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: <20111013161045.GA4100@Smoke> On Thu, Oct 13, 2011 at 11:45:06AM +0200, candide wrote: > Dart is the very new language created by Google to replace Javascript. > So Python was not able to do the job? Or may be they don't know > about Python at Google ;) ? Google's a big supporter for Python...I think Guido working being employed there has something to do with it, but I could be conspiring. Python is not an appropriate language for client-side web scripts, it's just too good for such a lowly job. ;) From anikom15 at gmail.com Thu Oct 13 12:12:44 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 13 Oct 2011 09:12:44 -0700 Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: <20111013161244.GB4100@Smoke> On Thu, Oct 13, 2011 at 09:07:09PM +1100, Chris Angelico wrote: > On Thu, Oct 13, 2011 at 8:45 PM, candide wrote: > > Dart is the very new language created by Google to replace Javascript. > > So Python was not able to do the job? Or may be they don't know about Python > > at Google ;) ? > > > > Python, as I found out to my detriment, is practically impossible to > sandbox effectively. Any language that hopes to gain full traction in > a browser-based environment MUST be secure against scripts gaining too > much control over the browser chrome. > > Also, Dart is looking to support (optional) strict typing, which > Python doesn't do. That's a fairly major performance enhancement. > > ChrisA You mean static typing? From moky.math at gmail.com Thu Oct 13 12:31:39 2011 From: moky.math at gmail.com (Laurent Claessens) Date: Thu, 13 Oct 2011 18:31:39 +0200 Subject: 1/2 evaluates to 0 In-Reply-To: <02dcde33-1b25-4a46-8cb6-65bfccc007e8@n18g2000vbv.googlegroups.com> References: <4e95806c$0$29986$c3e8da3$5496439d@news.astraweb.com> <4E96B7A8.5050203@gmail.com> <02dcde33-1b25-4a46-8cb6-65bfccc007e8@n18g2000vbv.googlegroups.com> Message-ID: <4E97126B.2090504@gmail.com> > You should get in touch with the Sage developers. In the Sage FAQ they > say that "until SciPy is ported to run with Python 3.x and Cython > supports Python 3.x, Sage will continue to use Python 2.x." ``scipy.weave``." > > So according to the Sage FAQ there is no reason why Sage shouldn't > support Python 3. Maybe the FAQ is not up to date. Nowadays the reason for not stepping to 3.x is "manpower" ;) (this question comes back two or three times a year on the Sages' list. Next time the question arises, I'll point out your remark) Scipy and Cython are just two of the biggest python parts in Sage, but there are many others ... 'till sage itself. Have a good afternoon Laurent From ian.g.kelly at gmail.com Thu Oct 13 13:14:23 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 13 Oct 2011 11:14:23 -0600 Subject: Dynamically altering __init__ In-Reply-To: References: Message-ID: 2011/10/13 K??ri?inen Anssi : > import parser > import types > st = parser.suite(src) > dyn_func = parser.compilest(st) > f = types.FunctionType(dyn_func, {}, '__init__') > im = types.MethodType(f, None, Foo) > Foo() > Foo.__init__ = im > Foo(1, 2, 3) > > The result is: TypeError: () takes no arguments (4 given). I have > figured out that when I call f(), I am actually executing the src as is, not > the defined function in the src. But I can't figure out how to get a > reference to my_init_func. You can either pull the function code object out of the module code object constants: ... st_code = parser.compilest(st) func_code = st_code.co_consts[0] f = types.FunctionType(func_code, {}, '__init__') ... But you should take care to ensure that the function code object actually is the first constant. Or you can just exec your suite and pull the function from its globals. src_globals = {} exec src in src_globals my_init_func = src_globals['my_init_func'] Cheers, Ian From anssi.kaariainen at thl.fi Thu Oct 13 14:00:39 2011 From: anssi.kaariainen at thl.fi (=?iso-8859-1?Q?K=E4=E4ri=E4inen_Anssi?=) Date: Thu, 13 Oct 2011 21:00:39 +0300 Subject: Dynamically altering __init__ In-Reply-To: References: , Message-ID: Ian Kelly wrote: """ You can either pull the function code object out of the module code object constants: ... st_code = parser.compilest(st) func_code = st_code.co_consts[0] f = types.FunctionType(func_code, {}, '__init__') ... But you should take care to ensure that the function code object actually is the first constant. Or you can just exec your suite and pull the function from its globals. src_globals = {} exec src in src_globals my_init_func = src_globals['my_init_func'] """ Thank you very much. I will post a link to a complete example once I have done the AST transformations etc. I hope this will be useful to readers of this list. I didn't find such an example, so maybe the next asker will find it... And when I inevitably do something the wrong way in my example, I am sure you will correct me :) However, this might take some time before ready, I am new to this stuff. If there is already an example somewhere, that would be really helpful to me. Just a quick note, I tested this on Python2.6, and got around 2.3 seconds per million objects. With an init doing the setattr loop, I got around 4.7 seconds. So the speed difference is there, but as expected, it isn't that big. Python3 had similar results. - Anssi K??ri?inen From martin.hellwig at gmail.com Thu Oct 13 16:20:13 2011 From: martin.hellwig at gmail.com (Martin P. Hellwig) Date: Thu, 13 Oct 2011 21:20:13 +0100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: References: Message-ID: On 13/10/2011 15:13, Stefan Behnel wrote: > Martin P. Hellwig, 13.10.2011 14:35: >> I was wondering if there could be an advantage to add another control >> flow >> statement. > > Changes at that level must be very well justified, are often rejected > for the reason of being not too complicated to write in some other form > and are close to impossible to get accepted when requiring a new keyword. > > Also, the right place to discuss (and, more importantly, search for > previous) ideas about language changes is the python-ideas mailing list. > > >> For the purpose of this writing let's say "ooo" which stands for 'out of >> order'. >> >> For example; >> >> def do_something(): >> a = 4 >> b = 2 >> c = 1 >> ooo: >> a += 1 >> b += 2 >> c += 3 >> print(a, b, c) >> >> What I would expect to happen that all statements within the ooo block >> may >> be executed out >> of order. The block itself waits till all statements are returned before >> continuing. > > This looks like a rather special case. What if you need more than one > statement to accomplish a single step? Aah yes haven't thought about that, was more thinking like wrap multiple steps in a function and put that as one line, but yeah that kind of stuff gets very unpythonic very quickly. > What if the number of parallel > tasks is not fixed at coding time? I don't think there are many problems > that you can solve with this feature. > > Also: the GIL will not allow you to take a major advantage from the > parallel execution of a set of statements, as only one of the statements > can use the interpreter at a time. Well I was more or less thinking in the line that the interpreter when parsing such a statement can, if there are multiple cpu's available, fire the appropriate amount of other interpreters and do all the passing and locking of data for you. > > And, on a related note: Cython has freshly gained support for parallel > loops based on OpenMP, so you may be able to solve your problem with > Cython instead of using plain Python. > Well funny enough I don't really have a problem with it, I am a happy consumer of multiprocessing, but I was just wondering if there would be a way to do it simpler and more pythonic. > Stefan > Thanks for your feedback it was very enlightening although for what the idea is concerned disappointing as it more or less makes it obvious that such a thing is a no-go. Cheers, Martin From bc at freeuk.com Thu Oct 13 17:38:43 2011 From: bc at freeuk.com (BartC) Date: Thu, 13 Oct 2011 22:38:43 +0100 Subject: Opportunity missed by Python ? In-Reply-To: <4e96b324$0$1007$426a34cc@news.free.fr> References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: "candide" wrote in message news:4e96b324$0$1007$426a34cc at news.free.fr... > Dart is the very new language created by Google to replace Javascript. > So Python was not able to do the job? Or may be they don't know about > Python at Google ;) ? The entire resources of Google available, and they re-invent C! https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/client/samples/spirodraw/Spirodraw.dart -- Bartc From rosuav at gmail.com Thu Oct 13 17:45:23 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 14 Oct 2011 08:45:23 +1100 Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: On Fri, Oct 14, 2011 at 8:38 AM, BartC wrote: > The entire resources of Google available, and they re-invent C! Syntactically, C has a lot going for it. If you want to invent a new language and have developers grok it easily, borrowing syntax from C will help a lot. But in this case, I think the derivation is from JavaScript (which itself derives from C), making Dart a more-similar replacement. ChrisA From tdsimpson at gmail.com Thu Oct 13 17:59:22 2011 From: tdsimpson at gmail.com (MrPink) Date: Thu, 13 Oct 2011 14:59:22 -0700 (PDT) Subject: Reading a file into a data structure.... Message-ID: This is a continuing to a post I made in August: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b072cfadf998deae/ce6d4d09911e4107?lnk=gst&q=MrPink#ce6d4d09911e4107 I got some free time to work with Python again and have some followup questions. For example, I have a list in a text file like this: Example list of lottery drawings: date,wb,wb,wb,wb,wb,bb 4/1/2011,5,1,45,23,27,27 5/1/2011,15,23,8,48,22,32 6/1/2011,33,49,21,16,34,1 7/1/2011,9,3,13,22,45,41 8/1/2011,54,1,24,39,35,18 .... Ticket: startdate,enddate,wb,wb,wb,wb,wb,bb 4/1/2011,8/1/2011,5,23,32,21,3,27 I am trying to determine the optimal way to organize the data structure of the drawing list, search the drawing list, and mark the matches in the drawing list. f = open("C:\temp\drawinglist.txt", "r") lines = f.readlines() f.close() drawing = lines[1].split() The results in drawing is this: drawing[0] = '4/1/2011' drawing[1] = '5' drawing[2] = '1' drawing[3] = '45' drawing[4] = '23' drawing[5] = '27' drawing[6] = '27' I need to convert drawing[0] to a date datatype. This works, but I'm sure there is a better way. from datetime import date month, day, year = drawing[0].split('/') drawing[0] = date(int(year), int(month), int(day)) For searching, I need to determine if the date of the drawing is within the date range of the ticket. If yes, then mark which numbers in the drawing match the numbers in the ticket. ticket[0] = '4/1/2011' ticket[0] = '8/1/2011' ticket[0] = '5' ticket[0] = '23' ticket[0] = '32' ticket[0] = '21' ticket[0] = '3' ticket[0] = 27' drawing[0] = '4/1/2011' (match) drawing[1] = '5' (match) drawing[2] = '1' drawing[3] = '45' drawing[4] = '23' (match) drawing[5] = '27' drawing[6] = '27' (match) I'm debating on structuring the drawing list like this: drawing[0] = '4/1/2011' drawing[1][0] = '5' drawing[1][1] = '1' drawing[1][2] = '45' drawing[1][3] = '23' drawing[1][4] = '27' drawing[2] = '27' Sort drawing[1] from low to high drawing[1][0] = '1' drawing[1][1] = '5' drawing[1][2] = '23' drawing[1][3] = '27' drawing[1][4] = '45' I want to keep the drawing list in memory for reuse. Any guidance would be most helpful and appreciated. BTW, I want to learn, so be careful not to do too much of the work for me. I'm using WingIDE to do my work. Thanks, From dihedral88888 at googlemail.com Thu Oct 13 18:05:55 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Thu, 13 Oct 2011 15:05:55 -0700 (PDT) Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: <21380825.697.1318543555990.JavaMail.geo-discussion-forums@prdw1> As long as there are tools to translate scripts or source code between the two languages. More new evolved powerful programming languages arenot problems at all for experienced programmers. From dihedral88888 at googlemail.com Thu Oct 13 18:05:55 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Thu, 13 Oct 2011 15:05:55 -0700 (PDT) Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: <21380825.697.1318543555990.JavaMail.geo-discussion-forums@prdw1> As long as there are tools to translate scripts or source code between the two languages. More new evolved powerful programming languages arenot problems at all for experienced programmers. From nhodgson at iinet.net.au Thu Oct 13 18:21:31 2011 From: nhodgson at iinet.net.au (Neil Hodgson) Date: Fri, 14 Oct 2011 09:21:31 +1100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: <07d3c24c-608c-4721-8fce-2b0c2a96493e@u2g2000yqc.googlegroups.com> References: <07d3c24c-608c-4721-8fce-2b0c2a96493e@u2g2000yqc.googlegroups.com> Message-ID: <6-ednfDRIusm-QrTnZ2dnUVZ_uednZ2d@westnet.com.au> jkn: > FWIW, this looks rather like the 'PAR' construct of Occam to me. > > http://en.wikipedia.org/wiki/Occam_%28programming_language%29 Earlier than that, 'par' is from Algol 68: http://en.wikipedia.org/wiki/ALGOL_68#par:_Parallel_processing Neil From rhodri at wildebst.demon.co.uk Thu Oct 13 18:21:48 2011 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Thu, 13 Oct 2011 23:21:48 +0100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: <07d3c24c-608c-4721-8fce-2b0c2a96493e@u2g2000yqc.googlegroups.com> Message-ID: On Thu, 13 Oct 2011 15:33:27 +0100, jkn wrote: > FWIW, this looks rather like the 'PAR' construct of Occam to me. > > http://en.wikipedia.org/wiki/Occam_%28programming_language%29 I was going to say the same thing. Occam's answer to Stefan's question about what to do if you want more than one statement executed per step was to wrap sequences of statements in a SEQ construct. You end up indenting a long way very fast if you aren't careful. I'm afraid much as I love PAR, Python's dynamicism makes it rather more 'exciting' than it was in occam. -- Rhodri James *-* Wildebeest Herder to the Masses From ian.g.kelly at gmail.com Thu Oct 13 18:28:24 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 13 Oct 2011 16:28:24 -0600 Subject: Reading a file into a data structure.... In-Reply-To: References: Message-ID: On Thu, Oct 13, 2011 at 3:59 PM, MrPink wrote: > This is a continuing to a post I made in August: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/b072cfadf998deae/ce6d4d09911e4107?lnk=gst&q=MrPink#ce6d4d09911e4107 > > I got some free time to work with Python again and have some followup > questions. > > For example, I have a list in a text file like this: > Example list of lottery drawings: > date,wb,wb,wb,wb,wb,bb > 4/1/2011,5,1,45,23,27,27 > 5/1/2011,15,23,8,48,22,32 > 6/1/2011,33,49,21,16,34,1 > 7/1/2011,9,3,13,22,45,41 > 8/1/2011,54,1,24,39,35,18 > .... > > Ticket: > startdate,enddate,wb,wb,wb,wb,wb,bb > 4/1/2011,8/1/2011,5,23,32,21,3,27 > > I am trying to determine the optimal way to organize the data > structure of the drawing list, search the drawing list, and mark the > matches in the drawing list. > > f = open("C:\temp\drawinglist.txt", "r") > lines = f.readlines() > f.close() > drawing = lines[1].split() That looks like a CSV file. If the contents are tightly constrained then it may not matter, but if not then you should consider using the csv module to read the lines, which will handle inconvenient details like quoting and escape characters for you. > I need to convert drawing[0] to a date datatype. ?This works, but I'm > sure there is a better way. > from datetime import date > month, day, year = drawing[0].split('/') > drawing[0] = date(int(year), int(month), int(day)) If you already know the format: from datetime import datetime drawing[0] = datetime.strptime(drawing[0], '%m/%d/%Y').date() If you can't be sure of the format, then I recommend using the python-dateutil parser.parse() function, which will try to work it out on the fly. From joncle at googlemail.com Thu Oct 13 19:42:22 2011 From: joncle at googlemail.com (Jon Clements) Date: Thu, 13 Oct 2011 16:42:22 -0700 (PDT) Subject: Reading a file into a data structure.... References: Message-ID: On Oct 13, 10:59?pm, MrPink wrote: > This is a continuing to a post I made in August:http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > I got some free time to work with Python again and have some followup > questions. > > For example, I have a list in a text file like this: > Example list of lottery drawings: > date,wb,wb,wb,wb,wb,bb > 4/1/2011,5,1,45,23,27,27 > 5/1/2011,15,23,8,48,22,32 > 6/1/2011,33,49,21,16,34,1 > 7/1/2011,9,3,13,22,45,41 > 8/1/2011,54,1,24,39,35,18 > .... > > Ticket: > startdate,enddate,wb,wb,wb,wb,wb,bb > 4/1/2011,8/1/2011,5,23,32,21,3,27 > > I am trying to determine the optimal way to organize the data > structure of the drawing list, search the drawing list, and mark the > matches in the drawing list. > > f = open("C:\temp\drawinglist.txt", "r") > lines = f.readlines() > f.close() > drawing = lines[1].split() > > The results in drawing is this: > drawing[0] = '4/1/2011' > drawing[1] = '5' > drawing[2] = '1' > drawing[3] = '45' > drawing[4] = '23' > drawing[5] = '27' > drawing[6] = '27' > > I need to convert drawing[0] to a date datatype. ?This works, but I'm > sure there is a better way. > from datetime import date > month, day, year = drawing[0].split('/') > drawing[0] = date(int(year), int(month), int(day)) > > For searching, I need to determine if the date of the drawing is > within the date range of the ticket. ?If yes, then mark which numbers > in the drawing match the numbers in the ticket. > > ticket[0] = '4/1/2011' > ticket[0] = '8/1/2011' > ticket[0] = '5' > ticket[0] = '23' > ticket[0] = '32' > ticket[0] = '21' > ticket[0] = '3' > ticket[0] = 27' > > drawing[0] = '4/1/2011' (match) > drawing[1] = '5' (match) > drawing[2] = '1' > drawing[3] = '45' > drawing[4] = '23' (match) > drawing[5] = '27' > drawing[6] = '27' (match) > > I'm debating on structuring the drawing list like this: > drawing[0] = '4/1/2011' > drawing[1][0] = '5' > drawing[1][1] = '1' > drawing[1][2] = '45' > drawing[1][3] = '23' > drawing[1][4] = '27' > drawing[2] = '27' > > Sort drawing[1] from low to high > drawing[1][0] = '1' > drawing[1][1] = '5' > drawing[1][2] = '23' > drawing[1][3] = '27' > drawing[1][4] = '45' > > I want to keep the drawing list in memory for reuse. > > Any guidance would be most helpful and appreciated. > BTW, I want to learn, so be careful not to do too much of the work for > me. > I'm using WingIDE to do my work. > > Thanks, - Use the csv module to read the file - Use strptime to process the date field - Use a set for draw numbers (you'd have to do pure equality on the bb) - Look at persisting in a sqlite3 DB (maybe with a custom convertor) hth, Jon. From dihedral88888 at googlemail.com Thu Oct 13 20:11:27 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Thu, 13 Oct 2011 17:11:27 -0700 (PDT) Subject: [Python-ideas] Implement comparison operators for range objects In-Reply-To: References: <20111012163144.GB6393@pantoffel-wg.de> <4E95CF7D.6000000@pearwood.info> <4E95D394.9000205@mrabarnett.plus.com> Message-ID: <19444957.1328.1318551088183.JavaMail.geo-discussion-forums@prho12> How about iterable objects supported in python? Is a countable object iterable definitely? Also the tail recursion technique is useful for the same function with few arguments that calls itself. The lisp compiler would emit machine codes with fast jumps and passing arguments in registers or stacks very efficiently. From steve+comp.lang.python at pearwood.info Thu Oct 13 22:16:37 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 14 Oct 2011 13:16:37 +1100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: Message-ID: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> Martin P. Hellwig wrote: > I was wondering if there could be an advantage to add another control > flow statement. > For the purpose of this writing let's say "ooo" which stands for 'out of > order'. [...] > What I would expect to happen that all statements within the ooo block > may be executed out > of order. The block itself waits till all statements are returned before > continuing. Why do you think this needs to be a language statement? You can have that functionality *right now*, without waiting for a syntax update, by use of the multiprocessing module, or a third party module. http://docs.python.org/library/multiprocessing.html http://wiki.python.org/moin/ParallelProcessing There's no need for forcing language changes on everyone, whether they need it or not, for features that can easily be implemented as library code. -- Steven From roy at panix.com Thu Oct 13 22:19:05 2011 From: roy at panix.com (Roy Smith) Date: Thu, 13 Oct 2011 22:19:05 -0400 Subject: Looking for browser emulator Message-ID: I've got to write some tests in python which simulate getting a page of HTML from an http server, finding a link, clicking on it, and then examining the HTML on the next page to make sure it has certain features. I can use urllib to do the basic fetching, and lxml gives me the tools to find the link I want and extract its href attribute. What's missing is dealing with turning the href into an absolute URL that I can give to urlopen(). Browsers implement all sorts of stateful logic such as "if the URL has no hostname, use the same hostname as the current page". I'm talking about something where I can execute this sequence of calls: urlopen("http://foo.com:9999/bar") urlopen("/baz") and have the second one know that it needs to get "http://foo.com:9999/baz". Does anything like that exist? I'm really trying to stay away from Selenium and go strictly with something I can run under unittest. From joncle at googlemail.com Thu Oct 13 22:42:31 2011 From: joncle at googlemail.com (Jon Clements) Date: Thu, 13 Oct 2011 19:42:31 -0700 (PDT) Subject: Looking for browser emulator References: Message-ID: <2323f3d7-42ff-4de5-9006-4741e865f09c@a9g2000yqo.googlegroups.com> On Oct 14, 3:19?am, Roy Smith wrote: > I've got to write some tests in python which simulate getting a page of > HTML from an http server, finding a link, clicking on it, and then > examining the HTML on the next page to make sure it has certain features. > > I can use urllib to do the basic fetching, and lxml gives me the tools > to find the link I want and extract its href attribute. ?What's missing > is dealing with turning the href into an absolute URL that I can give to > urlopen(). ?Browsers implement all sorts of stateful logic such as "if > the URL has no hostname, use the same hostname as the current page". ? > I'm talking about something where I can execute this sequence of calls: > > urlopen("http://foo.com:9999/bar") > urlopen("/baz") > > and have the second one know that it needs to get > "http://foo.com:9999/baz". ?Does anything like that exist? > > I'm really trying to stay away from Selenium and go strictly with > something I can run under unittest. lxml.html.make_links_absolute() ? From joncle at googlemail.com Thu Oct 13 22:43:16 2011 From: joncle at googlemail.com (Jon Clements) Date: Thu, 13 Oct 2011 19:43:16 -0700 (PDT) Subject: Looking for browser emulator References: Message-ID: On Oct 14, 3:19?am, Roy Smith wrote: > I've got to write some tests in python which simulate getting a page of > HTML from an http server, finding a link, clicking on it, and then > examining the HTML on the next page to make sure it has certain features. > > I can use urllib to do the basic fetching, and lxml gives me the tools > to find the link I want and extract its href attribute. ?What's missing > is dealing with turning the href into an absolute URL that I can give to > urlopen(). ?Browsers implement all sorts of stateful logic such as "if > the URL has no hostname, use the same hostname as the current page". ? > I'm talking about something where I can execute this sequence of calls: > > urlopen("http://foo.com:9999/bar") > urlopen("/baz") > > and have the second one know that it needs to get > "http://foo.com:9999/baz". ?Does anything like that exist? > > I'm really trying to stay away from Selenium and go strictly with > something I can run under unittest. lxml.html.make_links_absolute() ? From roy at panix.com Thu Oct 13 22:53:06 2011 From: roy at panix.com (Roy Smith) Date: Thu, 13 Oct 2011 22:53:06 -0400 Subject: Looking for browser emulator References: <2323f3d7-42ff-4de5-9006-4741e865f09c@a9g2000yqo.googlegroups.com> Message-ID: In article <2323f3d7-42ff-4de5-9006-4741e865f09c at a9g2000yqo.googlegroups.com>, Jon Clements wrote: > On Oct 14, 3:19?am, Roy Smith wrote: > > I've got to write some tests in python which simulate getting a page of > > HTML from an http server, finding a link, clicking on it, and then > > examining the HTML on the next page to make sure it has certain features. > > > > I can use urllib to do the basic fetching, and lxml gives me the tools > > to find the link I want and extract its href attribute. ?What's missing > > is dealing with turning the href into an absolute URL that I can give to > > urlopen(). ?Browsers implement all sorts of stateful logic such as "if > > the URL has no hostname, use the same hostname as the current page". ? > > I'm talking about something where I can execute this sequence of calls: > > > > urlopen("http://foo.com:9999/bar") > > urlopen("/baz") > > > > and have the second one know that it needs to get > > "http://foo.com:9999/baz". ?Does anything like that exist? > > > > I'm really trying to stay away from Selenium and go strictly with > > something I can run under unittest. > > lxml.html.make_links_absolute() ? Interesting. That might be exactly what I'm looking for. Thanks! From miki.tebeka at gmail.com Thu Oct 13 23:31:10 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 13 Oct 2011 20:31:10 -0700 (PDT) Subject: Looking for browser emulator In-Reply-To: References: Message-ID: <10390190.52.1318563071117.JavaMail.geo-discussion-forums@prfp13> IIRC mechanize can do that. From gherron at islandtraining.com Thu Oct 13 23:55:31 2011 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 13 Oct 2011 20:55:31 -0700 Subject: Looking for browser emulator In-Reply-To: References: Message-ID: <4E97B2B3.7060505@islandtraining.com> On 10/13/2011 07:19 PM, Roy Smith wrote: > I've got to write some tests in python which simulate getting a page of > HTML from an http server, finding a link, clicking on it, and then > examining the HTML on the next page to make sure it has certain features. > > I can use urllib to do the basic fetching, and lxml gives me the tools > to find the link I want and extract its href attribute. What's missing > is dealing with turning the href into an absolute URL that I can give to > urlopen(). Browsers implement all sorts of stateful logic such as "if > the URL has no hostname, use the same hostname as the current page". > I'm talking about something where I can execute this sequence of calls: > > urlopen("http://foo.com:9999/bar") > urlopen("/baz") > > and have the second one know that it needs to get > "http://foo.com:9999/baz". Does anything like that exist? > > I'm really trying to stay away from Selenium and go strictly with > something I can run under unittest. Try mechanize http://wwwsearch.sourceforge.net/mechanize/ billed as Stateful programmatic web browsing in Python. I handles clicking on links, cookies, logging in/out, and filling in of forms in the same way as a "real" browser, but it's all under programmatic control from Python. In Ubuntu, it's the python-mechanize package. From roy at panix.com Fri Oct 14 00:13:17 2011 From: roy at panix.com (Roy Smith) Date: Fri, 14 Oct 2011 00:13:17 -0400 Subject: Looking for browser emulator References: Message-ID: In article , Gary Herron wrote: > Try mechanize > http://wwwsearch.sourceforge.net/mechanize/ > billed as > Stateful programmatic web browsing in Python. Wow, this is cool, thanks! It even does cookies! From pavlovevidence at gmail.com Fri Oct 14 02:05:26 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 13 Oct 2011 23:05:26 -0700 (PDT) Subject: argparse zero-length switch Message-ID: <17016857.666.1318572326692.JavaMail.geo-discussion-forums@prmi2> Is it possible to specify a zero-length switch? Here's what I mean. I have a use case where some users would have to enter a section name on the command line almost every time, whereas other users (the ones using only one section) will never have to enter the section name. I don't want to burden users with only one "section" to always enter the section name as a required argument, but I also want to make it as convenient as possible to enter the section name for those who need to. My thought, on the thinking that practicality beats purity, was to create a zero-length switch using a different prefix character (say, @) to indicate the section name. So instead of typing this: sp subcommand -s abc foo bar they could type this: sp subcommand @abc foo bar Admittedly a small benefit. I tried the following but argparse doesn't seem to do what I'd hoped: p = argparse.ArgumentParser(prefix_chars='-@') p.add_argument('@',type=str,dest='section') ar = p.parse_args(['@abc']) This throws an exception claiming unrecognized arguments. Is there a way (that's not a hack) to do this? Since the current behavior of the above code seems to do nothing useful, it could be added to argparse with very low risk of backwards incompatibility. Carl Banks From pavlovevidence at gmail.com Fri Oct 14 02:56:20 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 13 Oct 2011 23:56:20 -0700 (PDT) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> Message-ID: <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> On Thursday, October 13, 2011 7:16:37 PM UTC-7, Steven D'Aprano wrote: > > What I would expect to happen that all statements within the ooo block > > may be executed out > > of order. The block itself waits till all statements are returned before > > continuing. > > Why do you think this needs to be a language statement? > > You can have that functionality *right now*, without waiting for a syntax > update, by use of the multiprocessing module, or a third party module. > > http://docs.python.org/library/multiprocessing.html > http://wiki.python.org/moin/ParallelProcessing > > There's no need for forcing language changes on everyone, whether they need > it or not, for features that can easily be implemented as library code. This goes a little beyond a simple threading mechanism, though. It's more like guidance to the compiler that you don't care what order these are executed in; the compiler is then free to take advantage of this advice however it like. That could be to spawn threads, but it could also compile instructions to optimize pipelining and cacheing. The compiler could also ignore it. But you can see that, fully realized, syntax like that can do much more than can be done with library code. Obviously that extra capability is a very long way off for being useful in CPython. Carl Banks From pavlovevidence at gmail.com Fri Oct 14 03:06:15 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 14 Oct 2011 00:06:15 -0700 (PDT) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: References: Message-ID: <6347919.1520.1318575975788.JavaMail.geo-discussion-forums@prng5> On Thursday, October 13, 2011 5:35:30 AM UTC-7, Martin P. Hellwig wrote: > What I would expect to happen that all statements within the ooo block > may be executed out > of order. The block itself waits till all statements are returned before > continuing. > > What do you think? The statement is kind of limiting as a unit of uncaring. What if you have two statements that you do want to be executed in order, but still don't care what order they are executed in relative to other sets of two statements? Better would be to have a set of blocks that the compiler is free to execute asynchronously relative to each other (I'll call it async). async: a += 1 f *= a async: b += 1 e *= b async: c += 1 d *= c There is utterly no chance of this syntax entering Python. Carl Banks From __peter__ at web.de Fri Oct 14 03:41:26 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 14 Oct 2011 09:41:26 +0200 Subject: argparse zero-length switch References: <17016857.666.1318572326692.JavaMail.geo-discussion-forums@prmi2> Message-ID: Carl Banks wrote: > Is it possible to specify a zero-length switch? Here's what I mean. > > I have a use case where some users would have to enter a section name on > the command line almost every time, whereas other users (the ones using > only one section) will never have to enter the section name. I don't want > to burden users with only one "section" to always enter the section name > as a required argument, but I also want to make it as convenient as > possible to enter the section name for those who need to. > > My thought, on the thinking that practicality beats purity, was to create > a zero-length switch using a different prefix character (say, @) to > indicate the section name. So instead of typing this: > > sp subcommand -s abc foo bar > > they could type this: > > sp subcommand @abc foo bar > > Admittedly a small benefit. I tried the following but argparse doesn't > seem to do what I'd hoped: > > p = argparse.ArgumentParser(prefix_chars='-@') > p.add_argument('@',type=str,dest='section') > ar = p.parse_args(['@abc']) > > This throws an exception claiming unrecognized arguments. > > Is there a way (that's not a hack) to do this? Since the current behavior > of the above code seems to do nothing useful, it could be added to > argparse with very low risk of backwards incompatibility. If the number of positional arguments is otherwise fixed you could make section a positional argument with nargs="?" >>> import argparse >>> parser = argparse.ArgumentParser() >>> _ = parser.add_argument("section", nargs="?") >>> _ = parser.add_argument("foo") >>> _ = parser.add_argument("bar") >>> parser.parse_args(["alpha", "beta"]) Namespace(bar='beta', foo='alpha', section=None) >>> parser.parse_args(["alpha", "beta", "gamma"]) Namespace(bar='gamma', foo='beta', section='alpha') From librarama at gmail.com Fri Oct 14 03:45:14 2011 From: librarama at gmail.com (Libra) Date: Fri, 14 Oct 2011 00:45:14 -0700 (PDT) Subject: Graph editor Message-ID: <7ce425e6-0831-4c71-a2e1-d6f6d0b4ee4b@o19g2000vbk.googlegroups.com> Hi, I would like to build a simple graph editor, allowing me to add nodes and edges via the mouse, along with the possibility to edit it (delete/ move nodes and edges, double click on object to pop-up a form where I can insert object related info, and so forth) and bind edges to nodes (that is, when I move a node, the attached edges move accordingly). I should also put an image (a bitmap of png) in the background of the graph. I've seen many GUI libraries (from TkInter to wxPython) but I was wondering if there is a specific graphic library (with good documentation and maybe examples) simplifying the rapid development of such an application. Thanks Libra From peter.marczis at nsn.com Fri Oct 14 04:19:31 2011 From: peter.marczis at nsn.com (Peter G. Marczis) Date: Fri, 14 Oct 2011 11:19:31 +0300 Subject: Fwd: os.statvfs bug or my incompetence ? In-Reply-To: <4E97DB66.50302@nsn.com> References: <4E97DB66.50302@nsn.com> Message-ID: <4E97F093.4000203@nsn.com> An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Fri Oct 14 05:33:49 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 14 Oct 2011 20:33:49 +1100 Subject: argparse zero-length switch References: <17016857.666.1318572326692.JavaMail.geo-discussion-forums@prmi2> Message-ID: <87pqhzvrwi.fsf@benfinney.id.au> Carl Banks writes: > I have a use case where some users would have to enter a section name > on the command line almost every time, whereas other users (the ones > using only one section) will never have to enter the section name. Sounds like a typical case where you want an option that takes an argument, with a default for when the option is not specified. As you probably know, ?argparse? already handles this fine. > I don't want to burden users with only one "section" to always enter > the section name as a required argument, but I also want to make it as > convenient as possible to enter the section name for those who need > to. Yes. The latter need only specify the section explicitly, with ?-s foo? or whatever. > My thought, on the thinking that practicality beats purity, was to > create a zero-length switch using a different prefix character (say, > @) to indicate the section name. So instead of typing this: > > sp subcommand -s abc foo bar What's wrong with that? That's a normal way to do it, consistent with other command-line interfaces. Why deviate from that? > they could type this: > > sp subcommand @abc foo bar > > Admittedly a small benefit. I don't see the benefit of that which would be worth teaching that unconventional command-line syntax. -- \ ?Two paradoxes are better than one; they may even suggest a | `\ solution.? ?Edward Teller | _o__) | Ben Finney From atalucas at gmail.com Fri Oct 14 06:30:51 2011 From: atalucas at gmail.com (atalucas at gmail.com) Date: Fri, 14 Oct 2011 03:30:51 -0700 (PDT) Subject: Something works in Python but not in cgi. Message-ID: <6e4551eb-20c4-4dcb-8e69-c5fefb47f3e1@q9g2000yqm.googlegroups.com> Hi, I need to make work a programm on the Web. I make tests like Hello World and also with GET and it works good. The problem comes in the line gas = importPhase("gri30.cti") The computer don?t find the file "gri30.cti"(this file was not in workspace), then I put it in the same folder and the program crash. Knows someone where is the problem??? #!D:\Python25\python.exe print "Content-Type: text/html\n" import cgitb; cgitb.enable() import cgi from workplace import * gas = importPhase("gri30.cti") print "Cantera" print '' print '' print "" From miki.tebeka at gmail.com Fri Oct 14 09:37:02 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 14 Oct 2011 06:37:02 -0700 (PDT) Subject: Something works in Python but not in cgi. In-Reply-To: <6e4551eb-20c4-4dcb-8e69-c5fefb47f3e1@q9g2000yqm.googlegroups.com> References: <6e4551eb-20c4-4dcb-8e69-c5fefb47f3e1@q9g2000yqm.googlegroups.com> Message-ID: <19751516.906.1318599422237.JavaMail.geo-discussion-forums@prmi2> The working directory of the webserver is probably not the one of the script. You should specify full path to the file. One way to do it is: from os.path import dirname, join filename = join(dirname(__file__), 'gri30.cti') HTH -- Miki Tebeka http://pythonwise.blogspot.com From tjreedy at udel.edu Fri Oct 14 10:11:50 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Oct 2011 10:11:50 -0400 Subject: Fwd: os.statvfs bug or my incompetence ? In-Reply-To: <4E97F093.4000203@nsn.com> References: <4E97DB66.50302@nsn.com> <4E97F093.4000203@nsn.com> Message-ID: On 10/14/2011 4:19 AM, Peter G. Marczis wrote: > import os > os.statvfs('/') ... > os.statvfs('/') > *OSError: [Errno 0] Error: '/'* > > # python --version > Python 2.6.2 > > # arch > mips64 > > os.stat works fine. 2.6.2 is a few years old. If there is a bug, it might have been fixed by 2.6.6 released a year ago, or 2.7.2 just a few months ago. -- Terry Jan Reedy From k.sahithi2862 at gmail.com Fri Oct 14 10:14:23 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Fri, 14 Oct 2011 07:14:23 -0700 (PDT) Subject: FOR ONLY HOT GUYS SEE THIS Message-ID: FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html From buzzard at urubu.freeserve.co.uk Fri Oct 14 10:37:13 2011 From: buzzard at urubu.freeserve.co.uk (duncan smith) Date: Fri, 14 Oct 2011 15:37:13 +0100 Subject: Graph editor In-Reply-To: <7ce425e6-0831-4c71-a2e1-d6f6d0b4ee4b@o19g2000vbk.googlegroups.com> References: <7ce425e6-0831-4c71-a2e1-d6f6d0b4ee4b@o19g2000vbk.googlegroups.com> Message-ID: On 14/10/11 08:45, Libra wrote: > Hi, > I would like to build a simple graph editor, allowing me to add nodes > and edges via the mouse, along with the possibility to edit it (delete/ > move nodes and edges, double click on object to pop-up a form where I > can insert object related info, and so forth) and bind edges to nodes > (that is, when I move a node, the attached edges move accordingly). I > should also put an image (a bitmap of png) in the background of the > graph. > > I've seen many GUI libraries (from TkInter to wxPython) but I was > wondering if there is a specific graphic library (with good > documentation and maybe examples) simplifying the rapid development of > such an application. > I've used wxPython and ogl (http://www.wxpython.org/docs/api/wx.lib.ogl-module.html) for my graph editors; in conjunction with graphviz for the layout. There are ogl examples in the wxPython demo. Duncan From ramit.prasad at jpmorgan.com Fri Oct 14 10:45:41 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 14 Oct 2011 10:45:41 -0400 Subject: Opportunity missed by Python ? In-Reply-To: <21380825.697.1318543555990.JavaMail.geo-discussion-forums@prdw1> References: <4e96b324$0$1007$426a34cc@news.free.fr> <21380825.697.1318543555990.JavaMail.geo-discussion-forums@prdw1> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F216FAD8E@EMARC112VS01.exchad.jpmchase.net> >As long as there are tools to translate scripts or source code between the two languages. More new evolved powerful programming >languages arenot problems at all for experienced programmers. More often than not, these conversion utilities are a source of terrible code. They are good for getting a quick job done, but not for code that has long term use. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From dihedral88888 at googlemail.com Fri Oct 14 11:02:07 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Fri, 14 Oct 2011 08:02:07 -0700 (PDT) Subject: 1/2 evaluates to 0 In-Reply-To: References: Message-ID: <19699772.1760.1318604527365.JavaMail.geo-discussion-forums@prng5> How about fractions to be computed in hundreds or even thousands of digits in precision? OK, just write programs to compute PI and the Euler number in hundreds or even thousands of digits to test various kind of programming languages. This is a sophomore school home work for gifted kids to play with programmings. From dihedral88888 at googlemail.com Fri Oct 14 11:20:31 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Fri, 14 Oct 2011 08:20:31 -0700 (PDT) Subject: 1/2 evaluates to 0 In-Reply-To: <19699772.1760.1318604527365.JavaMail.geo-discussion-forums@prng5> References: <19699772.1760.1318604527365.JavaMail.geo-discussion-forums@prng5> Message-ID: <13198363.1773.1318605631288.JavaMail.geo-discussion-forums@prng5> Maybe one should try to compute C(n,k) in additions only by the Pascal triangle first! This is simpler for senior high school kids to play with python! From dickinsm at gmail.com Fri Oct 14 11:33:01 2011 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 14 Oct 2011 08:33:01 -0700 (PDT) Subject: Implement comparison operators for range objects References: <20111012163144.GB6393@pantoffel-wg.de> <4E95CF7D.6000000@pearwood.info> <4E95D394.9000205@mrabarnett.plus.com> Message-ID: On Oct 12, 8:24?pm, Ian Kelly wrote: > On Wed, Oct 12, 2011 at 11:51 AM, MRAB wrote: > >> Aside: > > >> I'm astonished to see that range objects have a count method! What's the > >> purpose of that? Any value's count will either be 0 or 1, and a more > >> appropriate test would be `value in range`: > > >> ?>>> 17 in range(2, 30, 3) # like r.count(17) => 1 > >> True > >> ?>>> 18 in range(2, 30, 3) # like r.count(18) => 0 > >> False > > > In Python 2, range returns a list, and lists have a .count method. > > Could that be the reason? > > Python 2 xrange objects do not have a .count method. ?Python 3 range > objects do have a .count method. ?The addition is curious, to say the > least. See http://bugs.python.org/issue9213 -- Mark From steve+comp.lang.python at pearwood.info Fri Oct 14 11:48:35 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 15 Oct 2011 02:48:35 +1100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> Message-ID: <4e9859d4$0$30003$c3e8da3$5496439d@news.astraweb.com> Carl Banks wrote: > On Thursday, October 13, 2011 7:16:37 PM UTC-7, Steven D'Aprano wrote: >> > What I would expect to happen that all statements within the ooo block >> > may be executed out >> > of order. The block itself waits till all statements are returned >> > before continuing. >> >> Why do you think this needs to be a language statement? >> >> You can have that functionality *right now*, without waiting for a syntax >> update, by use of the multiprocessing module, or a third party module. >> >> http://docs.python.org/library/multiprocessing.html >> http://wiki.python.org/moin/ParallelProcessing >> >> There's no need for forcing language changes on everyone, whether they >> need it or not, for features that can easily be implemented as library >> code. > > This goes a little beyond a simple threading mechanism, though. The multiprocessing module is not a simple threading mechanism, and neither are the libraries listed in the ParallelProcessing page. -- Steven From subscriber at antifraud.irs.gov Fri Oct 14 12:01:39 2011 From: subscriber at antifraud.irs.gov (Internal Revenue Service United States Department of the Treasury) Date: Fri, 14 Oct 2011 10:01:39 -0600 Subject: U.S. Department of the Treasury IRS.gov Message-ID: <6011251481.S7LOLOL8323380@lzgoory.icywmnqgwwsqgnq.net> Taxpayer ID: commensurate-00000700955060USTax Type: INCOME TAXIssue: Unreported/Underreported Income (Fraud Application)Please review your tax statement on Internal Revenue Service (IRS) website (click on the link below):download tax statement: report-00000700952560US.DOChttp://www.irs.gov. -------------- next part -------------- An HTML attachment was scrubbed... URL: From twestley at gmail.com Fri Oct 14 14:04:40 2011 From: twestley at gmail.com (Terry) Date: Fri, 14 Oct 2011 11:04:40 -0700 (PDT) Subject: .py and .pyc files in read-only directory Message-ID: <33c406fa-c563-440f-83f5-99557b2e0643@h5g2000vbf.googlegroups.com> I'm having a problem with my iPhone/iPad app, Python Math, a Python 2.7 interpreter. All the Python modules are delivered in what Apple calls the app bundle. They are in a read-only directory. This means that Python cannot write .pyc files to that directory. (I get a deny write error when doing this.) I tried using compileall to precompile all the modules, but now I get an unlink error because Python apparently wants to rebuild the .pyc files. I've considered two solutions: 1) Delete all the .py files, delivering only the .pyc, or 2) Redirecting the .pyc files into a separate, writable directory. Will solution 1) work? I don't know how to do 2) and the only reference I can find to that are a withdrawn PEP, 304. Suggestions? From no.email at nospam.invalid Fri Oct 14 14:17:44 2011 From: no.email at nospam.invalid (Paul Rubin) Date: Fri, 14 Oct 2011 11:17:44 -0700 Subject: Fwd: os.statvfs bug or my incompetence ? References: <4E97DB66.50302@nsn.com> <4E97F093.4000203@nsn.com> Message-ID: <7x39evwi7r.fsf@ruckus.brouhaha.com> Terry Reedy writes: >> os.statvfs('/') >> *OSError: [Errno 0] Error: '/'* >> >> # python --version >> Python 2.6.2 > > 2.6.2 is a few years old. If there is a bug, it might have been fixed > by 2.6.6 released a year ago, or 2.7.2 just a few months ago. os.statvfs('/') works fine or me on Python 2.6.2 (r262:71600, Jun 4 2010, 18:28:58) [GCC 4.4.3 20100127 (Red Hat 4.4.3-4)] on linux2 From anikom15 at gmail.com Fri Oct 14 14:24:49 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Fri, 14 Oct 2011 11:24:49 -0700 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> Message-ID: <20111014182448.GB9255@Smoke> On Thu, Oct 13, 2011 at 11:56:20PM -0700, Carl Banks wrote: > On Thursday, October 13, 2011 7:16:37 PM UTC-7, Steven D'Aprano wrote: > > > What I would expect to happen that all statements within the ooo block > > > may be executed out > > > of order. The block itself waits till all statements are returned before > > > continuing. > > > > Why do you think this needs to be a language statement? > > > > You can have that functionality *right now*, without waiting for a syntax > > update, by use of the multiprocessing module, or a third party module. > > > > http://docs.python.org/library/multiprocessing.html > > http://wiki.python.org/moin/ParallelProcessing > > > > There's no need for forcing language changes on everyone, whether they need > > it or not, for features that can easily be implemented as library code. > > This goes a little beyond a simple threading mechanism, though. It's more like guidance to the compiler that you don't care what order these are executed in; the compiler is then free to take advantage of this advice however it like. That could be to spawn threads, but it could also compile instructions to optimize pipelining and cacheing. The compiler could also ignore it. But you can see that, fully realized, syntax like that can do much more than can be done with library code. > > Obviously that extra capability is a very long way off for being useful in CPython. > > While we're at it, let's throw in the register keyword. From chris at simplistix.co.uk Fri Oct 14 14:33:35 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 14 Oct 2011 19:33:35 +0100 Subject: Seven Python Developers Needed $125K In-Reply-To: References: Message-ID: <4E98807F.7090909@simplistix.co.uk> I'd suggest you post to the job board rather than spamming the list: http://www.python.org/community/jobs/howto/ cheers, Chris On 11/10/2011 19:16, WR wrote: > Top Global Consulting Firm in NYC needs 7 Python Developers > > Up to $125K depending on experience > > Solid knowledge of fundamental Python concepts. At least three years Python experience required. > > For more info email Joseph at Washresearch.com > > Joseph Ryan > Washington Research Associates Inc > (202) 408-7025 > -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From chris at simplistix.co.uk Fri Oct 14 14:34:27 2011 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 14 Oct 2011 19:34:27 +0100 Subject: Want to make the transition to games? In-Reply-To: References: Message-ID: <4E9880B3.7000706@simplistix.co.uk> Please don't spam this list with jobs, especially if they have nothing to do with Python. If they do, use the job board instead: http://www.python.org/community/jobs/howto/ cheers, Chris On 12/10/2011 05:49, Marta wrote: > Hi, > > I'm working as an onsite recruiting consultant and we are looking for > top engineers who want to work with other very accomplished > engineers. If you have a CS degree, strong in C++ and want to make > the transition to games, please email me your resume. > > Cheers, > > Marta Daglow -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From clp2 at rebertia.com Fri Oct 14 15:31:46 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 14 Oct 2011 12:31:46 -0700 Subject: .py and .pyc files in read-only directory In-Reply-To: <33c406fa-c563-440f-83f5-99557b2e0643@h5g2000vbf.googlegroups.com> References: <33c406fa-c563-440f-83f5-99557b2e0643@h5g2000vbf.googlegroups.com> Message-ID: On Fri, Oct 14, 2011 at 11:04 AM, Terry wrote: > I'm having a problem with my iPhone/iPad app, Python Math, a Python > 2.7 interpreter. All the Python modules are delivered in what Apple > calls the app bundle. They are in a read-only directory. This means > that Python cannot write .pyc files to that directory. (I get a deny > write error when doing this.) I tried using compileall to precompile > all the modules, but now I get an unlink error because Python > apparently wants to rebuild the .pyc files. You can stop Python from trying to write .pyc files by using the environment variable PYTHONDONTWRITEBYTECODE, the interpreter's -B command line option, or by setting sys.dont_write_bytecode to True. Cheers, Chris From ian.g.kelly at gmail.com Fri Oct 14 15:48:38 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Oct 2011 13:48:38 -0600 Subject: .py and .pyc files in read-only directory In-Reply-To: References: <33c406fa-c563-440f-83f5-99557b2e0643@h5g2000vbf.googlegroups.com> Message-ID: On Fri, Oct 14, 2011 at 1:31 PM, Chris Rebert wrote: > On Fri, Oct 14, 2011 at 11:04 AM, Terry wrote: >> I'm having a problem with my iPhone/iPad app, Python Math, a Python >> 2.7 interpreter. All the Python modules are delivered in what Apple >> calls the app bundle. They are in a read-only directory. This means >> that Python cannot write .pyc files to that directory. (I get a deny >> write error when doing this.) I tried using compileall to precompile >> all the modules, but now I get an unlink error because Python >> apparently wants to rebuild the .pyc files. > > You can stop Python from trying to write .pyc files by using the > environment variable PYTHONDONTWRITEBYTECODE, the interpreter's -B > command line option, or by setting sys.dont_write_bytecode to True. This won't make Python use the .pyc files provided, though. It will just recompile the .py files and then not try to write out the bytecode. If you really want to force it to use the .pyc's, then don't include the .py files. Note that if you do this, you'll need to make sure that the version of Python used to compile the .pyc files is the same minor release as the version used to run them (more specifically, the two versions must return the same string from imp.get_magic()). HTH, Ian From twestley at gmail.com Fri Oct 14 16:39:24 2011 From: twestley at gmail.com (Terry) Date: Fri, 14 Oct 2011 13:39:24 -0700 (PDT) Subject: .py and .pyc files in read-only directory In-Reply-To: References: <33c406fa-c563-440f-83f5-99557b2e0643@h5g2000vbf.googlegroups.com> Message-ID: <25190838.4422.1318624764846.JavaMail.geo-discussion-forums@vbmh5> Thanks, that's very useful. And it explains why Python Math wants to rewrite the .pyc files: imp.get_magic() returns (null) whereas on my Mac where I compiled them, get_magic() returns '\x03\xf3\r\n'. Now I just have to figure out why I'm getting nothing useful from get_magic(). I assume this would have to be fixed to try solution 1), i.e., leaving out the .py files and delivering only the .pyc. Terry From zaffino.p at gmail.com Fri Oct 14 16:55:23 2011 From: zaffino.p at gmail.com (Paolo Zaffino) Date: Fri, 14 Oct 2011 22:55:23 +0200 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: Nobody can help me? 2011/10/12 Paolo Zaffino > I wrote a function thaht works on a 3D matrix. > As first thing I have an array and I want reshape it into a 3D matrix (for > further manipulations). > For this reason I wrote in a row: > > matrix=matrix.reshape(a, b, c).T > > It work fine on GNU/Linux and Mac OS but not on Windows. > In Windows I get this error: > > matrix=matrix.reshape(a, b, c).T > > ValueError: total size of new array must be unchanged > > Thank you. > > > > > 2011/10/11 David Robinow > >> 2011/10/11 Paolo Zaffino : >> > Nobody can help me? >> Nope, not unless you post some code. Your problem description is too >> vague. >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pengyu.ut at gmail.com Fri Oct 14 17:29:50 2011 From: pengyu.ut at gmail.com (Peng Yu) Date: Fri, 14 Oct 2011 16:29:50 -0500 Subject: How to generate error when argument are not supplied and there is no explicit defults (in optparse)? Message-ID: Hi, The following code doesn't give me error, even I don't specify the value of filename from the command line arguments. filename gets 'None'. I checked the manual, but I don't see a way to let OptionParser fail if an argument's value (which has no default explicitly specified) is not specified. I may miss some thing in the manual. Could any expert let me know if there is a way to do so? Thanks! #!/usr/bin/env python from optparse import OptionParser usage = 'usage: %prog [options] arg1 arg2' parser = OptionParser(usage=usage) parser.set_defaults(verbose=True) parser.add_option('-f', '--filename') #(options, args) = parser.parse_args(['-f', 'file.txt']) (options, args) = parser.parse_args() print options.filename -- Regards, Peng From ramit.prasad at jpmorgan.com Fri Oct 14 17:30:57 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 14 Oct 2011 17:30:57 -0400 Subject: Re-raise different exception with original stack trace Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F217865A4@EMARC112VS01.exchad.jpmchase.net> Hi all, Hopefully you guys can help me with my problem. Basically I have a UI program that can "save" information. The UI passes the save to the controller and the controller saves a file and does some post processing. If saving the file fails, I want to handle the error differently than if the error was in post processing. In both cases the possible exceptions are varied and unknown so I cannot pick and choose certain exception. The problem with the sample program below is that the stack trace is replaced by the re-raise. What would be the best way(s) to get the original stack trace in save_from_UI if the exception occurs in post_process? Using Python 2.6 and Windows(XP and 7) / Linux. Def save_from_model(): save() # do not catch exception (could be any exception) try: post_process() except Exception as e: #do something raise CustomException() # "wrap" exception so bar knows to handle it differently def save_from_UI(): try: foo() except CustomException() as e: # How do I get the original stacktrace instead of the reraise? except Exception as e: # do something else with this exception Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From python at mrabarnett.plus.com Fri Oct 14 17:54:27 2011 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Oct 2011 22:54:27 +0100 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: <4E98AF93.4030908@mrabarnett.plus.com> On 14/10/2011 21:55, Paolo Zaffino wrote: > Nobody can help me? > Others have already tried to help you. What is the shape and size of 'matrix' before, and what are the values of 'a', 'b' and 'c'? Print them in the ones which work (GNU/Linux and Mac OS) and the one which doesn't (Windows). Do they print the same values? Do not assume that they are the same. Print them to make sure. > > 2011/10/12 Paolo Zaffino > > > I wrote a function thaht works on a 3D matrix. > As first thing I have an array and I want reshape it into a 3D > matrix (for further manipulations). > For this reason I wrote in a row: > > matrix=matrix.reshape(a, b, c).T > > It work fine on GNU/Linux and Mac OS but not on Windows. > In Windows I get this error: > > matrix=matrix.reshape(a, b, c).T > > ValueError: total size of new array must be unchanged > > Thank you. > > 2011/10/11 David Robinow > > > 2011/10/11 Paolo Zaffino >: > > Nobody can help me? > Nope, not unless you post some code. Your problem description > is too vague. > From ramit.prasad at jpmorgan.com Fri Oct 14 17:55:07 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 14 Oct 2011 17:55:07 -0400 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F217865FA@EMARC112VS01.exchad.jpmchase.net> From: python-list-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of Paolo Zaffino Sent: Friday, October 14, 2011 3:55 PM To: python-list at python.org Subject: Re: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows Nobody can help me? 2011/10/12 Paolo Zaffino I wrote a function thaht works on a 3D matrix. As first thing I have an array and I want reshape it into a 3D matrix (for further manipulations). For this reason I wrote in a row: matrix=matrix.reshape(a, b, c).T It work fine on GNU/Linux and Mac OS but not on Windows. In Windows I get this error: matrix=matrix.reshape(a, b, c).T ValueError: total size of new array must be unchanged Thank you. 2011/10/11 David Robinow 2011/10/11 Paolo Zaffino : > Nobody can help me? ?Nope, not unless you post some code. Your problem description is too vague. ============================================================================== You can do this by converting to an array. >>> mat = numpy.matrix( [[1,2,],[3,4],[5,6],[7,8]] ) >>> numpy.array( mat ) array([[1, 2], [3, 4], [5, 6], [7, 8]]) >>> a = _ >>> numpy.reshape( a, (2,2,2)) array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From tdsimpson at gmail.com Fri Oct 14 18:10:05 2011 From: tdsimpson at gmail.com (MrPink) Date: Fri, 14 Oct 2011 15:10:05 -0700 (PDT) Subject: Can I search a list for a range of values? Message-ID: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> I have a list like so: a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14] I would like to get a subset from the list with value between 10 and 20 (inclusive). b = [10,13,15,14,20] Is there a way to do this with a list or other data type? Thanks, From rosuav at gmail.com Fri Oct 14 18:20:33 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Oct 2011 09:20:33 +1100 Subject: Can I search a list for a range of values? In-Reply-To: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> Message-ID: On Sat, Oct 15, 2011 at 9:10 AM, MrPink wrote: > I have a list like so: > > a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14] > > I would like to get a subset from the list with value between 10 and > 20 (inclusive). > > b = [10,13,15,14,20] > > Is there a way to do this with a list or other data type? Try a list comprehension: >>> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14] >>> [i for i in a if i>=10 if i<=20] [10, 20, 15, 13, 14] This preserves order from the original list. I don't know what order your result list is in, but you can always rejig things after. ChrisA From ian.g.kelly at gmail.com Fri Oct 14 18:24:00 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Oct 2011 16:24:00 -0600 Subject: Can I search a list for a range of values? In-Reply-To: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> Message-ID: On Fri, Oct 14, 2011 at 4:10 PM, MrPink wrote: > I have a list like so: > > a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14] > > I would like to get a subset from the list with value between 10 and > 20 (inclusive). > > b = [10,13,15,14,20] > > Is there a way to do this with a list or other data type? Use a list comprehension: b = [x for x in a if 10 <= x <= 20] Cheers, Ian From python.list at tim.thechases.com Fri Oct 14 18:30:25 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 14 Oct 2011 17:30:25 -0500 Subject: Can I search a list for a range of values? In-Reply-To: References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> Message-ID: <4E98B801.7090900@tim.thechases.com> On 10/14/11 17:20, Chris Angelico wrote: > Try a list comprehension: > >>>> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14] >>>> [i for i in a if i>=10 if i<=20] > [10, 20, 15, 13, 14] The double-if is new to me. I thought it was an error when I first saw it, but it seems to be legit syntax (or at least one that 2.7 tolerates, intentionally or otherwise...). I think I'd make it clearer with either [i for i in a if i>=10 and i<=20] or even more clearly: [i for i in a if 10 <= i <= 20] -tkc From rosuav at gmail.com Fri Oct 14 18:48:05 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Oct 2011 09:48:05 +1100 Subject: Can I search a list for a range of values? In-Reply-To: <4E98B801.7090900@tim.thechases.com> References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> Message-ID: On Sat, Oct 15, 2011 at 9:30 AM, Tim Chase wrote: > The double-if is new to me. ?I thought it was an error when I first saw it, > but it seems to be legit syntax (or at least one that 2.7 tolerates, > intentionally or otherwise...). ?I think I'd make it clearer with either > > Yeah, it's legal because you can nest fors and ifs in a list comp. Stylistic difference, I used "if" instead of "and" because there's no way that it could be a bitwise and. (It's a cross-language safety net that I sometimes use.) Although the 10<=i<=20 option is definitely superior to both. ChrisA From python at mrabarnett.plus.com Fri Oct 14 18:49:53 2011 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Oct 2011 23:49:53 +0100 Subject: Re-raise different exception with original stack trace In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F217865A4@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F217865A4@EMARC112VS01.exchad.jpmchase.net> Message-ID: <4E98BC91.3010207@mrabarnett.plus.com> On 14/10/2011 22:30, Prasad, Ramit wrote: > Hi all, > Hopefully you guys can help me with my problem. > > Basically I have a UI program that can "save" information. The UI passes the save to the controller and the controller saves a file and does some post processing. If saving the file fails, I want to handle the error differently than if the error was in post processing. In both cases the possible exceptions are varied and unknown so I cannot pick and choose certain exception. The problem with the sample program below is that the stack trace is replaced by the re-raise. What would be the best way(s) to get the original stack trace in save_from_UI if the exception occurs in post_process? Using Python 2.6 and Windows(XP and 7) / Linux. > > Def save_from_model(): > save() # do not catch exception (could be any exception) > try: > post_process() > except Exception as e: > #do something > raise CustomException() # "wrap" exception so bar knows to handle it differently > > def save_from_UI(): > try: > foo() > except CustomException() as e: > # How do I get the original stacktrace instead of the reraise? > except Exception as e: > # do something else with this exception > You could save a reference to the exception in the custom exception: class CustomException(Exception): def __init__(self, e): Exception.__init__(self) self.exc = e def save_from_model(): save() # do not catch exception (could be any exception) try: post_process() except Exception as e: #do something raise CustomException(e) def save_from_UI(): try: foo() except CustomException as e: # Original exception is e.exc except Exception as e: # do something else with this exception From ian.g.kelly at gmail.com Fri Oct 14 18:58:42 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Oct 2011 16:58:42 -0600 Subject: Can I search a list for a range of values? In-Reply-To: References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> Message-ID: On Fri, Oct 14, 2011 at 4:48 PM, Chris Angelico wrote: > On Sat, Oct 15, 2011 at 9:30 AM, Tim Chase > wrote: >> The double-if is new to me. ?I thought it was an error when I first saw it, >> but it seems to be legit syntax (or at least one that 2.7 tolerates, >> intentionally or otherwise...). ?I think I'd make it clearer with either >> >> > > Yeah, it's legal because you can nest fors and ifs in a list comp. > Stylistic difference, I used "if" instead of "and" because there's no > way that it could be a bitwise and. (It's a cross-language safety net > that I sometimes use.) Although the 10<=i<=20 option is definitely > superior to both. At least in Python, there is no way that "and" could be a bitwise and either, since it cannot be overloaded. From ian.g.kelly at gmail.com Fri Oct 14 19:01:04 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Oct 2011 17:01:04 -0600 Subject: Can I search a list for a range of values? In-Reply-To: <4E98B801.7090900@tim.thechases.com> References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> Message-ID: On Fri, Oct 14, 2011 at 4:30 PM, Tim Chase wrote: > On 10/14/11 17:20, Chris Angelico wrote: >> >> Try a list comprehension: >> >>>>> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14] >>>>> [i for i in a if i>=10 if i<=20] >> >> [10, 20, 15, 13, 14] > > The double-if is new to me. ?I thought it was an error when I first saw it, > but it seems to be legit syntax (or at least one that 2.7 tolerates, > intentionally or otherwise...). ?I think I'd make it clearer with either > > ?[i for i in a if i>=10 and i<=20] > > or even more clearly: > > ?[i for i in a if 10 <= i <= 20] As long as we're nitpicking, I'll point out that "i" is an inappropriate variable name here, since it is normally used to denote indices, not data. That's why I used "x" in my response instead. ;-) Cheers, Ian From python.list at tim.thechases.com Fri Oct 14 19:24:13 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 14 Oct 2011 18:24:13 -0500 Subject: Can I search a list for a range of values? In-Reply-To: References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> Message-ID: <4E98C49D.50402@tim.thechases.com> On 10/14/11 18:01, Ian Kelly wrote: > On Fri, Oct 14, 2011 at 4:30 PM, Tim Chase >> or even more clearly: >> >> [i for i in a if 10<= i<= 20] > > As long as we're nitpicking, I'll point out that "i" is an > inappropriate variable name here, since it is normally used to > denote indices, not data. That's why I used "x" in my > response instead. ;-) Depending on your historical programming-language baggage, "i" is usually either an index or integer data, and since the source was a list of integers, "i" didn't seem inappropriate. Same for other common data-types: [f for f in (1.1, 2.2, 3.3) if 2.0 <= f < 3.0] [s for s in ("cat", "hat", "mat") if "bat" < s < "fat"] [c for c in "hello, world!" if 'a' <= c <= 'z'] -tkc From tdsimpson at gmail.com Fri Oct 14 19:36:27 2011 From: tdsimpson at gmail.com (Troy S) Date: Fri, 14 Oct 2011 19:36:27 -0400 Subject: Can I search a list for a range of values? In-Reply-To: References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> Message-ID: Can something like this be done with dictionarys? For example, these are the keys in the dictionary from the call: dict.keys() ['20110601', '20110604', '20110608', '20110611', '20110615', '20110618', '20110622', '20110625', '20110629', '20110702', '20110706','20110709', '20110713', '20110716', '20110720', '20110723', '20110727', '20110730', '20110803', '20110806', '20110810','20110813', '20110817', '20110820', '20110824', '20110827', '20110831', '20110903', '20110907', '20110910', '20110914','20110917', '20110921', '20110924', '20110928', '20111001', '20111005', '20111008'] Is there a way to find all items between '20110809' and '20110911'? So the subset would be: ['20110810','20110813', '20110817', '20110820', '20110824', '20110827', '20110831', '20110903', '20110907', '20110910'] The keys are strings that represent a date in the format: 'YYYYMMDD'. Thanks, On Fri, Oct 14, 2011 at 6:24 PM, Ian Kelly wrote: > On Fri, Oct 14, 2011 at 4:10 PM, MrPink wrote: >> I have a list like so: >> >> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14] >> >> I would like to get a subset from the list with value between 10 and >> 20 (inclusive). >> >> b = [10,13,15,14,20] >> >> Is there a way to do this with a list or other data type? > > Use a list comprehension: > > b = [x for x in a if 10 <= x <= 20] > > Cheers, > Ian > -- Troy S From ian.g.kelly at gmail.com Fri Oct 14 19:37:51 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Oct 2011 17:37:51 -0600 Subject: Can I search a list for a range of values? In-Reply-To: <4E98C49D.50402@tim.thechases.com> References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> <4E98C49D.50402@tim.thechases.com> Message-ID: On Fri, Oct 14, 2011 at 5:24 PM, Tim Chase wrote: > Depending on your historical programming-language baggage, "i" is usually > either an index or integer data, and since the source was a list of > integers, "i" didn't seem inappropriate. ?Same for other common data-types: > > ?[f for f in (1.1, 2.2, 3.3) if 2.0 <= f < 3.0] > ?[s for s in ("cat", "hat", "mat") if "bat" < s < "fat"] > ?[c for c in "hello, world!" if 'a' <= c <= 'z'] "f" makes me think "function", not "float". As a general rule, though, I prefer to name variables for what they represent, not for their type. From tdsimpson at gmail.com Fri Oct 14 19:44:07 2011 From: tdsimpson at gmail.com (MrPink) Date: Fri, 14 Oct 2011 16:44:07 -0700 (PDT) Subject: How to test if object is an integer? Message-ID: Is there a function in Python that can be used to test if the value in a string is an integer? I had to make one up for myself and it looks like this: def isInt(s): try: i = int(s) return True except ValueError: return False From vim at tim.thechases.com Fri Oct 14 19:45:12 2011 From: vim at tim.thechases.com (Tim Chase) Date: Fri, 14 Oct 2011 18:45:12 -0500 Subject: Can I search a list for a range of values? In-Reply-To: References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> Message-ID: <4E98C988.3070707@tim.thechases.com> On 10/14/11 18:36, Troy S wrote: > Can something like this be done with dictionarys? > > For example, these are the keys in the dictionary from the call: dict.keys() > > ['20110601', '20110604', '20110608', '20110611', '20110615', > '20110618', '20110622', '20110625', '20110629', '20110702', > '20110706','20110709', '20110713', '20110716', '20110720', '20110723', > '20110727', '20110730', '20110803', '20110806', '20110810','20110813', > '20110817', '20110820', '20110824', '20110827', '20110831', > '20110903', '20110907', '20110910', '20110914','20110917', '20110921', > '20110924', '20110928', '20111001', '20111005', '20111008'] > > Is there a way to find all items between '20110809' and '20110911'? > So the subset would be: > ['20110810','20110813', '20110817', '20110820', '20110824', > '20110827', '20110831', '20110903', '20110907', '20110910'] > > The keys are strings that represent a date in the format: 'YYYYMMDD'. Since strings are comparable, you certainly can: keys = [k for k in d.keys() if '20110809' < k < '20110911'] -tkc From ian.g.kelly at gmail.com Fri Oct 14 19:46:28 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 14 Oct 2011 17:46:28 -0600 Subject: Can I search a list for a range of values? In-Reply-To: References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> Message-ID: On Fri, Oct 14, 2011 at 5:36 PM, Troy S wrote: > Can something like this be done with dictionarys? > > For example, these are the keys in the dictionary from the call: dict.keys() > > ['20110601', '20110604', '20110608', '20110611', '20110615', > '20110618', '20110622', '20110625', '20110629', '20110702', > '20110706','20110709', '20110713', '20110716', '20110720', '20110723', > '20110727', '20110730', '20110803', '20110806', '20110810','20110813', > '20110817', '20110820', '20110824', '20110827', '20110831', > '20110903', '20110907', '20110910', '20110914','20110917', '20110921', > '20110924', '20110928', '20111001', '20111005', '20111008'] > > Is there a way to find all items between '20110809' and '20110911'? > So the subset would be: > ['20110810','20110813', '20110817', '20110820', '20110824', > '20110827', '20110831', '20110903', '20110907', '20110910'] Sure, dictionaries also support iteration. date_range = [d for d in source_dict if '20110809' <= d <= '20110911'] Or if you want the result to also be a dictionary: (Python 3) date_range = {d:v for d, v in source_dict.items() if '20110809' <= d <= '20110911'} (Python 2) date_range = dict((d,v) for d, v in source_dict.iteritems() if '20110809' <= d <= '20110911') You might also want to consider storing your dates as datetime.date objects rather than strings, but since you already have them formatted for lexicographical sorting it's not important for this. Cheers, Ian From rosuav at gmail.com Fri Oct 14 19:47:12 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Oct 2011 10:47:12 +1100 Subject: Can I search a list for a range of values? In-Reply-To: References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> Message-ID: On Sat, Oct 15, 2011 at 9:58 AM, Ian Kelly wrote: > At least in Python, there is no way that "and" could be a bitwise and > either, since it cannot be overloaded. Like I said, cross-language safety-net. Sure it's not an issue here, but when I write code in multiple languages, it's less embarrassing to use an odd construct like that than to post code that outright doesn't work. :) ChrisA From wuwei23 at gmail.com Fri Oct 14 20:49:04 2011 From: wuwei23 at gmail.com (alex23) Date: Fri, 14 Oct 2011 17:49:04 -0700 (PDT) Subject: Opportunity missed by Python ? References: <4e96b324$0$1007$426a34cc@news.free.fr> Message-ID: <1dd5aa8c-7a41-4108-8940-ef666cd2ddb9@t38g2000prg.googlegroups.com> On Oct 13, 8:07?pm, Chris Angelico wrote: > Python, as I found out to my detriment, is practically impossible to > sandbox effectively. The latest version of PyPy introduces a prototype sandbox: http://pypy.org/features.html#sandboxing It'll be interesting to see how effective this is. From rosuav at gmail.com Fri Oct 14 20:55:46 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Oct 2011 11:55:46 +1100 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: On Sat, Oct 15, 2011 at 10:44 AM, MrPink wrote: > Is there a function in Python that can be used to test if the value in > a string is an integer? ?I had to make one up for myself and it looks > like this: > > def isInt(s): > ? ?try: > ? ? ? ?i = int(s) > ? ? ? ?return True > ? ?except ValueError: > ? ? ? ?return False There's some ambiguity in the definition of "is an integer". For instance, is "0x100" an integer? Is "0800"? If your definition of "is an integer" is "can be passed to int() without triggering an exception" (which is probably the most useful), then your above code is about perfect. The only change I'd make is to not have an isInt function at all, but simply to try/except at the point where you need to make the conversion. ChrisA From wauue at qq.com Fri Oct 14 21:00:11 2011 From: wauue at qq.com (=?gbk?B?z6fD9Q==?=) Date: Sat, 15 Oct 2011 09:00:11 +0800 Subject: How to test if object is an integer? Message-ID: retrun True if type(i) is int else False ------------------ Original ------------------ From: "Chris Angelico"; Date: Sat, Oct 15, 2011 08:55 AM To: "python-list"; Subject: Re: How to test if object is an integer? On Sat, Oct 15, 2011 at 10:44 AM, MrPink wrote: > Is there a function in Python that can be used to test if the value in > a string is an integer? I had to make one up for myself and it looks > like this: > > def isInt(s): > try: > i = int(s) > return True > except ValueError: > return False There's some ambiguity in the definition of "is an integer". For instance, is "0x100" an integer? Is "0800"? If your definition of "is an integer" is "can be passed to int() without triggering an exception" (which is probably the most useful), then your above code is about perfect. The only change I'd make is to not have an isInt function at all, but simply to try/except at the point where you need to make the conversion. ChrisA -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Fri Oct 14 21:05:53 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Oct 2011 12:05:53 +1100 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: 2011/10/15 ?? : > retrun True if type(i) is int else False That tests if the object is already an int; the OP asked if a string contains an integer. ChrisA From clp2 at rebertia.com Fri Oct 14 21:10:56 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 14 Oct 2011 18:10:56 -0700 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: On Fri, Oct 14, 2011 at 6:05 PM, Chris Angelico wrote: > 2011/10/15 ?? : >> retrun True if type(i) is int else False > > That tests if the object is already an int; the OP asked if a string > contains an integer. Additionally: * the if-then-else there is unnecessary since `type(i) is int` already returns a bool * such a type test is normally and better written `isinstance(i, int)` Cheers, Chris R. From wuwei23 at gmail.com Fri Oct 14 21:23:15 2011 From: wuwei23 at gmail.com (alex23) Date: Fri, 14 Oct 2011 18:23:15 -0700 (PDT) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> Message-ID: <7c0baafc-70df-46ec-8482-8bbf267c8231@t38g2000prg.googlegroups.com> On Oct 14, 4:56?pm, Carl Banks wrote: > But you can see that, fully realized, syntax like that can do much more > than can be done with library code. Well sure, but imaginary syntax can do _anything_. That doesn't mean it's possible within CPython. From tjreedy at udel.edu Fri Oct 14 21:27:26 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Oct 2011 21:27:26 -0400 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: On 10/14/2011 9:05 PM, Chris Angelico wrote: > 2011/10/15 ??: >> retrun True if type(i) is int else False > > That tests if the object is already an int; the OP asked if a string > contains an integer. The misleading subject line did not. It should have been "How to test if a string contains an integer?" -- Terry Jan Reedy From ben+python at benfinney.id.au Fri Oct 14 21:51:41 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 15 Oct 2011 12:51:41 +1100 Subject: How to test if object is an integer? References: Message-ID: <87hb3buimq.fsf@benfinney.id.au> Terry Reedy writes: > On 10/14/2011 9:05 PM, Chris Angelico wrote: > > That tests if the object is already an int; the OP asked if a string > > contains an integer. > > The misleading subject line did not. It should have been "How to test > if a string contains an integer?" Which would still be misleading :-) Even better is ?How to test whether a string is a valid representation of an integer?? I say that's better because it gets to the relevant point of asking *which* representations you want to test for ? what qualifies as valid for your particular use case, and what does not. There's no single right answer; the programmer must choose exactly what they want to test for. -- \ ?When I was a little kid we had a sand box. It was a quicksand | `\ box. I was an only child... eventually.? ?Steven Wright | _o__) | Ben Finney From ben+python at benfinney.id.au Fri Oct 14 21:52:44 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 15 Oct 2011 12:52:44 +1100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> <7c0baafc-70df-46ec-8482-8bbf267c8231@t38g2000prg.googlegroups.com> Message-ID: <87d3dzuikz.fsf@benfinney.id.au> alex23 writes: > On Oct 14, 4:56?pm, Carl Banks wrote: > > But you can see that, fully realized, syntax like that can do much more > > than can be done with library code. > > Well sure, but imaginary syntax can do _anything_. That doesn't mean > it's possible within CPython. +1 QotW -- \ ?The opposite of a correct statement is a false statement. But | `\ the opposite of a profound truth may well be another profound | _o__) truth.? ?Niels Bohr | Ben Finney From clp2 at rebertia.com Fri Oct 14 22:15:59 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 14 Oct 2011 19:15:59 -0700 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: <7c0baafc-70df-46ec-8482-8bbf267c8231@t38g2000prg.googlegroups.com> References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> <7c0baafc-70df-46ec-8482-8bbf267c8231@t38g2000prg.googlegroups.com> Message-ID: On Fri, Oct 14, 2011 at 6:23 PM, alex23 wrote: > On Oct 14, 4:56?pm, Carl Banks wrote: >> But you can see that, fully realized, syntax like that can do much more >> than can be done with library code. > > Well sure, but imaginary syntax can do _anything_. That doesn't mean > it's possible within CPython. But it's The Future now! Where are my jetpack and `dwim` statement, dammit?! :-) Cheers, Chris From wuwei23 at gmail.com Fri Oct 14 22:32:35 2011 From: wuwei23 at gmail.com (alex23) Date: Fri, 14 Oct 2011 19:32:35 -0700 (PDT) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: Message-ID: <4c79d47c-c6ce-49b5-931e-c1bf5e94af75@c14g2000pro.googlegroups.com> On Oct 13, 10:35?pm, "Martin P. Hellwig" wrote: > def do_something(): > ? ? ?a = 4 > ? ? ?b = 2 > ? ? ?c = 1 > ? ? ?ooo: > ? ? ? ? ?a += 1 > ? ? ? ? ?b += 2 > ? ? ? ? ?c += 3 > ? ? ?print(a, b, c) > > What I would expect to happen that all statements within the ooo block > may be executed out > of order. The block itself waits till all statements are returned before > continuing. > > What do you think? You can do this right now with Python 3.2+ and concurrent.futures: from concurrent.futures import ThreadPoolExecutor from functools import partial import time class DoSomething: a = 4 b = 2 c = 1 def add(self, prop, val): cur = getattr(self, prop) time.sleep(cur) print('Adding %d to %s' % (val, prop)) setattr(self, prop, cur + val) def __init__(self): with ThreadPoolExecutor(max_workers=3) as pool: pool.submit(self.add, 'a', 1) pool.submit(self.add, 'b', 2) pool.submit(self.add, 'c', 3) print(self.a, self.b, self.c) DoSomething() Here we call 'ooo' the ThreadPoolExecutor context manager :) From wuwei23 at gmail.com Fri Oct 14 22:35:17 2011 From: wuwei23 at gmail.com (alex23) Date: Fri, 14 Oct 2011 19:35:17 -0700 (PDT) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: <4c79d47c-c6ce-49b5-931e-c1bf5e94af75@c14g2000pro.googlegroups.com> Message-ID: <9f5ca51b-2dd6-46cb-b3e5-02560c11f1c5@31g2000prz.googlegroups.com> On Oct 15, 12:32?pm, alex23 wrote: > from functools import partial You can ignore this, sorry, leftover from earlier code :) From wuwei23 at gmail.com Fri Oct 14 22:44:44 2011 From: wuwei23 at gmail.com (alex23) Date: Fri, 14 Oct 2011 19:44:44 -0700 (PDT) Subject: Python library for generating SQL queries [selects, alters, inserts and commits] References: <4E945CD6.3040502@tim.thechases.com> Message-ID: <46e6f128-cc7e-4232-a286-ef3ef8fc36b6@t38g2000prg.googlegroups.com> Tim Chase wrote: > I'm not sure it can entirely be chalked up to not looking hard > enough. It's explicitly cited in the feature list: Raw SQL statement mapping SQLA's object relational query facilities can accommodate raw SQL statements as well as plain result sets, and object instances can be generated from these results in the same manner as any other ORM operation. Any hyper-optimized query that you or your DBA can cook up, you can run in SQLAlchemy http://www.sqlalchemy.org/features.html That it's expression language translates down to pure SQL is also shown within the first few sections of the tutorial too: http://www.sqlalchemy.org/docs/core/tutorial.html I'm not sure how they could make it more obvious. From tdsimpson at gmail.com Fri Oct 14 22:59:38 2011 From: tdsimpson at gmail.com (MrPink) Date: Fri, 14 Oct 2011 19:59:38 -0700 (PDT) Subject: Reading a file into a data structure.... References: Message-ID: <763d6391-fc4d-4b47-b0c3-d3ad16e0fc38@gy7g2000vbb.googlegroups.com> This is what I have been able to accomplish: def isInt(s): try: i = int(s) return True except ValueError: return False f = open("powerball.txt", "r") lines = f.readlines() f.close() dDrawings = {} for line in lines: if isInt(line[0]): t = line.split() d = t[0] month,day,year = t[0].split("/") i = int(year + month + day) wb = t[1:6] wb.sort() pb = t[6] r = {'d':d,'wb':wb,'pb':pb} dDrawings[i] = r The dictionary dDrawings contains records like this: dDrawings[19971101] {'pb': '20', 'd': '11/01/1997', 'wb': ['22', '25', '28', '33', '37']} I am now able to search for ticket in a date range. keys = dDrawings.keys() b = [key for key in keys if 20110909 <= key <= 20111212] How would I search for matching wb (White Balls) in the drawings? Is there a better way to organize the data so that it will be flexible enough for different types of searches? Search by date range, search by pb, search by wb matches, etc. I hope this all makes sense. Thanks, On Oct 13, 7:42?pm, Jon Clements wrote: > On Oct 13, 10:59?pm,MrPink wrote: > > > > > > > > > > > This is a continuing to a post I made in August:http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > > I got some free time to work with Python again and have some followup > > questions. > > > For example, I have a list in a text file like this: > > Example list of lottery drawings: > > date,wb,wb,wb,wb,wb,bb > > 4/1/2011,5,1,45,23,27,27 > > 5/1/2011,15,23,8,48,22,32 > > 6/1/2011,33,49,21,16,34,1 > > 7/1/2011,9,3,13,22,45,41 > > 8/1/2011,54,1,24,39,35,18 > > .... > > > Ticket: > > startdate,enddate,wb,wb,wb,wb,wb,bb > > 4/1/2011,8/1/2011,5,23,32,21,3,27 > > > I am trying to determine the optimal way to organize the data > > structure of the drawing list, search the drawing list, and mark the > > matches in the drawing list. > > > f = open("C:\temp\drawinglist.txt", "r") > > lines = f.readlines() > > f.close() > > drawing = lines[1].split() > > > The results in drawing is this: > > drawing[0] = '4/1/2011' > > drawing[1] = '5' > > drawing[2] = '1' > > drawing[3] = '45' > > drawing[4] = '23' > > drawing[5] = '27' > > drawing[6] = '27' > > > I need to convert drawing[0] to a date datatype. ?This works, but I'm > > sure there is a better way. > > from datetime import date > > month, day, year = drawing[0].split('/') > > drawing[0] = date(int(year), int(month), int(day)) > > > For searching, I need to determine if the date of the drawing is > > within the date range of the ticket. ?If yes, then mark which numbers > > in the drawing match the numbers in the ticket. > > > ticket[0] = '4/1/2011' > > ticket[0] = '8/1/2011' > > ticket[0] = '5' > > ticket[0] = '23' > > ticket[0] = '32' > > ticket[0] = '21' > > ticket[0] = '3' > > ticket[0] = 27' > > > drawing[0] = '4/1/2011' (match) > > drawing[1] = '5' (match) > > drawing[2] = '1' > > drawing[3] = '45' > > drawing[4] = '23' (match) > > drawing[5] = '27' > > drawing[6] = '27' (match) > > > I'm debating on structuring the drawing list like this: > > drawing[0] = '4/1/2011' > > drawing[1][0] = '5' > > drawing[1][1] = '1' > > drawing[1][2] = '45' > > drawing[1][3] = '23' > > drawing[1][4] = '27' > > drawing[2] = '27' > > > Sort drawing[1] from low to high > > drawing[1][0] = '1' > > drawing[1][1] = '5' > > drawing[1][2] = '23' > > drawing[1][3] = '27' > > drawing[1][4] = '45' > > > I want to keep the drawing list in memory for reuse. > > > Any guidance would be most helpful and appreciated. > > BTW, I want to learn, so be careful not to do too much of the work for > > me. > > I'm using WingIDE to do my work. > > > Thanks, > > - Use the csv module to read the file > - Use strptime to process the date field > - Use a set for draw numbers (you'd have to do pure equality on the > bb) > - Look at persisting in a sqlite3 DB (maybe with a custom convertor) > > hth, > > Jon. From rosuav at gmail.com Sat Oct 15 00:24:40 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Oct 2011 15:24:40 +1100 Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> <7c0baafc-70df-46ec-8482-8bbf267c8231@t38g2000prg.googlegroups.com> Message-ID: On Sat, Oct 15, 2011 at 1:15 PM, Chris Rebert wrote: > On Fri, Oct 14, 2011 at 6:23 PM, alex23 wrote: >> Well sure, but imaginary syntax can do _anything_. That doesn't mean >> it's possible within CPython. > > But it's The Future now! Where are my jetpack and `dwim` statement, > dammit?! ?:-) If you can imagine something your language can't do, you're not using enough preprocessors. ChrisA who, frustrated by Java about ten years ago, started running his .java files through the C preprocessor... and it can get a lot worse than that From rosuav at gmail.com Sat Oct 15 00:30:44 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Oct 2011 15:30:44 +1100 Subject: Reading a file into a data structure.... In-Reply-To: <763d6391-fc4d-4b47-b0c3-d3ad16e0fc38@gy7g2000vbb.googlegroups.com> References: <763d6391-fc4d-4b47-b0c3-d3ad16e0fc38@gy7g2000vbb.googlegroups.com> Message-ID: On Sat, Oct 15, 2011 at 1:59 PM, MrPink wrote: > def isInt(s): > ? ?try: > ? ? ? ?i = int(s) > ? ? ? ?return True > ? ?except ValueError: > ? ? ? ?return False > > f = open("powerball.txt", "r") > lines = f.readlines() > f.close() > > dDrawings = {} > for line in lines: > ? ?if isInt(line[0]): > ? ? ? ?t = line.split() > ? ? ? ?d = t[0] > ? ? ? ?month,day,year = t[0].split("/") > ? ? ? ?i = int(year + month + day) > ? ? ? ?wb = t[1:6] > ? ? ? ?wb.sort() > ? ? ? ?pb = t[6] > ? ? ? ?r = {'d':d,'wb':wb,'pb':pb} > ? ? ? ?dDrawings[i] = r > Here's a quick rejig: dDrawings = {} for line in open("powerball.txt"): try: t = line.split() d = t[0] month,day,year = t[0].split("/") i = int(year + month + day) wb = t[1:6] wb.sort() pb = t[6] r = {'d':d,'wb':wb,'pb':pb} dDrawings[i] = r except ValueError: pass There are two significant differences. One is that the file is kept open until processing is complete, rather than reading the file into a list and then iterating over the list. Your processing is pretty simple, so it's unlikely to make a difference, but if you're doing a lengthy operation on the lines of text, or conversely if you're reading in gigs and gigs of file, you may want to take that into consideration. The other change is that a ValueError _anywhere_ in processing will cause the line to be silently ignored. If this isn't what you want, then shorten the try/except block and make it use 'continue' instead of 'pass' (which will then silently ignore that line, but leave the rest of processing unguarded by try/except). The most likely cause of another ValueError is this line: month,day,year = t[0].split("/") If there are not precisely two slashes, this will: >>> a,b,c="asdf/qwer".split("/") Traceback (most recent call last): File "", line 1, in a,b,c="asdf/qwer".split("/") ValueError: need more than 2 values to unpack Do you want this to cause the line to be ignored, or to noisily abort the whole script? ChrisA From clp2 at rebertia.com Sat Oct 15 00:47:53 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 14 Oct 2011 21:47:53 -0700 Subject: Reading a file into a data structure.... In-Reply-To: <763d6391-fc4d-4b47-b0c3-d3ad16e0fc38@gy7g2000vbb.googlegroups.com> References: <763d6391-fc4d-4b47-b0c3-d3ad16e0fc38@gy7g2000vbb.googlegroups.com> Message-ID: On Fri, Oct 14, 2011 at 7:59 PM, MrPink wrote: > This is what I have been able to accomplish: > > def isInt(s): > ? ?try: > ? ? ? ?i = int(s) > ? ? ? ?return True > ? ?except ValueError: > ? ? ? ?return False > > f = open("powerball.txt", "r") > lines = f.readlines() > f.close() > > dDrawings = {} > for line in lines: > ? ?if isInt(line[0]): > ? ? ? ?t = line.split() > ? ? ? ?d = t[0] > ? ? ? ?month,day,year = t[0].split("/") > ? ? ? ?i = int(year + month + day) > ? ? ? ?wb = t[1:6] > ? ? ? ?wb.sort() > ? ? ? ?pb = t[6] > ? ? ? ?r = {'d':d,'wb':wb,'pb':pb} > ? ? ? ?dDrawings[i] = r > > The dictionary dDrawings contains records like this: > dDrawings[19971101] > {'pb': '20', 'd': '11/01/1997', 'wb': ['22', '25', '28', '33', '37']} > > I am now able to search for ticket in a date range. > keys = dDrawings.keys() > b = [key for key in keys if 20110909 <= key <= 20111212] > > How would I search for matching wb (White Balls) in the drawings? > > Is there a better way to organize the data so that it will be flexible > enough for different types of searches? > Search by date range, search by pb, search by wb matches, etc. > > I hope this all makes sense. from datetime import datetime from collections import namedtuple, defaultdict # for efficient searching by date: import bisect DATE_FORMAT = "%m/%d/%Y" Ticket = namedtuple('Ticket', "white_balls powerball date".split()) powerball2ticket = defaultdict(set) whiteball2ticket = defaultdict(set) tickets_by_date = [] with open("powerball.txt", "r") as f: for line in f: if not line[0].isdigit(): # what are these other lines anyway? continue # skip such lines fields = line.split() date = datetime.strptime(fields[0], DATE_FORMAT).date() white_balls = frozenset(int(num_str) for num_str in fields[1:6]) powerball = int(fields[6]) ticket = Ticket(white_balls, powerball, date) powerball2ticket[powerball].add(ticket) for ball in white_balls: whiteball2ticket[ball].add(ticket) tickets_by_date.append(ticket) tickets_by_date.sort(key=lambda ticket: ticket.date) print(powerball2ticket[7]) # all tickets with a 7 powerball print(whiteball2ticket[3]) # all tickets with a non-power 3 ball Cheers, Chris -- http://rebertia.com From miki.tebeka at gmail.com Sat Oct 15 01:20:53 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 14 Oct 2011 22:20:53 -0700 (PDT) Subject: How to generate error when argument are not supplied and there is no explicit defults (in optparse)? In-Reply-To: References: Message-ID: <25425134.106.1318656053412.JavaMail.geo-discussion-forums@prho12> Don't specify it as an option, but as an argument. If you're on a new version of python, you should probably use argparse. From miki.tebeka at gmail.com Sat Oct 15 01:20:53 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 14 Oct 2011 22:20:53 -0700 (PDT) Subject: How to generate error when argument are not supplied and there is no explicit defults (in optparse)? In-Reply-To: References: Message-ID: <25425134.106.1318656053412.JavaMail.geo-discussion-forums@prho12> Don't specify it as an option, but as an argument. If you're on a new version of python, you should probably use argparse. From sathyapriyavikash at gmail.com Sat Oct 15 01:43:52 2011 From: sathyapriyavikash at gmail.com (sathya priya) Date: Fri, 14 Oct 2011 22:43:52 -0700 (PDT) Subject: Dear friends find ur life partner here visit now Message-ID: http://123maza.com/48/share486/ From tjreedy at udel.edu Sat Oct 15 02:03:50 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 15 Oct 2011 02:03:50 -0400 Subject: How to test if object is an integer? In-Reply-To: <87hb3buimq.fsf@benfinney.id.au> References: <87hb3buimq.fsf@benfinney.id.au> Message-ID: On 10/14/2011 9:51 PM, Ben Finney wrote: > Terry Reedy writes: > >> On 10/14/2011 9:05 PM, Chris Angelico wrote: > >>> That tests if the object is already an int; the OP asked if a string >>> contains an integer. >> >> The misleading subject line did not. It should have been "How to test >> if a string contains an integer?" > Which would still be misleading :-) > > Even better is ?How to test whether a string is a valid representation > of an integer?? I agree, but that is more than I would ask of a newbie, whereas asking people to ask the same question in subject line and text, even if the question is inadequate, is reasonable. > I say that's better because it gets to the relevant point of asking > *which* representations you want to test for ? what qualifies as valid > for your particular use case, and what does not. There's no single right > answer; the programmer must choose exactly what they want to test for. Yes. Even the wrong subject line question is ambiguous, as any of int, bool, float, complex, decimal.Decimal, and fractions.Fraction can have an integer value, as might user class instances, and, of course, depending on context, bytes and strings. -- Terry Jan Reedy From anikom15 at gmail.com Sat Oct 15 02:04:12 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Fri, 14 Oct 2011 23:04:12 -0700 Subject: Can I search a list for a range of values? In-Reply-To: References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> Message-ID: <20111015060412.GA12454@Smoke> On Fri, Oct 14, 2011 at 05:01:04PM -0600, Ian Kelly wrote: > On Fri, Oct 14, 2011 at 4:30 PM, Tim Chase > wrote: > > On 10/14/11 17:20, Chris Angelico wrote: > >> > >> Try a list comprehension: > >> > >>>>> a = [2,4,5,6,3,9,10,34,39,59,20,15,13,14] > >>>>> [i for i in a if i>=10 if i<=20] > >> > >> [10, 20, 15, 13, 14] > > > > The double-if is new to me. ?I thought it was an error when I first saw it, > > but it seems to be legit syntax (or at least one that 2.7 tolerates, > > intentionally or otherwise...). ?I think I'd make it clearer with either > > > > ?[i for i in a if i>=10 and i<=20] > > > > or even more clearly: > > > > ?[i for i in a if 10 <= i <= 20] > > As long as we're nitpicking, I'll point out that "i" is an > inappropriate variable name here, since it is normally used to denote > indices, not data. That's why I used "x" in my response instead. ;-) > O that's what i stands for. I always thought it was integer o_O From aaabbb16 at hotmail.com Sat Oct 15 02:20:22 2011 From: aaabbb16 at hotmail.com (aaabbb16 at hotmail.com) Date: Fri, 14 Oct 2011 23:20:22 -0700 (PDT) Subject: I am a newbie for python and try to understand class Inheritance. Message-ID: Test.py #!/usr/bin/python from my_lib import my_function class my_class(my_function.name): def __initial__(self, name); pass def test(): print "this is a test" If __name__ == '__maim__': my_class.main() --------------------------------------------------- my_lib.py class my_function() ....... ........ Can anyone finish above code and let me try to understand Class inheritance? TIA. -david From clp2 at rebertia.com Sat Oct 15 03:04:13 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 15 Oct 2011 00:04:13 -0700 Subject: I am a newbie for python and try to understand class Inheritance. In-Reply-To: References: Message-ID: On Fri, Oct 14, 2011 at 11:20 PM, wrote: > Test.py > #!/usr/bin/python > from my_lib import my_function > class my_class(my_function.name): Why are you subclassing my_function.name and not just my_function? > ? ?def __initial__(self, name); > ? ? ? ? pass The initializer method should be named "__init__", not "__initial__". > ? ?def test(): You forgot to include "self" as a parameter, like so: def test(self): > ? ? ? print "this is a test" > > If __name__ == '__maim__': That should be "__main__" with an N, not "__maim__" with an M. And "if" must be in all-lowercase. > ? ?my_class.main() Your class doesn't define any method named "main" (you only defined test() and __initial__() ), so this call will fail. > --------------------------------------------------- > my_lib.py > class my_function() You're missing a colon after the parentheses. Also, you're writing a class, not a function, so please rename the class something less confusing. > Can anyone finish above code and let me try to understand > Class inheritance? > TIA. Have you read any Python tutorial? There are several basic errors in your code which would suggest that you haven't. You really ought to; it's well worth it. The Beginner's Guide links to 2 lists of tutorials: http://wiki.python.org/moin/BeginnersGuide There's also the python-tutor mailing list, which is specifically geared towards answering beginner questions: http://mail.python.org/mailman/listinfo/tutor Cheers, Chris -- http://rebertia.com From jason.swails at gmail.com Sat Oct 15 03:09:09 2011 From: jason.swails at gmail.com (Jason Swails) Date: Sat, 15 Oct 2011 03:09:09 -0400 Subject: I am a newbie for python and try to understand class Inheritance. In-Reply-To: References: Message-ID: On Sat, Oct 15, 2011 at 2:20 AM, wrote: > Test.py > #!/usr/bin/python > from my_lib import my_function > class my_class(my_function.name): > Classes must inherit from other classes -- not variables or functions. > def __initial__(self, name); > This should be "def __init__(self, name):" (: not ; and __init__, not __initial__) pass > def test(): > print "this is a test" > > If __name__ == '__maim__': > I think this should be '__main__' > my_class.main() > This only makes sense if your my_class has a main() attribute function to it. Note that the typical way of dealing with classes is to instantiate different classes. > > Can anyone finish above code and let me try to understand > Class inheritance? > You appear to be confusing functions and classes. Functions are chunks of code that you (optionally) pass variables to in order to perform a specific task. Classes, on the other hand, are the heart of OOP. They are useful for creating an abstraction layer to make certain problems easier and reading code easier as well. (It also helps break down the problem into more manageable pieces, which facilitates collaborative projects). For instance, let's say you want to deal with shapes. You can define a shape via a class class Shape(object): """ Base shape class """ def __init__(self, vertices): """ Obviously if any of the vertices are collinear num_sides will be wrong. This is an example """ self.vertices = vertices self.num_sides = len(vertices) def draw(self, canvas): """ Draws the given shape on a passed canvas. Pretend there is working code here """ def area(self): """ Calculates the area of this shape and returns it as a floating point number """ return Now you can create different shapes as you need them user_shape_1 = Shape( ((0,0), (0,1), (1,1), (1,0)) ) user_shape_2 = Shape( ((-1,-1), (0,0), (-1,0)) ) Now you have 2 different shapes. If you have some kind of canvas object (from Tk, perhaps), you can draw either shape up there by calling one of its functions: user_shape_1.draw(my_canvas) As you can see, the simple call user_shape_1.draw(my_canvas) is self explanatory -- it draws the shape on the given canvas. This allows easy re-use of code. Now we get into inheritance. Let's suppose that we want a specific type of shape. For instance, a circle (that is defined by an infinite number of vertices). In this case, a circle is still a shape, so it should have every attribute that a normal shape has. Thus, we can define a circle class as follows: class Circle(Shape): """ Circle inherits from Shape """ number_vertex_points = 1000 # Default number of vertex points I want to define a circle def __init__(self, center, radius): """ Define the self.vertices here to trace out a circle as closely as you want """ Now, each time we instantiate a Circle class, that class has every attribute that Shape has, in addition to any additional attribute you give to Circle (and if the same attribute is defined in both places, the definition in Circle overrides that definition). Thus, in this case we can define a Circle with a center and radius (much easier than vertices!), and we can tell Circle how we want the vertices defined to get as close an approximation to a circle as we want. HTH (I'm sure others can explain this better than I can), Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sat Oct 15 03:37:35 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 15 Oct 2011 00:37:35 -0700 Subject: I am a newbie for python and try to understand class Inheritance. In-Reply-To: References: Message-ID: On Sat, Oct 15, 2011 at 12:09 AM, Jason Swails wrote: > For instance, let's say you want to deal with shapes.? You can define a > shape via a class > > class Shape(object): > ?? """ Base shape class """ > Now we get into inheritance.? Let's suppose that we want a specific type of > shape.? For instance, a circle (that is defined by an infinite number of > vertices).? In this case, a circle is still a shape, so it should have every > attribute that a normal shape has.? Thus, we can define a circle class as > follows: > > class Circle(Shape): > ?? """ Circle inherits from Shape """ > ?? number_vertex_points = 1000 # Default number of vertex points I want to > define a circle > ?? def __init__(self, center, radius): > ????? """ Define the self.vertices here to trace out a circle as closely as > you want """ > > Now, each time we instantiate a Circle class, that class has every attribute > that Shape has, in addition to any additional attribute you give to Circle > (and if the same attribute is defined in both places, the definition in > Circle overrides that definition).? Thus, in this case we can define a > Circle with a center and radius (much easier than vertices!), and we can > tell Circle how we want the vertices defined to get as close an > approximation to a circle as we want. Sidenote: It's funny that the shapes example gets used so often, despite the fact that pursuing it much further so easily leads to the Circle-Ellipse / Rectangle-Square problem. Cheers, Chris From aaabbb16 at hotmail.com Sat Oct 15 03:59:48 2011 From: aaabbb16 at hotmail.com (aaabbb16 at hotmail.com) Date: Sat, 15 Oct 2011 00:59:48 -0700 (PDT) Subject: I am a newbie for python and try to understand class Inheritance. References: Message-ID: <751ee720-652c-4ea2-9521-a9017a9be679@k16g2000prb.googlegroups.com> On 10?15?, ??12?04?, Chris Rebert wrote: > On Fri, Oct 14, 2011 at 11:20 PM, ? wrote: > > Test.py > > #!/usr/bin/python > > from my_lib import test > > class my_class(my_function.name): > > Why are you subclassing my_function.name and not just my_function? try to inherit or change "name" attribute in "my_function". > > > ? ?def __initial__(self, name); > > ? ? ? ? pass > > The initializer method should be named "__init__", not "__initial__". ipad is so smart, it thinks I have spelling problem and correct it. haha. sorry about it. > > > ? ?def test(): > > You forgot to include "self" as a parameter, like so: > ? ? def test(self): right thanks! > > > ? ? ? print "this is a test" > > > If __name__ == '__maim__': > > That should be "__main__" with an N, not "__maim__" with an M. > And "if" must be in all-lowercase. mistyping > > ? ?my_class.main() > > Your class doesn't define any method named "main" (you only defined > test() and __initial__() ), so this call will fail. how to do it? > > --------------------------------------------------- > > my_lib.py > > class my_function() > > You're missing a colon after the parentheses. Also, you're writing a > class, not a function, so please rename the class something less > confusing. sure. i like call it from my_lib > > > Can anyone finish above code and let me try to understand > > Class inheritance? > > TIA. > > Have you read any Python tutorial? There are several basic errors in > your code which would suggest that you haven't. You really ought to; > it's well worth it. > The Beginner's Guide links to 2 lists of tutorials:http://wiki.python.org/moin/BeginnersGuide > > There's also the python-tutor mailing list, which is specifically > geared towards answering beginner questions:http://mail.python.org/mailman/listinfo/tutor > > Cheers, > Chris > --http://rebertia.com Thanks Chris! I'll check that link. Test.py #!/usr/bin/python from my_lib import p_test class my_class(p_test.name): def __initial__(self, name): pass def test(self): print "this is a test" If __name__ == '__main__': my_class.main() --------------------------------------------------- my_lib.py class p_test() ....... ........ Can anyone finish it and give me a demo. Class inheritance? for this case, it inherit/change p_test "name" attribute. I try to quick understand how to inherit parent attribute TIA. david From clp2 at rebertia.com Sat Oct 15 04:11:53 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 15 Oct 2011 01:11:53 -0700 Subject: I am a newbie for python and try to understand class Inheritance. In-Reply-To: <751ee720-652c-4ea2-9521-a9017a9be679@k16g2000prb.googlegroups.com> References: <751ee720-652c-4ea2-9521-a9017a9be679@k16g2000prb.googlegroups.com> Message-ID: On Sat, Oct 15, 2011 at 12:59 AM, wrote: > On 10?15?, ??12?04?, Chris Rebert wrote: >> On Fri, Oct 14, 2011 at 11:20 PM, ? wrote: >> > ? ?my_class.main() >> >> Your class doesn't define any method named "main" (you only defined >> test() and __initial__() ), so this call will fail. > how to do it? You'd define a method named "main", just like with "test". You would then call it by doing: my_class().main() > Test.py > #!/usr/bin/python > from my_lib import p_test > class my_class(p_test.name): > ? ?def __initial__(self, name): > ? ? ? ? pass > ? ?def test(self): > ? ? ? print "this is a test" > > If __name__ == '__main__': > ? ?my_class.main() > --------------------------------------------------- > my_lib.py > class p_test() > ....... > ........ > > Can anyone finish it and give me a demo. > Class inheritance? > for this case, it inherit/change p_test "name" attribute. > I try to quick understand how to inherit parent attribute my_lib.py: class ParentClass(object): def __init__(self, name): self.name = name self.species = "Human" test.py: from my_lib import ParentClass class MyClass(ParentClass): def __init__(self, name): super(MyClass, self).__init__(name + " Jones") def print_name(self): print "My name is", self.name print "And I am a", self.species MyClass("Bob").print_name() Note that classes are conventionally named using CamelCaseLikeThis instead of underscore_separated_words. Cheers, Chris From gagsl-py2 at yahoo.com.ar Sat Oct 15 04:21:04 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 15 Oct 2011 01:21:04 -0700 (PDT) Subject: why msvcrt.printf show the first char only? References: <88550536-6cc5-452c-8bca-ba91b175323a@l39g2000pro.googlegroups.com> Message-ID: On 12 oct, 08:50, Nobody wrote: > On Wed, 12 Oct 2011 04:18:25 -0700, install... at 189.cn wrote: > > from ctypes import * > > msvcrt = cdll.msvcrt > > message_string = "Hello world!\n" > > print(msvcrt.printf("Testing: %s", message_string)) > > > when running in eclipse, the result is: > > 1 > > T > > > when running in IDLE, then result is: > > 1 > > > why is that? > > Odd. I get 22 when running from IDLE. > > Also, when using the console, it actually prints the text. I suspect that > stdout gets block-buffered when using an IDE. I can't see any way to get a > reference to stdout, so you can't fflush() it. Launch IDLE from the command line and you'll see the text output. To the OP: I bet your Eclipse runs Python 2.x and IDLE is 3.x. In Python 3.x, "Test..." is a Unicode string, internally represented using two bytes per character. (In contrast, in Python 2.x, "Test..." is a byte string, and u"Test..." is unicode). All ASCII characters have a 0 as their second byte in its internal representation. printf expects a byte string, and stops as soon as it sees the '\0' following the 'T' in 'Testing'. Either use wprintf("Testing..."), or encode the Unicode object into a byte string before calling: printf("Testing...".encode(sys.stdout.encoding)), or tell ctypes about the right parameter type: printf = msvcrt.printf printf.argtypes = [c_char_p] printf("Testing\n") -- Gabriel Genellina From love_ram2040 at yahoo.com Sat Oct 15 04:44:33 2011 From: love_ram2040 at yahoo.com (porxy) Date: Sat, 15 Oct 2011 01:44:33 -0700 (PDT) Subject: Site to open blocked sites, and prohibited and encoded Message-ID: <426ed123-e11a-484f-9d7c-3699b3d84715@h14g2000yqi.googlegroups.com> Site to open blocked sites, and prohibited and encoded http://myway.x90x.net/ From alec.taylor6 at gmail.com Sat Oct 15 04:49:57 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Sat, 15 Oct 2011 19:49:57 +1100 Subject: Site to open blocked sites, and prohibited and encoded In-Reply-To: <426ed123-e11a-484f-9d7c-3699b3d84715@h14g2000yqi.googlegroups.com> References: <426ed123-e11a-484f-9d7c-3699b3d84715@h14g2000yqi.googlegroups.com> Message-ID: Large list: http://proxy.org/ On Sat, Oct 15, 2011 at 7:44 PM, porxy wrote: > Site to open blocked sites, and prohibited and encoded > > http://myway.x90x.net/ > -- > http://mail.python.org/mailman/listinfo/python-list > From steve+comp.lang.python at pearwood.info Sat Oct 15 07:53:16 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 15 Oct 2011 22:53:16 +1100 Subject: Can I search a list for a range of values? References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> Message-ID: <4e99742d$0$29979$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > Yeah, it's legal because you can nest fors and ifs in a list comp. > Stylistic difference, I used "if" instead of "and" because there's no > way that it could be a bitwise and. If you're using Python, there's no way that it could be a bitwise and. > (It's a cross-language safety net that I sometimes use.) I'm not familiar with a language that uses Python syntax but "and" is a bitwise and. Which language is that? -- Steven From steve+comp.lang.python at pearwood.info Sat Oct 15 07:54:46 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 15 Oct 2011 22:54:46 +1100 Subject: argparse zero-length switch References: <17016857.666.1318572326692.JavaMail.geo-discussion-forums@prmi2> Message-ID: <4e997487$0$29979$c3e8da3$5496439d@news.astraweb.com> Carl Banks wrote: > So instead of typing this: > > sp subcommand -s abc foo bar > > they could type this: > > sp subcommand @abc foo bar > > Admittedly a small benefit. I would call it a *cost* and not a benefit at all. Instead of using a standard, familiar user interface for entering command options, you introduce a second special purpose mechanism *just* for entering a section name. -s is at least a mnemonic for "section", @ is not. And it isn't like you gain any extra clarity or expressiveness, or even a major saving of typing! "-s" vs "@". You don't even save a key stroke: "@" requires two keystrokes, just as "-s" does. (Okay, perhaps you save a key stroke if you type a space after the -s.) -s section_name is pretty simple already. Spelling it @section_name is not sufficiently more simple to make up for the burden of introducing unfamiliar syntax. -- Steven From dihedral88888 at googlemail.com Sat Oct 15 08:16:02 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sat, 15 Oct 2011 05:16:02 -0700 (PDT) Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> <21380825.697.1318543555990.JavaMail.geo-discussion-forums@prdw1> Message-ID: <7741987.1212.1318680962678.JavaMail.geo-discussion-forums@prmr13> Conversion utilities are used to ease the burdens for programmers to translate source scripts and codes into different languages or even the same language with revisions. Check for translators for C, C++, PASCAL, BASIC, and FORTRAN and also SWIG, PYREX, CYTHON, JYTHON and etc.. From dihedral88888 at googlemail.com Sat Oct 15 08:16:02 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sat, 15 Oct 2011 05:16:02 -0700 (PDT) Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> <21380825.697.1318543555990.JavaMail.geo-discussion-forums@prdw1> Message-ID: <7741987.1212.1318680962678.JavaMail.geo-discussion-forums@prmr13> Conversion utilities are used to ease the burdens for programmers to translate source scripts and codes into different languages or even the same language with revisions. Check for translators for C, C++, PASCAL, BASIC, and FORTRAN and also SWIG, PYREX, CYTHON, JYTHON and etc.. From rosuav at gmail.com Sat Oct 15 08:45:28 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 15 Oct 2011 23:45:28 +1100 Subject: Can I search a list for a range of values? In-Reply-To: <4e99742d$0$29979$c3e8da3$5496439d@news.astraweb.com> References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> <4E98B801.7090900@tim.thechases.com> <4e99742d$0$29979$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Oct 15, 2011 at 10:53 PM, Steven D'Aprano wrote: > I'm not familiar with a language that uses Python syntax but "and" is a > bitwise and. Which language is that? > I'm not familiar with any either, it's just that I have a few habits that I slip into. ChrisA From invalid at invalid.invalid Sat Oct 15 09:47:07 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Sat, 15 Oct 2011 13:47:07 +0000 (UTC) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> Message-ID: On 2011-10-14, Westley Mart?nez wrote: > On Thu, Oct 13, 2011 at 11:56:20PM -0700, Carl Banks wrote: > > While we're at it, let's throw in the register keyword. Yah! C compilers have been ignoring it for ages, and I miss it. -- Grant From kevin.p.dwyer at gmail.com Sat Oct 15 10:46:57 2011 From: kevin.p.dwyer at gmail.com (Kev Dwyer) Date: Sat, 15 Oct 2011 15:46:57 +0100 Subject: Fwd: os.statvfs bug or my incompetence ? References: <4E97DB66.50302@nsn.com> <4E97F093.4000203@nsn.com> Message-ID: Peter G. Marczis wrote: Hello Peter, Welcome to the list. Have you tried calling statvfs from a C program? What happens if you do? Best regards, Kev From chris.cocuzzo at gmail.com Sat Oct 15 11:03:21 2011 From: chris.cocuzzo at gmail.com (pngrv) Date: Sat, 15 Oct 2011 08:03:21 -0700 (PDT) Subject: Help with beginner form using lpthw.web Message-ID: <19577343.847.1318691001313.JavaMail.geo-discussion-forums@vbzc27> Hey -- I'm still learning what all of the different exceptions and errors mean. What I'd like to do is grab a bit of assistance figuring out the error I'm getting so that I can keep moving. My python code for this particular part of the app looks like this: class rs_request: def GET(self): return render.rs_request() def POST(self): form = web.input(name='Dood', project='Awesome', locations='1', engines='1') request_string = 'Request: %s, %s, %s, %s' % (form.name, form.project, form.locations, form.engines) return render.index(request_string = request_string) My HTML: Please Use This Form To Request Resources
Name:
Project:
# of Locations:
# of Engines:



$def with (request_string) $if request_string: I just wanted to say $request_string. $else: Hello, world! And seeing this error: at /rs_request invalid syntax Template traceback: File 'templates/rs_request.html', line 30 (rs_request.html, line 30) Python /Library/Python/2.7/site-packages/web/template.py in compile_template, line 909 Web GET http://localhost:8080/rs_request So, it seems to be indicating that my GET request is broken, but I don't really understand why. Can anyone help? From eswint at vt.edu Sat Oct 15 11:17:17 2011 From: eswint at vt.edu (Ethan Swint) Date: Sat, 15 Oct 2011 11:17:17 -0400 Subject: Python hangs: Problem with wxPython, threading, pySerial, or events? Message-ID: <4E99A3FD.1010708@vt.edu> Hi- I'm experiencing crashes in my Win32 Python 2.7 application which appear to be linked to pyzmq. At the moment, I can't even kill the "python.exe *32" process in the Windows Task Manager. At the moment I'm running the script using Ipython by calling C:\Python27\pythonw.exe "/python27/scripts/ipython-qtconsole-script.pyw" -pylab but I also experience similar behavior when running within Eclipse. I've included an error message at the end which appears in the Windows 'cmd' window, but the message is not reflected in the pylab window. My attached device is transmitting <160><1><2><3><4><80> and is received correctly when I run the sample pyserial script 'wxTerminal.py'. In my application, however, the message appears to get characters out of order or drop bytes. If there's a better place to post or if you'd like more info, let me know. Thanks, Ethan ------------------Serial Port Listening Thread---------------------------------------- def MotorRxThread(self): """Thread that handles the incoming traffic. Does buffer input and generates an SerialRxEvent""" while self.alive.isSet(): #loop while alive event is true text = self.serMotor.read(1) #read one, with timeout if text: #check if not timeout n = self.serMotor.inWaiting() #look if there is more to read if n: text = text + self.serMotor.read(n) #get it #log to terminal printstring = "MotorRxThread: " for b in text: printstring += str(ord(b)) + " " print printstring #pdb.set_trace() if self.motorRx0.proc_string(text): print "Message: cmd: " + str(self.motorRx0.cmd) + " data: " + str(self.motorRx0.data) event = SerialRxSpeedEvent(self.GetId(), text) self.GetEventHandler().AddPendingEvent(event) -----------------\Serial Port Listening Thread---------------------------------------- ----------------Thread Start&Stop------------------------------------------------------ def StartMotorThread(self): """Start the receiver thread""" self.motorThread = threading.Thread(target=self.MotorRxThread) self.motorThread.setDaemon(1) self.alive.set() self.motorThread.start() def StopMotorThread(self): """Stop the receiver thread, wait until it's finished.""" if self.motorThread is not None: self.alive.clear() #clear alive event for thread self.motorThread.join() #wait until thread has finished self.motorThread = None self.serMotor.close() #close the serial port connection ----------------\Thread Start&Stop------------------------------------------------------ -------------------Error message -------------------------------------------------------- ValueError: '' is not in list ([], ['', '', '', '{"date":"2011-10-15T10:24:27.231000","username":"kernel","session":"82906c8a-1235-44d0-b65d- 0882955305c1","msg_id":"7cfcd155-bc05-4f47-9c39-094252223dab","msg_type":"stream"}', '{"date":"2011-10-15T10:24:27.23100 0","username":"kernel","session":"82906c8a-1235-44d0-b65d-0882955305c1","msg_id":"f4b88228-b353-4cfb-9bbe-ae524ee1ac38", "msg_type":"stream"}', '{"date":"2011-10-15T10:24:00.774000","username":"username","session":"9f393860-c2ab-44e9-820d-8f 08ae35044e","msg_id":"13a46e93-8da2-487b-ab12-6cae47b1ac34","msg_type":"execute_request"}', '{"date":"2011-10-15T10:24:0 0.774000","username":"username","session":"9f393860-c2ab-44e9-820d-8f08ae35044e","msg_id":"13a46e93-8da2-487b-ab12-6cae4 7b1ac34","msg_type":"execute_request"}', '{"data":"\\nMotorRxThread: 0 MotorRxThread: 4 ","name":"stdout"}']) ERROR:root:Exception in I/O handler for fd Traceback (most recent call last): File "C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\ioloop.py", line 291, in start self._handlers[fd](fd, events) File "C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\stack_context.py", line 133, in wrapped callback(*args, **kwargs) File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", line 448, in _handle_events self._handle_recv() File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", line 458, in _handle_recv ident,msg = self.session.recv(self.socket) File "C:\Python27\lib\site-packages\IPython\zmq\session.py", line 585, in recv raise e ValueError: No JSON object could be decoded ERROR:root:Exception in I/O handler for fd Traceback (most recent call last): File "C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\ioloop.py", line 291, in start self._handlers[fd](fd, events) File "C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\stack_context.py", line 133, in wrapped callback(*args, **kwargs) File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", line 448, in _handle_events self._handle_recv() File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", line 458, in _handle_recv ident,msg = self.session.recv(self.socket) File "C:\Python27\lib\site-packages\IPython\zmq\session.py", line 579, in recv idents, msg_list = self.feed_identities(msg_list, copy) File "C:\Python27\lib\site-packages\IPython\zmq\session.py", line 609, in feed_identities idx = msg_list.index(DELIM) ValueError: '' is not in list --------------------------------------------------------------------------- ZMQError Traceback (most recent call last) C:\Users\Ethan\ in () C:\Python27\lib\site-packages\IPython\zmq\ipkernel.pyc in main() 671 """Run an IPKernel as an application""" 672 app = IPKernelApp.instance() --> 673 app.initialize() 674 app.start() 675 C:\Python27\lib\site-packages\IPython\zmq\ipkernel.pyc in initialize(self=, arg v=None) 604 ) 605 def initialize(self, argv=None): --> 606 super(IPKernelApp, self).initialize(argv) 607 self.init_shell() 608 self.init_extensions() C:\Python27\lib\site-packages\IPython\zmq\kernelapp.pyc in initialize(self=, ar gv=None) 213 self.init_session() 214 self.init_poller() --> 215 self.init_sockets() 216 self.init_io() 217 self.init_kernel() C:\Python27\lib\site-packages\IPython\zmq\kernelapp.pyc in init_sockets(self=) 148 149 self.shell_socket = context.socket(zmq.XREP) --> 150 self.shell_port = self._bind_socket(self.shell_socket, self.shell_port) 151 self.log.debug("shell XREP Channel on port: %i"%self.shell_port) 152 C:\Python27\lib\site-packages\IPython\zmq\kernelapp.pyc in _bind_socket(self=, s=, port=50104) 137 port = s.bind_to_random_port(iface) 138 else: --> 139 s.bind(iface + ':%i'%port) 140 return port 141 C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\core\socket.pyd in zmq.core.socket.Socket.bind (zmq\core\s ocket.c:4527)() ZMQError: Address in use ---------\ERROR MESSAGE-------------------------------------------------- From debatem1 at gmail.com Sat Oct 15 13:12:22 2011 From: debatem1 at gmail.com (geremy condra) Date: Sat, 15 Oct 2011 10:12:22 -0700 Subject: Opportunity missed by Python ? In-Reply-To: <1dd5aa8c-7a41-4108-8940-ef666cd2ddb9@t38g2000prg.googlegroups.com> References: <4e96b324$0$1007$426a34cc@news.free.fr> <1dd5aa8c-7a41-4108-8940-ef666cd2ddb9@t38g2000prg.googlegroups.com> Message-ID: On Fri, Oct 14, 2011 at 5:49 PM, alex23 wrote: > On Oct 13, 8:07?pm, Chris Angelico wrote: >> Python, as I found out to my detriment, is practically impossible to >> sandbox effectively. > > The latest version of PyPy introduces a prototype sandbox: > > http://pypy.org/features.html#sandboxing > > It'll be interesting to see how effective this is. Please note that their sandbox, while a good idea, is not a guaranteed jail. It's enforced by replacing calls to external libraries with trampoline stubs, but does not appear to have any intrinsic mechanism to prevent calls from being issued without it. That means that if you were able to successfully inject code you would be no more protected here than with any other process. Geremy Condra > -- > http://mail.python.org/mailman/listinfo/python-list > From dihedral88888 at googlemail.com Sat Oct 15 13:27:39 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sat, 15 Oct 2011 10:27:39 -0700 (PDT) Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> <1dd5aa8c-7a41-4108-8940-ef666cd2ddb9@t38g2000prg.googlegroups.com> Message-ID: <13798736.1338.1318699659752.JavaMail.geo-discussion-forums@prmr13> The undetected recursive call loop in some states that can be hacked or would hang and crush! Every program has to be run in a VM is just one solution but that will slow down a lot. From dihedral88888 at googlemail.com Sat Oct 15 13:27:39 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sat, 15 Oct 2011 10:27:39 -0700 (PDT) Subject: Opportunity missed by Python ? In-Reply-To: References: <4e96b324$0$1007$426a34cc@news.free.fr> <1dd5aa8c-7a41-4108-8940-ef666cd2ddb9@t38g2000prg.googlegroups.com> Message-ID: <13798736.1338.1318699659752.JavaMail.geo-discussion-forums@prmr13> The undetected recursive call loop in some states that can be hacked or would hang and crush! Every program has to be run in a VM is just one solution but that will slow down a lot. From woodygar at sky.com Sat Oct 15 13:30:59 2011 From: woodygar at sky.com (Gary) Date: Sat, 15 Oct 2011 18:30:59 +0100 Subject: hi can someone help please key bind Message-ID: <4E99C353.6070602@sky.com> Hi im trying to use key bind on Tkinter to call this function def Start(): for i in range(60,-1,-1): ent['text'] = i time.sleep(1) root.update() ent['text'] = 'Time Out!' root.update() i know the function is ok as i have assigned a button and i calls the function as i expect but root.bind('',Start) gives the following error Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__ return self.func(*args) TypeError: Start() takes no arguments (1 given) Thanks From gnarlodious at gmail.com Sat Oct 15 14:00:17 2011 From: gnarlodious at gmail.com (Gnarlodious) Date: Sat, 15 Oct 2011 11:00:17 -0700 (PDT) Subject: Loop through a dict changing keys Message-ID: What is the best way (Python 3) to loop through dict keys, examine the string, change them if needed, and save the changes to the same dict? So for input like this: {'Mobile': 'string', 'context': '', 'order': '7', 'time': 'True'} I want to booleanize 'True', turn '7' into an integer, escape '', and ignore 'string'. Any elegant Python way to do this? -- Gnarlie From alex.kapps at web.de Sat Oct 15 15:31:06 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Sat, 15 Oct 2011 21:31:06 +0200 Subject: Loop through a dict changing keys In-Reply-To: References: Message-ID: <4E99DF7A.6060707@web.de> On 15.10.2011 20:00, Gnarlodious wrote: > What is the best way (Python 3) to loop through dict keys, examine the > string, change them if needed, and save the changes to the same dict? > > So for input like this: > {'Mobile': 'string', 'context': '', 'order': '7', > 'time': 'True'} > > I want to booleanize 'True', turn '7' into an integer, escape > '', and ignore 'string'. > > Any elegant Python way to do this? > > -- Gnarlie I think JSON could be of some use, but I've not used it yet, otherwise something like this could do it: #!/usr/bin/python from cgi import escape def convert(string): for conv in (int, lambda x: {'True': True, 'False': False}[x], escape): try: return conv(string) except (KeyError, ValueError): pass return string d = {'Mobile': 'string', 'context': '', 'order': '7', 'time': 'True'} print d for key in d: d[key] = convert(d[key]) print d $ ./conv.py {'Mobile': 'string', 'order': '7', 'context': '', 'time': 'True'} {'Mobile': 'string', 'order': 7, 'context': '<malicious code>', 'time': True} From python at mrabarnett.plus.com Sat Oct 15 15:34:14 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 15 Oct 2011 20:34:14 +0100 Subject: hi can someone help please key bind In-Reply-To: <4E99C353.6070602@sky.com> References: <4E99C353.6070602@sky.com> Message-ID: <4E99E036.4060102@mrabarnett.plus.com> On 15/10/2011 18:30, Gary wrote: > Hi im trying to use key bind on Tkinter to call this function > > def Start(): > for i in range(60,-1,-1): > ent['text'] = i > time.sleep(1) > root.update() > ent['text'] = 'Time Out!' > root.update() > > i know the function is ok as i have assigned a button and i calls the > function as i expect > but > root.bind('',Start) > gives the following error > > Exception in Tkinter callback > Traceback (most recent call last): > File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__ > return self.func(*args) > TypeError: Start() takes no arguments (1 given) > The function will be called with an 'event' parameter, but you've defined it function to accept no parameters, hence the error message. From alex.kapps at web.de Sat Oct 15 15:35:08 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Sat, 15 Oct 2011 21:35:08 +0200 Subject: hi can someone help please key bind In-Reply-To: <4E99C353.6070602@sky.com> References: <4E99C353.6070602@sky.com> Message-ID: <4E99E06C.9050904@web.de> On 15.10.2011 19:30, Gary wrote: > Hi im trying to use key bind on Tkinter to call this function > > def Start(): > for i in range(60,-1,-1): > ent['text'] = i > time.sleep(1) > root.update() > ent['text'] = 'Time Out!' > root.update() > > i know the function is ok as i have assigned a button and i calls > the function as i expect > but > root.bind('',Start) > gives the following error > > Exception in Tkinter callback > Traceback (most recent call last): > File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__ > return self.func(*args) > TypeError: Start() takes no arguments (1 given) > > Thanks As the error indicates, the callback function is called with an argument, but you don't provide one. That argument is an Event instance, so you can get details about the event. Use def Start(event): ... BTW. functions, unlike classes should be all lower-case. From python at mrabarnett.plus.com Sat Oct 15 15:37:38 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 15 Oct 2011 20:37:38 +0100 Subject: Loop through a dict changing keys In-Reply-To: References: Message-ID: <4E99E102.2050904@mrabarnett.plus.com> On 15/10/2011 19:00, Gnarlodious wrote: > What is the best way (Python 3) to loop through dict keys, examine the > string, change them if needed, and save the changes to the same dict? > > So for input like this: > {'Mobile': 'string', 'context': '', 'order': '7', > 'time': 'True'} > > I want to booleanize 'True', turn '7' into an integer, escape > '', and ignore 'string'. > > Any elegant Python way to do this? > How about: for key, value in my_dict.items(): if value == "True": my_dict[key] = True From alex.kapps at web.de Sat Oct 15 15:48:54 2011 From: alex.kapps at web.de (Alexander Kapps) Date: Sat, 15 Oct 2011 21:48:54 +0200 Subject: Usefulness of the "not in" operator In-Reply-To: References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4e907583$0$29989$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E99E3A6.7030001@web.de> On 10.10.2011 19:29, Nobody wrote: > On Sun, 09 Oct 2011 02:25:27 +0200, Alexander Kapps wrote: > >> Even if it's off-topic, could you add some similar explanations for >> Church numerals (maybe Lambda calculus it isn't too much?) > > The Church numeral for N is a function of two arguments which applies its > first argument N times to its second, i.e. (f^N)(x) = f(f(...(f(x))...)). [SNIP] Thanks! That's a lot more understandable than Wikipedia. Some brain-food for the winter. ;-) From sundstromen at gmail.com Sat Oct 15 16:13:19 2011 From: sundstromen at gmail.com (=?ISO-8859-1?Q?Jan_Sundstr=F6m?=) Date: Sat, 15 Oct 2011 13:13:19 -0700 (PDT) Subject: How do I get curses to work in Python 3.2 on win-64? Message-ID: <3bc2636a-85b5-47bd-9a47-7c9ee16b2a75@w5g2000yqw.googlegroups.com> How do I get curses to work in Python 3.2 on win-64? I'm new to Python and when exploring Python in console I want to use some simple functions for console programming that don't emulate a typewriter terminal but rather a text screen terminal. I want to be able to clear the screen, position the cursor and do unbuffered reading from the keyboard. Also setting different colors for the text and background. That could in Windows be accomplished by the handy WConio (http:// newcenturycomputers.net/projects/wconio.html) which contains just about everything that is needed for a console application to become useful. However I want to accomplish it in Python 3.2 because I lack the experience to build it myself. Now an alternative would be to use some flavor of curses. Although having a plethora of unnecessary functions it has the advantage of existing for different platforms. I'm currently running Python 3.2.2 on win-64 When Python is installed there is a Python32/Lib/curses library. As I understand it this is only a some sort of wrapper for a curses module to be downloaded and installed later?? So I downloaded and installed a curses module I that found and which seemed appropriate: curses-2.2.win-amd64-py3.2.exe from http://www.lfd.uci.edu/~gohlke/pythonlibs/ It installed some stuff directly in Python32/lib/sitepackages. Now when I try in a program to do things like: import curses stdscr = curses.initscr Python complains it can't find curses. However if I do import _curses stdscr = _curses.initscr etc., everything works fine. I shouldn't have to write the underscores though?? How can I fix that? Should I try to find some other version of curses? It seems I haven't yet grasped how to install a Python module? /John From dihedral88888 at googlemail.com Sat Oct 15 16:38:54 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sat, 15 Oct 2011 13:38:54 -0700 (PDT) Subject: Loop through a dict changing keys In-Reply-To: References: Message-ID: <17691715.1416.1318711141838.JavaMail.geo-discussion-forums@prmr13> Is there an FAQ available here? Please check the PYTHON official site and the active state PYTHON examples first, also check the PLEAC comparisons of a lot programming languages first! ----------------------------------------------------------------------------- Nothing is more thrilling to obtain black magics in text books! From dihedral88888 at googlemail.com Sat Oct 15 16:38:54 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Sat, 15 Oct 2011 13:38:54 -0700 (PDT) Subject: Loop through a dict changing keys In-Reply-To: References: Message-ID: <17691715.1416.1318711141838.JavaMail.geo-discussion-forums@prmr13> Is there an FAQ available here? Please check the PYTHON official site and the active state PYTHON examples first, also check the PLEAC comparisons of a lot programming languages first! ----------------------------------------------------------------------------- Nothing is more thrilling to obtain black magics in text books! From devplayer at gmail.com Sat Oct 15 17:00:20 2011 From: devplayer at gmail.com (DevPlayer) Date: Sat, 15 Oct 2011 14:00:20 -0700 (PDT) Subject: Can I search a list for a range of values? References: <5adec840-0778-4678-8aa8-be34b128cbba@hv4g2000vbb.googlegroups.com> Message-ID: <073a2e4d-0fd9-4680-9fcb-447b264d19e9@w5g2000yqw.googlegroups.com> On Oct 14, 7:46?pm, Ian Kelly wrote: > On Fri, Oct 14, 2011 at 5:36 PM, Troy S wrote: > (Python 3) > date_range = {d:v for d, v in source_dict.items() if '20110809' <= d > <= '20110911'} > Ian- Hide quoted text - > - Show quoted text - (Python 2.7) supports dictionary comprehensions. I prehaps as early as 2.5. From rurpy at yahoo.com Sat Oct 15 17:22:41 2011 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Sat, 15 Oct 2011 14:22:41 -0700 (PDT) Subject: How to generate error when argument are not supplied and there is no explicit defults (in optparse)? References: Message-ID: On 10/14/2011 03:29 PM, Peng Yu wrote: > Hi, > > The following code doesn't give me error, even I don't specify the > value of filename from the command line arguments. filename gets > 'None'. I checked the manual, but I don't see a way to let > OptionParser fail if an argument's value (which has no default > explicitly specified) is not specified. I may miss some thing in the > manual. Could any expert let me know if there is a way to do so? > Thanks! > > #!/usr/bin/env python > > from optparse import OptionParser > > usage = 'usage: %prog [options] arg1 arg2' > parser = OptionParser(usage=usage) > parser.set_defaults(verbose=True) > parser.add_option('-f', '--filename') > > #(options, args) = parser.parse_args(['-f', 'file.txt']) > (options, args) = parser.parse_args() > > print options.filename You can check it yourself. I find I use a pretty standard pattern with optparse: def main (args, opts): ... def parse_cmdline (): p = OptionParser() p.add_option('-f', '--filename') options, args = parser.parse_args() if not options.filename: p.error ("-f option required") if len (args) != 2: p.error ("Expected exactly 2 arguments") # Other checks can obviously be done here too. return args, options if __name__ == '__main__': args, opts = parse_cmdline() main (args, opts) While one can probably subclass OptionParser or use callbacks to achieve the same end, I find the above approach simple and easy to follow. I also presume you know that you have can optparse produce a usage message by adding 'help' arguments to the add_option() calls? And as was mentioned in another post, argparse in Python 2.7 (or in earlier Pythons by downloading/installing it yourself) can do the checking you want. From devplayer at gmail.com Sat Oct 15 17:31:20 2011 From: devplayer at gmail.com (DevPlayer) Date: Sat, 15 Oct 2011 14:31:20 -0700 (PDT) Subject: I am a newbie for python and try to understand class Inheritance. References: Message-ID: On Oct 15, 2:20?am, aaabb... at hotmail.com wrote: > Test.py > ----------- > #!/usr/bin/python > > from my_lib import my_function > > class MyClass(my_function): # usually class names start capital > > """We know you're not forgetting to document.""" > > ? ? def __init__(self, name): > super(MyClass, self).__init__(name) > ? ? ? ? # self.name = name automatically added from base class > > ? ? def test(self): > ? ? ? ? print "this is a test", self.name > > def __call__(self, name): > > # if you are subclassing something named my_function > # then other Python coders -might- expect the subclass > # to behave like a function. > > print "Now this class acts like a function %s" % name > print "because it has a def __call__(self,...)." > return True # not needed but because functions do stuff > > If __name__ == '__main__': > ? ? myclass_instance = MyClass('David') # confusing isn't it to subclass something called my_function > ================================================ > my_lib.py > --------- > class my_function(object): > > """This class acts like a function.""" > > def __init__(self, name): > self.name = SpamSpamAndEggs(name) > > def __call__(self): > # do stuff > return self.name.upper() > ... > > -david I editted your code to something closer to what is expected. Not a law but just a recommendation. Also defining a class my_function(..): --might-- be confusing to others as in Python there are things called functions that look like this: def my_function(name): print "Hi %s" % name note the use of "def" and not "class" Of course if you are making classes that represent custom application "functions" verse Python "functions" then yeah, calling your class: class MyFunction(object): ... makes sense I included the __doc__ "You are documenting" stuff because you seem so new. Otherwise when posting here they're not expected to be in these posts. From devplayer at gmail.com Sat Oct 15 18:04:24 2011 From: devplayer at gmail.com (DevPlayer) Date: Sat, 15 Oct 2011 15:04:24 -0700 (PDT) Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> Message-ID: <4acd4e59-cf83-47f5-ac6c-ee0cbec8aa34@u13g2000vbx.googlegroups.com> On Oct 8, 8:41?am, Alain Ketterlin wrote: > candide writes: > > Python provides > > > ? ? -- the not operator, meaning logical negation > > ? ? -- the in operator, meaning membership > > > On the other hand, Python provides the not in operator meaning > > non-membership. However, it seems we can reformulate any "not in" > > expression using only "not" and "in" operation. > > Sure, but note that you can also reformulate != using not and ==, < > using not and >=, etc. Operators like "not in" and "is not" should > really be considered single tokens, even though they seem to use "not". > And I think they are really convenient. > > -- Alain. 1. I thought "x not in y" was later added as syntax sugar for "not x in y" meaning they used the same set of tokens. (Too lazy to check the actual tokens) 2. "x not in y" ==>> (True if y.__call__(x) else False) class Y(object): def __contains__(self, x): for item in y: if x == y: return True return False And if you wanted "x not in y" to be a different token you'd have to ADD class Y(object): def __not_contained__(self, x): for item in self: if x == y: return False return True AND with __not_contained__() you'd always have to iterate the entire sequence to make sure even the last item doesn't match. SO with one token "x not in y" you DON'T have to itterate through the entire sequence thus it is more effiecient. From gshanemiller at verizon.net Sat Oct 15 19:00:17 2011 From: gshanemiller at verizon.net (Shane) Date: Sat, 15 Oct 2011 16:00:17 -0700 (PDT) Subject: type(), modules: clarification please Message-ID: <598dc382-bbc0-49e1-ad30-ff6b61b977f6@w5g2000yqw.googlegroups.com> Hi, When one writes, > className='Employee' > baseClasses = ... > dictionary = { ... } > newClass = type( className, , dictionary) in what module does newClass belong? If it's the current module what code do I run to print out the name of that module in a.b.c... form? Related: If I want to make `newClass' into a module called, say, a.b.c.d.e how do I do that? This doesn't work: > className='a.b.c.d.e.Employee' > newClass = type( className, , dictionary) As far as I know the correct procedure involves three steps: > import a.b.c.d.e as targetModule > newClass = type( className, , dictionary) > setattr( targetModule, 'newClassInTarget', newClass ) > obj = targetModule.newClassInTarget() I am not sure if newClass remains a valid type in whatever module it was created in. Final question. If, as an academic exercise I wanted to recursively dump all the classes in a module (and its sub-modules) would I do this? [I use some pseudo code]: def dump( namespace ): for i in dir(namespace): if i is a class: print i elif i is a module: dump(i) dump( ) Thank you From clp2 at rebertia.com Sat Oct 15 19:18:46 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 15 Oct 2011 16:18:46 -0700 Subject: type(), modules: clarification please In-Reply-To: <598dc382-bbc0-49e1-ad30-ff6b61b977f6@w5g2000yqw.googlegroups.com> References: <598dc382-bbc0-49e1-ad30-ff6b61b977f6@w5g2000yqw.googlegroups.com> Message-ID: On Sat, Oct 15, 2011 at 4:00 PM, Shane wrote: > Hi, > > When one writes, > >> className='Employee' >> baseClasses = ... >> dictionary = { ... } >> newClass = type( className, , dictionary) > > in what module does newClass belong? If it's the current module That does seem to be the case. > what code > do I run to print out the name of that module in a.b.c... form? newClass.__module__ is a string containing the (apparently) qualified name of the module wherein newClass was defined. > Final question. If, as an academic exercise I wanted to recursively > dump > all the classes in a module (and its sub-modules) would I do this? [I > use > some pseudo code]: > > def dump( namespace ): > ? ? ? for i in dir(namespace): > ? ? ? ? ? ? ?if i is a class: > ? ? ? ? ? ? ? ? ? print i > ? ? ? ? ? ? ?elif i is a module: > ? ? ? ? ? ? ? ? ? dump(i) > > dump( ) Pretty much, though `i` is just a string, so you'll need to use getattr() to get the actual value of the corresponding variable. You may also need to watch out for circular references so that your function doesn't get stuck in an infinite loop. FYI, `inspect` module had functions to test for class-ness and module-ness. http://docs.python.org/library/inspect.html Cheers, Chris -- http://rebertia.com From pod at internode.on.net Sat Oct 15 19:53:32 2011 From: pod at internode.on.net (PoD) Date: 15 Oct 2011 23:53:32 GMT Subject: Loop through a dict changing keys References: Message-ID: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Oct 2011 11:00:17 -0700, Gnarlodious wrote: > What is the best way (Python 3) to loop through dict keys, examine the > string, change them if needed, and save the changes to the same dict? > > So for input like this: > {'Mobile': 'string', 'context': '', 'order': '7', > 'time': 'True'} > > I want to booleanize 'True', turn '7' into an integer, escape > '', and ignore 'string'. > > Any elegant Python way to do this? > > -- Gnarlie How about data = { 'Mobile': 'string', 'context': '', 'order': '7', 'time': 'True'} types={'Mobile':str,'context':str,'order':int,'time':bool} for k,v in data.items(): data[k] = types[k](v) From tdsimpson at gmail.com Sat Oct 15 21:48:57 2011 From: tdsimpson at gmail.com (Troy S) Date: Sat, 15 Oct 2011 21:48:57 -0400 Subject: Reading a file into a data structure.... In-Reply-To: References: <763d6391-fc4d-4b47-b0c3-d3ad16e0fc38@gy7g2000vbb.googlegroups.com> Message-ID: Chris, Thanks for the help. I am using the powerball numbers from this text file downloaded from the site. http://www.powerball.com/powerball/winnums-text.txt The first row is the header/fieldnames and the file starts off like this: Draw Date WB1 WB2 WB3 WB4 WB5 PB PP 10/12/2011 43 10 12 23 47 18 3 10/08/2011 35 03 37 27 45 31 5 10/05/2011 46 07 43 54 20 17 4 10/01/2011 27 43 12 23 01 31 3 09/28/2011 41 51 30 50 53 08 2 09/24/2011 27 12 03 04 44 26 5 09/21/2011 47 52 55 48 12 13 4 The testing of a digit was used to skip the first row only. I'm stil dissecting your Python code to better understand the use of collection, namedtuples, etc. I have not found many examples/descriptions yet about collections, namedtuples, etc. I don't quite understand them that much. Do you know of a reference that can break this stuff down better for me? The couple of books that I have on Python do not go into collection, namedtuples, etc that much. Thanks, On Sat, Oct 15, 2011 at 12:47 AM, Chris Rebert wrote: > On Fri, Oct 14, 2011 at 7:59 PM, MrPink wrote: >> This is what I have been able to accomplish: >> >> def isInt(s): >> ? ?try: >> ? ? ? ?i = int(s) >> ? ? ? ?return True >> ? ?except ValueError: >> ? ? ? ?return False >> >> f = open("powerball.txt", "r") >> lines = f.readlines() >> f.close() >> >> dDrawings = {} >> for line in lines: >> ? ?if isInt(line[0]): >> ? ? ? ?t = line.split() >> ? ? ? ?d = t[0] >> ? ? ? ?month,day,year = t[0].split("/") >> ? ? ? ?i = int(year + month + day) >> ? ? ? ?wb = t[1:6] >> ? ? ? ?wb.sort() >> ? ? ? ?pb = t[6] >> ? ? ? ?r = {'d':d,'wb':wb,'pb':pb} >> ? ? ? ?dDrawings[i] = r >> >> The dictionary dDrawings contains records like this: >> dDrawings[19971101] >> {'pb': '20', 'd': '11/01/1997', 'wb': ['22', '25', '28', '33', '37']} >> >> I am now able to search for ticket in a date range. >> keys = dDrawings.keys() >> b = [key for key in keys if 20110909 <= key <= 20111212] >> >> How would I search for matching wb (White Balls) in the drawings? >> >> Is there a better way to organize the data so that it will be flexible >> enough for different types of searches? >> Search by date range, search by pb, search by wb matches, etc. >> >> I hope this all makes sense. > > from datetime import datetime > from collections import namedtuple, defaultdict > # for efficient searching by date: import bisect > > DATE_FORMAT = "%m/%d/%Y" > Ticket = namedtuple('Ticket', "white_balls powerball date".split()) > > powerball2ticket = defaultdict(set) > whiteball2ticket = defaultdict(set) > tickets_by_date = [] > > with open("powerball.txt", "r") as f: > ? ?for line in f: > ? ? ? ?if not line[0].isdigit(): > ? ? ? ? ? ?# what are these other lines anyway? > ? ? ? ? ? ?continue # skip such lines > > ? ? ? ?fields = line.split() > > ? ? ? ?date = datetime.strptime(fields[0], DATE_FORMAT).date() > ? ? ? ?white_balls = frozenset(int(num_str) for num_str in fields[1:6]) > ? ? ? ?powerball = int(fields[6]) > ? ? ? ?ticket = Ticket(white_balls, powerball, date) > > ? ? ? ?powerball2ticket[powerball].add(ticket) > ? ? ? ?for ball in white_balls: > ? ? ? ? ? ?whiteball2ticket[ball].add(ticket) > ? ? ? ?tickets_by_date.append(ticket) > > tickets_by_date.sort(key=lambda ticket: ticket.date) > > print(powerball2ticket[7]) # all tickets with a 7 powerball > print(whiteball2ticket[3]) # all tickets with a non-power 3 ball > > > Cheers, > Chris > -- > http://rebertia.com > -- Troy S From tdsimpson at gmail.com Sat Oct 15 22:18:18 2011 From: tdsimpson at gmail.com (MrPink) Date: Sat, 15 Oct 2011 19:18:18 -0700 (PDT) Subject: Reading a file into a data structure.... References: <763d6391-fc4d-4b47-b0c3-d3ad16e0fc38@gy7g2000vbb.googlegroups.com> Message-ID: I did not understand what a tuple was. So it was very hard for me to understand what a namedtuple was and follow the code. Then I looked up the word at dictionary.com and got this: http://dictionary.reference.com/browse/tuple tuple: computing a row of values in a relational database Now I understand a little better what a tuple is and can follow the code better. A namedtuple seems like a dictionary type. I'll need to read up on the difference between the two. Thanks again. On Oct 15, 12:47?am, Chris Rebert wrote: > On Fri, Oct 14, 2011 at 7:59 PM,MrPink wrote: > > This is what I have been able to accomplish: > > > def isInt(s): > > ? ?try: > > ? ? ? ?i = int(s) > > ? ? ? ?return True > > ? ?except ValueError: > > ? ? ? ?return False > > > f = open("powerball.txt", "r") > > lines = f.readlines() > > f.close() > > > dDrawings = {} > > for line in lines: > > ? ?if isInt(line[0]): > > ? ? ? ?t = line.split() > > ? ? ? ?d = t[0] > > ? ? ? ?month,day,year = t[0].split("/") > > ? ? ? ?i = int(year + month + day) > > ? ? ? ?wb = t[1:6] > > ? ? ? ?wb.sort() > > ? ? ? ?pb = t[6] > > ? ? ? ?r = {'d':d,'wb':wb,'pb':pb} > > ? ? ? ?dDrawings[i] = r > > > The dictionary dDrawings contains records like this: > > dDrawings[19971101] > > {'pb': '20', 'd': '11/01/1997', 'wb': ['22', '25', '28', '33', '37']} > > > I am now able to search for ticket in a date range. > > keys = dDrawings.keys() > > b = [key for key in keys if 20110909 <= key <= 20111212] > > > How would I search for matching wb (White Balls) in the drawings? > > > Is there a better way to organize the data so that it will be flexible > > enough for different types of searches? > > Search by date range, search by pb, search by wb matches, etc. > > > I hope this all makes sense. > > from datetime import datetime > from collections import namedtuple, defaultdict > # for efficient searching by date: import bisect > > DATE_FORMAT = "%m/%d/%Y" > Ticket = namedtuple('Ticket', "white_balls powerball date".split()) > > powerball2ticket = defaultdict(set) > whiteball2ticket = defaultdict(set) > tickets_by_date = [] > > with open("powerball.txt", "r") as f: > ? ? for line in f: > ? ? ? ? if not line[0].isdigit(): > ? ? ? ? ? ? # what are these other lines anyway? > ? ? ? ? ? ? continue # skip such lines > > ? ? ? ? fields = line.split() > > ? ? ? ? date = datetime.strptime(fields[0], DATE_FORMAT).date() > ? ? ? ? white_balls = frozenset(int(num_str) for num_str in fields[1:6]) > ? ? ? ? powerball = int(fields[6]) > ? ? ? ? ticket = Ticket(white_balls, powerball, date) > > ? ? ? ? powerball2ticket[powerball].add(ticket) > ? ? ? ? for ball in white_balls: > ? ? ? ? ? ? whiteball2ticket[ball].add(ticket) > ? ? ? ? tickets_by_date.append(ticket) > > tickets_by_date.sort(key=lambda ticket: ticket.date) > > print(powerball2ticket[7]) # all tickets with a 7 powerball > print(whiteball2ticket[3]) # all tickets with a non-power 3 ball > > Cheers, > Chris > --http://rebertia.com From pavlovevidence at gmail.com Sat Oct 15 23:29:40 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 15 Oct 2011 20:29:40 -0700 (PDT) Subject: argparse zero-length switch In-Reply-To: References: <17016857.666.1318572326692.JavaMail.geo-discussion-forums@prmi2> Message-ID: <7643428.719.1318735780945.JavaMail.geo-discussion-forums@prgv7> On Friday, October 14, 2011 12:41:26 AM UTC-7, Peter Otten wrote: > Carl Banks wrote: > > > Is it possible to specify a zero-length switch? Here's what I mean. > > > > I have a use case where some users would have to enter a section name on > > the command line almost every time, whereas other users (the ones using > > only one section) will never have to enter the section name. I don't want > > to burden users with only one "section" to always enter the section name > > as a required argument, but I also want to make it as convenient as > > possible to enter the section name for those who need to. > > > > My thought, on the thinking that practicality beats purity, was to create > > a zero-length switch using a different prefix character (say, @) to > > indicate the section name. So instead of typing this: > > > > sp subcommand -s abc foo bar > > > > they could type this: > > > > sp subcommand @abc foo bar > > > > Admittedly a small benefit. I tried the following but argparse doesn't > > seem to do what I'd hoped: > > > > p = argparse.ArgumentParser(prefix_chars='-@') > > p.add_argument('@',type=str,dest='section') > > ar = p.parse_args(['@abc']) > > > > This throws an exception claiming unrecognized arguments. > > > > Is there a way (that's not a hack) to do this? Since the current behavior > > of the above code seems to do nothing useful, it could be added to > > argparse with very low risk of backwards incompatibility. > > If the number of positional arguments is otherwise fixed you could make > section a positional argument with nargs="?" The positional arguments aren't fixed, otherwise I would have done it that way. I ended up deciding to prescan the command line for arguments starting with @, and that actually has some benefits over doing it with argparse. (One little surprise is if you pass it something like "-x @abc foo", where foo is the argument of -x.) I don't really care for or agree with Steven and Ben Finney's foolish consistency. I already weighed it against the benefits of consistency, and decided that this parameter was easily important enough to warrant special treatment. It's actually a good thing for this parameter to look different from other switches; it marks it as specially important. Carl Banks From pavlovevidence at gmail.com Sat Oct 15 23:32:18 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 15 Oct 2011 20:32:18 -0700 (PDT) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) In-Reply-To: <7c0baafc-70df-46ec-8482-8bbf267c8231@t38g2000prg.googlegroups.com> References: <4e979b85$0$33912$c3e8da3$66d3cc2f@news.astraweb.com> <20805576.111.1318575380863.JavaMail.geo-discussion-forums@prhj35> <7c0baafc-70df-46ec-8482-8bbf267c8231@t38g2000prg.googlegroups.com> Message-ID: <6575958.1562.1318735938474.JavaMail.geo-discussion-forums@prmr13> On Friday, October 14, 2011 6:23:15 PM UTC-7, alex23 wrote: > On Oct 14, 4:56?pm, Carl Banks > wrote: > > But you can see that, fully realized, syntax like that can do much more > > than can be done with library code. > > Well sure, but imaginary syntax can do _anything_. That doesn't mean > it's possible within CPython. Hey, thanks for backing me up on that sentiment. :) Carl Banks From rosuav at gmail.com Sat Oct 15 23:45:33 2011 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 16 Oct 2011 14:45:33 +1100 Subject: argparse zero-length switch In-Reply-To: <7643428.719.1318735780945.JavaMail.geo-discussion-forums@prgv7> References: <17016857.666.1318572326692.JavaMail.geo-discussion-forums@prmi2> <7643428.719.1318735780945.JavaMail.geo-discussion-forums@prgv7> Message-ID: On Sun, Oct 16, 2011 at 2:29 PM, Carl Banks wrote: > I don't really care for or agree with Steven and Ben Finney's foolish consistency. ?I already weighed it against the benefits of consistency, and decided that this parameter was easily important enough to warrant special treatment. ?It's actually a good thing for this parameter to look different from other switches; it marks it as specially important. I'll weigh in then - in favour of the "foolish" consistency. It's a far more valuable feature than you might imagine. Think how much time your users (even yourself) are going to spend using your program; now think how much time those same people will spend using other programs. You can't fight something that's orders of magnitude bigger than you, so what you'll be doing is creating a special-case that has to be kept in the user's mind. You'll also run into trouble if anyone has a file name that begins @; this situation already exists, but I think most people know not to create a file called "-rf" (and even then, most Unix programs accept "--" to mean "end of options, the next thing is a filename"). Do what everyone else does. You'll thank yourself for it in a year or so. ChrisA From cjgohlke at gmail.com Sun Oct 16 00:59:04 2011 From: cjgohlke at gmail.com (Christoph Gohlke) Date: Sat, 15 Oct 2011 21:59:04 -0700 (PDT) Subject: How do I get curses to work in Python 3.2 on win-64? References: <3bc2636a-85b5-47bd-9a47-7c9ee16b2a75@w5g2000yqw.googlegroups.com> Message-ID: <57034ebb-5278-4a48-9e12-4e068eda820c@v8g2000pro.googlegroups.com> On Oct 15, 1:13?pm, Jan Sundstr?m wrote: > How do I get curses to work in Python 3.2 on win-64? > > I'm new to Python and when exploring Python in console I want to use > some > simple functions for console programming that don't emulate a > typewriter > terminal but rather a text screen terminal. I want to be able to clear > the screen, position the cursor > and do unbuffered reading from the keyboard. Also setting different > colors for the text and background. > > That could in Windows be accomplished by the handy WConio (http:// > newcenturycomputers.net/projects/wconio.html) > which contains just about everything that is needed for a console > application to become useful. > > However I want to accomplish it in Python 3.2 because I lack the > experience to build it myself. Now an alternative would > be to use some flavor of curses. Although having a plethora of > unnecessary functions it has the advantage of > existing for different platforms. > > I'm currently running Python 3.2.2 on win-64 > When Python is installed there is a Python32/Lib/curses library. As I > understand it this is only a some sort of > wrapper for a curses module to be downloaded and installed later?? > > So I downloaded and installed a curses module I that found and which > seemed appropriate: > > curses-2.2.win-amd64-py3.2.exe > > from > > http://www.lfd.uci.edu/~gohlke/pythonlibs/ > > It installed some stuff directly in Python32/lib/sitepackages. > > Now when I try in a program to do things like: > > import curses > stdscr = curses.initscr > > Python complains it can't find curses. However if I do > > import _curses > stdscr = _curses.initscr > > etc., everything works fine. I shouldn't have to write the underscores > though?? > How can I fix that? > Should I try to find some other version of curses? > > It seems I haven't yet grasped how to install a Python module? > > /John `import curses` should work. What exactly is the error message? Does `import curses` work outside your program/program directory? The curses package is part of the standard library and usually installed in Python32\Lib\curses. On Windows the _curses.pyd files is missing in the standard distribution. curses-2.2.win-amd64-py3.2.exe installs the missing _curses.pyd file into Lib/site-packages. From cjgohlke at gmail.com Sun Oct 16 01:05:17 2011 From: cjgohlke at gmail.com (Christoph Gohlke) Date: Sat, 15 Oct 2011 22:05:17 -0700 (PDT) Subject: SciPy/NumPy: read, write images using Python3 References: <9ca46882-acb1-4a23-8b6b-69539ff37d08@n15g2000vbn.googlegroups.com> Message-ID: On Oct 9, 8:43?am, thegripper wrote: > In SciPy / NumPy, the primary way to read and write images is PIL. But > PIL does not yet support Python3. Is there some good way to read, > write, and resize images in a NumPy and Python3 environment? Try Scikits.image . It uses a plugin system to read/write images to/from numpy arrays via FreeImage, PyQt, FITS, GDAL, etc. Other options: Unofficial PIL ports, e.g. or PythonMagick GDAL for raster geospatial data formats PyGame 1.9.2pre , uses SDL_image PyQt 4 From steve+comp.lang.python at pearwood.info Sun Oct 16 01:05:25 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Oct 2011 05:05:25 GMT Subject: Usefulness of the "not in" operator References: <4e902932$0$23273$426a34cc@news.free.fr> <87ehyn8xlp.fsf@dpt-info.u-strasbg.fr> <4acd4e59-cf83-47f5-ac6c-ee0cbec8aa34@u13g2000vbx.googlegroups.com> Message-ID: <4e9a6614$0$29971$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Oct 2011 15:04:24 -0700, DevPlayer wrote: > 1. I thought "x not in y" was later added as syntax sugar for "not x in > y" > meaning they used the same set of tokens. (Too lazy to check the actual > tokens) Whether the compiler has a special token for "not in" is irrelevant. Perhaps it uses one token, or two, or none at all because a pre-processor changes "x not in y" to "not x in y". That's an implementation detail. What's important is whether it is valid syntax or not, and how it is implemented. As it turns out, the Python compiler does not distinguish the two forms: >>> from dis import dis >>> dis(compile('x not in y', '', 'single')) 1 0 LOAD_NAME 0 (x) 3 LOAD_NAME 1 (y) 6 COMPARE_OP 7 (not in) 9 PRINT_EXPR 10 LOAD_CONST 0 (None) 13 RETURN_VALUE >>> dis(compile('not x in y', '', 'single')) 1 0 LOAD_NAME 0 (x) 3 LOAD_NAME 1 (y) 6 COMPARE_OP 7 (not in) 9 PRINT_EXPR 10 LOAD_CONST 0 (None) 13 RETURN_VALUE Also for what it is worth, "x not in y" goes back to at least Python 1.5, and possibly even older. (I don't have any older versions available to test.) > 2. "x not in y" ==>> (True if y.__call__(x) else False) y.__call__ is irrelevant. But for what it's worth: (1) Instead of writing "y.__call__(x)", write "y(x)" (2) Instead of writing "True if blah else False", write "bool(blah)". > class Y(object): > def __contains__(self, x): > for item in y: > if x == y: > return True > return False You don't have to define a __contains__ method if you just want to test each item sequentially. All you need is to obey the sequence protocol and define a __getitem__ that works in the conventional way: >>> class Test: ... def __init__(self, args): ... self._data = list(args) ... def __getitem__(self, i): ... return self._data[i] ... >>> t = Test("abcde") >>> "c" in t True >>> "x" in t False Defining a specialist __contains__ method is only necessary for non- sequences, or if you have some fast method for testing whether an item is in the object quickly. If all you do is test each element one at a time, in numeric order, don't bother writing __contains__. > And if you wanted "x not in y" to be a different token you'd have to ADD Tokens are irrelevant. "x not in y" is defined to be the same as "not x in y" no matter what. You can't define "not in" to do something completely different. > class Y(object): > def __not_contained__(self, x): > for item in self: > if x == y: > return False > return True > > AND with __not_contained__() you'd always have to iterate the entire > sequence to make sure even the last item doesn't match. > > SO with one token "x not in y" you DON'T have to itterate through the > entire sequence thus it is more effiecient. That's not correct. -- Steven From steve+comp.lang.python at pearwood.info Sun Oct 16 01:14:45 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Oct 2011 05:14:45 GMT Subject: argparse zero-length switch References: <17016857.666.1318572326692.JavaMail.geo-discussion-forums@prmi2> <7643428.719.1318735780945.JavaMail.geo-discussion-forums@prgv7> Message-ID: <4e9a6845$0$29971$c3e8da3$5496439d@news.astraweb.com> On Sat, 15 Oct 2011 20:29:40 -0700, Carl Banks wrote: > I don't really care for or agree with Steven and Ben Finney's foolish > consistency. I already weighed it against the benefits of consistency, > and decided that this parameter was easily important enough to warrant > special treatment. It's actually a good thing for this parameter to > look different from other switches; it marks it as specially important. It seems to me that a parameter hardly deserves to be called "specially important" if it is optional and the user can leave it out. "Specially unimportant" is probably a better description. At the end of the day, your claimed motivation for inventing this anti- mnemonic was, and I quote, "to make it as convenient as possible to enter the section name". If you honestly think that typing shift-2 is more convenient than typing -s then go right ahead and do what you like. No skin off my nose. -- Steven From greg.ewing at canterbury.ac.nz Sun Oct 16 01:27:01 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sun, 16 Oct 2011 18:27:01 +1300 Subject: argparse zero-length switch In-Reply-To: <4e997487$0$29979$c3e8da3$5496439d@news.astraweb.com> References: <17016857.666.1318572326692.JavaMail.geo-discussion-forums@prmi2> <4e997487$0$29979$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9fv895F3meU1@mid.individual.net> Steven D'Aprano wrote: > And it isn't like you gain any extra clarity or expressiveness, or even a > major saving of typing! "-s" vs "@". You don't even save a key stroke: "@" > requires two keystrokes, just as "-s" does. Also keep in mind that not all keystrokes are equal. Someone who uses all their fingers probably finds "-s" faster and easier to type than "@". I certainly do. -- Greg From joncle at googlemail.com Sun Oct 16 03:18:40 2011 From: joncle at googlemail.com (Jon Clements) Date: Sun, 16 Oct 2011 00:18:40 -0700 (PDT) Subject: Loop through a dict changing keys References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> Message-ID: <3b79994f-8891-4ab8-bd23-f6fb4e063155@e4g2000vbw.googlegroups.com> On Oct 16, 12:53?am, PoD wrote: > On Sat, 15 Oct 2011 11:00:17 -0700, Gnarlodious wrote: > > What is the best way (Python 3) to loop through dict keys, examine the > > string, change them if needed, and save the changes to the same dict? > > > So for input like this: > > {'Mobile': 'string', 'context': '', 'order': '7', > > 'time': 'True'} > > > I want to booleanize 'True', turn '7' into an integer, escape > > '', and ignore 'string'. > > > Any elegant Python way to do this? > > > -- Gnarlie > > How about > > data = { > ? ? 'Mobile': 'string', > ? ? 'context': '', > ? ? 'order': '7', > ? ? 'time': 'True'} > types={'Mobile':str,'context':str,'order':int,'time':bool} > > for k,v in data.items(): > ? ? data[k] = types[k](v) Bit of nit-picking, but: >>> bool('True') True >>> bool('False') True >>> bool('') False From masood.524 at gmail.com Sun Oct 16 04:03:51 2011 From: masood.524 at gmail.com (masood shaik) Date: Sun, 16 Oct 2011 01:03:51 -0700 (PDT) Subject: callling python function in c Message-ID: <8ca2fc3e-a3be-49c4-8107-a47385bc0911@w26g2000pro.googlegroups.com> Hi I am trying to call python function from c code.The following program i got from the web source while i am trying to run this program it throws an segmentation fault.I am working on Ubuntu 10.10 version.Can anyone guide me please The following program call_function.c // call_function.c - A sample of calling python functions from C code // #include #include int main(int argc, char *argv[]) { int i; PyObject *pName, *pModule, *pDict, *pFunc, *pArgs, *pValue; if (argc < 3) { printf("Usage: exe_name python_source function_name\n"); return 1; } // Initialize the Python Interpreter Py_Initialize(); // Build the name object pName = PyString_FromString(argv[1]); // Load the module object pModule = PyImport_Import(pName); // pDict is a borrowed reference pDict = PyModule_GetDict(pModule); // pFunc is also a borrowed reference pFunc = PyDict_GetItemString(pDict, argv[2]); if (PyCallable_Check(pFunc)) { // Prepare the argument list for the call if( argc > 3 ) { pArgs = PyTuple_New(argc - 3); for (i = 0; i < argc - 3; i++) { pValue = PyInt_FromLong(atoi(argv[i + 3])); if (!pValue) { PyErr_Print(); return 1; } PyTuple_SetItem(pArgs, i, pValue); } pValue = PyObject_CallObject(pFunc, pArgs); if (pArgs != NULL) { Py_DECREF(pArgs); } } else { pValue = PyObject_CallObject(pFunc, NULL); } if (pValue != NULL) { printf("Return of call : %ld\n", PyInt_AsLong(pValue)); Py_DECREF(pValue); } else { PyErr_Print(); } } else { PyErr_Print(); } // Clean up Py_DECREF(pModule); Py_DECREF(pName); // Finish the Python Interpreter Py_Finalize(); return 0; } py_function.py '''py_function.py - Python source designed to demonstrate the use of python embedding''' def multiply(): c = 12345*6789 print 'The result of 12345 x 6789 :', c return c def multiply1(a,b): c = a*b print 'The result of', a, 'x', b, ':', c return c Regards Masood From ian.g.kelly at gmail.com Sun Oct 16 06:15:17 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 16 Oct 2011 04:15:17 -0600 Subject: Reading a file into a data structure.... In-Reply-To: References: <763d6391-fc4d-4b47-b0c3-d3ad16e0fc38@gy7g2000vbb.googlegroups.com> Message-ID: On Sat, Oct 15, 2011 at 8:18 PM, MrPink wrote: > I did not understand what a tuple was. > So it was very hard for me to understand what a namedtuple was and > follow the code. > Then I looked up the word at dictionary.com and got this: > http://dictionary.reference.com/browse/tuple > > tuple: ?computing ?a row of values in a relational database > > Now I understand a little better what a tuple is and can follow the > code better. Python tuples do not have anything to do with relational databases. You would get a better introduction from Wikipedia: http://en.wikipedia.org/wiki/Tuple In Python, tuples are nothing more than immutable sequences, as opposed to lists, which are mutable sequences. Another way of characterizing the difference between lists and tuples is in how they are typically used. A list is typically used for a homogeneous (meaning all elements are treated in the same way) sequence containing an arbitrary number of unrelated objects. A tuple is typically used for a heterogeneous sequence of a certain length. For example, a tuple might be expected to contain exactly two strings and an int that are related in some fashion. > A namedtuple seems like a dictionary type. ?I'll need to read up on > the difference between the two. A namedtuple is a tuple subclass where each of the elements the tuple is expected to contain has been given a specific name for ease of reference. The names are essentially aliases for numerical indices. It differs from a dictionary in that it is ordered and only contains elements with specific names (and always contains those elements), whereas a dictionary contains arbitrary key-value pairs. From pod at internode.on.net Sun Oct 16 07:12:31 2011 From: pod at internode.on.net (PoD) Date: 16 Oct 2011 11:12:31 GMT Subject: Loop through a dict changing keys References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <3b79994f-8891-4ab8-bd23-f6fb4e063155@e4g2000vbw.googlegroups.com> Message-ID: <4e9abc1f$0$14058$c3e8da3$76491128@news.astraweb.com> On Sun, 16 Oct 2011 00:18:40 -0700, Jon Clements wrote: > On Oct 16, 12:53?am, PoD wrote: >> On Sat, 15 Oct 2011 11:00:17 -0700, Gnarlodious wrote: >> > What is the best way (Python 3) to loop through dict keys, examine >> > the string, change them if needed, and save the changes to the same >> > dict? >> >> > So for input like this: >> > {'Mobile': 'string', 'context': '', 'order': '7', >> > 'time': 'True'} >> >> > I want to booleanize 'True', turn '7' into an integer, escape >> > '', and ignore 'string'. >> >> > Any elegant Python way to do this? >> >> > -- Gnarlie >> >> How about >> >> data = { >> ? ? 'Mobile': 'string', >> ? ? 'context': '', >> ? ? 'order': '7', >> ? ? 'time': 'True'} >> types={'Mobile':str,'context':str,'order':int,'time':bool} >> >> for k,v in data.items(): >> ? ? data[k] = types[k](v) > > Bit of nit-picking, but: > >>>> bool('True') > True >>>> bool('False') > True >>>> bool('') > False Oops :) Brain fade. From patlnorr at aim.com Sun Oct 16 10:00:16 2011 From: patlnorr at aim.com (54321) Date: Sun, 16 Oct 2011 07:00:16 -0700 (PDT) Subject: INSTANT PLAY (FLASH) CASINO GAMES Message-ID: <7b1cd41f-9474-4ebf-87d6-97643b391035@g16g2000yqi.googlegroups.com> INSTANT PLAY (FLASH) CASINO GAMES Bettwo.com offers the most prominent casino games including Blackjack, Baccarat, Poker, Craps, Video Poker, Roulette, Slots and many more. Our team of developers strives to introduce exciting new games every month to ensure our customers are playing the most advanced online casino games in the world. Bettwo.com's software was developed and is maintained by RealTime Gaming, one of the leading online gaming software companies in the world. RealTime Gaming's Random Number Generator (RNG) has been tested and certified by Technical Systems Testing, guaranteeing you absolute fairness in every game. Bettwo.com provides the internet's best instant play online casino action. Play our exciting casino games directly in your browser with no download needed! The Flash-based suite of casino games includes a wide selection to choose from, all featuring remarkable graphics combined with smooth, exciting gameplay. Downloading the software to your PC, as opposed to web-based play in your browser, makes the games much quicker and more stable, since all the casino graphics and multimedia effects are already installed on your computer, and US players are welcome - BetTwo.com. http://www.bettwo.com/ Company name: BetTwo.com From nvidhya01 at gmail.com Sun Oct 16 10:04:52 2011 From: nvidhya01 at gmail.com (n v) Date: Sun, 16 Oct 2011 07:04:52 -0700 (PDT) Subject: anagonda sucks ))))))))))))))) Message-ID: http://123maza.com/48/silver424/ From emile at fenx.com Sun Oct 16 12:09:50 2011 From: emile at fenx.com (Emile van Sebille) Date: Sun, 16 Oct 2011 09:09:50 -0700 Subject: Help with beginner form using lpthw.web In-Reply-To: <19577343.847.1318691001313.JavaMail.geo-discussion-forums@vbzc27> References: <19577343.847.1318691001313.JavaMail.geo-discussion-forums@vbzc27> Message-ID: On 10/15/2011 8:03 AM pngrv said... > > > Please Use This Form To Request Resources > > >
> Name:
> Project:
> # of Locations:
> # of Engines: >

> Where do you close this tag? >

>
> $def with (request_string) > $if request_string: > I just wanted to say$request_string. > $else: > Hello, world! > > > > And seeing this error: > at /rs_request > invalid syntax Template traceback: File 'templates/rs_request.html', line 30 (rs_request.html, line 30) Emile From sundstromen at gmail.com Sun Oct 16 12:16:44 2011 From: sundstromen at gmail.com (=?ISO-8859-1?Q?Jan_Sundstr=F6m?=) Date: Sun, 16 Oct 2011 09:16:44 -0700 (PDT) Subject: How do I get curses to work in Python 3.2 on win-64? References: <3bc2636a-85b5-47bd-9a47-7c9ee16b2a75@w5g2000yqw.googlegroups.com> <57034ebb-5278-4a48-9e12-4e068eda820c@v8g2000pro.googlegroups.com> Message-ID: On 16 Okt, 06:59, Christoph Gohlke wrote: > On Oct 15, 1:13?pm, Jan Sundstr?m wrote: > > > > `import curses` should work. What exactly is the error message? Does > `import curses` work outside your program/program directory? > > The curses package is part of the standard library and usually > installed in Python32\Lib\curses. On Windows the ?_curses.pyd files is > missing in the standard distribution. curses-2.2.win-amd64-py3.2.exe > installs the missing _curses.pyd file into Lib/site-packages. Thanks for the tip to check in what library it works, that set me on track tofind a silly mistake that I had done. Now everything works fine. But, how come that the Windows distribution for Python doesn't include the _curses.pyd file? From ramapraba2653 at gmail.com Sun Oct 16 12:21:07 2011 From: ramapraba2653 at gmail.com (SUPREME) Date: Sun, 16 Oct 2011 09:21:07 -0700 (PDT) Subject: SEXY HOT PHOTOS & VIDEOS Message-ID: FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html From gnarlodious at gmail.com Sun Oct 16 14:20:49 2011 From: gnarlodious at gmail.com (Gnarlodious) Date: Sun, 16 Oct 2011 11:20:49 -0700 (PDT) Subject: Loop through a dict changing keys References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> Message-ID: <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> On Oct 15, 5:53?pm, PoD wrote: > data = { > ? ? 'Mobile': 'string', > ? ? 'context': '', > ? ? 'order': '7', > ? ? 'time': 'True'} > types={'Mobile':str,'context':str,'order':int,'time':bool} > > for k,v in data.items(): > ? ? data[k] = types[k](v) Thanks for the tip, I didn't know you could do that. I ended up filtering the values the bulky way, but it gives me total control over what internet users feed my program. -- Gnarlie From hobson42 at gmail.com Sun Oct 16 17:35:14 2011 From: hobson42 at gmail.com (Ian) Date: Sun, 16 Oct 2011 22:35:14 +0100 Subject: python.org appears to be down Message-ID: <4E9B4E12.1040209@gmail.com> Hopefully someone who can do something about it will read this. From rosuav at gmail.com Sun Oct 16 17:44:22 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 17 Oct 2011 08:44:22 +1100 Subject: python.org appears to be down In-Reply-To: <4E9B4E12.1040209@gmail.com> References: <4E9B4E12.1040209@gmail.com> Message-ID: On Mon, Oct 17, 2011 at 8:35 AM, Ian wrote: > Hopefully someone who can do something about it will read this. Working for me. What are you seeing as down? ChrisA From gshanemiller at verizon.net Sun Oct 16 19:11:18 2011 From: gshanemiller at verizon.net (Shane) Date: Sun, 16 Oct 2011 16:11:18 -0700 (PDT) Subject: type vs. module (part2) Message-ID: <242f9fff-a607-4435-a317-200282e84377@o19g2000vbk.googlegroups.com> In the following t,t1 are the result of built-in call type() -- the form that takes three arguments. Therefore they are classes. Consider the following output: print type(t) > print id(t) >1234567 print t.__module__ >a.b.t.d print type(t1) > print id(t1) >1234568 print t1.__module__ >a.b.t.d I now have two questions: How does Python allow two classes of the same type as evidenced by identical ``print type()' output and different id outputs? Also, which module is t,t1 actually in? Is it "a.b.f"? Or is it "a.b.t.d". I am totally confused. From steve+comp.lang.python at pearwood.info Sun Oct 16 19:25:48 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 16 Oct 2011 23:25:48 GMT Subject: Loop through a dict changing keys References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> Message-ID: <4e9b67fb$0$29967$c3e8da3$5496439d@news.astraweb.com> On Sun, 16 Oct 2011 11:20:49 -0700, Gnarlodious wrote: > On Oct 15, 5:53?pm, PoD wrote: > >> data = { >> ? ? 'Mobile': 'string', >> ? ? 'context': '', >> ? ? 'order': '7', >> ? ? 'time': 'True'} >> types={'Mobile':str,'context':str,'order':int,'time':bool} >> >> for k,v in data.items(): >> ? ? data[k] = types[k](v) > > Thanks for the tip, I didn't know you could do that. I ended up > filtering the values the bulky way, What is "the bulky way"? > but it gives me total control over > what internet users feed my program. Why does this not fill me with confidence? As Jon Clements has already spotted a major bug in the above: using bool as shown is not correct. Furthermore, converting '' into a string does nothing, since it is already a string. Gnarlodious, it is good that you are concerned about code injection attacks, but defending against them is not simple or easy. I don't intend to sound condescending, but when your response to being shown a simple filter that maps keys to types is to say "I didn't know you could do that", that's a good warning that your Python experience may not be quite up to the job of out-guessing the sort of obscure tricks hostile attackers may use. If you think that defending against malicious code is simple, you should read this blob post: http://tav.espians.com/a-challenge-to-break-python-security.html and the thread which inspired it: http://mail.python.org/pipermail/python-dev/2009-February/086401.html How do you sanitize user input? -- Steven From ganesh at cs.utah.edu Sun Oct 16 19:52:03 2011 From: ganesh at cs.utah.edu (Ganesh Gopalakrishnan) Date: Sun, 16 Oct 2011 17:52:03 -0600 Subject: Equal sets with unequal print and str() representations Message-ID: <4E9B6E23.9050106@cs.utah.edu> This probably is known, but a potential pitfall (was, for me) nevertheless. I suspect it is due to hash collisions between 's3' and 's13' in this case? It happens only rarely, depending on the contents of the set. >>> S1 = {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'} S1 = {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'} >>> S2 = {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'} S2 = {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'} >>> S1 S1 {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'} >>> S2 S2 {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'} >>> S1==S2 S1==S2 True >>> str(S1) str(S1) "{'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'}" >>> str(S2) str(S2) "{'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'}" >>> str(S1) == str(S2) False -- Ganesh From gnarlodious at gmail.com Sun Oct 16 20:41:55 2011 From: gnarlodious at gmail.com (Gnarlodious) Date: Sun, 16 Oct 2011 17:41:55 -0700 (PDT) Subject: Loop through a dict changing keys References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> <4e9b67fb$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: <66deee18-6595-474e-876d-84e1de21baa2@31g2000prt.googlegroups.com> On Oct 16, 5:25?pm, Steven D'Aprano wrote: > How do you sanitize user input? Thanks for your concern. This is what I now have, which merely expands each value into its usable type (unquotes them): # filter each value try: var=int(var) except ValueError: if var in ('False', 'True'): var=eval(var) # extract booleans else: var=cgi.escape(var) This is really no filtering at all, since all CGI variables are written to a dictionary without checking. However, if there is no receiver for the value I should be safe, right? I am also trapping some input at mod_wsgi, like php query strings. And that IP address gets quarantined. If you can suggest what attack words to block I'll thank you for it. I also have a system to reject variables that are not in a list, but waiting to see what the logfiles show before deploying it. -- Gnarlie http://Gnarlodious.com From ian.g.kelly at gmail.com Sun Oct 16 21:17:57 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 16 Oct 2011 19:17:57 -0600 Subject: Equal sets with unequal print and str() representations In-Reply-To: <4E9B6E23.9050106@cs.utah.edu> References: <4E9B6E23.9050106@cs.utah.edu> Message-ID: On Sun, Oct 16, 2011 at 5:52 PM, Ganesh Gopalakrishnan wrote: > This probably is known, but a potential pitfall (was, for me) nevertheless. > I suspect it is due to hash collisions between 's3' and 's13' in this case? > It happens only rarely, depending on the contents of the set. I'm not sure exactly which keys are colliding here, but in general the iteration order of a set (or dict) depends not just on the contents, but also on the order of insertion. And of course the repr depends on the iteration order -- anything consistent would require sorting, which would be O(n log n) and is not even necessarily well-defined. From ben+python at benfinney.id.au Sun Oct 16 22:23:47 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 17 Oct 2011 13:23:47 +1100 Subject: Equal sets with unequal print and str() representations References: Message-ID: <878vokuzik.fsf@benfinney.id.au> Ganesh Gopalakrishnan writes: > This probably is known, but a potential pitfall (was, for me) nevertheless. > I suspect it is due to hash collisions between 's3' and 's13' in this > case? What is the actual problem? What behaviour is occurring that doesn't match your expectation? > >>> S1==S2 > S1==S2 > True > >>> str(S1) > str(S1) > "{'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'}" > >>> str(S2) > str(S2) > "{'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'}" > >>> str(S1) == str(S2) > False Right, that's all correct (though I don't know why some of your expressions are being shown twice). A deliberate property of a set is that its items are unordered. Since sets are unordered, the string representation may show the items in an arbitrary and unpredictable sequence. Don't write any code that depends on a predictable sequence of retrieval from an unordered collection. So what did you expect instead, and what supports that expectation? -- \ ?When we pray to God we must be seeking nothing ? nothing.? | `\ ?Saint Francis of Assisi | _o__) | Ben Finney From gshanemiller at verizon.net Sun Oct 16 22:43:20 2011 From: gshanemiller at verizon.net (Shane) Date: Sun, 16 Oct 2011 19:43:20 -0700 (PDT) Subject: define module in non-standard location? Message-ID: <74a49f0a-a1db-491b-8a66-c6fdcb9a924d@v15g2000vbm.googlegroups.com> Normally if one has a code set under a directory "top_level" like this: top_level: __main__.py a __init__.py b __init__.py then this directory structure is naturally satisfies this line in __main__.py: >import a.b But support, for some stupid reason --- say a.b is user defined code --- that I want to locate modules a and a.b somewhere else under another directory "other_top_level". What would the line "import a.b" in __main__,py be replaced by? Thank you From tjreedy at udel.edu Sun Oct 16 22:47:09 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 16 Oct 2011 22:47:09 -0400 Subject: Equal sets with unequal print and str() representations In-Reply-To: References: <4E9B6E23.9050106@cs.utah.edu> Message-ID: On 10/16/2011 9:17 PM, Ian Kelly wrote: > On Sun, Oct 16, 2011 at 5:52 PM, Ganesh Gopalakrishnan > wrote: >> This probably is known, but a potential pitfall (was, for me) nevertheless. >> I suspect it is due to hash collisions between 's3' and 's13' in this case? >> It happens only rarely, depending on the contents of the set. > > I'm not sure exactly which keys are colliding here, but in general the > iteration order of a set (or dict) depends not just on the contents, > but also on the order of insertion. And of course the repr depends on > the iteration order -- anything consistent would require sorting, > which would be O(n log n) and is not even necessarily well-defined. To put it another way, any dependence on the arbitrary ordering of unordered collections in iteration or displays is a programming error. -- Terry Jan Reedy From steve+comp.lang.python at pearwood.info Sun Oct 16 23:31:44 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Oct 2011 03:31:44 GMT Subject: Loop through a dict changing keys References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> <4e9b67fb$0$29967$c3e8da3$5496439d@news.astraweb.com> <66deee18-6595-474e-876d-84e1de21baa2@31g2000prt.googlegroups.com> Message-ID: <4e9ba19f$0$29992$c3e8da3$5496439d@news.astraweb.com> On Sun, 16 Oct 2011 17:41:55 -0700, Gnarlodious wrote: > On Oct 16, 5:25?pm, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: > >> How do you sanitize user input? > Thanks for your concern. This is what I now have, which merely expands > each value into its usable type (unquotes them): > > # filter each value > try: > var=int(var) Should be safe, although I suppose if an attacker passed (say) five hundred thousand "9" digits, it might take int() a while to generate the long int. Instant DOS attack. A blunt object fix for that is to limit the user input to (say) 500 characters, which should be long enough for any legitimate input string. But that will depend on your application. > except ValueError: > if var in ('False', 'True'): > var=eval(var) # extract booleans Well, that's safe, but slow, and it might encourage some future maintainer to use eval in less safe ways. I'd prefer: try: {'True': True, 'False': False}[var] except KeyError: pass # try something else (To be a little more user-friendly, use var.strip().title() instead of just var.) > else: > var=cgi.escape(var) > > This is really no filtering at all, since all CGI variables are written > to a dictionary without checking. However, if there is no receiver for > the value I should be safe, right? What do you mean "no receiver"? If you mean that you don't pass the values to eval, exec, use them in SQL queries, call external shell scripts, etc., then that seems safe to me. But I'm hardly an expert on security, so don't take my word on it. And it depends on what you end up doing in the CGI script. > I am also trapping some input at mod_wsgi, like php query strings. And > that IP address gets quarantined. If you can suggest what attack words > to block I'll thank you for it. That's the wrong approach. Don't block words in a blacklist. Block everything that doesn't appear in a whitelist. Otherwise you're vulnerable to a blackhat coming up with an attack word that you never thought of. There's one of you and twenty million of them. Guess who has the advantage? -- Steven From wuwei23 at gmail.com Sun Oct 16 23:37:21 2011 From: wuwei23 at gmail.com (alex23) Date: Sun, 16 Oct 2011 20:37:21 -0700 (PDT) Subject: type vs. module (part2) References: <242f9fff-a607-4435-a317-200282e84377@o19g2000vbk.googlegroups.com> Message-ID: <1ac0f1eb-4ee6-4a1a-8306-85085021ca6e@y35g2000pre.googlegroups.com> On Oct 17, 9:11?am, Shane wrote: > I now have two questions: How does Python allow two classes of the > same > type as evidenced by identical ``print type()' output and > different id > outputs? You are looking at the id of two _instances_ of the class, not of the class itself. >>> class Example(object): ... pass ... >>> e1, e2 = Example(), Example() >>> type(e1), type(e2) (, ) >>> id(type(e1)), id(type(e2)) (20882000, 20882000) >>> id(e1), id(e2) (25931760, 25968816) > Also, which module is t,t1 actually in? Is it "a.b.f"? Or is it > "a.b.t.d". Which module did you declare them in? What makes you think they're defined somewhere other than what .__module__ is telling you? My guess is your class is in a.b.f, your instances are created in a.b.t.d, and you've demonstrated very powerfully the value of meaningful names in code. > I am totally confused. And you have the source code. Imagine how we feel. From steve+comp.lang.python at pearwood.info Sun Oct 16 23:55:29 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Oct 2011 03:55:29 GMT Subject: define module in non-standard location? References: <74a49f0a-a1db-491b-8a66-c6fdcb9a924d@v15g2000vbm.googlegroups.com> Message-ID: <4e9ba731$0$29992$c3e8da3$5496439d@news.astraweb.com> On Sun, 16 Oct 2011 19:43:20 -0700, Shane wrote: > Normally if one has a code set under a directory "top_level" like this: > > top_level: > __main__.py > a > __init__.py > b > __init__.py > > then this directory structure is naturally satisfies this line in > __main__.py: > >>import a.b > > But support, for some stupid reason --- say a.b is user defined code --- > that I want > to locate modules a and a.b somewhere else under another directory > "other_top_level". You mean like this? top_level/ __main__.py other_top_level/ a/ __init__.py b/ __init__.py > What would the line "import a.b" in __main__,py be replaced by? Make sure other_top_level is in your PYTHONPATH, and then just use "import a.b" as before. Either use your shell to do something like this: export PYTHONPATH=other_top_level:$PYTHONPATH (that's using bash syntax, other shells may need something different), or in __main__.py do this: import sys sys.path.append(other_top_level) -- Steven From gshanemiller at verizon.net Mon Oct 17 00:38:11 2011 From: gshanemiller at verizon.net (Shane) Date: Sun, 16 Oct 2011 21:38:11 -0700 (PDT) Subject: define module in non-standard location? References: <74a49f0a-a1db-491b-8a66-c6fdcb9a924d@v15g2000vbm.googlegroups.com> <4e9ba731$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Oct 16, 11:55?pm, Steven D'Aprano wrote: > On Sun, 16 Oct 2011 19:43:20 -0700, Shane wrote: > > Normally if one has a code set under a directory "top_level" like this: > > > top_level: > > ? ?__main__.py > > ? ?a > > ? ? ? __init__.py > > ? ? ? b > > ? ? ? ? ?__init__.py > > > then this directory structure is naturally satisfies this line in > > __main__.py: > > >>import a.b > > > But support, for some stupid reason --- say a.b is user defined code --- > > that I want > > to locate modules a and a.b somewhere else under another directory > > "other_top_level". > > You mean like this? > > top_level/ > ? ? __main__.py > other_top_level/ > ? ? a/ > ? ? ? ? __init__.py > ? ? ? ? b/ > ? ? ? ? ? ? __init__.py > > > What would the line "import a.b" in __main__,py be replaced by? > > Make sure other_top_level is in your PYTHONPATH, and then just use > "import a.b" as before. > > Either use your shell to do something like this: > > export PYTHONPATH=other_top_level:$PYTHONPATH > > (that's using bash syntax, other shells may need something different), or > in __main__.py do this: > > import sys > sys.path.append(other_top_level) > > -- > Steven Cheers. Thanks From steve+comp.lang.python at pearwood.info Mon Oct 17 02:32:00 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Oct 2011 06:32:00 GMT Subject: type vs. module (part2) References: <242f9fff-a607-4435-a317-200282e84377@o19g2000vbk.googlegroups.com> Message-ID: <4e9bcbe0$0$29992$c3e8da3$5496439d@news.astraweb.com> On Sun, 16 Oct 2011 16:11:18 -0700, Shane wrote: > In the following t,t1 are the result of built-in call type() -- the form > that takes three arguments. Are you sure about that? Because my explanation below will depend entirely on this alleged fact: that t and t1 themselves are classes, not instances. To be sure (well, *nearly* sure), please print t and t1 and see whether you get something like: print t => or print t => > Therefore they are classes. Consider the following output: > > print type(t) >> > print id(t) >>1234567 > print t.__module__ >>a.b.t.d > > print type(t1) >> > print id(t1) >>1234568 > print t1.__module__ >>a.b.t.d > > I now have two questions: How does Python allow two classes of the same > type as evidenced by identical ``print type()' output and > different id outputs? When you use the class statement, you end up with one class with one name, but that's not a hard rule about classes. It's just a convention. You can have multiple identical classes so long as you assign them to different names. For example: >>> class Spam: # bind a class "Spam" to the global name "Spam" ... pass ... >>> Ham = Spam # bind the class object to another global name >>> >>> class Spam: # and re-use the old name for a new class ... x = 1 ... >>> print Ham, Spam __main__.Spam __main__.Spam What's going on here? The secret is that classes (and functions!) generally have *two* names. The first name is their internal name, the name they report when you print them. The second is the name of the variable (or variables!) they are bound to. Nobody says that they MUST match, although they often do. When you use the class statement, Python's interpreter ensures that you start off with the two names matching, but as you can see from above, they don't necessarily stay matching. But the type() function doesn't enforce that: >>> brie = type('cheese', (), {}) >>> cheddar = type('cheese', (), {}) >>> brie is cheddar False >>> print brie, cheddar Both brie and cheddar know their own name as "cheese", but the names you use to refer to them are different. So, bringing this back to your examples... Both t and t1 are classes, both know their internal name as "F", but they are different classes, as seen by the fact that their IDs are different. > Also, which module is t,t1 actually in? Is it "a.b.f"? Or is it > "a.b.t.d". Since they are two independent classes, it could easily be "both, one for each". -- Steven From steve+comp.lang.python at pearwood.info Mon Oct 17 02:35:19 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Oct 2011 06:35:19 GMT Subject: type vs. module (part2) References: <242f9fff-a607-4435-a317-200282e84377@o19g2000vbk.googlegroups.com> <4e9bcbe0$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e9bcca7$0$29992$c3e8da3$5496439d@news.astraweb.com> On Mon, 17 Oct 2011 06:32:00 +0000, Steven D'Aprano wrote: > So, bringing this back to your examples... > > Both t and t1 are classes, both know their internal name as "F", but > they are different classes, as seen by the fact that their IDs are > different. Oops, no, sorry, a mistake... assuming you are correct that both t and t1 are classes, we don't have enough information to know what they believe they are called. (Printing t and t1 should tell you.) What we know is that their *metaclass* (the class of a class) knows itself as "F". -- Steven From ladasky at my-deja.com Mon Oct 17 02:52:30 2011 From: ladasky at my-deja.com (John Ladasky) Date: Sun, 16 Oct 2011 23:52:30 -0700 (PDT) Subject: Language Enhancement Idea to help with multi-processing (your opinions please) References: <4c79d47c-c6ce-49b5-931e-c1bf5e94af75@c14g2000pro.googlegroups.com> Message-ID: <15a00455-eee9-4806-b940-5d40073f7fe4@v8g2000pro.googlegroups.com> On Oct 14, 7:32?pm, alex23 wrote: > You can do this right now with Python 3.2+ and concurrent.futures: > > from concurrent.futures import ThreadPoolExecutor You may have finally sold me on struggling through the upgrade from Python 2.6! I've been doing reasonably well with the Multiprocessing module, but it looks like the syntax of ThreadPoolExecutor offers some significant improvements. Here's hoping that numpy, scipy, and matplotlib are all Python 3.x- compatible by now... From ulrich.eckhardt at dominolaser.com Mon Oct 17 03:22:59 2011 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Mon, 17 Oct 2011 09:22:59 +0200 Subject: callling python function in c In-Reply-To: <8ca2fc3e-a3be-49c4-8107-a47385bc0911@w26g2000pro.googlegroups.com> References: <8ca2fc3e-a3be-49c4-8107-a47385bc0911@w26g2000pro.googlegroups.com> Message-ID: Am 16.10.2011 10:03, schrieb masood shaik: > I am trying to call python function from c code.The following > program i got from the web source while i am trying to run this > program it throws an segmentation fault. Try checking what functions returns instead of blindly using it. Use a debugger to find out where exactly it segfaults. Uli From lanyjie at yahoo.com Mon Oct 17 04:42:04 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Mon, 17 Oct 2011 01:42:04 -0700 (PDT) Subject: strange comparison result with 'is' Message-ID: <1318840924.74377.YahooMailNeo@web121512.mail.ne1.yahoo.com> Hi all,? This is quite strange when I used the Python shell with IDLE: >>> x = [] >>> id(getattr(x, 'pop')) == id(x.pop) True >>> getattr(x, 'pop') is x.pop False >>>? I suppose since the two things have the same id, the 'is'-test? should give a True value, but I get a False value.? Any particular reason for breaking this test? I am quite?confused as I show this before a large? audience only to find the result denies my prediction. The python version is 3.2.2; I am not sure about other versions. Regards, Yingjie -------------- next part -------------- An HTML attachment was scrubbed... URL: From noreply at python.org Mon Oct 17 05:13:39 2011 From: noreply at python.org (Automatic Email Delivery Software) Date: Mon, 17 Oct 2011 12:13:39 +0300 Subject: Message could not be delivered Message-ID: The original message was received at Mon, 17 Oct 2011 12:13:39 +0300 from python.org [153.233.80.188] ----- The following addresses had permanent fatal errors ----- ----- Transcript of session follows ----- while talking to python.org.: >>> MAIL From:"Automatic Email Delivery Software" <<< 501 "Automatic Email Delivery Software" ... Refused -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: RemovedAttachments518.txt URL: From __peter__ at web.de Mon Oct 17 05:19:35 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 17 Oct 2011 11:19:35 +0200 Subject: strange comparison result with 'is' References: <1318840924.74377.YahooMailNeo@web121512.mail.ne1.yahoo.com> Message-ID: Yingjie Lan wrote: > This is quite strange when I used the Python shell with IDLE: > >>>> x = [] >>>> id(getattr(x, 'pop')) == id(x.pop) > > True >>>> getattr(x, 'pop') is x.pop > False >>>> > > I suppose since the two things have the same id, the 'is'-test > should give a True value, but I get a False value. > > Any particular reason for breaking this test? > I am quite confused as I show this before a large > audience only to find the result denies my prediction. > > The python version is 3.2.2; I am not sure about other versions. The getattr() call is just a distraction. Every x.pop attribute access creates a new method object. In the case of >>> x.pop is x.pop False they have to reside in memory simultaneously while in the expression >>> id(x.pop) == id(x.pop) True a list.pop method object is created, its id() is taken (which is actually its address) and then the method object is released so that its memory address can be reused for the second x.pop. So in the latter case the two method objects can (and do) share the same address because they don't need to exist at the same time. From tjreedy at udel.edu Mon Oct 17 05:33:00 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 Oct 2011 05:33:00 -0400 Subject: strange comparison result with 'is' In-Reply-To: <1318840924.74377.YahooMailNeo@web121512.mail.ne1.yahoo.com> References: <1318840924.74377.YahooMailNeo@web121512.mail.ne1.yahoo.com> Message-ID: On 10/17/2011 4:42 AM, Yingjie Lan wrote: > Hi all, > > This is quite strange when I used the Python shell with IDLE: Nothing to do with IDLE > >>> x = [] >> >> id(getattr(x, 'pop')) == id(x.pop) > True > >>> getattr(x, 'pop') is x.pop > False > I suppose since the two things have the same id, the 'is'-test > should give a True value, but I get a False value. id and is are notorious for confusing beginners. You actually created 4 bound method objects -- but not all at the same time. IDs only only unique among simultaneously existing objects. It is an accident of the CPython implementation that two of them have the same id, even though they are different objects. The second line is the correct one. > Any particular reason for breaking this test? > I am quite confused as I show this before a large > audience only to find the result denies my prediction. Don't show this sort of thing. Name your objects so they do not get garbage collected in the middle of any demonstration. -- Terry Jan Reedy From faucheuses at gmail.com Mon Oct 17 06:32:51 2011 From: faucheuses at gmail.com (faucheuse) Date: Mon, 17 Oct 2011 03:32:51 -0700 (PDT) Subject: Problem with a wx notebook Message-ID: Hi there, I've created a wx NoteBook in wich I set multiples panels in wich I set one or more sizers. But nothing displays in the notebook, everything is outside. I've been searching an answer for 2 days ><. Can you help me plz ? Here is my code(with only one panel, to sum up the code) : class StreamingActivationDialog(wx.Dialog): def __init__(self, *args, **kwds): # begin wxGlade: StreamingActivationDialog.__init__ kwds["style"] = wx.DEFAULT_DIALOG_STYLE wx.Dialog.__init__(self, *args, **kwds) self.bitmap_1_copy = wx.StaticBitmap(self, -1, wx.Bitmap("img\ \logo.png", wx.BITMAP_TYPE_ANY)) self.labelDnD = wx.StaticText(self, -1, "Si vous avez d?j? un fichier d'activation, faite le glisser dans cette fenetre") self.keyBitmap = wx.StaticBitmap(self, -1, wx.Bitmap("img\ \key.bmp", wx.BITMAP_TYPE_ANY)) self.conclude = wx.StaticText(self, -1, _("test"), style=wx.ALIGN_CENTRE) ### Panel ### self.intro3_label = wx.StaticText(self, -1, "Envoyez un mail ? \nactivation at monmail.com\ncontenant le code :",style=wx.ALIGN_CENTRE) self.activationCode_label= wx.StaticText(self, -1, "123456789", style=wx.TE_READONLY) self.copy2_Button = wx.Button(self, -1, "Copier dans le presse- papier") self.copy2_Button.Bind(wx.EVT_BUTTON, PanelMail.onCopy) ############## self.note = wx.Notebook(self, wx.ID_ANY, style=wx.BK_LEFT, size=wx.Size(100, 341)) self.page3 = wx.Panel(self.note) imagelist = wx.ImageList(94, 94) bitmap1 = wx.Bitmap("img\\a.bmp", wx.BITMAP_TYPE_BMP ) imagelist.Add(bitmap1) self.note.AssignImageList(imagelist) self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: StreamingActivationDialog.__set_properties self.SetTitle(_("Activation de FlashProcess")) self.SetBackgroundColour(wx.Colour(255, 255, 255)) #self.linkProblem.SetForegroundColour(wx.Colour(0, 0, 0)) # end wxGlade def __do_layout(self): # begin wxGlade: StreamingActivationDialog.__do_layout self.grid_sizer_1 = wx.FlexGridSizer(6, 1, 0, 0) self.grid_sizer_2 = wx.FlexGridSizer(1, 2, 0, 30) self.grid_sizer_1.Add(self.bitmap_1_copy, 0, wx.TOP|wx.BOTTOM| wx.EXPAND, 10) ### Page 3 ### sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.intro3_label, 0, wx.BOTTOM|wx.ALIGN_CENTER, 5) sizer.Add(self.activationCode_label, 0, wx.BOTTOM| wx.ALIGN_CENTER, 20) sizer.Add(self.copy2_Button, 0, wx.ALIGN_CENTER, 20) self.page3.SetSizer(sizer) sizer.Fit(self.page3) ############## self.note.AddPage(self.page3, "", False, 0) self.Bind(wx.EVT_TOOLBOOK_PAGE_CHANGED, self.OnPageChanged) self.Bind(wx.EVT_TOOLBOOK_PAGE_CHANGING, self.OnPageChanging) self.grid_sizer_1.Add(self.note, 0, wx.EXPAND, 20) self.grid_sizer_1.Add(self.labelDnD, 0, wx.TOP| wx.ALIGN_CENTER_HORIZONTAL, 20) self.grid_sizer_2.Add(self.keyBitmap, 0, wx.LEFT, 10) self.grid_sizer_2.Add(self.labelDnD, 0, wx.LEFT, 20) self.grid_sizer_1.Add(self.grid_sizer_2, 0, wx.EXPAND, 20) self.grid_sizer_1.Add(self.conclude, 0, wx.TOP| wx.ALIGN_CENTER_HORIZONTAL, 20) self.SetSizer(self.grid_sizer_1) self.grid_sizer_1.Fit(self) self.Layout() # end wxGlade def OnPageChanged(self, event): event.Skip() def OnPageChanging(self, event): event.Skip() From rosuav at gmail.com Mon Oct 17 06:43:31 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 17 Oct 2011 21:43:31 +1100 Subject: Loop through a dict changing keys In-Reply-To: <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> Message-ID: On Mon, Oct 17, 2011 at 5:20 AM, Gnarlodious wrote: > On Oct 15, 5:53?pm, PoD wrote: > >> types={'Mobile':str,'context':str,'order':int,'time':bool} >> >> for k,v in data.items(): >> ? ? data[k] = types[k](v) > > Thanks for the tip, I didn't know you could do that. I ended up > filtering the values the bulky way, but it gives me total control over > what internet users feed my program. It should be noted that this will not in any way sanitize data['context']. It calls the str() function on it, thus ensuring that it's a string, but that's all. If you're needing to deal with (potentially) malicious input, you'll want to swap in a function that escapes it in some way (if it's going into a database, your database engine will usually provide a 'quote' or 'escape' function; if it's to go into a web page, I think cgi.escape is what you want). ChrisA From devplayer at gmail.com Mon Oct 17 08:59:04 2011 From: devplayer at gmail.com (DevPlayer) Date: Mon, 17 Oct 2011 05:59:04 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> Message-ID: > DevPlayer ?wrote: > >I still assert that contradiction is caused by narrow perspective. > >By that I mean: just because an objects scope may not see a certain > >condition, doesn't mean that condition is non-existant. > Groetjes Albert wrote: > This is a far cry from the bible stating that someone is his > own grand father. Or going to great length to prove that Jezus > (through Jozef) is a descendant of David. Then declaring it > a dogma that Jozef has nothing to do with it. Do you not see? For ... One man's garbage is another man's treasure. One man's delusion is another man's epiphany. One man's untruth is another man's belief. One man's thing to attack is another mans thing to shield and defend. One man's logical undenighable truth is another man's small part of a bigger picture. As has been said for example does 1+1 = 2. Only in one small persepective. Whaa? what wack job says stuff like that? 1+1 = 10. In the bigger picture there is more then one numberic base besides decimal, such as binary. Or then one might say there are only 10 integer numbers from 0 to 9 or from 1 to 10 if you like. Again in the limited view, true, but in the larger view no. The Elucid numbering scale is not the only numbering scale ever invented, or needed for that matter. http://en.wikipedia.org/wiki/Euclidean_geometry "Euclid's axioms seemed so intuitively obvious that any theorem proved from them was deemed true in an absolute, often metaphysical, sense. Today, however, many other self-consistent non-Euclidean geometries are known, the first ones having been discovered in the early 19th century. An implication of Einstein's theory of general relativity is that Euclidean space is a good approximation to the properties of physical space ..." > Groetjes Albert wrote: > (It being ... well ... you know ...) Um... Huh? sorry didn't know what you meant. You got me on that one. Ellipses just put my brain into recursive mode. > Groetjes Albert wrote: > (I have this book, it is called "the amusing bible" with all > flippant and contradictory stuff pointed out by a French > 1930 communist. Cartoons too. ) I likely would find it very funny. > Economic growth -- being exponential -- ultimately falters. How true indeed. From nvidhya01 at gmail.com Mon Oct 17 09:23:38 2011 From: nvidhya01 at gmail.com (n v) Date: Mon, 17 Oct 2011 06:23:38 -0700 (PDT) Subject: @@@@@@@@@@@@@@@@@@@ Message-ID: <6adf527d-69f7-4ed9-a8b2-f2d3029c8508@y35g2000pre.googlegroups.com> http://123maza.com/48/silver424/ From steve+comp.lang.python at pearwood.info Mon Oct 17 10:34:34 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 17 Oct 2011 14:34:34 GMT Subject: [OT] Re: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> Message-ID: <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> On Mon, 17 Oct 2011 05:59:04 -0700, DevPlayer wrote: > As has been said for example does 1+1 = 2. Only in one small > persepective. Whaa? what wack job says stuff like that? 1+1 = 10. In the > bigger picture there is more then one numberic base besides decimal, > such as binary. That is no more deep and meaningful than the fact that while some people say "one plus one equals two", others say "eins und eins gleich zwei", some say "un et un fait deux" and some say "???? ? ???? ???? ???". Regardless of whether you write two, zwei, ???, ???, 2 (in decimal), 10 (in binary), II (in Roman numerals) or even {0,1} using set theory notation, the number remains the same, only the symbol we use to label it is different. Do not confuse the map for the territory. -- Steven From brian.curtin at gmail.com Mon Oct 17 10:42:40 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Mon, 17 Oct 2011 09:42:40 -0500 Subject: How do I get curses to work in Python 3.2 on win-64? In-Reply-To: References: <3bc2636a-85b5-47bd-9a47-7c9ee16b2a75@w5g2000yqw.googlegroups.com> <57034ebb-5278-4a48-9e12-4e068eda820c@v8g2000pro.googlegroups.com> Message-ID: On Sun, Oct 16, 2011 at 11:16, Jan Sundstr?m wrote: > On 16 Okt, 06:59, Christoph Gohlke wrote: >> On Oct 15, 1:13?pm, Jan Sundstr?m wrote: >> >> >> >> `import curses` should work. What exactly is the error message? Does >> `import curses` work outside your program/program directory? >> >> The curses package is part of the standard library and usually >> installed in Python32\Lib\curses. On Windows the ?_curses.pyd files is >> missing in the standard distribution. curses-2.2.win-amd64-py3.2.exe >> installs the missing _curses.pyd file into Lib/site-packages. > > Thanks for the tip to check in what library it works, that set me on > track tofind a silly mistake that I had done. Now everything works > fine. > > But, how come that the Windows distribution for Python doesn't include > the _curses.pyd file? It's not a standard library module on Windows. The curses Christoph mentioned is built on the PDCurses library, which is an external project. From dihedral88888 at googlemail.com Mon Oct 17 12:21:35 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Mon, 17 Oct 2011 09:21:35 -0700 (PDT) Subject: Loop through a dict changing keys In-Reply-To: References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> Message-ID: <31199636.1883.1318868495227.JavaMail.geo-discussion-forums@prfp13> Uh, sounds reasonable, if one loops over an index variable that could be altered during the loop execution then the loop may not end as expected. From dihedral88888 at googlemail.com Mon Oct 17 12:21:35 2011 From: dihedral88888 at googlemail.com (88888 dihedral) Date: Mon, 17 Oct 2011 09:21:35 -0700 (PDT) Subject: Loop through a dict changing keys In-Reply-To: References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> Message-ID: <31199636.1883.1318868495227.JavaMail.geo-discussion-forums@prfp13> Uh, sounds reasonable, if one loops over an index variable that could be altered during the loop execution then the loop may not end as expected. From anikom15 at gmail.com Mon Oct 17 12:29:39 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Mon, 17 Oct 2011 09:29:39 -0700 Subject: Equal sets with unequal print and str() representations In-Reply-To: <4E9B6E23.9050106@cs.utah.edu> References: <4E9B6E23.9050106@cs.utah.edu> Message-ID: <20111017162939.GA23669@Smoke> On Sun, Oct 16, 2011 at 05:52:03PM -0600, Ganesh Gopalakrishnan wrote: > This probably is known, but a potential pitfall (was, for me) > nevertheless. I suspect it is due to hash collisions between 's3' > and 's13' in this case? It happens only rarely, depending on the > contents of the set. > > >>> S1 = {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'} > S1 = {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'} > >>> S2 = {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'} > S2 = {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'} > >>> S1 > S1 > {'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'} > >>> S2 > S2 > {'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'} > >>> S1==S2 > S1==S2 > True > >>> str(S1) > str(S1) > "{'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'}" > >>> str(S2) > str(S2) > "{'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'}" > >>> str(S1) == str(S2) > False This is because sets do not preserve order. From tjreedy at udel.edu Mon Oct 17 13:53:13 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 17 Oct 2011 13:53:13 -0400 Subject: strange comparison result with 'is' In-Reply-To: References: <1318840924.74377.YahooMailNeo@web121512.mail.ne1.yahoo.com> Message-ID: On 10/17/2011 5:19 AM, Peter Otten wrote: > The getattr() call is just a distraction. Every x.pop attribute access > creates a new method object. In the case of > >>>> x.pop is x.pop > False > > they have to reside in memory simultaneously while in the expression > >>>> id(x.pop) == id(x.pop) > True > > a list.pop method object is created, its id() is taken (which is actually > its address) and then the method object is released so that its memory > address can be reused for the second x.pop. > > So in the latter case the two method objects can (and do) share the same > address because they don't need to exist at the same time. This has come up enough that I opened http://bugs.python.org/issue13203 ============================================================== Newbies too often do something like (3.2.2, ) >>> id(getattr(x, 'pop')) == id(x.pop) True and get confused by the (invalid) result, whereas >>> a,b=getattr(x, 'pop'),x.pop >>> id(a)==id(b) False works properly. I think we should add a sentence or two or three to the id() doc, such as Since a newly created argument object is either destroyed or becomes inaccessible before the function returns, *id(obj)* is only useful and valid if *obj* exists prior to the call and therefore after its return. The value of an expression such as *id(666)== id(667)* is arbitrary and meaningless. The id of the first int object might or might not be reused for the second one. ==================================================================== With something like this added, we could just say 'read the id() doc'. -- Terry Jan Reedy From ian.g.kelly at gmail.com Mon Oct 17 14:12:27 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 17 Oct 2011 12:12:27 -0600 Subject: Loop through a dict changing keys In-Reply-To: <31199636.1883.1318868495227.JavaMail.geo-discussion-forums@prfp13> References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> <31199636.1883.1318868495227.JavaMail.geo-discussion-forums@prfp13> Message-ID: On Mon, Oct 17, 2011 at 10:21 AM, 88888 dihedral wrote: > Uh, sounds reasonable, if one loops over an index variable ?that could be altered during the loop execution then the loop may not end as expected. >From the docs: "Iterating views while adding or deleting entries in the dictionary may raise a RuntimeError or fail to iterate over all entries." Changing the values of existing entries while iterating is considered to be safe, though. From miki.tebeka at gmail.com Mon Oct 17 14:38:08 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 17 Oct 2011 11:38:08 -0700 (PDT) Subject: python.org appears to be down In-Reply-To: References: Message-ID: <12197444.1847.1318876688689.JavaMail.geo-discussion-forums@prmr25> http://www.isup.me/python.org ;) From miki.tebeka at gmail.com Mon Oct 17 14:38:08 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 17 Oct 2011 11:38:08 -0700 (PDT) Subject: python.org appears to be down In-Reply-To: References: Message-ID: <12197444.1847.1318876688689.JavaMail.geo-discussion-forums@prmr25> http://www.isup.me/python.org ;) From devplayer at gmail.com Mon Oct 17 14:44:27 2011 From: devplayer at gmail.com (DevPlayer) Date: Mon, 17 Oct 2011 11:44:27 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Oct 17, 10:34?am, Steven D'Aprano wrote: > On Mon, 17 Oct 2011 05:59:04 -0700, DevPlayer wrote: > > As has been said for example does 1+1 = 2. Only in one small > > persepective. Whaa? what wack job says stuff like that? 1+1 = 10. In the > > bigger picture there is more then one numberic base besides decimal, > > such as binary. > > That is no more deep and meaningful than the fact that while some people > say "one plus one equals two", others say "eins und eins gleich zwei", > some say "un et un fait deux" and some say "???? ? ???? ???? ???". > Regardless of whether you write two, zwei, ???, ???, 2 (in decimal), 10 > (in binary), II (in Roman numerals) or even {0,1} using set theory > notation, the number remains the same, only the symbol we use to label it > is different. > > Do not confuse the map for the territory. > Steven Good point. But I disagree: The symbol is not only used to label it. The symbol is used to put it in context in reference to something else. "2" is a quantity in decimal, but in binary, "2" is not a quantity nor is 01+01==10 equal to "2" from withIN the binary perspective. Those symantics are symbolic of concepts which are being equated to quantities OUTSIDE of the binary perspective. True binary states, True + True does not equal two True, correct? Programmers use binary "math" to -represent- quantity. Here you are arranging syntax to change meaning -out of scope-. The original machine language notation inventors could have said in binary there is no 1+1 they could have said "1 Jumps 1 means "A"", or "On repowers On equals 5th gate in nand circuit". To reitterate, I agree with you that it doesn't matter what symbology you use if that symobology represents "same-stateness" -FROM a broader perspective (i.e. scope). BUT in binary, in the narrow scope of binary logic there is no "2". The available states are restrained to the scope you place them, when WITHIN that scope. (using caps to try to be clear and I don't intend to say you are wrong and I am right but to say, I disagree because of this logic. Said differently I intend to explain, not to demoralize or offend). "1+1=10" is being viewed as 2 because of a larger world view is being used, a broader perspective. Using broader concepts of numbers and math which is a superset of a strictly binary system and is also a superset of a decimal only view. Remember a computer does not function with concepts of "2" or "a" or "15". Computers function in ons and offs and "indeterminate" states. The binary representation of "10" to a computer does not mean "2". That quantity representation is something the human applies to that state. Perhaps a differant analogy made by someone else. Many years ago, I've studied the "The Fourth Dimension" a book based mostly on math by Rudy Rucker. There are a few books with that name but this one is algra based. It attempts to teach the reader to be able to view 4 dimensional objects using 3 dimensional and even 2 dimensional translations of "mapped" objects - with a 4 dimensional view. There are two popular schools of thought on this attempt. 1. It's impossible or us to concieve of a 4 dimentional space objects within our 3 dimentional senses and perceptions. and 2. We can conceive with our mind-s eye 4 dimensional objects much like we concieve of 2 dimentional objects (the plane) and even harder one dimensional objects. The author attempts to teach by first using an analogy. First he clarifies that for his purposes of 4 dimensional space, that no dimension axis in his math singularly represents time or anything ephemeral like the supernatural or energy or such. Each fo the 4 dimensions represent an axis in a physical vector. He then creates a 3 dimensional man who lives in a 3 dimensional world. This 3d man sees up, down, north, south, east, west. And he can see a plane or even a line. But the 3d man does not see the 4th axis because he is not made of that vector and does not therefore have sensory to perceive that axis. The author then goes on to show a 2d man does not see the 3rd axis and then better explains how the 1d man can only "see" in left or right directions. Following that story further, keeping to certain assumptions about 1d space, puts the man in a binary world view, where there is no "2", much like a computer. there is not "2" there is only 10, which TO YOU is a 2. but to the 1d man and the computer is a 10. Of course when you try to limit someone's view to make a point about a limited view it sounds rediculas. Supposition is often that way after all. > That is no more deep and meaningful than the fact that while some people > say "one plus one equals two", others say "eins und eins gleich zwei", > some say "un et un fait deux" and some say "???? ? ???? ???? ???". > Regardless of whether you write two, zwei, ???, ???, 2 (in decimal), 10 > (in binary), II (in Roman numerals) or even {0,1} using set theory > notation, the number remains the same, only the symbol we use to label it > is different. Also here you are talking about syntax as if it were symantics or mnuemonics. Symbology is a superset of those three terms and they are not entirely equivelent although -closely- knitted in function and purpose. Context (=limited perspective) is revelent if not entirely revelent when using symantics coupled with symbols. For example: One man's war is a another man's liberation. Here the word symbol "war" has different meanings for each man. The two smantics is to apply the notion of war (fighting/killing) to the purpose of war (rebellion to what is "good" (man1) to removal from what is "bad" (man2)). Along with my notion of the "Duality of Nature", also puts around the idea-almost-belief that "Everything is symantics". These two goofy notions are tightly linked (at least in my musings). Ever hear/read the term: "It's all good."? A reference to Karma and how things will work out for the better in the end inspite of what you see now... A great example of "Everything is Symantics". Apart of that notion btw is that: No symbol completely and entirely represents a thing, a person, a place, an idea completely and accurately, only partially. And symbology is very tied into "Relativity" (of perspective) (another term I apply to "Duality of Nature" where in DoN there exists at least two extreme but opposite states, in "Relativity" has something LIKE extremes but they are vectors of state and not limited sets of state with a infinite range. for example the infinite range of numbers between 0 and 1 or 1 and 2. or for example where 0 and 1 are numeric synbols of off state and on state - two opposite and partially contradictory states. (Some say "None" is the opposite of a bool state). btw for those in electronics fields know that on and off states are mearly arbitary, chosen to be some function like 2 *square of power for on. In electronics on off states there are infinite levels of "on-ness" but only two points in that range are chosen to be revelent (was that 75% power I forget). And another weird notion to put forward. "2" as a numberic quantity by itself is utterly meaningless. Two what? It's the "what" that is revelent. I was going to go on to make some connection to "2" being a representive of "instantation" of objects and the place and usage of instances is meaningful but that chain of thought is just as windy as all the hot air I just gushed. Well. Hope you enjoyed my crazy. Later. From gnarlodious at gmail.com Mon Oct 17 14:50:41 2011 From: gnarlodious at gmail.com (Gnarlodious) Date: Mon, 17 Oct 2011 11:50:41 -0700 (PDT) Subject: Loop through a dict changing keys References: <4e9a1cfc$0$29887$c3e8da3$5496439d@news.astraweb.com> <2a78557d-cbc4-4dfc-8041-0c16dd44828a@d33g2000prb.googlegroups.com> <4e9b67fb$0$29967$c3e8da3$5496439d@news.astraweb.com> <66deee18-6595-474e-876d-84e1de21baa2@31g2000prt.googlegroups.com> <4e9ba19f$0$29992$c3e8da3$5496439d@news.astraweb.com> Message-ID: <07ebfa36-d0d7-4abb-86c0-ae5ab19e0729@p35g2000prp.googlegroups.com> Steven: Thanks for those tips, I've implemented all of them. Also only allowing whitelisted variable names. Feeling much more confident. -- Gnarlie From eswint at vt.edu Mon Oct 17 15:55:58 2011 From: eswint at vt.edu (Ethan Swint) Date: Mon, 17 Oct 2011 15:55:58 -0400 Subject: Python hangs: Problem with wxPython, threading, pySerial, or events? In-Reply-To: <4E99A3FD.1010708@vt.edu> References: <4E99A3FD.1010708@vt.edu> Message-ID: <4E9C884E.2050507@vt.edu> I just wanted to bump this back onto the list since I posted over the weekend. Thanks, Ethan On 10/15/2011 11:17 AM, Ethan Swint wrote: > Hi- > > I'm experiencing crashes in my Win32 Python 2.7 application which > appear to be linked to pyzmq. At the moment, I can't even kill the > "python.exe *32" process in the Windows Task Manager. I'm running the > script using Ipython by calling > > C:\Python27\pythonw.exe > "/python27/scripts/ipython-qtconsole-script.pyw" -pylab > > but I also experience similar behavior when running within Eclipse. > I've included an error message at the end which appears in the Windows > 'cmd' window, but the message is not reflected in the pylab window. > > My attached device is transmitting <160><1><2><3><4><80> and is > received correctly when I run the sample pyserial script > 'wxTerminal.py'. In my application, however, the message appears to > get characters out of order or drop bytes. > > If there's a better place to post or if you'd like more info, let me > know. > > Thanks, > Ethan > > ------------------Serial Port Listening > Thread---------------------------------------- > def MotorRxThread(self): > """Thread that handles the incoming traffic. Does buffer input and > generates an SerialRxEvent""" > while self.alive.isSet(): #loop while alive event is > true > text = self.serMotor.read(1) #read one, with timeout > if text: #check if not timeout > n = self.serMotor.inWaiting() #look if there is more to read > if n: > text = text + self.serMotor.read(n) #get it > #log to terminal > printstring = "MotorRxThread: " > for b in text: > printstring += str(ord(b)) + " " > print printstring > #pdb.set_trace() > if self.motorRx0.proc_string(text): > print "Message: cmd: " + str(self.motorRx0.cmd) + " data: " > + str(self.motorRx0.data) > event = SerialRxSpeedEvent(self.GetId(), text) > self.GetEventHandler().AddPendingEvent(event) > -----------------\Serial Port Listening > Thread---------------------------------------- > > ----------------Thread > Start&Stop------------------------------------------------------ > def StartMotorThread(self): > """Start the receiver thread""" > self.motorThread = threading.Thread(target=self.MotorRxThread) > self.motorThread.setDaemon(1) > self.alive.set() > self.motorThread.start() > > def StopMotorThread(self): > """Stop the receiver thread, wait until it's finished.""" > if self.motorThread is not None: > self.alive.clear() #clear alive event for thread > self.motorThread.join() #wait until thread has finished > self.motorThread = None > self.serMotor.close() #close the serial port connection > ----------------\Thread > Start&Stop------------------------------------------------------ > > -------------------Error message > -------------------------------------------------------- > ValueError: '' is not in list > ([], ['', '', '', > '{"date":"2011-10-15T10:24:27.231000","username":"kernel","session":"82906c8a-1235-44d0-b65d- > 0882955305c1","msg_id":"7cfcd155-bc05-4f47-9c39-094252223dab","msg_type":"stream"}', > '{"date":"2011-10-15T10:24:27.23100 > 0","username":"kernel","session":"82906c8a-1235-44d0-b65d-0882955305c1","msg_id":"f4b88228-b353-4cfb-9bbe-ae524ee1ac38", > > "msg_type":"stream"}', > '{"date":"2011-10-15T10:24:00.774000","username":"username","session":"9f393860-c2ab-44e9-820d-8f > 08ae35044e","msg_id":"13a46e93-8da2-487b-ab12-6cae47b1ac34","msg_type":"execute_request"}', > '{"date":"2011-10-15T10:24:0 > 0.774000","username":"username","session":"9f393860-c2ab-44e9-820d-8f08ae35044e","msg_id":"13a46e93-8da2-487b-ab12-6cae4 > > 7b1ac34","msg_type":"execute_request"}', '{"data":"\\nMotorRxThread: 0 > MotorRxThread: 4 ","name":"stdout"}']) > ERROR:root:Exception in I/O handler for fd object at 0x03ADFCC0> > Traceback (most recent call last): > File > "C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\ioloop.py", > line 291, in start > self._handlers[fd](fd, events) > File > "C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\stack_context.py", > line 133, in wrapped > callback(*args, **kwargs) > File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", > line 448, in _handle_events > self._handle_recv() > File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", > line 458, in _handle_recv > ident,msg = self.session.recv(self.socket) > File "C:\Python27\lib\site-packages\IPython\zmq\session.py", line > 585, in recv > raise e > ValueError: No JSON object could be decoded > ERROR:root:Exception in I/O handler for fd object at 0x03ADFCC0> > Traceback (most recent call last): > File > "C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\ioloop.py", > line 291, in start > self._handlers[fd](fd, events) > File > "C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\eventloop\stack_context.py", > line 133, in wrapped > callback(*args, **kwargs) > File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", > line 448, in _handle_events > self._handle_recv() > File "C:\Python27\lib\site-packages\IPython\zmq\kernelmanager.py", > line 458, in _handle_recv > ident,msg = self.session.recv(self.socket) > File "C:\Python27\lib\site-packages\IPython\zmq\session.py", line > 579, in recv > idents, msg_list = self.feed_identities(msg_list, copy) > File "C:\Python27\lib\site-packages\IPython\zmq\session.py", line > 609, in feed_identities > idx = msg_list.index(DELIM) > ValueError: '' is not in list > --------------------------------------------------------------------------- > > ZMQError Traceback (most recent call > last) > C:\Users\Ethan\ in () > > C:\Python27\lib\site-packages\IPython\zmq\ipkernel.pyc in main() > 671 """Run an IPKernel as an application""" > 672 app = IPKernelApp.instance() > --> 673 app.initialize() > 674 app.start() > 675 > > C:\Python27\lib\site-packages\IPython\zmq\ipkernel.pyc in > initialize(self=, arg > v=None) > 604 ) > 605 def initialize(self, argv=None): > --> 606 super(IPKernelApp, self).initialize(argv) > 607 self.init_shell() > 608 self.init_extensions() > > C:\Python27\lib\site-packages\IPython\zmq\kernelapp.pyc in > initialize(self=, ar > gv=None) > 213 self.init_session() > 214 self.init_poller() > --> 215 self.init_sockets() > 216 self.init_io() > 217 self.init_kernel() > > C:\Python27\lib\site-packages\IPython\zmq\kernelapp.pyc in > init_sockets(self=) > 148 > 149 self.shell_socket = context.socket(zmq.XREP) > --> 150 self.shell_port = self._bind_socket(self.shell_socket, > self.shell_port) > 151 self.log.debug("shell XREP Channel on port: > %i"%self.shell_port) > 152 > > C:\Python27\lib\site-packages\IPython\zmq\kernelapp.pyc in > _bind_socket(self=, > s=, port=50104) > 137 port = s.bind_to_random_port(iface) > 138 else: > --> 139 s.bind(iface + ':%i'%port) > 140 return port > 141 > > C:\Python27\lib\site-packages\pyzmq-2.1.9-py2.7-win32.egg\zmq\core\socket.pyd > in zmq.core.socket.Socket.bind (zmq\core\s > ocket.c:4527)() > > ZMQError: Address in use > ---------\ERROR MESSAGE-------------------------------------------------- > From mathias.lafeldt at googlemail.com Mon Oct 17 16:02:03 2011 From: mathias.lafeldt at googlemail.com (Mathias Lafeldt) Date: Mon, 17 Oct 2011 22:02:03 +0200 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: On Sat, Oct 15, 2011 at 1:44 AM, MrPink wrote: > > Is there a function in Python that can be used to test if the value in > a string is an integer? ?I had to make one up for myself and it looks > like this: > > def isInt(s): > ? ?try: > ? ? ? ?i = int(s) > ? ? ? ?return True > ? ?except ValueError: > ? ? ? ?return False According to [1], there're more Exceptions to test for: try: int(s) return True except (TypeError, ValueError, OverflowError): # int conversion failed return False [1] http://jaynes.colorado.edu/PythonIdioms.html, idiom "Catch errors rather than avoiding them to avoid cluttering your code with special cases" -Mathias From ganesh at cs.utah.edu Mon Oct 17 16:25:12 2011 From: ganesh at cs.utah.edu (Ganesh Gopalakrishnan) Date: Mon, 17 Oct 2011 14:25:12 -0600 Subject: Equal sets with unequal print and str() representations In-Reply-To: <878vokuzik.fsf@benfinney.id.au> References: <878vokuzik.fsf@benfinney.id.au> Message-ID: <4E9C8F28.3000605@cs.utah.edu> Thanks to all who replied - also to Ben. I had foolishly assumed that the same set exhibits the same rep on at least one platform. Like any bug, the falsity of my assumption took months to expose - till then, things had worked fine. Needless to say I'm new to Python. (The double printing is because I tend to work within an Emacs inferior shell.) Cheers, Ganesh On 10/16/11 8:23 PM, Ben Finney wrote: > Ganesh Gopalakrishnan writes: > >> This probably is known, but a potential pitfall (was, for me) nevertheless. >> I suspect it is due to hash collisions between 's3' and 's13' in this >> case? > What is the actual problem? What behaviour is occurring that doesn't > match your expectation? > >>>>> S1==S2 >> S1==S2 >> True >>>>> str(S1) >> str(S1) >> "{'s8', 's13', 's2', 's0', 's7', 's6', 's4', 's3', 's14'}" >>>>> str(S2) >> str(S2) >> "{'s8', 's3', 's2', 's0', 's7', 's6', 's4', 's13', 's14'}" >>>>> str(S1) == str(S2) >> False > Right, that's all correct (though I don't know why some of your > expressions are being shown twice). A deliberate property of a set is > that its items are unordered. > > > Since sets are unordered, the string representation may show the items > in an arbitrary and unpredictable sequence. Don't write any code that > depends on a predictable sequence of retrieval from an unordered > collection. > > So what did you expect instead, and what supports that expectation? > From enalicho at gmail.com Mon Oct 17 16:44:51 2011 From: enalicho at gmail.com (Noah Hall) Date: Mon, 17 Oct 2011 21:44:51 +0100 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: On Sat, Oct 15, 2011 at 12:44 AM, MrPink wrote: > > Is there a function in Python that can be used to test if the value in > a string is an integer? ?I had to make one up for myself and it looks > like this: > > def isInt(s): > ? ?try: > ? ? ? ?i = int(s) > ? ? ? ?return True > ? ?except ValueError: > ? ? ? ?return False There's the isdigit method, for example - >>> str = "1324325" >>> str.isdigit() True >>> str = "1232.34" >>> str.isdigit() False >>> str = "I am a string, not an int!" >>> str.isdigit() False From ben+python at benfinney.id.au Mon Oct 17 16:52:48 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Oct 2011 07:52:48 +1100 Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> Message-ID: <87vcrntk67.fsf@benfinney.id.au> DevPlayer writes: > Do you not see? For ... > One man's delusion is another man's epiphany. > One man's untruth is another man's belief. > One man's logical undenighable truth is another man's small part of a > bigger picture. Those are just not true. A belief that doesn't match reality is a delusion. That doesn't change when someone thinks it's an epiphany: it's still a delusion. If a claim about reality doesn't actually match reality, it's untrue. That doesn't change when someone believes it: it's still untrue, or claims it's ?part of a bigger picture?. If you make claims about reality, then you'd better be ready for them to be subjected to the tests of reality, or be ready for ridicule if you can't back them up with such tests. If, on the other hand, you claim a ?bigger picture?, then that's just another scope within reality and you haven't escaped any part of your burden to demonstrate that reality. If, on the gripping hand, you want to make claims that are *not* about reality, then be very clear about that at the beginning and don't try to shift the goalposts later. > http://en.wikipedia.org/wiki/Euclidean_geometry > "Euclid's axioms seemed so intuitively obvious that any theorem proved > from them was deemed true in an absolute, often metaphysical, sense. > Today, however, many other self-consistent non-Euclidean geometries > are known, the first ones having been discovered in the early 19th > century. An implication of Einstein's theory of general relativity is > that Euclidean space is a good approximation to the properties of > physical space ..." Yes. Anyone who claimed that Euclids axioms hold in real spacetime was *wrong*. If they believed it, they were *deluded*. There was no shame in that before the discovery that Euclid's axioms don't hold in real spacetime. But, once its falseness has been demonstrated, to handwave about ?one man's truth? and ?bigger picture? is an attempt to avoid the admission that the claim was false. It is uncomfortable ? sometimes painful ? to admit that one's belief does not match reality; and hence natural and common for us to seek to avoid that admission when the evidence is against our belief. But that doesn't lessen the delusion. -- \ ?Human reason is snatching everything to itself, leaving | `\ nothing for faith.? ?Bernard of Clairvaux, 1090?1153 CE | _o__) | Ben Finney From ben+python at benfinney.id.au Mon Oct 17 17:04:08 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Oct 2011 08:04:08 +1100 Subject: Equal sets with unequal print and str() representations References: <878vokuzik.fsf@benfinney.id.au> Message-ID: <87r52btjnb.fsf@benfinney.id.au> Ganesh Gopalakrishnan writes: > Thanks to all who replied - also to Ben. You're welcome. (Please don't top-post your replies.) > Needless to say I'm new to Python. Welcome to this forum, then! You would be wise to get a solid grounding in Python by working through the Python tutorial from beginning to end . Perform each exercise, experiment with it until you understand, and only then move on to the next. Repeat until done :-) -- \ ?Know what I hate most? Rhetorical questions.? ?Henry N. Camp | `\ | _o__) | Ben Finney From ian.g.kelly at gmail.com Mon Oct 17 17:49:08 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 17 Oct 2011 15:49:08 -0600 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: On Mon, Oct 17, 2011 at 2:44 PM, Noah Hall wrote: > There's the isdigit method, for example - > >>>> str = "1324325" >>>> str.isdigit() > True >>>> str = "1232.34" >>>> str.isdigit() > False >>>> str = "I am a string, not an int!" >>>> str.isdigit() > False That works for non-negative base-10 integers. But: >>> "-1234".isdigit() False Cheers, Ian From roy at panix.com Mon Oct 17 20:33:08 2011 From: roy at panix.com (Roy Smith) Date: Mon, 17 Oct 2011 20:33:08 -0400 Subject: How to test if object is an integer? References: Message-ID: In article , Mathias Lafeldt wrote: > According to [1], there're more Exceptions to test for: > > try: > int(s) > return True > except (TypeError, ValueError, OverflowError): # int conversion failed > return False I don't think I would catch TypeError here. It kind of depends on how isInt() is defined. Is it: def isInt(s): "Return True if s is a string representing an integer" or is it: def isInt(s): "Return True if s (which must be a string) represents an integer" If the latter, then passing a non-string violates the contract, and the function should raise TypeError. If the former, then you could make some argument for catching the TypeError and returning False, but I think the second version is what most people have in mind for isInt(). Can you even get an OverflowError any more in a modern Python? >>> int('99999999999999999999999999999999999999999999999999999999999999999') 99999999999999999999999999999999999999999999999999999999999999999L From ckaynor at zindagigames.com Mon Oct 17 20:40:00 2011 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Mon, 17 Oct 2011 17:40:00 -0700 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: Python 2.6 running on Windows 7: >>> 99.0**99**99 OverflowError: (34, 'Result too large') Traceback (most recent call last): ? File "", line 1, in OverflowError: (34, 'Result too large') However, from the documentation: "Because of the lack of standardization of floating point exception handling in C, most floating point operations also aren?t checked." (http://docs.python.org/library/exceptions.html#exceptions.OverflowError) Chris On Mon, Oct 17, 2011 at 5:33 PM, Roy Smith wrote: > > In article , > ?Mathias Lafeldt wrote: > > > According to [1], there're more Exceptions to test for: > > > > try: > > ? ? int(s) > > ? ? return True > > except (TypeError, ValueError, OverflowError): # int conversion failed > > ? ? return False > > > I don't think I would catch TypeError here. ?It kind of depends on how > isInt() is defined. ?Is it: > > def isInt(s): > ?"Return True if s is a string representing an integer" > > or is it: > > def isInt(s): > ?"Return True if s (which must be a string) represents an integer" > > If the latter, then passing a non-string violates the contract, and the > function should raise TypeError. ?If the former, then you could make > some argument for catching the TypeError and returning False, but I > think the second version is what most people have in mind for isInt(). > > Can you even get an OverflowError any more in a modern Python? > > >>> > int('99999999999999999999999999999999999999999999999999999999999999999') > 99999999999999999999999999999999999999999999999999999999999999999L > -- > http://mail.python.org/mailman/listinfo/python-list From ian.g.kelly at gmail.com Mon Oct 17 20:59:44 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 17 Oct 2011 18:59:44 -0600 Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: On Mon, Oct 17, 2011 at 6:40 PM, Chris Kaynor wrote: > Python 2.6 running on Windows 7: >>>> 99.0**99**99 > OverflowError: (34, 'Result too large') > Traceback (most recent call last): > ? File "", line 1, in > OverflowError: (34, 'Result too large') > > However, from the documentation: > "Because of the lack of standardization of floating point exception > handling in C, most floating point operations also aren?t checked." > (http://docs.python.org/library/exceptions.html#exceptions.OverflowError) I think what Roy meant was "can you even get an OverflowError from calling int() any more", to which I think the answer is no, since in modern Pythons int() will auto-promote to a long, and in Python 3 they're even the same thing. From lanyjie at yahoo.com Mon Oct 17 22:50:27 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Mon, 17 Oct 2011 19:50:27 -0700 (PDT) Subject: How to test if object is an integer? In-Reply-To: References: Message-ID: <1318906227.86720.YahooMailNeo@web121510.mail.ne1.yahoo.com> ----- Original Message ----- > From: Noah Hall > To: MrPink > Cc: python-list at python.org > Sent: Tuesday, October 18, 2011 4:44 AM > Subject: Re: How to test if object is an integer? > There's the isdigit method, for example - > >>>> str = "1324325" >>>> str.isdigit() > True >>>> str = "1232.34" >>>> str.isdigit() > False >>>> str = "I am a string, not an int!" >>>> str.isdigit() > False > There are some corner cases to be considered with this approach: 1. negative integers: '-3' 2. strings starting with '0': '03' 3. strings starting with one '+': '+3' From steve+comp.lang.python at pearwood.info Mon Oct 17 23:56:57 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 18 Oct 2011 03:56:57 GMT Subject: How to test if object is an integer? References: Message-ID: <4e9cf909$0$29992$c3e8da3$5496439d@news.astraweb.com> On Mon, 17 Oct 2011 18:59:44 -0600, Ian Kelly wrote: > On Mon, Oct 17, 2011 at 6:40 PM, Chris Kaynor > wrote: >> Python 2.6 running on Windows 7: >>>>> 99.0**99**99 >> OverflowError: (34, 'Result too large') Traceback (most recent call >> last): >> ? File "", line 1, in >> OverflowError: (34, 'Result too large') >> >> However, from the documentation: >> "Because of the lack of standardization of floating point exception >> handling in C, most floating point operations also aren?t checked." >> (http://docs.python.org/library/ exceptions.html#exceptions.OverflowError) > > I think what Roy meant was "can you even get an OverflowError from > calling int() any more", to which I think the answer is no, since in > modern Pythons int() will auto-promote to a long, and in Python 3 > they're even the same thing. You can still get an OverflowError: >>> inf = float('inf') >>> int(inf) Traceback (most recent call last): File "", line 1, in OverflowError: cannot convert float infinity to integer and similarly for Decimal('inf') as well. -- Steven From shilparani9030 at gmail.com Tue Oct 18 01:25:52 2011 From: shilparani9030 at gmail.com (SHILPA) Date: Mon, 17 Oct 2011 22:25:52 -0700 (PDT) Subject: SOUTH INDIAN HOT ACTRESS Message-ID: <0ccc957e-e05c-426a-aeb6-9fd4a04f1ff9@31g2000prt.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html From peter.marczis at nsn.com Tue Oct 18 01:43:41 2011 From: peter.marczis at nsn.com (Peter G. Marczis) Date: Tue, 18 Oct 2011 08:43:41 +0300 Subject: Fwd: os.statvfs bug or my incompetence ? In-Reply-To: References: <4E97DB66.50302@nsn.com> <4E97F093.4000203@nsn.com> Message-ID: <4E9D120D.2060302@nsn.com> Hi, not yet, I will check it today, thanks for the idea ! We may have some deeper problem... Br, Peter. On 10/15/2011 05:46 PM, ext Kev Dwyer wrote: > Peter G. Marczis wrote: > > > > Hello Peter, > > Welcome to the list. > > Have you tried calling statvfs from a C program? What happens if you do? > > Best regards, > > Kev > > > > From as at sci.fi Tue Oct 18 07:32:15 2011 From: as at sci.fi (Anssi Saari) Date: Tue, 18 Oct 2011 14:32:15 +0300 Subject: callling python function in c References: <8ca2fc3e-a3be-49c4-8107-a47385bc0911@w26g2000pro.googlegroups.com> Message-ID: masood shaik writes: > Hi > > I am trying to call python function from c code.The following > program i got from the web source while i am trying to run this > program it throws an segmentation fault. Yes, the call to PyImport_Import fails and returns a NULL. You could use the more complete example at http://docs.python.org/extending/embedding.html which includes some error handling... Anyways, apparently PyImport_Import can't import from the current working directory but with parameters like math sqrt 2 it returns the square root of 2. Setting PYTHONPATH to point to the working directory works for me, but I don't know if there's a more correct solution. From curty at free.fr Tue Oct 18 10:23:49 2011 From: curty at free.fr (Curt) Date: 18 Oct 2011 14:23:49 GMT Subject: [OT] Re: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2011-10-17, Steven D'Aprano wrote: > > That is no more deep and meaningful than the fact that while some people > say "one plus one equals two", others say "eins und eins gleich zwei", > some say "un et un fait deux" and some say "???? ? ???? ???? ???". **** Most of us say "un et un _font_ deux," in fact, because we know how to conjugate as well as perform simple arithmetic. :-) From ramit.prasad at jpmorgan.com Tue Oct 18 14:23:18 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Tue, 18 Oct 2011 14:23:18 -0400 Subject: Re-raise different exception with original stack trace In-Reply-To: <4E98BC91.3010207@mrabarnett.plus.com> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F217865A4@EMARC112VS01.exchad.jpmchase.net> <4E98BC91.3010207@mrabarnett.plus.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2186310B@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- From: python-list-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of MRAB Sent: Friday, October 14, 2011 5:50 PM To: python-list at python.org Subject: Re: Re-raise different exception with original stack trace On 14/10/2011 22:30, Prasad, Ramit wrote: > Hi all, > Hopefully you guys can help me with my problem. > > Basically I have a UI program that can "save" information. The UI passes the save to the controller and the controller saves a file and does some post processing. If saving the file fails, I want to handle the error differently than if the error was in post processing. In both cases the possible exceptions are varied and unknown so I cannot pick and choose certain exception. The problem with the sample program below is that the stack trace is replaced by the re-raise. What would be the best way(s) to get the original stack trace in save_from_UI if the exception occurs in post_process? Using Python 2.6 and Windows(XP and 7) / Linux. > > Def save_from_model(): > save() # do not catch exception (could be any exception) > try: > post_process() > except Exception as e: > #do something > raise CustomException() # "wrap" exception so bar knows to handle it differently > > def save_from_UI(): > try: > foo() > except CustomException() as e: > # How do I get the original stacktrace instead of the reraise? > except Exception as e: > # do something else with this exception > You could save a reference to the exception in the custom exception: class CustomException(Exception): def __init__(self, e): Exception.__init__(self) self.exc = e def save_from_model(): save() # do not catch exception (could be any exception) try: post_process() except Exception as e: #do something raise CustomException(e) def save_from_UI(): try: foo() except CustomException as e: # Original exception is e.exc except Exception as e: # do something else with this exception ======================================================================= Yes, but raising the CustomException replaces the last traceback and even with the saved exception, how would you get the original stacktrace? The only thing I can think is get the stacktrace and store it in the exception. That does not seem very Pythonic to me. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From ian.g.kelly at gmail.com Tue Oct 18 15:45:26 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 18 Oct 2011 13:45:26 -0600 Subject: Re-raise different exception with original stack trace In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2186310B@EMARC112VS01.exchad.jpmchase.net> References: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F217865A4@EMARC112VS01.exchad.jpmchase.net> <4E98BC91.3010207@mrabarnett.plus.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F2186310B@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Tue, Oct 18, 2011 at 12:23 PM, Prasad, Ramit wrote: > Yes, but raising the CustomException replaces the last traceback and even with the saved exception, how would you get the original stacktrace? The only thing I can think is get the stacktrace and store it in the exception. That does not seem very Pythonic to me. In Python 3 you could chain the exceptions with: except Exception as e: raise CustomException() from e There is no such syntax in Python 2, but you could manually store and retrieve the __cause__ and __traceback__ attributes similarly to the way Python 3 does it. See PEP 3134 for full details. HTH, Ian From devplayer at gmail.com Tue Oct 18 18:14:29 2011 From: devplayer at gmail.com (DevPlayer) Date: Tue, 18 Oct 2011 15:14:29 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <87vcrntk67.fsf@benfinney.id.au> Message-ID: <7f0318ad-d9de-4651-8e70-0e1258125c2c@b10g2000vbc.googlegroups.com> "3rd Base" From kwebb at teradactyl.com Tue Oct 18 21:37:00 2011 From: kwebb at teradactyl.com (Kristen J. Webb) Date: Tue, 18 Oct 2011 19:37:00 -0600 Subject: ssl module with C Message-ID: <4E9E29BC.8080307@teradactyl.com> Hi All, I'm hoping that the answer to this question will shed light on the Python/C interface and make me a much better python programer. I have a test TLS connection program in python (very breif) import socket, ssl news=socket.socket() news.connect() new_ssl=ssl.wrap_socket() new_ssl.read()/new_ssl.write() I'd like to pass my new_ssl to a C .so library so that I can SSL_read()/SSL_write. Why? Using the python/ssl interface gets me around so many issues with varies Linux distros as libssl.so is so unstandard. My idea is that using the installed python helps me to separte my own work-horse C code from the native openssl library. Can this be done? If not, the why should make me a better python programer! Many thanks in advance! Kris -- Mr. Kristen J. Webb Teradactyl LLC. PHONE: 1-505-242-1091 EMAIL: kwebb at teradactyl.com VISIT: http://www.teradactyl.com Home of the True incremental Backup System From steve+comp.lang.python at pearwood.info Tue Oct 18 23:05:28 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 19 Oct 2011 03:05:28 GMT Subject: [OT] Re: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> On Tue, 18 Oct 2011 14:23:49 +0000, Curt wrote: > On 2011-10-17, Steven D'Aprano > wrote: >> >> That is no more deep and meaningful than the fact that while some >> people say "one plus one equals two", others say "eins und eins gleich >> zwei", some say "un et un fait deux" and some say "???? ? ???? ???? >> ???". > **** > > Most of us say "un et un _font_ deux," in fact, because we know how to > conjugate as well as perform simple arithmetic. > > :-) I blame Google Translate. -- Steven From wuwei23 at gmail.com Tue Oct 18 23:58:05 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 18 Oct 2011 20:58:05 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: <3cbd7630-2dd0-4b36-9a76-a024364c2b0f@42g2000prp.googlegroups.com> DevPlayer wrote: > Ever hear/read the term: "It's all good."? A reference to Karma and > how things will work out for the better in the end inspite of what you > see now... A great example of "Everything is Symantics". "Semantics". Also: nonsense. You're conflating an ethical system with a _completely_ indepdent symbolic one via overloaded terminology. That's pretty true of most of your rants, actually. > And another weird notion to put forward. "2" as a numberic quantity by > itself is utterly meaningless. Two what? More nonsense. The whole field of number theory would like to dispute this point. So would Python: i = 2. What exactly does i hold? Two integers? From wuwei23 at gmail.com Wed Oct 19 00:03:22 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 18 Oct 2011 21:03:22 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <87vcrntk67.fsf@benfinney.id.au> Message-ID: On Oct 18, 6:52?am, Ben Finney wrote: > A belief that doesn't match reality is a delusion. That doesn't change > when someone thinks it's an epiphany: it's still a delusion. Apparently there was some talk about removing delusional as a classification from the DSM due to its definition being, in part, that it was an _unshared_ belief (which seems to be a loophole for not locking up the religious). With the advent of the internet, it's almost impossible to _not_ find someone who agrees with you, no matter how batshit crazy you might be :) From wuwei23 at gmail.com Wed Oct 19 00:05:42 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 18 Oct 2011 21:05:42 -0700 (PDT) Subject: strange comparison result with 'is' References: <1318840924.74377.YahooMailNeo@web121512.mail.ne1.yahoo.com> Message-ID: <95885d32-ecfd-4e70-9f35-4bcaad57e96f@u10g2000prl.googlegroups.com> On Oct 18, 3:53?am, Terry Reedy wrote: > This has come up enough that I opened http://bugs.python.org/issue13203 I really don't get the new Python user obsession with id(). I don't think I've ever used it, in production code or otherwise. From rustompmody at gmail.com Wed Oct 19 03:03:01 2011 From: rustompmody at gmail.com (rusi) Date: Wed, 19 Oct 2011 00:03:01 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Oct 17, 7:34?pm, Steven D'Aprano wrote: > That is no more deep and meaningful than the fact that while some people > say "one plus one equals two", others say "eins und eins gleich zwei", > some say "un et un fait deux" and some say "???? ? ???? ???? ???". > Regardless of whether you write two, zwei, ???, ???, 2 (in decimal), 10 > (in binary), II (in Roman numerals) or even {0,1} using set theory > notation, the number remains the same, only the symbol we use to label it > is different. And Ben said: > A belief that doesn't match reality is a delusion. That doesn't change > when someone thinks it's an epiphany: it's still a delusion. > If a claim about reality doesn't actually match reality, it's untrue. > That doesn't change when someone believes it: it's still untrue, or > claims it's ?part of a bigger picture?. These are classical platonist claims: In short objective reality exists aside from the subjective perception of it. Here is an extract from Gurevich's http://research.microsoft.com/en-us/um/people/gurevich/opera/123.pdf ------------------------------------------ Q: Still, most mathematicians are Platonists, is that right? A: I think so. Q: Somehow we independently grow to become Platonists. A: I do not think it is always independent. To an extent, we learn the attitude. I remember, in a geometry class, my teacher wanted to prove the congruence of two triangles. Let?s take a third triangle, she said, and I asked where do triangles come from. I worried that there may be no more triangles there. Those were hard times in Russia, and we were accustomed to shortages. Q: What did she say? A: She looked at me for a while and then said: ?Shut up?. But eventually I got the idea that you don?t have to build a triangle when you need one; all possible triangles exist ahead of time. -------------------------- Quantum physics would not exist if all physicists were as cock-sure of objective reality. Nor would computer science. Heres a capsule history: Kronecker and Cantor disagree on whether sets exist. K: Only numbers exist. C: All manner of infinite sets exist A generation later and continuing Hilbert and Brouwer disagree on what constitutes a proof A generation later Godel sets out to demolish Hilbert's formalist agenda. Turing tries to demolish Godel. He does not succeed (Simple questions turn out to be undecidable/non-computable. However a side-effect of his attempts is... the computer Python version: The integers that exist in builtin type int exist somehow differently from the integers in function nats def nats(): ... n = -1 ... while True: ... n +=1 ... yield n which once again exist differently from the integers in range(10). In short: To be a computer scientist (as against classical scientist) is to know that "to exist" "to be true" "to be valid" are more real valued than boolean predicates From aspineux at gmail.com Wed Oct 19 04:06:53 2011 From: aspineux at gmail.com (aspineux) Date: Wed, 19 Oct 2011 01:06:53 -0700 (PDT) Subject: fromutc: dt.tzinfo is not self: pytz.timezone('UTC').fromutc(datetime.utcnow()) Message-ID: hi >>> import pytz >>> from datetime import datetime >>> pytz.timezone('GMT0').fromutc(datetime.utcnow()) datetime.datetime(2011, 10, 19, 7, 54, 45, 579125, tzinfo=) >>> pytz.timezone('UTC').fromutc(datetime.utcnow()) Traceback (most recent call last): File "", line 1, in ValueError: fromutc: dt.tzinfo is not self >>> pytz.timezone('Europe/Brussels').fromutc(datetime.utcnow()) datetime.datetime(2011, 10, 19, 9, 55, 47, 787937, tzinfo=) Why does UTC fail ? Bug or feature ? From clp2 at rebertia.com Wed Oct 19 04:32:58 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 19 Oct 2011 01:32:58 -0700 Subject: fromutc: dt.tzinfo is not self: pytz.timezone('UTC').fromutc(datetime.utcnow()) In-Reply-To: References: Message-ID: On Wed, Oct 19, 2011 at 1:06 AM, aspineux wrote: > hi > >>>> import pytz >>>> from datetime import datetime >>>> pytz.timezone('GMT0').fromutc(datetime.utcnow()) > datetime.datetime(2011, 10, 19, 7, 54, 45, 579125, > tzinfo=) >>>> ?pytz.timezone('UTC').fromutc(datetime.utcnow()) > Traceback (most recent call last): > ?File "", line 1, in > ValueError: fromutc: dt.tzinfo is not self >>>> pytz.timezone('Europe/Brussels').fromutc(datetime.utcnow()) > datetime.datetime(2011, 10, 19, 9, 55, 47, 787937, tzinfo= 'Europe/Brussels' CEST+2:00:00 DST>) > > Why does UTC fail ? > Bug or feature ? Dunno, but it might be worth noting that the examples in the pytz docs don't use .fromutc(). Have you tried using .localize() instead? Or specifically in the case of UTC, datetime.utcnow().replace(tzinfo=pytz.utc) ? Cheers, Chris From ben+python at benfinney.id.au Wed Oct 19 07:06:40 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Oct 2011 22:06:40 +1100 Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <87vcrntk67.fsf@benfinney.id.au> Message-ID: <87fwips0jj.fsf@benfinney.id.au> alex23 writes: > On Oct 18, 6:52?am, Ben Finney wrote: > > A belief that doesn't match reality is a delusion. That doesn't change > > when someone thinks it's an epiphany: it's still a delusion. > > Apparently there was some talk about removing delusional as a > classification from the DSM due to its definition being, in part, that > it was an _unshared_ belief (which seems to be a loophole for not > locking up the religious). Does the DSM define delusion dependent on who shares the belief? I thought that was, rather, part of the definition of delusional disorder. In other words, some delusions don't count as disorders because plenty of people share them, but are still delusions. Just as most people's vision has some imperfection, but visual disorders would be diagnosed in some smaller subset of those people. I don't have access to the DSM, though, so can only speculate based on indirect sources . -- \ ?For myself, I am an optimist ? it does not seem to be much use | `\ being anything else.? ?Winston Churchill, 1954-11-09 | _o__) | Ben Finney From rustompmody at gmail.com Wed Oct 19 07:17:41 2011 From: rustompmody at gmail.com (rusi) Date: Wed, 19 Oct 2011 04:17:41 -0700 (PDT) Subject: Equal sets with unequal print and str() representations References: <4E9B6E23.9050106@cs.utah.edu> Message-ID: On Oct 17, 7:47?am, Terry Reedy wrote: > On 10/16/2011 9:17 PM, Ian Kelly wrote: > > > On Sun, Oct 16, 2011 at 5:52 PM, Ganesh Gopalakrishnan > > ?wrote: > >> This probably is known, but a potential pitfall (was, for me) nevertheless. > >> I suspect it is due to hash collisions between 's3' and 's13' in this case? > >> It happens only rarely, depending on the contents of the set. > > > I'm not sure exactly which keys are colliding here, but in general the > > iteration order of a set (or dict) depends not just on the contents, > > but also on the order of insertion. ?And of course the repr depends on > > the iteration order -- anything consistent would require sorting, > > which would be O(n log n) and is not even necessarily well-defined. > > To put it another way, any dependence on the arbitrary ordering of > unordered collections in iteration or displays is a programming error. Given that this is becoming a FAQ, I wonder if something like the above statement should go into the docs? From ben+python at benfinney.id.au Wed Oct 19 07:30:42 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Oct 2011 22:30:42 +1100 Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87botdrzfh.fsf@benfinney.id.au> rusi writes: > These are classical platonist claims: In short objective reality > exists aside from the subjective perception of it. Yes, that's the simplest explanation for the comparability of our observations: there's one reality and we all inhabit it. > Quantum physics would not exist if all physicists were as cock-sure of > objective reality. Not at all. It's because those physicists *are* sure that there is an objective reality that they are able to form testable hypotheses about it and come up with objective tests and make objectively-comparable observations of objective reality to see which hypotheses are objectively false. As a result, quantum physics is responsible for astoundingly accurate correspondence between its predictions of objective reality and what is actually observed. That's not grounds to be cock-sure of any particular explanation; the whole enterprise of scientific inquiry is based on trying to demonstrate that people's explanations are false. But it's certainly grounds to be confident that reality exists and is the same for everyone. People's subjective perception of reality can of course be wrong to varying degrees; and that's what science is designed to discover. But it is pointless to try to find out more about objective reality unless one takes objective reality as an axiom. > Heres a capsule history: [mathematicians disagree about reality and > much progress results] Yes, exactly. Much progress is made in testing prejudices and assumptions and hypotheses about objective reality to see which ones are objectively false, and not by abandoning objective reality for some ?my subjective perception is just as god as yours? miasma. That's just wrong-headed: subjective perception is commonly an inaccurate representation of what's real, and we delude ourselves if we think that doesn't apply to us. -- \ ?Don't be misled by the enormous flow of money into bad defacto | `\ standards for unsophisticated buyers using poor adaptations of | _o__) incomplete ideas.? ?Alan Kay | Ben Finney From rustompmody at gmail.com Wed Oct 19 08:17:37 2011 From: rustompmody at gmail.com (rusi) Date: Wed, 19 Oct 2011 05:17:37 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <87botdrzfh.fsf@benfinney.id.au> Message-ID: On Oct 19, 4:30?pm, Ben Finney wrote: > rusi writes: > > These are classical platonist claims: ?In short objective reality > > exists aside from the subjective perception of it. > > Yes, that's the simplest explanation for the comparability of our > observations: there's one reality and we all inhabit it. > > > Quantum physics would not exist if all physicists were as cock-sure of > > objective reality. > > Not at all. It's because those physicists *are* sure that there is an > objective reality that they are able to form testable hypotheses about > it and come up with objective tests and make objectively-comparable > observations of objective reality to see which hypotheses are > objectively false. It may be better to let the quantum physicists speak for themselves? [From http://www.marxists.org/reference/subject/philosophy/works/ge/heisenb3.htm] In classical physics science started from the belief - or should one say from the illusion? - that we could describe the world or at least parts of the world without any reference to ourselves. This division (into object and rest of the world) is arbitrary and historically a direct consequence of our scientific method; the use of the classical concepts is finally a consequence of the general human way of thinking. But this is already a reference to ourselves and in so far our description is not completely objective. Objectivity has become the first criterion for the value of any scientific result... (and the Copenhagen interpretation of) quantum theory corresponds to this ideal as far as possible. From curty at free.fr Wed Oct 19 09:15:54 2011 From: curty at free.fr (Curt) Date: 19 Oct 2011 13:15:54 GMT Subject: [OT] Re: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2011-10-19, Steven D'Aprano wrote: > On Tue, 18 Oct 2011 14:23:49 +0000, Curt wrote: > >> Most of us say "un et un _font_ deux," in fact, because we know how to >> conjugate as well as perform simple arithmetic. >> >> :-) > > > I blame Google Translate. > I thought you were trying to shine as a polyglot(math). From hg at schaathun.net Wed Oct 19 09:30:26 2011 From: hg at schaathun.net (Hans Georg Schaathun) Date: Wed, 19 Oct 2011 14:30:26 +0100 Subject: tiff/pbm in pyplot (ubuntu) Message-ID: Does anyone know how to get support for tiff/pbm in pyplot on Ubuntu (11.04)? This used to work for me, on some system, but when I attempt to regenerate my TIFF files on a new system, it all crashes. The error message is clear; TIFF and PBM are not supported, and the exception occurs in a call to imsave(). I know that someone will suggest to use PNG instead, converting with ImageMagick. Trouble is, when I load a grayscale PNG in python I get a 3D array with three colour channels. I need a 2D array, and I'd rather avoid the hassle of modifying all the occurrences to accept a 3D array and check that the colour channels are equal. I'll be grateful for any pointers, TIA -- :-- Hans Georg From ramit.prasad at jpmorgan.com Wed Oct 19 11:50:09 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 19 Oct 2011 11:50:09 -0400 Subject: [NUMPY] "ValueError: total size of new array must be unchanged" just on Windows In-Reply-To: References: <207e68fe-2402-4e47-8cf4-ea8bb2eaf818@j31g2000vbl.googlegroups.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F217865FA@EMARC112VS01.exchad.jpmchase.net> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F218F794A@EMARC112VS01.exchad.jpmchase.net> Redirecting to his question to the list. >I need of a matrix, not of an array. >But is this error due to a numpy bug? I am not an expert on NumPy/SciPy, but I do not believe matrixes are allowed to be 3 dimensional. Google only produced results of 3 dimensional arrays. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From admin at mbnoimi.net Wed Oct 19 13:14:49 2011 From: admin at mbnoimi.net (Muhammad Bashir Al-Noimi) Date: Wed, 19 Oct 2011 20:14:49 +0300 Subject: Python based silent installer, how to? Message-ID: <4E9F0589.9020005@mbnoimi.net> An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: admin.vcf Type: text/x-vcard Size: 332 bytes Desc: not available URL: From markus.mj at gmail.com Wed Oct 19 16:14:21 2011 From: markus.mj at gmail.com (markus.mj at gmail.com) Date: Wed, 19 Oct 2011 13:14:21 -0700 (PDT) Subject: Threading: Method trigger after thred finished Message-ID: <13676309.461.1319055261456.JavaMail.geo-discussion-forums@yqnv12> Hi, I am looking for help with following problem. I scripted threaded database query, with session open per thread, and queries delivered through queue. Every open DB session must be closed with "abort" or "commit", however on which event should I trigger the DB disconnect? Ideally it would close the DB as the thread class gets deconstructed, but "__del__" does never fire. How would you solve the problem? Here an non working example (bended from IBM developerWorks tutorial) that explains the situation: multi_query = ["query1","query2","query3","query4","query5","query6"] queue = Queue.Queue() class ThreadSql(threading.Thread): def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue #Open database connection instance self.session = DbConnect() def run(self): while True: #grabs query from queue query = self.queue.get() #Fire query and print result print self.session.SQL(query) #Queue job is done self.queue.task_done() # THIS PART IS NOT WORKING def __del__(self): #Disconnect Database session and commit or abort transactions self.session.Disconnect() print "The End" #--------------------------------- for i in range(5): t = ThreadUrl(queue) t.setDaemon(True) t.start() #Fill the queue for single_query in multi_query: queue.put(single_query) #Wait until query is empty and finish queue.join() Thank you for any idea! Markus From steve+comp.lang.python at pearwood.info Wed Oct 19 17:00:23 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 19 Oct 2011 21:00:23 GMT Subject: Python based silent installer, how to? References: Message-ID: <4e9f3a67$0$29974$c3e8da3$5496439d@news.astraweb.com> On Wed, 19 Oct 2011 20:14:49 +0300, Muhammad Bashir Al-Noimi wrote: > > > > > > > bidimailui-detected-decoding-type="UTF-8" bgcolor="#FFFFFF" > text="#000000"> >

Hi All,

>


>

Please don't send raw HTML (so-called "rich text") to mailing lists. It makes it very difficult for some people to read. If you must use HTML, please ensure your email client or news reader also sends a plain text version of the message as well. >

I'm using many python based packages (ex. href="http://launchpad.net/bzr/2.4/2.4.1/+download/bzr-2.4.1-1.win32- py2.6.exe">bzr-2.4.1-1.win32-py2.6.exe) > inside my installer.
>
> How can I install them silently in Windows?

That will depend on what your installer is, and whether it has an option for silent installation. Your question is unclear. What is the connection between Python and the installer? "I am installing Python on Windows." "Python is already installed, and I'm installing extra Python packages, using many different installers." "I'm installing applications using an installer written in Python." "I'm writing my own installer, using Python." or something else? If you want a better answer, you will need to explain what you are doing in more detail. -- Steven From steve+comp.lang.python at pearwood.info Wed Oct 19 17:01:39 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 19 Oct 2011 21:01:39 GMT Subject: [OT] Re: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> On Wed, 19 Oct 2011 13:15:54 +0000, Curt wrote: > On 2011-10-19, Steven D'Aprano > wrote: >> On Tue, 18 Oct 2011 14:23:49 +0000, Curt wrote: >> >>> Most of us say "un et un _font_ deux," in fact, because we know how to >>> conjugate as well as perform simple arithmetic. >>> >>> :-) >> >> >> I blame Google Translate. >> >> > I thought you were trying to shine as a polyglot(math). I am a poly-illiterate. I can't read or write hundreds of languages. -- Steven From steve+comp.lang.python at pearwood.info Wed Oct 19 17:03:21 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 19 Oct 2011 21:03:21 GMT Subject: fromutc: dt.tzinfo is not self: pytz.timezone('UTC').fromutc(datetime.utcnow()) References: Message-ID: <4e9f3b19$0$29974$c3e8da3$5496439d@news.astraweb.com> On Wed, 19 Oct 2011 01:06:53 -0700, aspineux wrote: > hi > >>>> import pytz >>>> from datetime import datetime >>>> pytz.timezone('GMT0').fromutc(datetime.utcnow()) > datetime.datetime(2011, 10, 19, 7, 54, 45, 579125, tzinfo= 'GMT0'>) >>>> pytz.timezone('UTC').fromutc(datetime.utcnow()) > Traceback (most recent call last): > File "", line 1, in > ValueError: fromutc: dt.tzinfo is not self >>>> pytz.timezone('Europe/Brussels').fromutc(datetime.utcnow()) > datetime.datetime(2011, 10, 19, 9, 55, 47, 787937, tzinfo= 'Europe/Brussels' CEST+2:00:00 DST>) > > Why does UTC fail ? > Bug or feature ? Looks like a bug to me. But I'm not an expert on pytz. Perhaps you should report it back to the package author. -- Steven From anikom15 at gmail.com Wed Oct 19 17:49:26 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Wed, 19 Oct 2011 14:49:26 -0700 Subject: [OT] Re: Benefit and belief In-Reply-To: <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20111019214926.GA31343@Smoke> On Wed, Oct 19, 2011 at 09:01:39PM +0000, Steven D'Aprano wrote: > On Wed, 19 Oct 2011 13:15:54 +0000, Curt wrote: > > > On 2011-10-19, Steven D'Aprano > > wrote: > >> On Tue, 18 Oct 2011 14:23:49 +0000, Curt wrote: > >> > >>> Most of us say "un et un _font_ deux," in fact, because we know how to > >>> conjugate as well as perform simple arithmetic. > >>> > >>> :-) > >> > >> > >> I blame Google Translate. > >> > >> > > I thought you were trying to shine as a polyglot(math). > > I am a poly-illiterate. I can't read or write hundreds of languages. I think you need to speak German fluently to be a good programmer. From ben+python at benfinney.id.au Wed Oct 19 18:12:54 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 20 Oct 2011 09:12:54 +1100 Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <87botdrzfh.fsf@benfinney.id.au> Message-ID: <8739eosk9l.fsf@benfinney.id.au> rusi writes: > This division (into object and rest of the world) is arbitrary and > historically a direct consequence of our scientific method; the use of > the classical concepts is finally a consequence of the general human > way of thinking. But this is already a reference to ourselves and in > so far our description is not completely objective. Yes, it's natural for humans to think in dualistic terms ? thinking that the self is separate from the external world ? and that thinking is unsupported by evidence so is probably wrong. That doesn't argue against the position I've been elaborating, and it doesn't say anything against objective reality. We humans are part of that objective reality, and descriptions of reality need to incorporate that fact. -- \ ?I got food poisoning today. I don't know when I'll use it.? | `\ ?Steven Wright | _o__) | Ben Finney From alec.taylor6 at gmail.com Wed Oct 19 18:35:45 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Thu, 20 Oct 2011 09:35:45 +1100 Subject: Python based silent installer, how to? In-Reply-To: <4E9F0589.9020005@mbnoimi.net> References: <4E9F0589.9020005@mbnoimi.net> Message-ID: Just download the msi (script is available to regenerate yourself) and run it with the silent swtich, something like: msiexec /x nameofmsi.msi On 10/20/11, Muhammad Bashir Al-Noimi wrote: > Hi All, > > > I'm using many python based packages (ex. bzr-2.4.1-1.win32-py2.6.exe) > inside my installer. > > How can I install them silently in Windows? > > PS > > Most installers has arguments for silent installation ex. NSIS based > installers has /S argument but I didn't find any reference for python based > installers > > -- > Best Regards > Muhammad Bashir Al-Noimi > My Blog: http://mbnoimi.net From steve+comp.lang.python at pearwood.info Wed Oct 19 23:55:44 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 20 Oct 2011 03:55:44 GMT Subject: Threading: Method trigger after thred finished References: <13676309.461.1319055261456.JavaMail.geo-discussion-forums@yqnv12> Message-ID: <4e9f9bc0$0$29974$c3e8da3$5496439d@news.astraweb.com> On Wed, 19 Oct 2011 13:14:21 -0700, markus.mj wrote: > Hi, > > I am looking for help with following problem. I scripted threaded > database query, with session open per thread, and queries delivered > through queue. Every open DB session must be closed with "abort" or > "commit", however on which event should I trigger the DB disconnect? > Ideally it would close the DB as the thread class gets deconstructed, > but "__del__" does never fire. The __del__ destructor method is not guaranteed to be called in a timely fashion, if at all. My *guess* is that the main Python environment is shutting down when the daemon threads get killed, and the __del__ method never gets a chance to run. To be honest, I'm not sure why you are using daemon threads. It seems to me that blocking until the queue is empty makes the use of daemon threads pointless, but I'm not experienced enough with threads to be sure. The usual advice is to explicitly call destructors rather than rely on automatic __del__ methods. Given that, this works for me: import threading import Queue import time # Fill the queue. queue = Queue.Queue() queries = ["query"+str(i) for i in range(10)] for query in queries: queue.put(query) # Make consumer threads. class ThreadSql(threading.Thread): def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue # Open database connection instance self.session = "+++connection+++" # DbConnect() self._open = True def run(self): while self._open: # Grab a query from queue. query = self.queue.get() # And process it. print self, query time.sleep(1) # Mark the queue job as done. self.queue.task_done() def close(self): print "Closing", self # self.session.Disconnect() self._open = False threads = [ThreadSql(queue) for _ in range(4)] for t in threads: t.setDaemon(True) t.start() # Wait until the queue is empty, then close the threads. queue.join() for t in threads: t.close() -- Steven From markus.mj at gmail.com Thu Oct 20 03:05:27 2011 From: markus.mj at gmail.com (Markus) Date: Thu, 20 Oct 2011 00:05:27 -0700 (PDT) Subject: Threading: Method trigger after thred finished References: <13676309.461.1319055261456.JavaMail.geo-discussion-forums@yqnv12> <4e9f9bc0$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: <7bb60119-a84a-4660-83ff-f9c50191a667@g25g2000yqh.googlegroups.com> On Oct 20, 5:55?am, Steven D'Aprano wrote: > On Wed, 19 Oct 2011 13:14:21 -0700, markus.mj wrote: > > Hi, > > > I am looking for help with following problem. I scripted threaded > > database query, with session open per thread, and queries delivered > > through queue. Every open DB session must be closed with "abort" or > > "commit", however on which event should I trigger the DB disconnect? > > Ideally it would close the DB as the thread class gets deconstructed, > > but "__del__" does never fire. > > The __del__ destructor method is not guaranteed to be called in a timely > fashion, if at all. My *guess* is that the main Python environment is > shutting down when the daemon threads get killed, and the __del__ method > never gets a chance to run. > > To be honest, I'm not sure why you are using daemon threads. It seems to > me that blocking until the queue is empty makes the use of daemon threads > pointless, but I'm not experienced enough with threads to be sure. > > The usual advice is to explicitly call destructors rather than rely on > automatic __del__ methods. Given that, this works for me: > > import threading > import Queue > import time > > # Fill the queue. > queue = Queue.Queue() > queries = ["query"+str(i) for i in range(10)] > for query in queries: > ? ? queue.put(query) > > # Make consumer threads. > class ThreadSql(threading.Thread): > ? ? def __init__(self, queue): > ? ? ? ? threading.Thread.__init__(self) > ? ? ? ? self.queue = queue > ? ? ? ? # Open database connection instance > ? ? ? ? self.session = "+++connection+++" ?# DbConnect() > ? ? ? ? self._open = True > > ? ? def run(self): > ? ? ? ? while self._open: > ? ? ? ? ? ? # Grab a query from queue. > ? ? ? ? ? ? query = self.queue.get() > ? ? ? ? ? ? # And process it. > ? ? ? ? ? ? print self, query > ? ? ? ? ? ? time.sleep(1) > ? ? ? ? ? ? # Mark the queue job as done. > ? ? ? ? ? ? self.queue.task_done() > > ? ? def close(self): > ? ? ? ? print "Closing", self > ? ? ? ? # self.session.Disconnect() > ? ? ? ? self._open = False > > threads = [ThreadSql(queue) for _ in range(4)] > for t in threads: > ? ? t.setDaemon(True) > ? ? t.start() > > # Wait until the queue is empty, then close the threads. > queue.join() > for t in threads: > ? ? t.close() > > -- > Steven Hi Steven, great point with the explicit call of destructor. I did a quick test and it is behaving exactly like I need. Thank you very much! Markus From steve+comp.lang.python at pearwood.info Thu Oct 20 04:04:16 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 20 Oct 2011 08:04:16 GMT Subject: Are range iterators thread safe? Message-ID: <4e9fd600$0$29974$c3e8da3$5496439d@news.astraweb.com> Using Python 3, are range_iterator objects thread-safe? I have tried this, and it seems to be safe: >>> from threading import Thread >>> x = iter(range(4)) >>> def doit(x): ... print("result =", next(x)) ... >>> threads = [Thread(target=doit, args=(x,)) for i in range(4)] >>> for t in threads: ... t.start() ... result = 0 result = 1 result = 2 result = 3 >>> -- Steven From oh at no.no Thu Oct 20 04:06:21 2011 From: oh at no.no (Uffe Kousgaard) Date: Thu, 20 Oct 2011 10:06:21 +0200 Subject: COM / .NET Message-ID: <4e9fd67f$0$281$14726298@news.sunsite.dk> Is python able to access COM libraries or .NET assemblies? If both, which is the easist or most popular? From mail at timgolden.me.uk Thu Oct 20 04:42:11 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 20 Oct 2011 09:42:11 +0100 Subject: COM / .NET In-Reply-To: <4e9fd67f$0$281$14726298@news.sunsite.dk> References: <4e9fd67f$0$281$14726298@news.sunsite.dk> Message-ID: <4E9FDEE3.7010401@timgolden.me.uk> On 20/10/2011 09:06, Uffe Kousgaard wrote: > Is python able to access COM libraries or .NET assemblies? If both, which is > the easist or most popular? You have a few choices in this regard: * CPython can access COM objects either via the pywin32 extensions[1] or via comtypes[2]. The former is maintained and is quite mature and stable (and has recently had a small fix made to allow more flexibility when dealing with COM VARIANTS). comtypes, I think, unmaintained, although perfectly usable and somewhat more flexible than pywin32 in certain respects. * Python.NET [3] is a project which was dormant for a while but which is now maintained once more. This is a sort of bridge between CPython and the .NET assemblies. * IronPython [4] is a project, originally run inside Microsoft, now spun off as an Open Source project, which re-implements Python as a 1st-class .NET language running on the DLR. From that you have full access to the .NET Framework and its facilities. [1] http://sourceforge.net/projects/pywin32/ [2] http://pypi.python.org/pypi/comtypes [3] http://pythonnet.sourceforge.net/ (not sure if that's the canonical URL for that project or not) [4] http://ironpython.net/ TJG From admin at mbnoimi.net Thu Oct 20 04:45:51 2011 From: admin at mbnoimi.net (Muhammad Bashir Al-Noimi) Date: Thu, 20 Oct 2011 11:45:51 +0300 Subject: Python based silent installer, how to? In-Reply-To: References: <4E9F0589.9020005@mbnoimi.net> Message-ID: <4E9FDFBF.2020801@mbnoimi.net> On 20/10/2011 01:35 ?, Alec Taylor wrote: > Just download the msi (script is available to regenerate yourself) and > run it with the silent swtich, something like: > > msiexec /x nameofmsi.msi Sorry I didn't explain what I'm looking for exactly. I've packages built by bdist_wininst, Is there any way for install them silently? Or is there any way for convert them to another format (ex. msi) in that way I can install them silently. -- Best Regards Muhammad Bashir Al-Noimi My Blog: http://mbnoimi.net -------------- next part -------------- A non-text attachment was scrubbed... Name: admin.vcf Type: text/x-vcard Size: 332 bytes Desc: not available URL: From admin at mbnoimi.net Thu Oct 20 05:05:24 2011 From: admin at mbnoimi.net (Muhammad Bashir Al-Noimi) Date: Thu, 20 Oct 2011 12:05:24 +0300 Subject: Python based silent installer, how to? In-Reply-To: <4e9f3a67$0$29974$c3e8da3$5496439d@news.astraweb.com> References: <4e9f3a67$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4E9FE454.7090106@mbnoimi.net> On 20/10/2011 12:00 ?, Steven D'Aprano wrote: > Please don't send raw HTML (so-called "rich text") to mailing lists. It > makes it very difficult for some people to read. If you must use HTML, > please ensure your email client or news reader also sends a plain text > version of the message as well. Sorry I forgot to configure my Thunderbird. > That will depend on what your installer is, and whether it has an option > for silent installation. > > Your question is unclear. What is the connection between Python and the > installer? > > "I am installing Python on Windows." > > "Python is already installed, and I'm installing extra Python packages, > using many different installers." > > "I'm installing applications using an installer written in Python." > > "I'm writing my own installer, using Python." > > or something else? > > > If you want a better answer, you will need to explain what you are doing > in more detail. I've packages built by bdist_wininst, Is there any way for install them silently? Or is there any way for convert them to another format (ex. msi) in that way I can install them silently. PS I tried to unzip that packages (I thought I may re-package un-zipped packages by NSIS or something else) and I discovered that the structure of directories of bdist_wininst packages so different! for example: ---xlwt-0.7.2.win32.exe--- PURELIB | |-- xlwt-0.7.2-py2.5.egg-info |-+ xlwt |-+ doc |-+ examples |-- __init__.py |-- antlr.py . . ---bzr-2.3.4-1.win32-py2.6.exe--- DATA |-- Doc PLATLIB | |-- bzr-2.3.4-py2.6.egg-info |-+ bzrlib |-+ bundle |-+ doc |-- __init__.py |-- _annotator_py.py . . SCRIPTS | |-- bzr |-- bzr-win32-bdist-postinstall.py -- Best Regards Muhammad Bashir Al-Noimi My Blog: http://mbnoimi.net -------------- next part -------------- A non-text attachment was scrubbed... Name: admin.vcf Type: text/x-vcard Size: 332 bytes Desc: not available URL: From oh at no.no Thu Oct 20 05:12:10 2011 From: oh at no.no (Uffe Kousgaard) Date: Thu, 20 Oct 2011 11:12:10 +0200 Subject: COM / .NET References: <4e9fd67f$0$281$14726298@news.sunsite.dk> Message-ID: <4e9fe5ec$0$290$14726298@news.sunsite.dk> "Tim Golden" wrote in message news:mailman.2075.1319100141.27778.python-list at python.org... > > You have a few choices in this regard: Thanks for a detailed reply. We'll start looking at [1] and [3]. From mail at timgolden.me.uk Thu Oct 20 05:12:45 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 20 Oct 2011 10:12:45 +0100 Subject: Python based silent installer, how to? In-Reply-To: <4E9FDFBF.2020801@mbnoimi.net> References: <4E9F0589.9020005@mbnoimi.net> <4E9FDFBF.2020801@mbnoimi.net> Message-ID: <4E9FE60D.8020009@timgolden.me.uk> On 20/10/2011 09:45, Muhammad Bashir Al-Noimi wrote: > On 20/10/2011 01:35 ?, Alec Taylor wrote: >> Just download the msi (script is available to regenerate yourself) and >> run it with the silent swtich, something like: >> >> msiexec /x nameofmsi.msi > Sorry I didn't explain what I'm looking for exactly. > > I've packages built by bdist_wininst, Is there any way for install them > silently? > Or is there any way for convert them to another format (ex. msi) in that > way I can install them silently. If you can get the source (specifically including the setup.py which I don't think is included in the wininst .zip) then you can use that to build an msi: python setup.py bdist_msi which you can then manage via the usual msiexec switches. It's often available from the same source as the wininst .exe and/or from the project's code repository. If not, you're down to reverse-engineering a suitable setup.py. For many projects this is pretty simple. TJG From stefan_ml at behnel.de Thu Oct 20 05:22:18 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 20 Oct 2011 11:22:18 +0200 Subject: Are range iterators thread safe? In-Reply-To: <4e9fd600$0$29974$c3e8da3$5496439d@news.astraweb.com> References: <4e9fd600$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano, 20.10.2011 10:04: > Using Python 3, are range_iterator objects thread-safe? > > I have tried this, and it seems to be safe: > > >>> from threading import Thread > >>> x = iter(range(4)) > >>> def doit(x): > ... print("result =", next(x)) > ... > >>> threads = [Thread(target=doit, args=(x,)) for i in range(4)] > >>> for t in threads: > ... t.start() > ... > result = 0 > result = 1 > result = 2 > result = 3 The GIL ensures it's thread safe. Stefan From admin at mbnoimi.net Thu Oct 20 07:14:04 2011 From: admin at mbnoimi.net (Muhammad Bashir Al-Noimi) Date: Thu, 20 Oct 2011 14:14:04 +0300 Subject: Python based silent installer, how to? In-Reply-To: <4E9FE60D.8020009@timgolden.me.uk> References: <4E9F0589.9020005@mbnoimi.net> <4E9FDFBF.2020801@mbnoimi.net> <4E9FE60D.8020009@timgolden.me.uk> Message-ID: <4EA0027C.1010001@mbnoimi.net> On 20/10/2011 12:12 ?, Tim Golden wrote: > If you can get the source (specifically including the setup.py > which I don't think is included in the wininst .zip) then you > can use that to build an msi: > > python setup.py bdist_msi > > which you can then manage via the usual msiexec switches. > > It's often available from the same source as the wininst .exe > and/or from the project's code repository. In case I got .egg file (ex. http://pypi.python.org/pypi/setuptools/0.6c11) from some website, can I use it as alternative to bdist_wininst package? In case 'yes' where I've to put .egg file? -- Best Regards Muhammad Bashir Al-Noimi My Blog: http://mbnoimi.net -------------- next part -------------- A non-text attachment was scrubbed... Name: admin.vcf Type: text/x-vcard Size: 332 bytes Desc: not available URL: From ben+python at benfinney.id.au Thu Oct 20 07:23:42 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 20 Oct 2011 22:23:42 +1100 Subject: Are range iterators thread safe? References: <4e9fd600$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87obxbrjnl.fsf@benfinney.id.au> Stefan Behnel writes: > Steven D'Aprano, 20.10.2011 10:04: > > Using Python 3, are range_iterator objects thread-safe? > The GIL ensures it's thread safe. The GIL applies only to CPython. What is the answer for other Python implementations which don't have a GIL? -- \ Eccles: ?I just saw the Earth through the clouds!? Lew: ?Did | `\ it look round?? Eccles: ?Yes, but I don't think it saw me.? | _o__) ?The Goon Show, _Wings Over Dagenham_ | Ben Finney From lists at cheimes.de Thu Oct 20 07:27:01 2011 From: lists at cheimes.de (Christian Heimes) Date: Thu, 20 Oct 2011 13:27:01 +0200 Subject: Threading: Method trigger after thred finished In-Reply-To: <4e9f9bc0$0$29974$c3e8da3$5496439d@news.astraweb.com> References: <13676309.461.1319055261456.JavaMail.geo-discussion-forums@yqnv12> <4e9f9bc0$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 20.10.2011 05:55, schrieb Steven D'Aprano: > # Make consumer threads. > class ThreadSql(threading.Thread): > def __init__(self, queue): > threading.Thread.__init__(self) > self.queue = queue > # Open database connection instance > self.session = "+++connection+++" # DbConnect() > self._open = True > > def run(self): > while self._open: > # Grab a query from queue. > query = self.queue.get() > # And process it. > print self, query > time.sleep(1) > # Mark the queue job as done. > self.queue.task_done() > > def close(self): > print "Closing", self > # self.session.Disconnect() > self._open = False The code may contain a subtle and nasty bug but this really depends on your database connection. Most db connections are neither thread safe nor reentrant and must not be shared between threads. However this code shares the connection across two threads. The __init__() method is run inside the thread that *creates* the new thread, not the new thread. Just the run() is executed in the new thread. I suggest that you acquire and close the connection inside the run() method protected by an try/finally or with block. Christian From 4k3nd0 at googlemail.com Thu Oct 20 08:34:14 2011 From: 4k3nd0 at googlemail.com (4k3nd0) Date: Thu, 20 Oct 2011 14:34:14 +0200 Subject: Insert Data with pymongo Message-ID: <4EA01546.3080609@gmail.com> Hi guys, i want to insert a JSON formated String into a mongoDB. But get some problem with the insert to the database. Traceback (most recent call last): File "obp_import_pb.py", line 102, in do_import() File "obp_import_pb.py", line 97, in do_import collection = db.pb_mp.insert(obp_transaction_json) File "/usr/lib64/python2.7/site-packages/pymongo/collection.py", line 274, in insert docs = [self.__database._fix_incoming(doc, self) for doc in docs] File "/usr/lib64/python2.7/site-packages/pymongo/database.py", line 249, in _fix_incoming son = manipulator.transform_incoming(son, collection) File "/usr/lib64/python2.7/site-packages/pymongo/son_manipulator.py", line 73, in transform_incoming son["_id"] = ObjectId() TypeError: 'str' object does not support item assignment I'm using json.dumps to format a json string obp_transaction_json = json.dumps(......) I took a look about the pymongo Doc, which didn't help me a bit. I using Python 2.7, on a Gentoo(Linux-3.0.5) AMD64 Greeting's from Germany, Akendo From stefan_ml at behnel.de Thu Oct 20 08:43:49 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 20 Oct 2011 14:43:49 +0200 Subject: Are range iterators thread safe? In-Reply-To: <87obxbrjnl.fsf@benfinney.id.au> References: <4e9fd600$0$29974$c3e8da3$5496439d@news.astraweb.com> <87obxbrjnl.fsf@benfinney.id.au> Message-ID: Ben Finney, 20.10.2011 13:23: > Stefan Behnel writes: > >> Steven D'Aprano, 20.10.2011 10:04: >>> Using Python 3, are range_iterator objects thread-safe? >> The GIL ensures it's thread safe. > > The GIL applies only to CPython. and PyPy. > What is the answer for other Python > implementations which don't have a GIL? That would basically be Jython and IronPython. Note that none of the three alternative implementations currently supports Python language version 3. So, the current answer for all existing Python 3 implementations is: the GIL ensures that it's thread safe. Stefan From roy at panix.com Thu Oct 20 08:54:13 2011 From: roy at panix.com (Roy Smith) Date: Thu, 20 Oct 2011 08:54:13 -0400 Subject: Insert Data with pymongo References: Message-ID: In article , 4k3nd0 <4k3nd0 at googlemail.com> wrote: > Hi guys, > > i want to insert a JSON formated String into a mongoDB. But get some > problem with the insert to the database. > > Traceback (most recent call last): > File "obp_import_pb.py", line 102, in > do_import() > File "obp_import_pb.py", line 97, in do_import > collection = db.pb_mp.insert(obp_transaction_json) > File "/usr/lib64/python2.7/site-packages/pymongo/collection.py", line > 274, in insert > docs = [self.__database._fix_incoming(doc, self) for doc in docs] > File "/usr/lib64/python2.7/site-packages/pymongo/database.py", line > 249, in _fix_incoming > son = manipulator.transform_incoming(son, collection) > File "/usr/lib64/python2.7/site-packages/pymongo/son_manipulator.py", > line 73, in transform_incoming > son["_id"] = ObjectId() > TypeError: 'str' object does not support item assignment > > > I'm using json.dumps to format a json string > > obp_transaction_json = json.dumps(......) > > I took a look about the pymongo Doc, which didn't help me a bit. > I using Python 2.7, on a Gentoo(Linux-3.0.5) AMD64 You haven't given enough information to even guess at the problem. Does the exception get thrown as part of the assignment, or evaluating the "....." you pass to json.dumps()? I would start by breaking things down into smaller pieces and seeing which piece raises the exception. Also, post more of your code so we can see what's going on. From lanyjie at yahoo.com Thu Oct 20 09:19:40 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Thu, 20 Oct 2011 06:19:40 -0700 (PDT) Subject: compare range objects Message-ID: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> Hi,? Is it possible to test if two range objects contain the same sequence of integers by the following algorithm in Python 3.2? 1. standardize the ending bound by letting it be the first excluded integer for the given step size. 2. compare the standardized starting bound, ending bound and step size: two ranges equal if and only if this triplet is the same. If that's correct, it would be good to have equality comparison on two ranges.? Further, it might also be good to have sub-sequence test on ranges without enumerating it. Cheers, Yingjie From lanyjie at yahoo.com Thu Oct 20 09:23:50 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Thu, 20 Oct 2011 06:23:50 -0700 (PDT) Subject: revive a generator Message-ID: <1319117030.48985.YahooMailNeo@web121516.mail.ne1.yahoo.com> Hi, it seems a generator expression can be used only once: >>> g = (x*x for x in range(3)) >>> for x in g: print x 0 1 4 >>> for x in g: print x #nothing printed >>> Is there any way to revive g here? Yingjie From rosuav at gmail.com Thu Oct 20 09:52:13 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Oct 2011 00:52:13 +1100 Subject: revive a generator In-Reply-To: <1319117030.48985.YahooMailNeo@web121516.mail.ne1.yahoo.com> References: <1319117030.48985.YahooMailNeo@web121516.mail.ne1.yahoo.com> Message-ID: On Fri, Oct 21, 2011 at 12:23 AM, Yingjie Lan wrote: > Hi, > > it seems a generator expression can be used only once: > >>>> g = (x*x for x in range(3)) >>>> for x in g: print x > 0 > 1 > 4 >>>> for x in g: print x #nothing printed >>>> > > Is there any way to revive g here? If you're not generating very much, just use a list comprehension instead; you can iterate over the list as many times as you like: >>> g = [x*x for x in range(3)] >>> for x in g: print(x) 0 1 4 >>> for x in g: print(x) 0 1 4 Of course, since this is Python 3, you need the parens on print, but I assume you had something else you were doing with x. ChrisA From paul.nospam at rudin.co.uk Thu Oct 20 10:28:53 2011 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Thu, 20 Oct 2011 15:28:53 +0100 Subject: revive a generator References: Message-ID: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> Yingjie Lan writes: > Hi, > > it seems a generator expression can be used only once: > >>>> g = (x*x for x in range(3)) >>>> for x in g: print x > 0 > 1 > 4 >>>> for x in g: print x #nothing printed >>>> > > Is there any way to revive g here? > Generators are like that - you consume them until they run out of values. You could have done [x*x for x in range(3)] and then iterated over that list as many times as you wanted. A generator doesn't have to remember all the values it generates so it can be more memory efficient that a list. Also it can, for example, generate an infinite sequence. From ian.g.kelly at gmail.com Thu Oct 20 12:00:57 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 20 Oct 2011 10:00:57 -0600 Subject: Are range iterators thread safe? In-Reply-To: References: <4e9fd600$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Oct 20, 2011 at 3:22 AM, Stefan Behnel wrote: > Steven D'Aprano, 20.10.2011 10:04: >> >> Using Python 3, are range_iterator objects thread-safe? >> >> I have tried this, and it seems to be safe: >> >> >>> from threading import Thread >> >>> x = iter(range(4)) >> >>> def doit(x): >> ... ? ? print("result =", next(x)) >> ... >> >>> threads = [Thread(target=doit, args=(x,)) for i in range(4)] >> >>> for t in threads: >> ... ? ? t.start() >> ... >> result = 0 >> result = 1 >> result = 2 >> result = 3 > > The GIL ensures it's thread safe. Because range_iterator objects are implemented in C and so calling the __next__ method is only a single bytecode instruction, correct? If they were implemented in Python the GIL would make no such assurance. From anikom15 at gmail.com Thu Oct 20 12:22:04 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 20 Oct 2011 09:22:04 -0700 Subject: compare range objects In-Reply-To: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> Message-ID: <20111020162204.GA26505@Smoke> On Thu, Oct 20, 2011 at 06:19:40AM -0700, Yingjie Lan wrote: > Hi,? > > Is it possible to test if two range objects contain the same sequence of integers by the following algorithm in Python 3.2? > > 1. standardize the ending bound by letting it be the first excluded integer for the given step size. > 2. compare the standardized starting bound, ending bound and step size: two ranges equal if and only if this triplet is the same. > > If that's correct, it would be good to have equality comparison on two ranges.? > > Further, it might also be good to have sub-sequence test on ranges without enumerating it. > There's already a discussion about this on python-ideas. But somebody please tell me, why would you ever need to compare ranges? From bulg at ngs.ru Thu Oct 20 13:28:11 2011 From: bulg at ngs.ru (Yosifov Pavel) Date: Thu, 20 Oct 2011 10:28:11 -0700 (PDT) Subject: Py3K: file inheritance Message-ID: In the Python 2.x was simple to create own file object: class MyFile(file): pass for example to reimplement write() or something else. How to do it in Python 3.x? From ian.g.kelly at gmail.com Thu Oct 20 13:42:13 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 20 Oct 2011 11:42:13 -0600 Subject: Py3K: file inheritance In-Reply-To: References: Message-ID: On Thu, Oct 20, 2011 at 11:28 AM, Yosifov Pavel wrote: > In the Python 2.x was simple to create own file object: > > class MyFile(file): > ?pass > > for example to reimplement write() or something else. How to do it in > Python 3.x? See the docs for the io module. Depending on what you want to do, you probably need to subclass either io.FileIO or io.TextIOWrapper. From gordon at panix.com Thu Oct 20 13:46:31 2011 From: gordon at panix.com (John Gordon) Date: Thu, 20 Oct 2011 17:46:31 +0000 (UTC) Subject: Benefits of xml.dom.minidom? Message-ID: I recently inherited some code that uses xml.dom.minidom to build a large XML document, and I noticed that it is quite slow and uses a ton of memory. I converted the same code to use lxml.etree and it is much faster and uses not nearly so much memory. Why is minidom so hungry for resources? What is it doing with all that memory and CPU? -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From hansmu at xs4all.nl Thu Oct 20 14:00:57 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Thu, 20 Oct 2011 20:00:57 +0200 Subject: compare range objects In-Reply-To: References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> Message-ID: <4ea061da$0$6941$e4fe514c@news2.news.xs4all.nl> On 20/10/11 18:22:04, Westley Mart?nez wrote: > On Thu, Oct 20, 2011 at 06:19:40AM -0700, Yingjie Lan wrote: >> Hi, >> >> Is it possible to test if two range objects contain the same sequence of integers by the following algorithm in Python 3.2? >> >> 1. standardize the ending bound by letting it be the first excluded integer for the given step size. >> 2. compare the standardized starting bound, ending bound and step size: two ranges equal if and only if this triplet is the same. >> >> If that's correct, it would be good to have equality comparison on two ranges. >> >> Further, it might also be good to have sub-sequence test on ranges without enumerating it. >> > > There's already a discussion about this on python-ideas. But somebody > please tell me, why would you ever need to compare ranges? It could be useful if you're unit-testing a function that returns a range. -- HansM From ian.g.kelly at gmail.com Thu Oct 20 14:14:56 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 20 Oct 2011 12:14:56 -0600 Subject: compare range objects In-Reply-To: <4ea061da$0$6941$e4fe514c@news2.news.xs4all.nl> References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <4ea061da$0$6941$e4fe514c@news2.news.xs4all.nl> Message-ID: On Thu, Oct 20, 2011 at 12:00 PM, Hans Mulder wrote: >> There's already a discussion about this on python-ideas. ?But somebody >> please tell me, why would you ever need to compare ranges? > > It could be useful if you're unit-testing a function that returns a range. Easy: list(range1) == list(range2) From ethan at stoneleaf.us Thu Oct 20 14:24:53 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 20 Oct 2011 11:24:53 -0700 Subject: compare range objects In-Reply-To: References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <4ea061da$0$6941$e4fe514c@news2.news.xs4all.nl> Message-ID: <4EA06775.4060003@stoneleaf.us> Ian Kelly wrote: > On Thu, Oct 20, 2011 at 12:00 PM, Hans Mulder wrote: >>> There's already a discussion about this on python-ideas. But somebody >>> please tell me, why would you ever need to compare ranges? >> It could be useful if you're unit-testing a function that returns a range. > > Easy: > > list(range1) == list(range2) The biggest reason in my mind for implementing range equality is that currently two ranges compare equal iff they are the same range. In other words: --> range(10) == range(10) False ~Ethan~ From driley at mantaro.com Thu Oct 20 14:25:47 2011 From: driley at mantaro.com (David Riley) Date: Thu, 20 Oct 2011 14:25:47 -0400 Subject: sysconfig on OS X 10.7 (Lion) and XCode 4.2 Message-ID: <5ED3F418-A03D-4BE6-91A5-51C0DF899FC5@mantaro.com> Hello all, I've struggled mightily to get Numpy and pyopencl installed on my brand-new Lion machine running XCode 4.2 (not recommended, I know, but I'm a sucker for punishment). I did finally succeed, anyway. I found that the greatest problem I had (after installing gfortran from a precompiled package) was getting setup.py and subsidiaries to use the right GCC. The python.org official builds of Python (I'm specifically using 3.2.2, though I'm sure this applies to 2.7 as well) have some trouble with building extensions because CC is specified as "gcc-4.2", which no longer exists in XCode 4.2 (one could chalk that up to being Apple's problem, but hey). The root of this problem is in the sysconfig module, which I assume has hardcoded names for the compiler, etc. Most insidious was fixing LDSHARED, which was gcc-4.2 with a bunch of flags appended to it including the system framework (for 10.6, I should point out, which is also what sysconfig returned for sysconfig.platform()). Is there any way to permanently override these values in sysconfig short of building my own Python and installing it? I'm having to override the environment variables whenever I build a C/C++ module, and it's getting to be a pain. For anyone looking for the answer to a similar problem (usually gcc-4.2 not being found when running setup.py), export the following environment variables to build things under XCode 4.2: CC=gcc CXX=g++ LDSHARED="gcc -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.7.sdk -isysroot /Developer/SDKs/MacOSX10.7.sdk -g" (obviously, replace 10.7 with 10.6 if you're building under 10.6) For example: sudo CC=gcc CXX=g++ LDSHARED="gcc -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.7.sdk -isysroot /Developer/SDKs/MacOSX10.7.sdk -g" pip install pyopencl This will override the default values taken from the sysconfig module. - Dave From dihedral88888 at googlemail.com Thu Oct 20 14:34:54 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Thu, 20 Oct 2011 11:34:54 -0700 (PDT) Subject: compare range objects In-Reply-To: <4ea061da$0$6941$e4fe514c@news2.news.xs4all.nl> References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <4ea061da$0$6941$e4fe514c@news2.news.xs4all.nl> Message-ID: <29301560.436.1319135694405.JavaMail.geo-discussion-forums@prms22> The range() in python is an iterable generator that returns an object ref/id. The xrange() is different. From chris at 3fdev.com Thu Oct 20 14:39:45 2011 From: chris at 3fdev.com (Christopher Saunders) Date: Thu, 20 Oct 2011 11:39:45 -0700 (PDT) Subject: google maps api help Message-ID: <7d3df23f-fc24-41f5-a4d3-87b2f4d44c77@13g2000prp.googlegroups.com> I have an excel sheet with a bunch of info regarding the stops a delivery truck makes throughout the day. I can successfully extract the information I need with xlrd. This is the code I am using: book = xlrd.open_workbook(r'c:\xytest.xls') sheet= book.sheet_by_index(0) odList = [] for i in range(1,6125): cID = sheet.row(i)[0].value #Company ID tID = sheet.row(i)[1].value #Truck ID xyCoord = sheet.row_values(i,start_colx = 8,end_colx = 10 ) #long and lat xyCoord.reverse() #reversed, so that lat,long is in correct format odList.append([cID,tID,xyCoord]) Printing odList give me this output where fields are [CompanyID,TruckID, Lat,Long] : [[5000020.0, 1.0, [35.779999, -78.115784]], [5000020.0, 1.0, [36.075812, -78.256766]], [5000020.0, 1.0, [35.779999, -78.115784]], [5000020.0, 2.0, [35.79528, -78.137549]], [5000020.0, 3.0, [35.79528, -78.137549]] I used list indices to grab the coordinates and query gmaps with: result = gmaps.directions(odList[0][2],odList[1][2]) time = result['Directions']['Duration']['seconds'] dist = result['Directions']['Distance']['meters'] Unfortunately, gmaps does not understand [35.779999, -78.115784], [36.075812, -78.256766], gmaps does understand (35.779999, -78.115784), (36.075812, -78.256766). Any ideas on how to get the query to send () instead of [] ? From hidura at gmail.com Thu Oct 20 14:55:38 2011 From: hidura at gmail.com (Hidura) Date: Thu, 20 Oct 2011 14:55:38 -0400 Subject: Benefits of xml.dom.minidom? In-Reply-To: References: Message-ID: I use minidom all the time and i don' t have that problem could you describe more of the process ? El oct 20, 2011 5:53 p.m., "John Gordon" escribi?: > > I recently inherited some code that uses xml.dom.minidom to build a large > XML document, and I noticed that it is quite slow and uses a ton of memory. > > I converted the same code to use lxml.etree and it is much faster and > uses not nearly so much memory. > > Why is minidom so hungry for resources? What is it doing with all that > memory and CPU? > > -- > John Gordon A is for Amy, who fell down the stairs > gordon at panix.com B is for Basil, assaulted by bears > -- Edward Gorey, "The Gashlycrumb Tinies" > > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan_ml at behnel.de Thu Oct 20 14:57:38 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 20 Oct 2011 20:57:38 +0200 Subject: Benefits of xml.dom.minidom? In-Reply-To: References: Message-ID: John Gordon, 20.10.2011 19:46: > I recently inherited some code that uses xml.dom.minidom to build a large > XML document, and I noticed that it is quite slow and uses a ton of memory. > > I converted the same code to use lxml.etree and it is much faster and > uses not nearly so much memory. > > Why is minidom so hungry for resources? What is it doing with all that > memory and CPU? Not much. It's memory hungry because it builds a tree from rather heavy XML objects and is neither optimised for speed nor for a low memory footprint. Its main purpose is to be (mostly) W3C DOM compatible. It's also been in the standard library for quite a bit longer than ElementTree, and predates lxml by years. That's the most likely reason why your original script was written using minidom. In a way, it's unfair to compare minidom with lxml.etree (or cElementTree, for that purpose), as the latter two were specifically designed for high performance and a much simpler API. Stefan From python at mrabarnett.plus.com Thu Oct 20 15:02:50 2011 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 20 Oct 2011 20:02:50 +0100 Subject: google maps api help In-Reply-To: <7d3df23f-fc24-41f5-a4d3-87b2f4d44c77@13g2000prp.googlegroups.com> References: <7d3df23f-fc24-41f5-a4d3-87b2f4d44c77@13g2000prp.googlegroups.com> Message-ID: <4EA0705A.8020602@mrabarnett.plus.com> On 20/10/2011 19:39, Christopher Saunders wrote: > I have an excel sheet with a bunch of info regarding the stops a > delivery truck makes throughout the day. I can successfully extract > the information I need with xlrd. This is the code I am using: > > book = xlrd.open_workbook(r'c:\xytest.xls') > sheet= book.sheet_by_index(0) > odList = [] > > for i in range(1,6125): > cID = sheet.row(i)[0].value #Company ID > tID = sheet.row(i)[1].value #Truck ID > xyCoord = sheet.row_values(i,start_colx = 8,end_colx = 10 ) #long > and lat > xyCoord.reverse() #reversed, so that lat,long is in correct format > odList.append([cID,tID,xyCoord]) > > > Printing odList give me this output where fields are > [CompanyID,TruckID, Lat,Long] : [[5000020.0, 1.0, [35.779999, > -78.115784]], [5000020.0, 1.0, [36.075812, -78.256766]], [5000020.0, > 1.0, [35.779999, -78.115784]], [5000020.0, 2.0, [35.79528, > -78.137549]], [5000020.0, 3.0, [35.79528, -78.137549]] > > I used list indices to grab the coordinates and query gmaps with: > > result = gmaps.directions(odList[0][2],odList[1][2]) > time = result['Directions']['Duration']['seconds'] > dist = result['Directions']['Distance']['meters'] > > Unfortunately, gmaps does not understand [35.779999, -78.115784], > [36.075812, -78.256766], gmaps does understand (35.779999, -78.115784), > (36.075812, -78.256766). Any ideas on how to get the query to send () > instead of [] ? Try turning the lists into tuples: result = gmaps.directions(tuple(odList[0][2]), tuple(odList[1][2])) From chris at 3fdev.com Thu Oct 20 15:28:44 2011 From: chris at 3fdev.com (Christopher Saunders) Date: Thu, 20 Oct 2011 12:28:44 -0700 (PDT) Subject: google maps api help References: <7d3df23f-fc24-41f5-a4d3-87b2f4d44c77@13g2000prp.googlegroups.com> Message-ID: On Oct 20, 1:02?pm, MRAB wrote: > On 20/10/2011 19:39, Christopher Saunders wrote: > > > > > > > > > > > I have an excel sheet with a bunch of info regarding the stops a > > delivery truck makes throughout the day. ?I can successfully extract > > the information I need with xlrd. ?This is the code I am using: > > > book = xlrd.open_workbook(r'c:\xytest.xls') > > sheet= book.sheet_by_index(0) > > odList = [] > > > for i in range(1,6125): > > ? ? ?cID = sheet.row(i)[0].value #Company ID > > ? ? ?tID = sheet.row(i)[1].value #Truck ID > > ? ? ?xyCoord = sheet.row_values(i,start_colx = 8,end_colx = 10 ) #long > > and lat > > ? ? ?xyCoord.reverse() #reversed, so that lat,long is in correct format > > ? ? ?odList.append([cID,tID,xyCoord]) > > > Printing odList give me this output where fields are > > [CompanyID,TruckID, Lat,Long] : [[5000020.0, 1.0, [35.779999, > > -78.115784]], [5000020.0, 1.0, [36.075812, -78.256766]], [5000020.0, > > 1.0, [35.779999, -78.115784]], [5000020.0, 2.0, [35.79528, > > -78.137549]], [5000020.0, 3.0, [35.79528, -78.137549]] > > > I used list indices to grab the coordinates and query gmaps with: > > > result = gmaps.directions(odList[0][2],odList[1][2]) > > time = result['Directions']['Duration']['seconds'] > > dist = result['Directions']['Distance']['meters'] > > > Unfortunately, gmaps does not understand [35.779999, -78.115784], > > [36.075812, -78.256766], gmaps does understand (35.779999, -78.115784), > > (36.075812, -78.256766). ?Any ideas on how to get the query to send () > > instead of [] ? > > Try turning the lists into tuples: > > result = gmaps.directions(tuple(odList[0][2]), tuple(odList[1][2])) Awesome, that worked! From tjreedy at udel.edu Thu Oct 20 15:56:30 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 20 Oct 2011 15:56:30 -0400 Subject: revive a generator In-Reply-To: <1319117030.48985.YahooMailNeo@web121516.mail.ne1.yahoo.com> References: <1319117030.48985.YahooMailNeo@web121516.mail.ne1.yahoo.com> Message-ID: On 10/20/2011 9:23 AM, Yingjie Lan wrote: > it seems a generator expression can be used only once: Generators are iterators. Once iterators raise StopIteration, they are supposed to continue doing so. A generator expression defines a temporary anonymous generator function that is called once to produce a generator and then deleted. It, like all comprehensions, is purely a convenient abbreviation. >>>> g = (x*x for x in range(3)) for x in g: print x > 0 1 4 >>>> for x in g: print x #nothing printed Define a named generator function (and add a parameter to make it more flexible and useful and reuse it. def g(n): for i in range(n): yield i*i Then, "for x in g(3)", "for x in g(8)", "for x in g(y*x)", etc, as many times as you want. You might call it 'square' or even 'r_square' instead of 'g'. -- Terry Jan Reedy From nad at acm.org Thu Oct 20 16:20:50 2011 From: nad at acm.org (Ned Deily) Date: Thu, 20 Oct 2011 13:20:50 -0700 Subject: sysconfig on OS X 10.7 (Lion) and XCode 4.2 References: <5ED3F418-A03D-4BE6-91A5-51C0DF899FC5@mantaro.com> Message-ID: In article <5ED3F418-A03D-4BE6-91A5-51C0DF899FC5 at mantaro.com>, David Riley wrote: > I've struggled mightily to get Numpy and pyopencl installed on my brand-new > Lion machine running XCode 4.2 (not recommended, I know, but I'm a sucker for > punishment). I did finally succeed, anyway. > > I found that the greatest problem I had (after installing gfortran from a > precompiled package) was getting setup.py and subsidiaries to use the right > GCC. The python.org official builds of Python (I'm specifically using 3.2.2, > though I'm sure this applies to 2.7 as well) have some trouble with building > extensions because CC is specified as "gcc-4.2", which no longer exists in > XCode 4.2 (one could chalk that up to being Apple's problem, but hey). > > The root of this problem is in the sysconfig module, which I assume has > hardcoded names for the compiler, etc. Most insidious was fixing LDSHARED, > which was gcc-4.2 with a bunch of flags appended to it including the system > framework (for 10.6, I should point out, which is also what sysconfig > returned for sysconfig.platform()). > > Is there any way to permanently override these values in sysconfig short of > building my own Python and installing it? I'm having to override the > environment variables whenever I build a C/C++ module, and it's getting to be > a pain. > > > > For anyone looking for the answer to a similar problem (usually gcc-4.2 not > being found when running setup.py), export the following environment > variables to build things under XCode 4.2: > > CC=gcc > CXX=g++ > LDSHARED="gcc -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 > -isysroot /Developer/SDKs/MacOSX10.7.sdk -isysroot > /Developer/SDKs/MacOSX10.7.sdk -g" > > (obviously, replace 10.7 with 10.6 if you're building under 10.6) > > For example: > > sudo CC=gcc CXX=g++ LDSHARED="gcc -bundle -undefined dynamic_lookup -arch > i386 -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.7.sdk -isysroot > /Developer/SDKs/MacOSX10.7.sdk -g" pip install pyopencl > > > This will override the default values taken from the sysconfig module. On OS X, Python's Distutils goes to some trouble to ensure that C extension modules are built with the same compiler and compatible settings as the Python interpreter itself was built. The current python.org 64-bit/32-bit installers (which I assume you are using) for 3.2.x and 2.7.x were built on 10.6 using the gcc-4.2 available in Xcode 3. Now that Xcode 4.2 has been released and has deleted gcc-4.2, that's a problem. A thorough building and testing cycle using the various compiler options (llvm-gcc and clang) is needed for Lion; there have been problems already reported and corrected for clang with Xcode 4.1. I'm starting to do that. It would be helpful if you could open an issue on the Python bug tracker (http://bugs.python.org) and summarize what you've found there. -- Ned Deily, nad at acm.org From greg.ewing at canterbury.ac.nz Thu Oct 20 17:05:46 2011 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Fri, 21 Oct 2011 10:05:46 +1300 Subject: COM / .NET In-Reply-To: References: <4e9fd67f$0$281$14726298@news.sunsite.dk> Message-ID: <9gbgpaFvh6U1@mid.individual.net> Tim Golden wrote: > You have a few choices in this regard: Also it's reportedly possible to register a .NET assembly as a COM library and use it that way. -- Greg From ramit.prasad at jpmorgan.com Thu Oct 20 17:26:37 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 20 Oct 2011 17:26:37 -0400 Subject: Problem with a wx notebook In-Reply-To: References: Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21A39706@EMARC112VS01.exchad.jpmchase.net> -----Original Message----- From: python-list-bounces+ramit.prasad=jpmorgan.com at python.org [mailto:python-list-bounces+ramit.prasad=jpmorgan.com at python.org] On Behalf Of faucheuse Sent: Monday, October 17, 2011 5:33 AM To: python-list at python.org Subject: Problem with a wx notebook Hi there, I've created a wx NoteBook in wich I set multiples panels in wich I set one or more sizers. But nothing displays in the notebook, everything is outside. I've been searching an answer for 2 days ><. Can you help me plz ? Here is my code(with only one panel, to sum up the code) : class StreamingActivationDialog(wx.Dialog): def __init__(self, *args, **kwds): # begin wxGlade: StreamingActivationDialog.__init__ kwds["style"] = wx.DEFAULT_DIALOG_STYLE wx.Dialog.__init__(self, *args, **kwds) self.bitmap_1_copy = wx.StaticBitmap(self, -1, wx.Bitmap("img\ \logo.png", wx.BITMAP_TYPE_ANY)) self.labelDnD = wx.StaticText(self, -1, "Si vous avez d?j? un fichier d'activation, faite le glisser dans cette fenetre") self.keyBitmap = wx.StaticBitmap(self, -1, wx.Bitmap("img\ \key.bmp", wx.BITMAP_TYPE_ANY)) self.conclude = wx.StaticText(self, -1, _("test"), style=wx.ALIGN_CENTRE) ### Panel ### self.intro3_label = wx.StaticText(self, -1, "Envoyez un mail ? \nactivation at monmail.com\ncontenant le code :",style=wx.ALIGN_CENTRE) self.activationCode_label= wx.StaticText(self, -1, "123456789", style=wx.TE_READONLY) self.copy2_Button = wx.Button(self, -1, "Copier dans le presse- papier") self.copy2_Button.Bind(wx.EVT_BUTTON, PanelMail.onCopy) ############## self.note = wx.Notebook(self, wx.ID_ANY, style=wx.BK_LEFT, size=wx.Size(100, 341)) self.page3 = wx.Panel(self.note) imagelist = wx.ImageList(94, 94) bitmap1 = wx.Bitmap("img\\a.bmp", wx.BITMAP_TYPE_BMP ) imagelist.Add(bitmap1) self.note.AssignImageList(imagelist) self.__set_properties() self.__do_layout() # end wxGlade def __set_properties(self): # begin wxGlade: StreamingActivationDialog.__set_properties self.SetTitle(_("Activation de FlashProcess")) self.SetBackgroundColour(wx.Colour(255, 255, 255)) #self.linkProblem.SetForegroundColour(wx.Colour(0, 0, 0)) # end wxGlade def __do_layout(self): # begin wxGlade: StreamingActivationDialog.__do_layout self.grid_sizer_1 = wx.FlexGridSizer(6, 1, 0, 0) self.grid_sizer_2 = wx.FlexGridSizer(1, 2, 0, 30) self.grid_sizer_1.Add(self.bitmap_1_copy, 0, wx.TOP|wx.BOTTOM| wx.EXPAND, 10) ### Page 3 ### sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(self.intro3_label, 0, wx.BOTTOM|wx.ALIGN_CENTER, 5) sizer.Add(self.activationCode_label, 0, wx.BOTTOM| wx.ALIGN_CENTER, 20) sizer.Add(self.copy2_Button, 0, wx.ALIGN_CENTER, 20) self.page3.SetSizer(sizer) sizer.Fit(self.page3) ############## self.note.AddPage(self.page3, "", False, 0) self.Bind(wx.EVT_TOOLBOOK_PAGE_CHANGED, self.OnPageChanged) self.Bind(wx.EVT_TOOLBOOK_PAGE_CHANGING, self.OnPageChanging) self.grid_sizer_1.Add(self.note, 0, wx.EXPAND, 20) self.grid_sizer_1.Add(self.labelDnD, 0, wx.TOP| wx.ALIGN_CENTER_HORIZONTAL, 20) self.grid_sizer_2.Add(self.keyBitmap, 0, wx.LEFT, 10) self.grid_sizer_2.Add(self.labelDnD, 0, wx.LEFT, 20) self.grid_sizer_1.Add(self.grid_sizer_2, 0, wx.EXPAND, 20) self.grid_sizer_1.Add(self.conclude, 0, wx.TOP| wx.ALIGN_CENTER_HORIZONTAL, 20) self.SetSizer(self.grid_sizer_1) self.grid_sizer_1.Fit(self) self.Layout() # end wxGlade def OnPageChanged(self, event): event.Skip() def OnPageChanging(self, event): event.Skip() ========================================= Is this still a problem? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From mwilson at the-wire.com Thu Oct 20 17:49:24 2011 From: mwilson at the-wire.com (Mel) Date: Thu, 20 Oct 2011 17:49:24 -0400 Subject: Problem with a wx notebook References: Message-ID: Prasad, Ramit wrote: > I've created a wx NoteBook in wich I set multiples panels in wich I > set one or more sizers. But nothing displays in the notebook, > everything is outside. I've been searching an answer for 2 days ><. > Can you help me plz ? Here is my code(with only one panel, to sum up > the code) : > > class StreamingActivationDialog(wx.Dialog): > def __init__(self, *args, **kwds): > # begin wxGlade: StreamingActivationDialog.__init__ > kwds["style"] = wx.DEFAULT_DIALOG_STYLE > wx.Dialog.__init__(self, *args, **kwds) > self.bitmap_1_copy = wx.StaticBitmap(self, -1, wx.Bitmap("img\ > \logo.png", wx.BITMAP_TYPE_ANY)) > self.labelDnD = wx.StaticText(self, -1, "Si vous avez d?j? un > fichier d'activation, faite le glisser dans cette fenetre") > self.keyBitmap = wx.StaticBitmap(self, -1, wx.Bitmap("img\ > \key.bmp", wx.BITMAP_TYPE_ANY)) > self.conclude = wx.StaticText(self, -1, _("test"), > style=wx.ALIGN_CENTRE) > > ### Panel ### > self.intro3_label = wx.StaticText(self, -1, "Envoyez un mail ? > \nactivation at monmail.com\ncontenant le code :",style=wx.ALIGN_CENTRE) > self.activationCode_label= wx.StaticText(self, -1, > "123456789", style=wx.TE_READONLY) > self.copy2_Button = wx.Button(self, -1, "Copier dans le presse- > papier") > self.copy2_Button.Bind(wx.EVT_BUTTON, PanelMail.onCopy) > ############## > > self.note = wx.Notebook(self, wx.ID_ANY, style=wx.BK_LEFT, > size=wx.Size(100, 341)) > self.page3 = wx.Panel(self.note) > > imagelist = wx.ImageList(94, 94) > bitmap1 = wx.Bitmap("img\\a.bmp", wx.BITMAP_TYPE_BMP ) > imagelist.Add(bitmap1) > self.note.AssignImageList(imagelist) > > self.__set_properties() > self.__do_layout() > # end wxGlade > > def __set_properties(self): > # begin wxGlade: StreamingActivationDialog.__set_properties > self.SetTitle(_("Activation de FlashProcess")) > self.SetBackgroundColour(wx.Colour(255, 255, 255)) > #self.linkProblem.SetForegroundColour(wx.Colour(0, 0, 0)) > # end wxGlade > > def __do_layout(self): > # begin wxGlade: StreamingActivationDialog.__do_layout > self.grid_sizer_1 = wx.FlexGridSizer(6, 1, 0, 0) > self.grid_sizer_2 = wx.FlexGridSizer(1, 2, 0, 30) > self.grid_sizer_1.Add(self.bitmap_1_copy, 0, wx.TOP|wx.BOTTOM| > wx.EXPAND, 10) > > > ### Page 3 ### > sizer = wx.BoxSizer(wx.VERTICAL) > sizer.Add(self.intro3_label, 0, wx.BOTTOM|wx.ALIGN_CENTER, 5) > sizer.Add(self.activationCode_label, 0, wx.BOTTOM| > wx.ALIGN_CENTER, 20) > sizer.Add(self.copy2_Button, 0, wx.ALIGN_CENTER, 20) > > self.page3.SetSizer(sizer) > sizer.Fit(self.page3) > ############## > > self.note.AddPage(self.page3, "", False, 0) [ ... ] It looks a though all the controls that are meant for page3 have been created with the top-level dialog as their parent. AFAIK this cannot be. self.page3 is (correctly) a child window of self.note, but the controls to be shown inside have to be children of self.page3 . Putting things into the sizers is not enough. In my own code, I usually define a separate class descended from wx.Panel to create a page3 instance with its own sizers, then create one of those with a a wx.Notebook instance as a parent, and add it to the notebook: def _new_capture_page (self): new_trace = TraceWindow (self.tracebook) self.tracebook.AddPage (new_trace, 'Capture %d' % (self.capture_serial,), select=True) return new_trace Hope this helps, Mel. From ramit.prasad at jpmorgan.com Thu Oct 20 18:05:00 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Thu, 20 Oct 2011 18:05:00 -0400 Subject: [OT] Re: Benefit and belief In-Reply-To: <20111019214926.GA31343@Smoke> References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> <20111019214926.GA31343@Smoke> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21A3979F@EMARC112VS01.exchad.jpmchase.net> >I think you need to speak German fluently to be a good programmer. Why? Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From redcat at catfolks.net Thu Oct 20 18:14:41 2011 From: redcat at catfolks.net (Redcat) Date: 20 Oct 2011 22:14:41 GMT Subject: [OT] Re: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9gbkqhFo5dU3@mid.individual.net> On Wed, 19 Oct 2011 14:49:26 -0700, Westley Mart?nez wrote: >> I am a poly-illiterate. I can't read or write hundreds of languages. > > I think you need to speak German fluently to be a good programmer. No, just Dutch :) From anikom15 at gmail.com Thu Oct 20 18:55:57 2011 From: anikom15 at gmail.com (Westley =?iso-8859-1?Q?Mart=EDnez?=) Date: Thu, 20 Oct 2011 15:55:57 -0700 Subject: [OT] Re: Benefit and belief In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21A3979F@EMARC112VS01.exchad.jpmchase.net> References: <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> <20111019214926.GA31343@Smoke> <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21A3979F@EMARC112VS01.exchad.jpmchase.net> Message-ID: <20111020225557.GA28340@Smoke> On Thu, Oct 20, 2011 at 06:05:00PM -0400, Prasad, Ramit wrote: > >I think you need to speak German fluently to be a good programmer. > Why? > I won't reveal my secrets to JP Morgan Chase! I am loyal to the mighty Bank of America. From rosuav at gmail.com Thu Oct 20 20:31:09 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Oct 2011 11:31:09 +1100 Subject: [OT] Re: Benefit and belief In-Reply-To: <9gbkqhFo5dU3@mid.individual.net> References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> <9gbkqhFo5dU3@mid.individual.net> Message-ID: On Fri, Oct 21, 2011 at 9:14 AM, Redcat wrote: > On Wed, 19 Oct 2011 14:49:26 -0700, Westley Mart?nez wrote: >> >> I think you need to speak German fluently to be a good programmer. > > No, just Dutch :) Whatever language it be, you do need to be competent in a human language to be a good programmer. I speak only English of all human languages (can comprehend a smattering of phrases in a few other languages, but no fluency), and there are plenty of programmers who speak only X for some other X, but you do need the skill of coalescing thoughts into words. If nothing else, it makes everyone's lives easier when you ask for help :) ChrisA From installman at 189.cn Thu Oct 20 21:08:54 2011 From: installman at 189.cn (installman at 189.cn) Date: Thu, 20 Oct 2011 18:08:54 -0700 (PDT) Subject: how to change the order of a button, static text or other components Message-ID: <9655f270-15a1-4d59-b5b0-4d2320e27440@h39g2000prh.googlegroups.com> what i want to do is,when i press a button, i change the order of selected components,how to do this? From clp2 at rebertia.com Thu Oct 20 21:26:07 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 20 Oct 2011 18:26:07 -0700 Subject: how to change the order of a button, static text or other components In-Reply-To: <9655f270-15a1-4d59-b5b0-4d2320e27440@h39g2000prh.googlegroups.com> References: <9655f270-15a1-4d59-b5b0-4d2320e27440@h39g2000prh.googlegroups.com> Message-ID: On Thu, Oct 20, 2011 at 6:08 PM, installman at 189.cn wrote: > what i want to do is,when i press a button, i change the order of > selected components,how to do this? Which GUI toolkit are you using? Cheers, Chris From lanyjie at yahoo.com Thu Oct 20 21:46:30 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Thu, 20 Oct 2011 18:46:30 -0700 (PDT) Subject: revive a generator In-Reply-To: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> ----- Original Message ----- > From: Paul Rudin > To: python-list at python.org > Cc: > Sent: Thursday, October 20, 2011 10:28 PM > Subject: Re: revive a generator > > Yingjie Lan writes: > >> Hi, >> >> it seems a generator expression can be used only once: >> >>>>> g = (x*x for x in range(3)) >>>>> for x in g: print x >> 0 >> 1 >> 4 >>>>> for x in g: print x #nothing printed >>>>> >> >> Is there any way to revive g here? >> > > Generators are like that - you consume them until they run out of > values. You could have done [x*x for x in range(3)] and then iterated > over that list as many times as you wanted. > > A generator doesn't have to remember all the values it generates so it > can be more memory efficient that a list. Also it can, for example, > generate an infinite sequence. > > Thanks a lot to all who answered my question.? I am still not sure why should we enforce that? a generator can not be reused after an explicit? request to revive it? From rosuav at gmail.com Thu Oct 20 21:51:38 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Oct 2011 12:51:38 +1100 Subject: revive a generator In-Reply-To: <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> Message-ID: On Fri, Oct 21, 2011 at 12:46 PM, Yingjie Lan wrote: > > Thanks a lot to all who answered my question. > I am still not sure why should we enforce that > a generator can not be reused after an explicit > request to revive it? Here's an example of an explicit request to revive the generator: >>> g = (x*x for x in range(3)) >>> for x in g: print x 0 1 4 >>> g = (x*x for x in range(3)) # revive the generator >>> for x in g: print x #now this will work 0 1 4 ChrisA From lanyjie at yahoo.com Thu Oct 20 21:55:00 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Thu, 20 Oct 2011 18:55:00 -0700 (PDT) Subject: compare range objects In-Reply-To: <20111020162204.GA26505@Smoke> References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> Message-ID: <1319162100.73735.YahooMailNeo@web121502.mail.ne1.yahoo.com> ----- Original Message ----- > From: Westley Mart?nez > To: python-list at python.org > Cc: > Sent: Friday, October 21, 2011 12:22 AM > Subject: Re: compare range objects > > There's already a discussion about this on python-ideas.? But somebody > please tell me, why would you ever need to compare ranges? In simulation, one can use range objects to denote a discrete domain, and domain comparison could be very useful. Not just equality, but also things like if one domain is contained in another. From lanyjie at yahoo.com Thu Oct 20 22:09:42 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Thu, 20 Oct 2011 19:09:42 -0700 (PDT) Subject: revive a generator In-Reply-To: References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> Message-ID: <1319162982.85636.YahooMailNeo@web121513.mail.ne1.yahoo.com> > Here's an example of an explicit request to revive the generator: > >>>> g = (x*x for x in range(3)) >>>> for x in g: print x > 0 > 1 > 4 >>>> g = (x*x for x in range(3)) # revive the generator >>>> for x in g: print x #now this will work > 0 > 1 > 4 > > ChrisA What if the generator is passed in as an argument? when you are writing a function? That is, the expression is not available?? Secondly, it would be nice to automatically revive it. For example, when another for-statement or other equivalent is applied to it. Yingjie From rosuav at gmail.com Thu Oct 20 22:16:30 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Oct 2011 13:16:30 +1100 Subject: compare range objects In-Reply-To: <1319162100.73735.YahooMailNeo@web121502.mail.ne1.yahoo.com> References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> <1319162100.73735.YahooMailNeo@web121502.mail.ne1.yahoo.com> Message-ID: On Fri, Oct 21, 2011 at 12:55 PM, Yingjie Lan wrote: > In simulation, one can use range objects to denote a discrete domain, > and domain comparison could be very useful. Not just equality, but also > things like if one domain is contained in another. > Hmm. I wonder would slice objects be appropriate? They're comparable: >>> a=slice(1,10) >>> b=slice(1,10) >>> a==b True They're not iterable though - not directly (but you could slice range(maxint) down to size). You could possibly use itertools.islice objects for a similar job, but they're not comparable. ChrisA From rustompmody at gmail.com Thu Oct 20 22:34:50 2011 From: rustompmody at gmail.com (rusi) Date: Thu, 20 Oct 2011 19:34:50 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> <9gbkqhFo5dU3@mid.individual.net> Message-ID: <6036ba50-cdf4-4eef-bc3a-dda4dc862b3a@h23g2000pra.googlegroups.com> On Oct 21, 5:31?am, Chris Angelico wrote: > On Fri, Oct 21, 2011 at 9:14 AM, Redcat wrote: > > On Wed, 19 Oct 2011 14:49:26 -0700, Westley Mart?nez wrote: > > >> I think you need to speak German fluently to be a good programmer. > > > No, just Dutch :) > > Whatever language it be, you do need to be competent in a human > language to be a good programmer. I speak only English of all human > languages (can comprehend a smattering of phrases in a few other > languages, but no fluency), and there are plenty of programmers who > speak only X for some other X, but you do need the skill of coalescing > thoughts into words. If nothing else, it makes everyone's lives easier > when you ask for help :) > > ChrisA The American programmer would profit more from learning Latin than from learning yet another programming language. Edsger Dijkstra in "On the fact that the Atlantic Ocean has two sides" http://www.cs.utexas.edu/users/EWD/transcriptions/EWD06xx/EWD611.html From installman at 189.cn Thu Oct 20 23:00:45 2011 From: installman at 189.cn (installman at 189.cn) Date: Thu, 20 Oct 2011 20:00:45 -0700 (PDT) Subject: how to change the order of a button, static text or other components References: <9655f270-15a1-4d59-b5b0-4d2320e27440@h39g2000prh.googlegroups.com> Message-ID: On 10?21?, ??9?26?, Chris Rebert wrote: > On Thu, Oct 20, 2011 at 6:08 PM, install... at 189.cn wrote: > > what i want to do is,when i press a button, i change the order of > > selected components,how to do this? > > Which GUI toolkit are you using? > > Cheers, > Chris wxpython. thx so much. From wuwei23 at gmail.com Thu Oct 20 23:04:54 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 20 Oct 2011 20:04:54 -0700 (PDT) Subject: compare range objects References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> <1319162100.73735.YahooMailNeo@web121502.mail.ne1.yahoo.com> Message-ID: On Oct 21, 12:16?pm, Chris Angelico wrote: > Hmm. I wonder would slice objects be appropriate? > They're not iterable though They're not hashable either, which kind of surprised me. From bulg at ngs.ru Fri Oct 21 00:17:41 2011 From: bulg at ngs.ru (Yosifov Pavel) Date: Thu, 20 Oct 2011 21:17:41 -0700 (PDT) Subject: Py3K: file inheritance References: Message-ID: <36acfea8-1649-4ee9-9959-2c611bdd4da2@f5g2000vbz.googlegroups.com> On 21 ???, 00:42, Ian Kelly wrote: > On Thu, Oct 20, 2011 at 11:28 AM, Yosifov Pavel wrote: > > In the Python 2.x was simple to create own file object: > > > class MyFile(file): > > ?pass > > > for example to reimplement write() or something else. How to do it in > > Python 3.x? > > See the docs for the io module. ?Depending on what you want to do, you > probably need to subclass either io.FileIO or io.TextIOWrapper. Little silly example: class MyFile(file): def __init__(self, *a, **ka): super(MyFile, self).__init__(*a, **ka) self.commented = 0 def write(self, s): if s.startswith("#"): self.commented += 1 super(MyFile, self).write(s) When I tried in Python 3.x to inherit FileIO or TextIOWrapper and then to use MyFile (ex., open(name, mode, encoding), write(s)...) I get errors like 'unsupported write' or AttributeError 'readable'... Can you show me similar simple example like above but in Python 3.x? From rosuav at gmail.com Fri Oct 21 01:20:55 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Oct 2011 16:20:55 +1100 Subject: Benefit and belief In-Reply-To: <6036ba50-cdf4-4eef-bc3a-dda4dc862b3a@h23g2000pra.googlegroups.com> References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> <9gbkqhFo5dU3@mid.individual.net> <6036ba50-cdf4-4eef-bc3a-dda4dc862b3a@h23g2000pra.googlegroups.com> Message-ID: On Fri, Oct 21, 2011 at 1:34 PM, rusi wrote: > The American programmer would profit more from learning Latin than > from learning yet another programming language. > > Edsger Dijkstra in "On the fact that the Atlantic Ocean has two > sides" > Expanding that quote: --- A thorough study of one or more foreign languages makes one much more conscious about one's own; because an excellent mastery of his native tongue is one of the computing scientist's most vital assets, I often feel that the American programmer would profit more from learning, say, Latin than from learning yet another programming language. --- The reason he recommends learning Latin is because it helps you master English. One of the benefits (if you like, a blessing in a REALLY good disguise) of being Australian is that we're forced to work internationally in a way that Americans aren't. You can write a program, even sell it and make your living off it, that never goes outside the boundaries of the US of A. Here in Australia, that's not really a viable option, which means our minds have to be able to 'skip to Honolulu and back in two seconds' as a regular thing. Yes, we can still restrict ourselves to English-speaking countries quite easily, but there's the encouragement to support Europe, and extending from there to the whole world. Of course, not everyone takes advantage of the opportunity thus afforded. There are still plenty of people who are ignorant of the difference between a character and a byte, who assume or mandate one date format, or who parse mailing addresses too strictly. But at least we have a bit of impetus. Which means it's more of a crime for an Aussie (or a European, for that matter) to muck up like that than it is for an American. Blessing or curse? Now I'm not even sure myself. :) ChrisA From ben+python at benfinney.id.au Fri Oct 21 02:36:48 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Oct 2011 17:36:48 +1100 Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> <9gbkqhFo5dU3@mid.individual.net> <6036ba50-cdf4-4eef-bc3a-dda4dc862b3a@h23g2000pra.googlegroups.com> Message-ID: <877h3yq29r.fsf@benfinney.id.au> rusi writes: > The American programmer would profit more from learning Latin than > from learning yet another programming language. > > Edsger Dijkstra in "On the fact that the Atlantic Ocean has two > sides" > > http://www.cs.utexas.edu/users/EWD/transcriptions/EWD06xx/EWD611.html It's ambiguous whether Dijkstra is saying anything positive about Latin there. He could be saying ?learning Latin would be a useful thing for average US programmers?. Or he could be saying ?learning any second natural human language ? even one as useless as Latin ? will benefit the average US programmer more than learning another programming language?. I prefer to think someone as wise as Dijkstra would not be deluded as to the value of Latin, and lean more toward the latter meaning. -- \ ?Everyone is entitled to their own opinions, but they are not | `\ entitled to their own facts.? ?US Senator Pat Moynihan | _o__) | Ben Finney From ian.g.kelly at gmail.com Fri Oct 21 02:50:35 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 21 Oct 2011 00:50:35 -0600 Subject: Py3K: file inheritance In-Reply-To: <36acfea8-1649-4ee9-9959-2c611bdd4da2@f5g2000vbz.googlegroups.com> References: <36acfea8-1649-4ee9-9959-2c611bdd4da2@f5g2000vbz.googlegroups.com> Message-ID: On Thu, Oct 20, 2011 at 10:17 PM, Yosifov Pavel wrote: > Little silly example: > > class MyFile(file): > ?def __init__(self, *a, **ka): > ? ?super(MyFile, self).__init__(*a, **ka) > ? ?self.commented = 0 > ?def write(self, s): > ? ?if s.startswith("#"): > ? ? ?self.commented += 1 > ? ? ?super(MyFile, self).write(s) > > When I tried in Python 3.x to inherit FileIO or TextIOWrapper and then > to use MyFile (ex., open(name, mode, encoding), write(s)...) I get > errors like 'unsupported write' or AttributeError 'readable'... Can > you show me similar simple example like above but in Python 3.x? class MyTextIO(io.TextIOWrapper): def __init__(self, *args, **kw): super().__init__(*args, **kw) self.commented = 0 def write(self, s): if s.startswith('#'): self.commented += 1 super().write(s) buffered = open(name, 'wb') textio = MyTextIO(buffered, encoding='utf-8') textio.write('line 1') textio.write('# line 2') textio.close() print(textio.commented) HTH, Ian From ian.g.kelly at gmail.com Fri Oct 21 02:54:45 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 21 Oct 2011 00:54:45 -0600 Subject: compare range objects In-Reply-To: References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> <1319162100.73735.YahooMailNeo@web121502.mail.ne1.yahoo.com> Message-ID: On Thu, Oct 20, 2011 at 8:16 PM, Chris Angelico wrote: > Hmm. I wonder would slice objects be appropriate? They're comparable: > >>>> a=slice(1,10) >>>> b=slice(1,10) >>>> a==b > True > > They're not iterable though - not directly (but you could slice > range(maxint) down to size). You could possibly use itertools.islice > objects for a similar job, but they're not comparable. They have completely different semantics for negative numbers. range(-7, 10) and range(maxint)[slice(-7, 10)] are two completely different things. Still, though, if slice objects are directly comparable, I can't see any reason why range objects shouldn't be. Cheers, Ian From pankaj.anand.26 at gmail.com Fri Oct 21 03:10:45 2011 From: pankaj.anand.26 at gmail.com (Pankaj) Date: Fri, 21 Oct 2011 00:10:45 -0700 (PDT) Subject: SMS api for python Message-ID: <07a0a94e-2b96-4149-a18c-2cf2836351d8@f3g2000pri.googlegroups.com> I want to make an api that would recieve the SMS text from the user and process it then send the result back to the use. Is there any api that I can use to do this?? From paul.nospam at rudin.co.uk Fri Oct 21 03:27:54 2011 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Fri, 21 Oct 2011 08:27:54 +0100 Subject: revive a generator References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> Yingjie Lan writes: > ----- Original Message ----- >> From: Paul Rudin >> Generators are like that - you consume them until they run out of >> values. You could have done [x*x for x in range(3)] and then iterated >> over that list as many times as you wanted. >> >> A generator doesn't have to remember all the values it generates so it >> can be more memory efficient that a list. Also it can, for example, >> generate an infinite sequence. >> >> > Thanks a lot to all who answered my question.? > I am still not sure why should we enforce that? > a generator can not be reused after an explicit? > request to revive it? The language has no explicit notion of a request to "revive" a generator. You could use the same syntax to make a new generator that yeilds the same values as the one you started with if that's what you want. As we've already discussed if you want to iterate several times over the same values then it probably makes sense to compute them and store them in e.g. a list (although there are always trade-offs between storage use and the cost of computing things again). From lanyjie at yahoo.com Fri Oct 21 03:59:04 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Fri, 21 Oct 2011 00:59:04 -0700 (PDT) Subject: revive a generator In-Reply-To: <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <1319183944.58926.YahooMailNeo@web121516.mail.ne1.yahoo.com> ----- Original Message ----- > From: Paul Rudin > To: python-list at python.org > Cc: > Sent: Friday, October 21, 2011 3:27 PM > Subject: Re: revive a generator > > > The language has no explicit notion of a request to "revive" a > generator. You could use the same syntax to make a new generator that > yeilds the same values as the one you started with if that's what you > want. > > As we've already discussed if you want to iterate several times over the > same values then it probably makes sense to compute them and store them > in e.g. a list (although there are always trade-offs between storage use > and the cost of computing things again). > > What if the generator involves a variable from another scope, and before re-generating, the variable changed its value. Also, the generator could be passed in as an argument, so that we don't know its exact expression. >>> vo = 34 >>>?g = (vo*x for x in range(3)) >>> def myfun(g): for i in g: print(i) vo ?+= 3 revive(g) #best if revived automatically for i in g: print(i) myfun(g) Yingjie From lanyjie at yahoo.com Fri Oct 21 04:02:53 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Fri, 21 Oct 2011 01:02:53 -0700 (PDT) Subject: revive a generator In-Reply-To: <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <1319184173.21862.YahooMailNeo@web121506.mail.ne1.yahoo.com> ----- Original Message ----- > From: Paul Rudin > The language has no explicit notion of a request to "revive" a > generator. You could use the same syntax to make a new generator that > yeilds the same values as the one you started with if that's what you > want. > > As we've already discussed if you want to iterate several times over the > same values then it probably makes sense to compute them and store them > in e.g. a list (although there are always trade-offs between storage use > and the cost of computing things again). > Oops, my former reply has the code indentation messed up? by the mail system. Here is a reformatted one: What if the generator involves a variable from another scope, and before re-generating, the variable changed its value. Also, the generator could be passed in as an argument, so that we don't know its exact expression. >>> vo = 34 >>>?g = (vo*x for x in range(3)) >>> def myfun(g): ? ? ? ? ? ? for i in g: print(i) ? ? ? ? ? ??vo ?+= 3 ? ? ? ? ? ??revive(g) #best if revived automatically ? ? ? ? ? ??for i in g: print(i) >>> myfun(g) Yingjie From sverreodegard at gmail.com Fri Oct 21 04:07:09 2011 From: sverreodegard at gmail.com (Sverre) Date: Fri, 21 Oct 2011 01:07:09 -0700 (PDT) Subject: Problem with inheritance Message-ID: I have to classes a and b class a(object): def __init__(self,x): self.x = x self.build() def build(self): return class b(a): def __init__(self,x): a.__init__(self,x) self.y = 0 # ??? def build(self): # do something self.y += 2*self.x t = b(1) The line marked with "???" will no be executed and I don't know the reason. This example is working as intended, but not not the code I'm working on. I'm using Eclipse. I don't know how to debug this problem. From sverreodegard at gmail.com Fri Oct 21 04:16:58 2011 From: sverreodegard at gmail.com (Sverre) Date: Fri, 21 Oct 2011 01:16:58 -0700 (PDT) Subject: Problem with inheritance References: Message-ID: On Oct 21, 10:07?am, Sverre wrote: > I have to classes a ?and b > > class a(object): > ? ? def __init__(self,x): > ? ? ? ? self.x = x > ? ? ? ? self.build() > > ? ? def build(self): > ? ? ? ? return > > class b(a): > ? ? def __init__(self,x): > ? ? ? ? a.__init__(self,x) > ? ? ? ? self.y = 0 ?# ??? > > ? ? def build(self): > ? ? ? ? # do something > ? ? ? ? self.y += 2*self.x > > ?t = b(1) > > The line marked with "???" will no be executed and I don't know the > reason. This example is working as intended, but not not the code I'm > working on. I'm using Eclipse. I don't know how to debug this > problem. I found the solution. I caused an exception in b.build that wasn't reported by Eclipse properly. From paul.nospam at rudin.co.uk Fri Oct 21 04:17:48 2011 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Fri, 21 Oct 2011 09:17:48 +0100 Subject: revive a generator References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <8739emlpw2.fsf@no-fixed-abode.cable.virginmedia.net> Yingjie Lan writes: > > > What if the generator involves a variable from another scope, > and before re-generating, the variable changed its value. > Also, the generator could be passed in as an argument, > so that we don't know its exact expression. > >>>> vo = 34 >>>>?g = (vo*x for x in range(3)) >>>> def myfun(g): > ? ? ? ? ? ? for i in g: print(i) > ? ? ? ? ? ??vo ?+= 3 > ? ? ? ? ? ??revive(g) #best if revived automatically > ? ? ? ? ? ??for i in g: print(i) >>>> myfun(g) > > I'm not really sure whether you intend g to yield the original values after your "revive" or new values based on the new value of vo. But still you can make a class that supports the iterator protocol and does whatever you want (but you can't use the generator expression syntax). If you want something along these lines you should probably read up on the .send() part of the generator protocol. As an aside you shouldn't really write code that uses a global in that way.. it'll end up biting you eventually. Anyway... we can speculate endlessly about non-existent language constructs, but I think we've probably done this one to death. From rosuav at gmail.com Fri Oct 21 04:27:40 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Oct 2011 19:27:40 +1100 Subject: revive a generator In-Reply-To: <1319184173.21862.YahooMailNeo@web121506.mail.ne1.yahoo.com> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> <1319184173.21862.YahooMailNeo@web121506.mail.ne1.yahoo.com> Message-ID: On Fri, Oct 21, 2011 at 7:02 PM, Yingjie Lan wrote: > What if the generator involves a variable from another scope, > and before re-generating, the variable changed its value. > Also, the generator could be passed in as an argument, > so that we don't know its exact expression. > There's actually no way to know that the generator's even deterministic. Try this, for instance: >>> g=(input("Enter value %d or blank to stop: "%n) for n in range(1,11)) >>> for s in g: if not s: break print("Processing input: "+s) It may not be particularly useful, but it's certainly legal. And this generator cannot viably be restarted. The only way is to cast it to list first, but that doesn't work when you have to stop reading expressions from the generator part way. What you could perhaps do is wrap the generator in something that saves its values: >>> class restartable(object): def __init__(self,gen): self.gen=gen self.yielded=[] self.iter=iter(self.yielded) def restart(self): self.iter=iter(self.yielded) def __iter__(self): return self def __next__(self): # Remove the underscores for Python 2 try: return self.iter.__next__() except StopIteration: pass ret=self.gen.__next__() self.yielded.append(ret) return ret >>> h=restartable(g) >>> for i in h: if not i: break print("Using: ",i) >>> h.restart() >>> for i in h: if not i: break print("Using: ",i) Complicated, but what this does is returns a value from its saved list if there is one, otherwise returns a value from the original generator. It can be restarted as many times as necessary, and any time you read "past the end" of where you've read so far, the original generator will be called upon. Actually, this model might be useful for a repeatable random-number generator. But those are more efficiently restarted by means of reseeding the PRNG. ChrisA From rosuav at gmail.com Fri Oct 21 04:34:56 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 21 Oct 2011 19:34:56 +1100 Subject: Problem with inheritance In-Reply-To: References: Message-ID: On Fri, Oct 21, 2011 at 7:07 PM, Sverre wrote: > The line marked with "???" will no be executed and I don't know the > reason. This example is working as intended, but not not the code I'm > working on. I'm using Eclipse. I don't know how to debug this > problem. > Did you notice the error you got when you tried? Copying and pasting your example into IDLE shows this (Python 3): >>> t=b(1) Traceback (most recent call last): File "", line 1, in t=b(1) File "", line 3, in __init__ a.__init__(self,x) File "", line 4, in __init__ self.build() File "", line 8, in build self.y += 2*self.x AttributeError: 'b' object has no attribute 'y' When a calls self.build(), it calls b's build() function. That tries to modify self.y, which then fails. If you put the self.y = 0 line above the chaining call to a.__init__, all is well. Incidentally, you may wish to replace the a.__init__ call with this: super().__init__(x) That way, you're not repeating the name 'a', and if you change the inheritance tree, you don't need to change your code. ChrisA From lanyjie at yahoo.com Fri Oct 21 04:40:54 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Fri, 21 Oct 2011 01:40:54 -0700 (PDT) Subject: revive a generator In-Reply-To: <8739emlpw2.fsf@no-fixed-abode.cable.virginmedia.net> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> <8739emlpw2.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <1319186454.92385.YahooMailNeo@web121502.mail.ne1.yahoo.com> ----- Original Message ----- > From: Paul Rudin > > I'm not really sure whether you intend g to yield the original values > after your "revive" or new values based on the new value of vo.? But > still you can make a class that supports the iterator protocol and does > whatever you want (but you can't use the generator expression syntax). > > If you want something along these lines you should probably read up on > the .send() part of the generator protocol. > > As an aside you shouldn't really write code that uses a global in that > way.. it'll end up biting you eventually. > > Anyway... we can speculate endlessly about non-existent language > constructs, but I think we've probably done this one to death. > -- Maybe no new language construct is needed: just define that x.send() revives a generator. Yingjie From clp2 at rebertia.com Fri Oct 21 04:41:07 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 21 Oct 2011 01:41:07 -0700 Subject: SMS api for python In-Reply-To: <07a0a94e-2b96-4149-a18c-2cf2836351d8@f3g2000pri.googlegroups.com> References: <07a0a94e-2b96-4149-a18c-2cf2836351d8@f3g2000pri.googlegroups.com> Message-ID: On Fri, Oct 21, 2011 at 12:10 AM, Pankaj wrote: > I want to make an api that would recieve the SMS text from the user > and process it then send the result back to the use. Is there any api > that I can use to do this?? There would seem to be several options: http://pypi.python.org/pypi?%3Aaction=search&term=sms&submit=search Cheers, Chris From lanyjie at yahoo.com Fri Oct 21 04:49:59 2011 From: lanyjie at yahoo.com (Yingjie Lan) Date: Fri, 21 Oct 2011 01:49:59 -0700 (PDT) Subject: revive a generator In-Reply-To: References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> <1319184173.21862.YahooMailNeo@web121506.mail.ne1.yahoo.com> Message-ID: <1319186999.52359.YahooMailNeo@web121506.mail.ne1.yahoo.com> ----- Original Message ----- > From: Chris Angelico > To: python-list at python.org > Cc: > Sent: Friday, October 21, 2011 4:27 PM > Subject: Re: revive a generator > > On Fri, Oct 21, 2011 at 7:02 PM, Yingjie Lan wrote: >> What if the generator involves a variable from another scope, >> and before re-generating, the variable changed its value. >> Also, the generator could be passed in as an argument, >> so that we don't know its exact expression. >> > > There's actually no way to know that the generator's even > deterministic. Try this, for instance: > >>>> g=(input("Enter value %d or blank to stop: "%n) for n in > range(1,11)) >>>> for s in g: > ??? if not s: break > ??? print("Processing input: "+s) > > It may not be particularly useful, but it's certainly legal. And this > generator cannot viably be restarted.? Depends on what you want. If you want ten more inputs from user, reviving this generator is certainly a good thing to do. > The only way is to cast it to > list first, but that doesn't work when you have to stop reading > expressions from the generator part way. > > What you could perhaps do is wrap the generator in something that > saves its values: > >>>> class restartable(object): > ??? def __init__(self,gen): > ??? ??? self.gen=gen > ??? ??? self.yielded=[] > ??? ??? self.iter=iter(self.yielded) > ??? def restart(self): > ??? ??? self.iter=iter(self.yielded) > ??? def __iter__(self): > ??? ??? return self > ??? def __next__(self): # Remove the underscores for Python 2 > ??? ??? try: > ??? ??? ??? return self.iter.__next__() > ??? ??? except StopIteration: > ??? ??? ??? pass > ??? ??? ret=self.gen.__next__() > ??? ??? self.yielded.append(ret) > ??? ??? return ret > >>>> h=restartable(g) >>>> for i in h: > ??? if not i: break > ??? print("Using: ",i) >>>> h.restart() >>>> for i in h: > ??? if not i: break > ??? print("Using: ",i) > > Complicated, but what this does is returns a value from its saved list > if there is one, otherwise returns a value from the original > generator. It can be restarted as many times as necessary, and any > time you read "past the end" of where you've read so far, the > original > generator will be called upon. > > Actually, this model might be useful for a repeatable random-number > generator. But those are more efficiently restarted by means of > reseeding the PRNG. > Sure. Or you would like to have the next few random numbers with? the same PRNG.? These two cases seem to be strong use cases for reviving a generator. Yingjie From durumdara at gmail.com Fri Oct 21 04:51:05 2011 From: durumdara at gmail.com (durumdara) Date: Fri, 21 Oct 2011 01:51:05 -0700 (PDT) Subject: No module named Pwd - under Apache 2.2 Message-ID: <5299bc04-e18d-487a-8774-ba0b2943d32e@a9g2000yqo.googlegroups.com> Hi! Win7/x64, Python 3.2, PyPGSQL f 3.2 and Apahce 2.2. I created a script that working in CGI mode, it is read some table, and returns with an XML. It was working with normal mode, under Pyscripter, and under command line. But! When I trying to use it from Apache 2.2 as cgi, I got the subjected error: "No module named Pwd" I checked the code. Everything is fine for the lines import postgresql # this is working con = postgresql.open(....) # this failed Traceback (most recent call last): File "C:/web/Apache2.2/cgi-bin/testpg.py", line 20, in Session Function() File "C:/web/Apache2.2/cgi-bin/testpg.py", line 38, in WebFunction db = postgresql.open("pq://postgres:m at localhost/webdbdb") File "C:\python32\lib\site-packages\postgresql\__init__.py", line 76, in open std_params = _pg_param.collect(prompt_title = None) File "C:\python32\lib\site-packages\postgresql\clientparameters.py", line 620, in collect cpd = normalize(extrapolate(chain(*d_parameters))) File "C:\python32\lib\site-packages\postgresql\clientparameters.py", line 563, in normalize for (k, v) in iter: File "C:\python32\lib\site-packages\postgresql\clientparameters.py", line 524, in extrapolate for item in iter: File "C:\python32\lib\site-packages\postgresql\clientparameters.py", line 130, in defaults user = getuser() or 'postgres' File "C:\python32\lib\getpass.py", line 156, in getuser import pwd ImportError: No module named pwd The Apache is running under my account (normal user). The sys.path is ok: ['C:\\web\\Apache2.2\\cgi-bin', 'C:\\Windows\\system32\\python32.zip', 'C:\\python32\\DLLs', 'C:\\python32\\lib', 'C:\\python32', 'C:\ \python32\\lib\\site-packages'] So we (me, and the postgresql's author) don't understand, why it happens. Any idea? Thanks for your help: dd From __peter__ at web.de Fri Oct 21 05:33:06 2011 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Oct 2011 11:33:06 +0200 Subject: No module named Pwd - under Apache 2.2 References: <5299bc04-e18d-487a-8774-ba0b2943d32e@a9g2000yqo.googlegroups.com> Message-ID: durumdara wrote: > Hi! > > Win7/x64, Python 3.2, PyPGSQL f 3.2 and Apahce 2.2. > > I created a script that working in CGI mode, it is read some table, > and returns with an XML. > > It was working with normal mode, under Pyscripter, and under command > line. > > But! > > When I trying to use it from Apache 2.2 as cgi, I got the subjected > error: > > "No module named Pwd" Remember that case matters in Python. Fortunately you included the traceback. > I checked the code. > Everything is fine for the lines > import postgresql # this is working > con = postgresql.open(....) # this failed > > Traceback (most recent call last): > File "C:/web/Apache2.2/cgi-bin/testpg.py", line 20, in Session > Function() > File "C:/web/Apache2.2/cgi-bin/testpg.py", line 38, in WebFunction db > = postgresql.open("pq://postgres:m at localhost/webdbdb") > File "C:\python32\lib\site-packages\postgresql\__init__.py", line 76, > in open std_params = _pg_param.collect(prompt_title = None) > File "C:\python32\lib\site-packages\postgresql\clientparameters.py", > line 620, in collect cpd = > normalize(extrapolate(chain(*d_parameters))) > File "C:\python32\lib\site-packages\postgresql\clientparameters.py", > line 563, in normalize for (k, v) in iter: > File "C:\python32\lib\site-packages\postgresql\clientparameters.py", > line 524, in extrapolate for item in iter: > File "C:\python32\lib\site-packages\postgresql\clientparameters.py", > line 130, in defaults user = getuser() or 'postgres' > File "C:\python32\lib\getpass.py", line 156, in getuser import pwd > ImportError: No module named pwd The direct cause is that pwd is not available on Windows: http://docs.python.org/dev/py3k/library/pwd.html """ 33.2. pwd ? The password database Platforms: Unix This module provides access to the Unix user account and password database. It is available on all Unix versions. """ The source of the failing function... ''' def getuser(): """Get the username from the environment or password database. First try various environment variables, then the password database. This works on Windows as long as USERNAME is set. """ import os for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'): user = os.environ.get(name) if user: return user # If this fails, the exception will "explain" why import pwd return pwd.getpwuid(os.getuid())[0] ''' ...suggests that you can make it work on Windows by setting the USERNAME environment variable (or any of the alternatives checked in the for-loop). Does postgresql use the os user as a fallback for the database user? If so you might consider providing the database user explicitly. From jeanmichel at sequans.com Fri Oct 21 05:49:49 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 21 Oct 2011 11:49:49 +0200 Subject: Problem with inheritance In-Reply-To: References: Message-ID: <4EA1403D.9000706@sequans.com> Sverre wrote: > I have to classes a and b > > > class a(object): > def __init__(self,x): > self.x = x > self.build() > > def build(self): > return > > class b(a): > def __init__(self,x): > a.__init__(self,x) > self.y = 0 # ??? > > def build(self): > # do something > self.y += 2*self.x > > t = b(1) > > The line marked with "???" will no be executed and I don't know the > reason. This example is working as intended, but not not the code I'm > working on. I'm using Eclipse. I don't know how to debug this > problem. > > By the way, you're executing self.y += 2*self.x before initializing it to 0. class b(a): def __init__(self,x): self.y = 0 a.__init__(self,x) Note that having the constructor of 'a' calling an overriden method by 'b' (build) is kinda funny. I would advise not to do so unless required. JM From rustompmody at gmail.com Fri Oct 21 05:56:09 2011 From: rustompmody at gmail.com (rusi) Date: Fri, 21 Oct 2011 02:56:09 -0700 (PDT) Subject: Benefit and belief References: <87zkho2glb.fsf@benfinney.id.au> <4e9c3cf9$0$29967$c3e8da3$5496439d@news.astraweb.com> <4e9e3e78$0$29974$c3e8da3$5496439d@news.astraweb.com> <4e9f3ab3$0$29974$c3e8da3$5496439d@news.astraweb.com> <9gbkqhFo5dU3@mid.individual.net> <6036ba50-cdf4-4eef-bc3a-dda4dc862b3a@h23g2000pra.googlegroups.com> <877h3yq29r.fsf@benfinney.id.au> Message-ID: On Oct 21, 11:36?am, Ben Finney wrote: > rusi writes: > > The American programmer would profit more from learning Latin than > > from learning yet another programming language. > > > Edsger Dijkstra in "On the fact that the Atlantic Ocean has two > > sides" > > >http://www.cs.utexas.edu/users/EWD/transcriptions/EWD06xx/EWD611.html > > It's ambiguous whether Dijkstra is saying anything positive about Latin > ?there. > > He could be saying ?learning Latin would be a useful thing for average > US programmers?. > > Or he could be saying ?learning any second natural human language ? even > one as useless as Latin ? will benefit the average US programmer more > than learning another programming language?. > > I prefer to think someone as wise as Dijkstra would not be deluded as to > the value of Latin, and lean more toward the latter meaning. Well if you see the additional lines Chris has added or other personal correspondences of EWD eg http://digitalundivide.blogspot.com/2005/12/ewd-personal-reflection.html Dijkstra clearly has a specific choice of latin. It is easier to discount your view -- Dijkstra is wise -- than to deny that Dijkstra was a devoted classicist -- music, languages and ultimately programming. And much bigger CSists than you and I -- eg Egon Borger, R W Hamming etc -- have called Dijkstra a nut. It seems to me that Dijkstra's quote would become a bit more meaningful if one went up, so to speak, the class hierarchy. He is talking of 3 languages -- English, Latin and ones native tongue. Generalizing (with slight inaccuracy) one could list 3 categories: a communication language b sacred/classical language c mother tongue Today a is singleton -- {English} b is roughly {sanskrit, hebrew, arabic, latin, greek} Each of these categories has a very different function just as Bach and beatles have different functions. From d at davea.name Fri Oct 21 07:11:49 2011 From: d at davea.name (Dave Angel) Date: Fri, 21 Oct 2011 07:11:49 -0400 Subject: revive a generator In-Reply-To: <1319162982.85636.YahooMailNeo@web121513.mail.ne1.yahoo.com> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> <1319162982.85636.YahooMailNeo@web121513.mail.ne1.yahoo.com> Message-ID: <4EA15375.9050004@davea.name> On 10/20/2011 10:09 PM, Yingjie Lan wrote: > > > What if the generator is passed in as an argument > when you are writing a function? That is, the expression > is not available? > > Secondly, it would be nice to automatically revive it. > For example, when another for-statement or other > equivalent is applied to it. > > Yingjie That last point would definitely be incompatible. It's quite useful to be able to peel some values off a generator, then use a for loop to get the remainder. Simplest example I can think of would be to read a file where the first line(s) represent header information, and the body is obtainable with a simple loop. I wouldn't be surprised if the csv module does that. Not arguing whether an explicit revival is useful or not. Although as others have pointed out, not all generators could accomplish it, and in some cases not unambiguously. -- DaveA From bulg at ngs.ru Fri Oct 21 08:36:28 2011 From: bulg at ngs.ru (Yosifov Pavel) Date: Fri, 21 Oct 2011 05:36:28 -0700 (PDT) Subject: Py3K: file inheritance References: mailman.2109.1319179873.27778.python-list@python.org Message-ID: <21ed0bdb-0907-4f51-a667-79fb9ea5ebbe@y8g2000yqf.googlegroups.com> On 21 ???, 13:50, Ian Kelly wrote: > On Thu, Oct 20, 2011 at 10:17 PM, Yosifov Pavel wrote: > > Little silly example: > > > class MyFile(file): > > ?def __init__(self, *a, **ka): > > ? ?super(MyFile, self).__init__(*a, **ka) > > ? ?self.commented = 0 > > ?def write(self, s): > > ? ?if s.startswith("#"): > > ? ? ?self.commented += 1 > > ? ? ?super(MyFile, self).write(s) > > > When I tried in Python 3.x to inherit FileIO or TextIOWrapper and then > > to use MyFile (ex., open(name, mode, encoding), write(s)...) I get > > errors like 'unsupported write' or AttributeError 'readable'... Can > > you show me similar simple example like above but in Python 3.x? > > class MyTextIO(io.TextIOWrapper): > ? ? def __init__(self, *args, **kw): > ? ? ? ? super().__init__(*args, **kw) > ? ? ? ? self.commented = 0 > ? ? def write(self, s): > ? ? ? ? if s.startswith('#'): > ? ? ? ? ? ? self.commented += 1 > ? ? ? ? ? ? super().write(s) > > buffered = open(name, 'wb') > textio = MyTextIO(buffered, encoding='utf-8') > textio.write('line 1') > textio.write('# line 2') > textio.close() > print(textio.commented) > > HTH, > Ian Thank you very much! From msarro at gmail.com Fri Oct 21 09:39:35 2011 From: msarro at gmail.com (Matty Sarro) Date: Fri, 21 Oct 2011 09:39:35 -0400 Subject: Automated form submissions Message-ID: Hey everyone. First, I apologize because I know this question has probably gotten asked a lot. I am looking to automate filling out web forms, and no, its not for spamming purposes. I have looked at mechanize so far, but I'm not sure it quite fits what I'm looking for. I know it can act as a browser and do some basic work with forms, but I couldn't find anything in their documentation about interacting with things like drop down boxes, etc. Is selenium a better choice for this? -Matt From steve+comp.lang.python at pearwood.info Fri Oct 21 09:48:43 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Oct 2011 13:48:43 GMT Subject: revive a generator References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> Message-ID: <4ea1783a$0$29968$c3e8da3$5496439d@news.astraweb.com> On Thu, 20 Oct 2011 19:09:42 -0700, Yingjie Lan wrote: >> Here's an example of an explicit request to revive the generator: > > >>>>> g = (x*x for x in range(3)) >>>>> for x in g: print x >> 0 >> 1 >> 4 >>>>> g = (x*x for x in range(3)) # revive the generator for x in g: >>>>> print x #now this will work >> 0 >> 1 >> 4 >> >> ChrisA > > > What if the generator is passed in as an argument when you are writing a > function? That is, the expression is not available? If the expression is not available, how do you expect to revive it? The expression is gone, it no longer exists. As you said in another post: "What if the generator involves a variable from another scope, and before re-generating, the variable changed its value." Exactly. In general, you *can't* revive general iterators. It simply isn't possible. The variables that defined it might be gone. They might be non-deterministic: random numbers, data from the Internet or a file system that has changed, or user input. Trying to enforce the rule "iterators must support restarting" is foolish: it can't be done. You use an iterator when you want to iterate over something *once*, that is why they exist. If you want to iterate over it twice, don't use an iterator, use a sequence. Forcing all iterators to save their data, on the off-chance that maybe somebody might want to iterate over it twice, defeats the purpose of an iterator. > Secondly, it would be nice to automatically revive it. For example, when > another for-statement or other equivalent is applied to it. Nice? No, it would be horrible. It goes against the basic concept of an iterator: iterators should be memory efficient, generating values lazily. If you want an iterable sequence that you can iterate over multiple times, then use a list, or a custom iterable class. If you want a socket wrench, use a socket wrench. Don't insist that hammers have to have a socket wrench attachment. -- Steven From k.sahithi2862 at gmail.com Fri Oct 21 09:57:28 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Fri, 21 Oct 2011 06:57:28 -0700 (PDT) Subject: NEW UPDATS Message-ID: FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ SAKUNI MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/sakuni-movie-stills.html 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html From gshanemiller at verizon.net Fri Oct 21 10:05:32 2011 From: gshanemiller at verizon.net (Shane) Date: Fri, 21 Oct 2011 07:05:32 -0700 (PDT) Subject: non-standard module location (again) Message-ID: Need to refine a question I asked earlier. If I have a module, |-- foo |-------| |-------|---bar |-------|-------| |-------|-------|---__init__.py then I can say import foo.bar But suppose I want to import foo.bar.stuff and stuff isn't located on under `bar' because it's user supplied code: |- stuff <- I want this to be logically under foo.bar |-------|---__init__.py <- even though it's not under bar in the computer's file system Now what: how to arrange to do command: import foo.bar.stuff From ian.g.kelly at gmail.com Fri Oct 21 10:25:22 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 21 Oct 2011 08:25:22 -0600 Subject: revive a generator In-Reply-To: <1319184173.21862.YahooMailNeo@web121506.mail.ne1.yahoo.com> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <877h3yls79.fsf@no-fixed-abode.cable.virginmedia.net> <1319184173.21862.YahooMailNeo@web121506.mail.ne1.yahoo.com> Message-ID: On Fri, Oct 21, 2011 at 2:02 AM, Yingjie Lan wrote: > Oops, my former reply has the code indentation messed up > by the mail system. Here is a reformatted one: > > > What if the generator involves a variable from another scope, > and before re-generating, the variable changed its value. > Also, the generator could be passed in as an argument, > so that we don't know its exact expression. In the former case, use a named generator function and call it twice to create two generators. In the latter case, don't pass in the generator as an argument. Pass in a callable that constructs the iterator instead. Modifying your example: vo = 34 def mygen(): for x in range(3): yield vo * x def myfun(g): global vo for i in g(): print(i) vo += 3 for i in g(): print(i) myfun(mygen) Cheers, Ian From invalid at invalid.invalid Fri Oct 21 10:32:36 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 21 Oct 2011 14:32:36 +0000 (UTC) Subject: Automated form submissions References: Message-ID: On 2011-10-21, Matty Sarro wrote: > First, I apologize because I know this question has probably gotten > asked a lot. I am looking to automate filling out web forms, and no, > its not for spamming purposes. I use ClientForm for that, and I'm happy with it. -- Grant Edwards grant.b.edwards Yow! MERYL STREEP is my at obstetrician! gmail.com From c.fangeux at gmail.com Fri Oct 21 10:33:32 2011 From: c.fangeux at gmail.com (c.fangeux at gmail.com) Date: Fri, 21 Oct 2011 07:33:32 -0700 (PDT) Subject: IDLE lost from Windows menu ! In-Reply-To: References: <264d1536-864b-4cd5-9930-b4f5e69e8d46@h38g2000yqn.googlegroups.com> Message-ID: <8750605.542.1319207612892.JavaMail.geo-discussion-forums@yqja14> Thanks Alec. For me it works with the following Default key : "C:\Python32\pythonw.exe" "C:\Python32\Lib\idlelib\idle.pyw" -e "%1" Otherwise IDLE does not open, only python was executed. From c.fangeux at gmail.com Fri Oct 21 10:33:32 2011 From: c.fangeux at gmail.com (c.fangeux at gmail.com) Date: Fri, 21 Oct 2011 07:33:32 -0700 (PDT) Subject: IDLE lost from Windows menu ! In-Reply-To: References: <264d1536-864b-4cd5-9930-b4f5e69e8d46@h38g2000yqn.googlegroups.com> Message-ID: <8750605.542.1319207612892.JavaMail.geo-discussion-forums@yqja14> Thanks Alec. For me it works with the following Default key : "C:\Python32\pythonw.exe" "C:\Python32\Lib\idlelib\idle.pyw" -e "%1" Otherwise IDLE does not open, only python was executed. From dihedral88888 at googlemail.com Fri Oct 21 11:07:12 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Fri, 21 Oct 2011 08:07:12 -0700 (PDT) Subject: non-standard module location (again) In-Reply-To: References: Message-ID: <5099513.170.1319209633099.JavaMail.geo-discussion-forums@pref15> 1. Define a new class with an instance of the foo class included so that one can use all foo's properties and add new attributes. 2. Derive a new class from foo that extends its properties with the properties in foo accessible. From ian.g.kelly at gmail.com Fri Oct 21 11:48:21 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 21 Oct 2011 09:48:21 -0600 Subject: non-standard module location (again) In-Reply-To: References: Message-ID: On Fri, Oct 21, 2011 at 8:05 AM, Shane wrote: > Need to refine a question I asked earlier. If I have a module, > > |-- ?foo > |-------| > |-------|---bar > |-------|-------| > |-------|-------|---__init__.py > > then I can say import foo.bar > > But suppose I want to import foo.bar.stuff and stuff isn't located on > under `bar' because it's user > supplied code: > > |- stuff ? ? ? ? ? ? ? ? ? ? ? ? ? ? <- I want this to be logically > under foo.bar > |-------|---__init__.py ? ? ? ? ? <- even though it's not under bar in > the computer's file system > > Now what: how to arrange to do command: import foo.bar.stuff I've never tried this myself, but I think that pkgutil.extend_path is what you're looking for. http://docs.python.org/library/pkgutil.html Cheers, Ian From aspineux at gmail.com Fri Oct 21 12:06:07 2011 From: aspineux at gmail.com (aspineux) Date: Fri, 21 Oct 2011 09:06:07 -0700 (PDT) Subject: fromutc: dt.tzinfo is not self: pytz.timezone('UTC').fromutc(datetime.utcnow()) References: <4e9f3b19$0$29974$c3e8da3$5496439d@news.astraweb.com> Message-ID: <66d73f14-7ad1-458c-8b3a-5794ed9de8f4@x20g2000vbl.googlegroups.com> On Oct 19, 11:03?pm, Steven D'Aprano wrote: > On Wed, 19 Oct 2011 01:06:53 -0700, aspineux wrote: > > hi > > >>>> import pytz > >>>> from datetime import datetime > >>>> pytz.timezone('GMT0').fromutc(datetime.utcnow()) > > datetime.datetime(2011, 10, 19, 7, 54, 45, 579125, tzinfo= > 'GMT0'>) > >>>> ?pytz.timezone('UTC').fromutc(datetime.utcnow()) > > Traceback (most recent call last): > > ? File "", line 1, in > > ValueError: fromutc: dt.tzinfo is not self > >>>> pytz.timezone('Europe/Brussels').fromutc(datetime.utcnow()) > > datetime.datetime(2011, 10, 19, 9, 55, 47, 787937, tzinfo= > 'Europe/Brussels' CEST+2:00:00 DST>) > > > Why does UTC fail ? > > Bug or feature ? > > Looks like a bug to me. But I'm not an expert on pytz. Perhaps you should > report it back to the package author. Done https://bugs.launchpad.net/pytz/+bug/879480 > > -- > Steven From ironfroggy at gmail.com Fri Oct 21 12:41:52 2011 From: ironfroggy at gmail.com (Calvin Spealman) Date: Fri, 21 Oct 2011 12:41:52 -0400 Subject: non-standard module location (again) In-Reply-To: References: Message-ID: I am biased, but you could use a plugin loader like straight.plugin at https://github.com/ironfroggy/straight.plugin On Fri, Oct 21, 2011 at 10:05 AM, Shane wrote: > Need to refine a question I asked earlier. If I have a module, > > |-- ?foo > |-------| > |-------|---bar > |-------|-------| > |-------|-------|---__init__.py > > then I can say import foo.bar > > But suppose I want to import foo.bar.stuff and stuff isn't located on > under `bar' because it's user > supplied code: > > |- stuff ? ? ? ? ? ? ? ? ? ? ? ? ? ? <- I want this to be logically > under foo.bar > |-------|---__init__.py ? ? ? ? ? <- even though it's not under bar in > the computer's file system > > Now what: how to arrange to do command: import foo.bar.stuff > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy From steve+comp.lang.python at pearwood.info Fri Oct 21 13:29:48 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 21 Oct 2011 17:29:48 GMT Subject: non-standard module location (again) References: Message-ID: <4ea1ac0c$0$29968$c3e8da3$5496439d@news.astraweb.com> On Fri, 21 Oct 2011 07:05:32 -0700, Shane wrote: > Need to refine a question I asked earlier. If I have a module, > > |-- foo > |-------| > |-------|---bar > |-------|-------| > |-------|-------|---__init__.py > > then I can say import foo.bar No you can't, not the way you have listed it. As shown, foo is just a directory, so "import foo" will fail. However, "import bar" may work, provided foo/bar is in the module search path. Perhaps you mean you have a package, with a sub-package: foo/ +-- __init__.py +-- bar/ ... +-- __init__.py Now you have TWO modules, foo and foo.bar, and you can "import foo.bar" successfully. > But suppose I want to import foo.bar.stuff and stuff isn't located on > under `bar' because it's user > supplied code: > > |- stuff <- I want this to be logically > under foo.bar > |-------|---__init__.py <- even though it's not under bar in > the computer's file system This is not clear what you are trying to do. Please explain more clearly what your module layout is. foo/ +-- __init__.py +-- stuff.py +-- bar/ ... +-- __init__.py Or: stuff.py foo/ +-- __init__.py +-- bar/ ... +-- __init__.py But since stuff is supposed to be a plugin, the most obvious, sensible way to lay out the modules would be: foo/ +-- __init__.py +-- plugins/ ... +-- __init__.py ... +-- stuff.py +-- bar/ ... +-- __init__.py and then "import foo.plugins.stuff". Clear, simple and obvious. > Now what: how to arrange to do command: import foo.bar.stuff Why do you want to call it foo.bar.stuff when it isn't actually foo.bar.stuff? Anyone trying to debug this will hate you, when they try to find a module foo/bar/stuff.py and can't find it because it doesn't exist. If you must play games with module locations, put this inside the foo/bar/__init__.py module: import foo.plugins.stuff as stuff and now you can say "import foo.bar.stuff". But why bother? Of course, plugin discovery is still a problem, but that's still a problem no matter what you do. Best to use a well-tested plugin library instead of trying to invent your own. -- Steven From ian.g.kelly at gmail.com Fri Oct 21 13:39:58 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 21 Oct 2011 11:39:58 -0600 Subject: how to change the order of a button, static text or other components In-Reply-To: References: <9655f270-15a1-4d59-b5b0-4d2320e27440@h39g2000prh.googlegroups.com> Message-ID: I assume you're arranging the components with a sizer. Remove them from the sizer, reinsert them in the order you want, and then call sizer.Layout(). Cheers, Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Oct 21 16:25:47 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 21 Oct 2011 16:25:47 -0400 Subject: revive a generator In-Reply-To: <1319162982.85636.YahooMailNeo@web121513.mail.ne1.yahoo.com> References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> <1319162982.85636.YahooMailNeo@web121513.mail.ne1.yahoo.com> Message-ID: Here is a class that creates a re-iterable from any callable, such as a generator function, that returns an iterator when called, + captured arguments to be given to the function. class reiterable(): def __init__(self, itercall, *args, **kwds): self.f = itercall # callable that returns an iterator self.args = args self.kwds = kwds def __iter__(self): return self.f(*self.args, **self.kwds) def squares(n): for i in range(n): yield i*i sq3 = reiterable(squares, 3) for i in sq3: print(i) for i in sq3: print(i) >>> 0 1 4 0 1 4 -- Terry Jan Reedy From ramit.prasad at jpmorgan.com Fri Oct 21 18:20:49 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Fri, 21 Oct 2011 18:20:49 -0400 Subject: how to change the order of a button, static text or other components In-Reply-To: <9655f270-15a1-4d59-b5b0-4d2320e27440@h39g2000prh.googlegroups.com> References: <9655f270-15a1-4d59-b5b0-4d2320e27440@h39g2000prh.googlegroups.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2F21AB4727@EMARC112VS01.exchad.jpmchase.net> >what i want to do is,when i press a button, i change the order of >selected components,how to do this? This is so vague, I am tempted to think it is spam....but on the chance it is not, I need a lot more information than you are providing to even attempt to give you any guidance. 1. By "button" do you mean keyboard/mouse or GUI; if you mean GUI button then what toolkit (Tk, wx, etc) are you referring to? 2. Define "selected components". How are they selected? What is a component? 3. Define "order" in regards to "components". Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From esj at harvee.org Fri Oct 21 19:30:32 2011 From: esj at harvee.org (Eric S. Johansson) Date: Fri, 21 Oct 2011 19:30:32 -0400 Subject: need python+windows edit control help Message-ID: <4EA20098.8040308@harvee.org> I'm back with yet another attempt at adding accessibility features using Python and NaturallySpeaking. I've simplified the concepts again and I really need some help from someone who knows Microsoft Windows and Python. My goal is developing a template for what I'm trying to do, then I can take over and generate some useful accessibility tools. The core idea is an accessibility adjunct program receiving focus at start-of-utterance and returns focus to the original application at end-of-utterance. The window associated with the program contains a grid. Within the grid is an active cell which can accept input. Any cell could be made active depending on the state of the program but only one cell accepts input at any one time. How would this be used? For example, the Skype IM window is atrocious for its disabled users. If one associated at two cell window accessibility adjunct program with Skype, the user could dictate, edit, retrain, etc. within the adjunct program and on command, return the data to Skype. One could also contain a small history so that like Skype, you could go back and edit a previously sent message. a second use case is found on my blog http://blog.esjworks.com which is the tool to create mangled codenames from speech. I think the grid model works better than individual text fields that I originally wrote because it allows me to make better use of a cache of previously generated symbols. Anyway, if anybody can help, I would really appreciate some assistance. --- eric From sigmundv at gmail.com Fri Oct 21 19:42:16 2011 From: sigmundv at gmail.com (SigmundV) Date: Fri, 21 Oct 2011 16:42:16 -0700 (PDT) Subject: compare range objects References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> Message-ID: <453d196e-4516-47f3-9d33-caea70d33a8f@l12g2000vby.googlegroups.com> On Oct 21, 2:55?am, Yingjie Lan wrote: > > In simulation, one can use range objects to denote a discrete domain, > and domain comparison could be very useful. Not just equality, but also > things like if one domain is contained in another. Can't sets [help(set)] be used for this? From skippy.hammond at gmail.com Fri Oct 21 22:03:04 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Sat, 22 Oct 2011 13:03:04 +1100 Subject: need python+windows edit control help In-Reply-To: <4EA20098.8040308@harvee.org> References: <4EA20098.8040308@harvee.org> Message-ID: <4EA22458.9080305@gmail.com> On 22/10/2011 10:30 AM, Eric S. Johansson wrote: > I'm back with yet another attempt at adding accessibility features using > Python and NaturallySpeaking. I've simplified the concepts again and I > really need some help from someone who knows Microsoft Windows and > Python. My goal is developing a template for what I'm trying to do, then > I can take over and generate some useful accessibility tools. The python-win32 at python.org mailing list might be the best place to look for help - although you will probably need to provide much more information before anyone can help. MSDN documents most of what you can do with edit control (look for windows messages starting with "EM_"), but without checking, I expect you will find programs like Skype don't use a Windows edit control at all. Mark From peter at engcorp.com Fri Oct 21 22:10:22 2011 From: peter at engcorp.com (Peter Hansen) Date: Fri, 21 Oct 2011 19:10:22 -0700 (PDT) Subject: Python on BlackBerry PlayBook Message-ID: <5b3f6a95-3296-4a62-8e0c-38461dd540a8@n18g2000vbv.googlegroups.com> I'm slightly surprised to search and not see any recent mention of Python running on the BlackBerry PlayBook. Since the PlayBook simulators (for developers) were first available late last year, they've contained Python 2.7. Some time before release, the permissions were changed so the binaries weren't accessible to developers or to apps. There's now a developer beta of the upcoming 2.0 release of the PlayBook's OS (built on QNX, previously named Tablet OS and now rebranded as BBX). Though this beta has almost none of the "user- facing" improvements included, much of what's below the covers is intact and probably fairly representative of how the final release will look. In this beta 2.0 release, I see a full installation of Python 3.2.1 (qnx6 build). (The 2.7 install is still present, and likely will remain for a long time, as it underpins some important features in the OS.) There are other clear signs that RIM/QNX have a significant chunk of Python related work done already, including a video with some TAT user interface demos ( http://www.youtube.com/watch?feature=player_embedded&v=Mia10Rekd0c ) where you can see (in 720P mode, around 3:30) files such as Accelerometer.py and Horizon.py along with a "PyCascadesSDK". Currently RIM has no public plans to make a Python SDK available to developers for use in building PlayBook/BBX apps (which would include the next generation of their phones). I believe if there were enough interest shown, this situation could change. So, I'm curious to what degree it would influence people's interest in developing apps for the PlayBook if they were to provide a full Python SDK, or even part of one which the community could flesh out, as one of the development platforms available for the PlayBook. For those not watching this area, the current set of platforms includes native C/C++, WebWorks (HTML5/JavaScript and other web standards), Java in the form of the now-beta Android player, and Adobe AIR (Flash/ActionScript3). I think Python would round that out very nicely. ;-) From dhoese at gmail.com Fri Oct 21 23:13:06 2011 From: dhoese at gmail.com (David Hoese) Date: Fri, 21 Oct 2011 22:13:06 -0500 Subject: shutil _isindir Message-ID: <4EA234C2.8020709@gmail.com> Hi, I wasn't really sure where to post this since the python-dev list seems way too official. I'm wondering/questioning the behavior of shutil.move. It currently does a check for if the dst is inside the src directory with a _destinsrc function. This function uses os.path.abspath to convert the arguments, but I think it should convert using os.path.realpath. A recent problem I had with this I ended up asking on stackoverflow: http://stackoverflow.com/questions/7854608/python-shutil-move-odd-softlinking So I was wondering if this sounds like a change that should happen in the shutil code or should programmers(me) just be more careful. I feel like it should be in the shutil code since its getting around a checked case (destination inside source) and it can end up deleting information when a move was intended. But then again this has been in the standard lib for a while now, so I'm guessing there are reasons for it...plus it was a dumb mistake by me. So I guess what I'm asking is what are the reasons that _destinsrc uses abspath instead of realpath? And is there a better place to ask this? FYI, I was provided this link to the shutil.py source on SO: http://hg.python.org/cpython/file/d30482d51c25/Lib/shutil.py#l262 -Dave From esj at harvee.org Fri Oct 21 23:45:58 2011 From: esj at harvee.org (Eric S. Johansson) Date: Fri, 21 Oct 2011 23:45:58 -0400 Subject: need python+windows edit control help In-Reply-To: <4EA22458.9080305@gmail.com> References: <4EA20098.8040308@harvee.org> <4EA22458.9080305@gmail.com> Message-ID: <4EA23C76.7010602@harvee.org> On 10/21/2011 10:03 PM, Mark Hammond wrote: > On 22/10/2011 10:30 AM, Eric S. Johansson wrote: >> I'm back with yet another attempt at adding accessibility features using >> Python and NaturallySpeaking. I've simplified the concepts again and I >> really need some help from someone who knows Microsoft Windows and >> Python. My goal is developing a template for what I'm trying to do, then >> I can take over and generate some useful accessibility tools. > > The python-win32 at python.org mailing list might be the best place to look for > help - although you will probably need to provide much more information before > anyone can help. MSDN documents most of what you can do with edit control > (look for windows messages starting with "EM_"), but without checking, I > expect you will find programs like Skype don't use a Windows edit control at all. > > Mark thanks for the pointer. When I talk about speech user interfaces in general and accessibility specifically, I find it's better to give a short overview (yes, this was short) before going into the details. I'll be clearer about what kind of help I need. --- eric From steve+comp.lang.python at pearwood.info Sat Oct 22 01:32:44 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Oct 2011 05:32:44 GMT Subject: compare range objects References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> <453d196e-4516-47f3-9d33-caea70d33a8f@l12g2000vby.googlegroups.com> Message-ID: <4ea2557c$0$29968$c3e8da3$5496439d@news.astraweb.com> On Fri, 21 Oct 2011 16:42:16 -0700, SigmundV wrote: > On Oct 21, 2:55?am, Yingjie Lan wrote: >> >> In simulation, one can use range objects to denote a discrete domain, >> and domain comparison could be very useful. Not just equality, but also >> things like if one domain is contained in another. > > Can't sets [help(set)] be used for this? Sure. But the downside of sets is that, like lists, they are not lazy, they actually store every value in them rather than calculate them as needed, so they are only suitable for relatively small domains. Compare: >>> sys.getsizeof(range(9999)) 20 >>> sys.getsizeof(set(range(9999))) 262256 Now consider: >>> sys.getsizeof(range(-999999999, 999999999)) 20 Converted to a set, the memory requirements will be quite large, and the processing time to do anything useful with it likewise inflated. If you need a data type to store large numeric domains, whether discrete or continuous, a tree of intervals storing the lower and upper bounds is probably the right solution. -- Steven From steve+comp.lang.python at pearwood.info Sat Oct 22 01:39:59 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Oct 2011 05:39:59 GMT Subject: revive a generator References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> <1319162982.85636.YahooMailNeo@web121513.mail.ne1.yahoo.com> Message-ID: <4ea2572e$0$29968$c3e8da3$5496439d@news.astraweb.com> On Fri, 21 Oct 2011 16:25:47 -0400, Terry Reedy wrote: > Here is a class that creates a re-iterable from any callable, such as a > generator function, that returns an iterator when called, + captured > arguments to be given to the function. > > class reiterable(): > def __init__(self, itercall, *args, **kwds): > self.f = itercall # callable that returns an iterator > self.args = args > self.kwds = kwds > def __iter__(self): > return self.f(*self.args, **self.kwds) > > def squares(n): > for i in range(n): > yield i*i > > sq3 = reiterable(squares, 3) We can do that even more simply, using a slightly different interface. >>> from functools import partial >>> sq3 = partial(squares, 3) sq3 is now an iterator factory. You can't iterate over it directly, but it's easy to restart: just call it to return a fresh iterator. >>> list(sq3()) [0, 1, 4] >>> list(sq3()) [0, 1, 4] -- Steven From __peter__ at web.de Sat Oct 22 03:58:10 2011 From: __peter__ at web.de (Peter Otten) Date: Sat, 22 Oct 2011 09:58:10 +0200 Subject: shutil _isindir References: <4EA234C2.8020709@gmail.com> Message-ID: David Hoese wrote: > I wasn't really sure where to post this since the python-dev list seems > way too official. I'm wondering/questioning the behavior of > shutil.move. It currently does a check for if the dst is inside the src > directory with a _destinsrc function. This function uses > os.path.abspath to convert the arguments, but I think it should convert > using os.path.realpath. A recent problem I had with this I ended up > asking on stackoverflow: > http://stackoverflow.com/questions/7854608/python-shutil-move-odd- softlinking > > So I was wondering if this sounds like a change that should happen in > the shutil code or should programmers(me) just be more careful. I feel > like it should be in the shutil code since its getting around a checked > case (destination inside source) and it can end up deleting information > when a move was intended. But then again this has been in the standard > lib for a while now, so I'm guessing there are reasons for it...plus it > was a dumb mistake by me. > > So I guess what I'm asking is what are the reasons that _destinsrc uses > abspath instead of realpath? And is there a better place to ask this? > > FYI, I was provided this link to the shutil.py source on SO: > http://hg.python.org/cpython/file/d30482d51c25/Lib/shutil.py#l262 Your suggestion makes sense to me and I don't see any disadvantages. I encourage you to file a bug report on bugs.python.org, preferably with a patch. If there are any problems with the proposed change they can be discussed there. From steve+comp.lang.python at pearwood.info Sat Oct 22 05:03:10 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Oct 2011 09:03:10 GMT Subject: shutil _isindir References: Message-ID: <4ea286ce$0$29968$c3e8da3$5496439d@news.astraweb.com> On Fri, 21 Oct 2011 22:13:06 -0500, David Hoese wrote: > So I guess what I'm asking is what are the reasons that _destinsrc uses > abspath instead of realpath? And is there a better place to ask this? Probably because abspath goes back to Python 1.5, while realpath is comparatively recent only going back to 2.2, and nobody has thought to change the code in shutil. I recommend you raise a bug/feature request on the bug tracker, preferably with a fix and a test demonstrating the problem. http://bugs.python.org/ -- Steven From pavlovevidence at gmail.com Sat Oct 22 05:38:57 2011 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 22 Oct 2011 02:38:57 -0700 (PDT) Subject: revive a generator In-Reply-To: References: Message-ID: <29012412.474.1319276337983.JavaMail.geo-discussion-forums@pref15> On Thursday, October 20, 2011 6:23:50 AM UTC-7, Yingjie Lan wrote: > Hi, > > it seems a generator expression can be used only once: > > >>> g = (x*x for x in range(3)) > >>> for x in g: print x > 0 > 1 > 4 > >>> for x in g: print x #nothing printed > >>> > > Is there any way to revive g here? Revive is the wrong word for what you want. Once an iterator (be it a generator or some other kind of iterator) is done, it's done. What you are asking for is, given a generator, to create a new generator from the same expression/function that created the original generator. This is not reviving, but recreating. I have two objections to this: a major ideological one and a minor practical one. The practical drawback to allowing generators to be recreated is that it forces all generators to carry around a reference to the code object that created it. if random.random() > 5: g = (x*x for x in xrange(3)) else: g = (x+x for x in xrange(3)) for y in g: print x revive(g) # which generator expression was it? # need to carry around a reference to be able to tell for y in g: print x Carrying a reference to a code object in turn carries around any closures used in the generator expression or function, so it can potentially keep a large amount of data alive. Given that the vast majority of generators would never be recreated, this is quite wasteful. My ideological objection is that it forces the programmer to be wary of the effects of recreation. Right now, if someone writes a generator expression, they can rely on the fact that it can only be iterated through once (per time the generator expression is evaluated). But if you allow a downstream user to recreate the generator at will, then the writer will always have to be wary of adverse side-effects if the generator is iterated through twice. So, although I can see it being occasionally useful, I'm going to opine that it is more trouble than it's worth. Carl Banks From vinay_sajip at yahoo.co.uk Sat Oct 22 08:09:14 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Sat, 22 Oct 2011 12:09:14 +0000 (UTC) Subject: logging: warn() methods and function to be deprecated. Message-ID: In response to an issue (#13235) raised on the Python bug tracker, I'm going to deprecate the warn() methods in the Logger and LoggerAdapter classes in the stdlib logging package, as well the module-level warn() function. The warn() variants were synonyms for the warning() methods and function, and a holdover from before the time that logging was added to Python.They were not documented; it's probably time to retire them, so I've added a DeprecationWarning to appear in 3.3, and they'll be completely removed in 3.4 (along with the WARN synonym for WARNING). With this change, all the logging levels are adjectives which apply to the logged message: DEBUG, INFO, WARNING, ERROR and CRITICAL. I don't believe the WARN/warn variants were used much, if at all - but this is just a heads up for anyone who might have used them. Regards, Vinay Sajip From dhoese at gmail.com Sat Oct 22 08:49:52 2011 From: dhoese at gmail.com (David Hoese) Date: Sat, 22 Oct 2011 07:49:52 -0500 Subject: shutil _isindir In-Reply-To: References: Message-ID: <4EA2BBF0.4050602@gmail.com> I was about to submit a bug report, but while testing I have figured out that my specific problem has been solved in Python 2.7 (server that I was using had 2.6 on it). You can see the differences here: 2.6: http://hg.python.org/cpython/file/b9a95ce2692c/Lib/shutil.py 2.7: http://hg.python.org/cpython/file/d30482d51c25/Lib/shutil.py You'll notice that in move(), there is now a check for the same file, which if they're not the same file you don't get unexpected deleted files. If you still think I should submit a bug report let me know and provide me with the test case...or just submit the bug yourself. -Dave P.S. Sorry for the original poor subject line, was a place holder that I forgot to change. On 10/22/2011 5:00 AM, python-list-request at python.org wrote: > Subject: > Re: shutil _isindir > From: > Steven D'Aprano > Date: > 10/22/2011 4:03 AM > > To: > python-list at python.org > > > On Fri, 21 Oct 2011 22:13:06 -0500, David Hoese wrote: > >> > So I guess what I'm asking is what are the reasons that _destinsrc uses >> > abspath instead of realpath? And is there a better place to ask this? > Probably because abspath goes back to Python 1.5, while realpath is > comparatively recent only going back to 2.2, and nobody has thought to > change the code in shutil. > > I recommend you raise a bug/feature request on the bug tracker, > preferably with a fix and a test demonstrating the problem. > > http://bugs.python.org/ From steve+comp.lang.python at pearwood.info Sat Oct 22 08:51:32 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Oct 2011 12:51:32 GMT Subject: compare range objects References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> <453d196e-4516-47f3-9d33-caea70d33a8f@l12g2000vby.googlegroups.com> <4ea2557c$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4ea2bc54$0$29968$c3e8da3$5496439d@news.astraweb.com> On Sat, 22 Oct 2011 05:32:44 +0000, Steven D'Aprano wrote: > On Fri, 21 Oct 2011 16:42:16 -0700, SigmundV wrote: > >> On Oct 21, 2:55?am, Yingjie Lan wrote: >>> >>> In simulation, one can use range objects to denote a discrete domain, >>> and domain comparison could be very useful. Not just equality, but >>> also things like if one domain is contained in another. [...] > If you need a data type to store large numeric domains, whether discrete > or continuous, a tree of intervals storing the lower and upper bounds is > probably the right solution. And purely by coincidence, I came across this today: http://docs.pylandro.com/pylandro-collections-range/0.1/tutorial.html I haven't used the library yet, but it looks impressive. -- Steven From mcepl at redhat.com Sat Oct 22 09:16:47 2011 From: mcepl at redhat.com (Matej Cepl) Date: Sat, 22 Oct 2011 15:16:47 +0200 Subject: help In-Reply-To: References: <9f8pa1Fsh8U3@mid.individual.net> Message-ID: On Oct 8, 2:51 pm, X1 wrote: > > easy_install does not exist on Fedora. That's a pure lie. mitmanek:~ $ sudo repoquery -qf /usr/bin/easy_install python-setuptools-0:0.6.10-3.el6.noarch mitmanek:~ $ Mat?j From ramapraba2653 at gmail.com Sat Oct 22 09:38:01 2011 From: ramapraba2653 at gmail.com (SUPREME) Date: Sat, 22 Oct 2011 06:38:01 -0700 (PDT) Subject: LATEST MOVIE HOT PHOTO STILLS` Message-ID: <362c2e06-e9dd-4be7-a473-02e36c01252d@h23g2000pra.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ SAKUNI MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/sakuni-movie-stills.html 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html SNEHA ULLAL HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/sneha-ullal-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html From steve+comp.lang.python at pearwood.info Sat Oct 22 11:02:47 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 22 Oct 2011 15:02:47 GMT Subject: help References: <9f8pa1Fsh8U3@mid.individual.net> Message-ID: <4ea2db17$0$29968$c3e8da3$5496439d@news.astraweb.com> On Sat, 22 Oct 2011 15:16:47 +0200, Matej Cepl wrote: > On Oct 8, 2:51 pm, X1 wrote: >> >> easy_install does not exist on Fedora. > > That's a pure lie. Rather than assume malice, we should give X1 the benefit of the doubt and assume he genuinely believed what he wrote but was merely mistaken. -- Steven From sigmundv at gmail.com Sat Oct 22 13:51:07 2011 From: sigmundv at gmail.com (SigmundV) Date: Sat, 22 Oct 2011 10:51:07 -0700 (PDT) Subject: compare range objects References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> <453d196e-4516-47f3-9d33-caea70d33a8f@l12g2000vby.googlegroups.com> <4ea2557c$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <57fe18d1-b66c-4b8c-bb83-a8994498d2cf@u13g2000vbx.googlegroups.com> On Oct 22, 6:32?am, Steven D'Aprano wrote: > > Sure. But the downside of sets is that, like lists, they are not lazy, Thank you for pointing this out. I agree that it's not a viable alternative for large domains. Storing the bounds and the resolution should be enough. /Sigmund From jonathan at jloescher.com Sat Oct 22 18:18:17 2011 From: jonathan at jloescher.com (Jonathan Loescher) Date: Sat, 22 Oct 2011 15:18:17 -0700 (PDT) Subject: Books to lean Python 3 Web Programming? Message-ID: Can anyone recommend a good book to learn the web programming aspects of Python 3? From gnarlodious at gmail.com Sat Oct 22 20:26:22 2011 From: gnarlodious at gmail.com (Gnarlodious) Date: Sat, 22 Oct 2011 17:26:22 -0700 (PDT) Subject: How to isolate a constant? Message-ID: Say this: class tester(): _someList = [0, 1] def __call__(self): someList = self._someList someList += "X" return someList test = tester() But guess what, every call adds to the variable that I am trying to copy each time: test() > [0, 1, 'X'] test() > [0, 1, 'X', 'X'] Can someone explain this behavior? And how to prevent a classwide constant from ever getting changed? -- Gnarlie From clp2 at rebertia.com Sat Oct 22 20:41:23 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 22 Oct 2011 17:41:23 -0700 Subject: How to isolate a constant? In-Reply-To: References: Message-ID: On Sat, Oct 22, 2011 at 5:26 PM, Gnarlodious wrote: > Say this: > > class tester(): Style note: either have it explicitly subclass `object`, or don't include the parens at all. Empty parens for the superclasses is just weird. > ? ? ? ?_someList = [0, 1] > ? ? ? ?def __call__(self): > ? ? ? ? ? ? ? ?someList = self._someList > ? ? ? ? ? ? ? ?someList += "X" > ? ? ? ? ? ? ? ?return someList > > test = tester() > > But guess what, every call adds to the variable that I am trying to > copy each time: > test() >> [0, 1, 'X'] > test() >> [0, 1, 'X', 'X'] > > > Can someone explain this behavior? The line `someList = self._someList` does NOT copy the list. It make `someList` point to the same existing list object. Hence, modifications to that object from either variable will affect the other. Similarly, `someList += "X"` modifies someList *in-place*; it does not produce a new list object. The upshot is that you're just modifying and returning references to *the same list* repeatedly, never producing a new list object. > And how to prevent a classwide > constant from ever getting changed? Python doesn't have any language-enforced notion of constants. So, short of writing/using a library to try and enforce such a notion, you're out of luck. You could use an immutable datatype (e.g. a tuple) instead of a mutable one (e.g. a list) as some level of safeguard though. Cheers, Chris -- http://rebertia.com From python at mrabarnett.plus.com Sat Oct 22 20:46:55 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 23 Oct 2011 01:46:55 +0100 Subject: How to isolate a constant? In-Reply-To: References: Message-ID: <4EA363FF.4070803@mrabarnett.plus.com> On 23/10/2011 01:26, Gnarlodious wrote: > Say this: > > class tester(): > _someList = [0, 1] > def __call__(self): > someList = self._someList > someList += "X" > return someList > > test = tester() > > But guess what, every call adds to the variable that I am trying to > copy each time: > test() >> [0, 1, 'X'] > test() >> [0, 1, 'X', 'X'] > > > Can someone explain this behavior? And how to prevent a classwide > constant from ever getting changed? > '_someList' is part of the class itself. This: someList = self._someList just creates a new _reference to the list and this: someList += "X" appends the items of the sequence "X" to the list. Note that a string is also a sequence of characters, so: >>> x = [] >>> x += "XY" >>> x ['X', 'Y'] Python will copy something only when you tell it to copy. A simple way of copying a list is to slice it: someList = self._someList[:] From gnarlodious at gmail.com Sat Oct 22 21:01:52 2011 From: gnarlodious at gmail.com (Gnarlodious) Date: Sat, 22 Oct 2011 18:01:52 -0700 (PDT) Subject: How to isolate a constant? References: Message-ID: <7840d89c-3648-45fe-ae6f-d3bb2ca2abdb@z28g2000pro.googlegroups.com> On Oct 22, 6:41?pm, Chris Rebert wrote: > The line `someList = self._someList` does NOT copy the list. It make > `someList` point to the same existing list object. Thanks for all those explanations, I've already fixed it with a tuple. Which is more reliable anyway. -- Gnarlie From lchaplin13 at gmail.com Sun Oct 23 00:09:04 2011 From: lchaplin13 at gmail.com (Lee) Date: Sat, 22 Oct 2011 21:09:04 -0700 (PDT) Subject: Exception Handling (C - extending python) Message-ID: Hi all, Where does PyExc_TypeError (and alike) points to? I can see its declaration - PyAPI_DATA(PyObject *) PyExc_TypeError; - in pyerrors.h but I cannot figure out what it is its value, where it is initialized. Any help is greatly appreciated. Lee From rustompmody at gmail.com Sun Oct 23 01:08:31 2011 From: rustompmody at gmail.com (rusi) Date: Sat, 22 Oct 2011 22:08:31 -0700 (PDT) Subject: compare range objects References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> <453d196e-4516-47f3-9d33-caea70d33a8f@l12g2000vby.googlegroups.com> <4ea2557c$0$29968$c3e8da3$5496439d@news.astraweb.com> <57fe18d1-b66c-4b8c-bb83-a8994498d2cf@u13g2000vbx.googlegroups.com> Message-ID: <019dd721-055c-4aa3-aa03-6c355c2b3e18@k13g2000prg.googlegroups.com> On Oct 22, 10:51?pm, SigmundV wrote: > On Oct 22, 6:32?am, Steven D'Aprano > +comp.lang.pyt... at pearwood.info> wrote: > > > Sure. But the downside of sets is that, like lists, they are not lazy, > > Thank you for pointing this out. I agree that it's not a viable > alternative for large domains. Storing the bounds and the resolution > should be enough. > > /Sigmund This kind of question is a nontrivial research issue -- dealt with for example in the polyhedral language alpha: http://www.irisa.fr/cosi/Rajopadhye/dag-talk.ps From dihedral88888 at googlemail.com Sun Oct 23 01:12:16 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Sat, 22 Oct 2011 22:12:16 -0700 (PDT) Subject: How to isolate a constant? In-Reply-To: <7840d89c-3648-45fe-ae6f-d3bb2ca2abdb@z28g2000pro.googlegroups.com> References: <7840d89c-3648-45fe-ae6f-d3bb2ca2abdb@z28g2000pro.googlegroups.com> Message-ID: <12317784.900.1319346736804.JavaMail.geo-discussion-forums@prfk19> Thank you for the good trick for a static class owned property. Someone might object this but this is really useful. From steve+comp.lang.python at pearwood.info Sun Oct 23 01:32:56 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 23 Oct 2011 05:32:56 GMT Subject: How to isolate a constant? References: <7840d89c-3648-45fe-ae6f-d3bb2ca2abdb@z28g2000pro.googlegroups.com> Message-ID: <4ea3a707$0$29968$c3e8da3$5496439d@news.astraweb.com> On Sat, 22 Oct 2011 18:01:52 -0700, Gnarlodious wrote: > On Oct 22, 6:41?pm, Chris Rebert wrote: > >> The line `someList = self._someList` does NOT copy the list. It make >> `someList` point to the same existing list object. > Thanks for all those explanations, I've already fixed it with a tuple. > Which is more reliable anyway. No, tuples are not "more reliable" than lists. Don't make the mistake of confusing your inexperience and lack of understanding about Python's object model for "lists are unreliable". They are completely reliable. You just have to learn how they work, and not make invalid assumptions about how they work. You wouldn't say "Nails are more reliable than screws, because I hammered a screw into a plaster wall and it just fell out." Of course it fell out: you used it incorrectly for what you needed. -- Steven From stefan_ml at behnel.de Sun Oct 23 05:06:54 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 23 Oct 2011 11:06:54 +0200 Subject: Exception Handling (C - extending python) In-Reply-To: References: Message-ID: Lee, 23.10.2011 06:09: > Where does PyExc_TypeError (and alike) points to? I can see its > declaration - PyAPI_DATA(PyObject *) PyExc_TypeError; - in pyerrors.h > but I cannot figure out what it is its value, where it is > initialized. It gets initialised inside of the interpreter core and then points to a Python object. > Any help is greatly appreciated. The question is: why do you ask? What exactly do you want to do? If you ask a more targeted question, you will get an answer that will help you further. Stefan From apometron.listas.cinco at gmail.com Sun Oct 23 06:03:54 2011 From: apometron.listas.cinco at gmail.com (apometron) Date: Sun, 23 Oct 2011 08:03:54 -0200 Subject: What is wrong with my code? Message-ID: <4EA3E68A.5010301@gmail.com> import os nome = sys.argv[1] final = nome for i in nome: print i if nome[i] = "_": final[i] = " " os.rename(nome, final) From clp2 at rebertia.com Sun Oct 23 06:08:33 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Oct 2011 03:08:33 -0700 Subject: What is wrong with my code? In-Reply-To: <4EA3E68A.5010301@gmail.com> References: <4EA3E68A.5010301@gmail.com> Message-ID: On Sun, Oct 23, 2011 at 3:03 AM, apometron wrote: > import os > nome = sys.argv[1] You did not `import sys`, so you'll get a NameError there. > final = nome > for i in nome: > ? ?print i > ? ?if nome[i] = "_": > ? ? ? ?final[i] = " " Strings aren't mutable in Python; you can't assign to slices of them. So you'll get a TypeError on the previous line. Cheers, Chris From paul.nospam at rudin.co.uk Sun Oct 23 06:23:38 2011 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Sun, 23 Oct 2011 11:23:38 +0100 Subject: How to isolate a constant? References: <7840d89c-3648-45fe-ae6f-d3bb2ca2abdb@z28g2000pro.googlegroups.com> Message-ID: <87y5wcj9at.fsf@no-fixed-abode.cable.virginmedia.net> Gnarlodious writes: > Thanks for all those explanations, I've already fixed it with a tuple. > Which is more reliable anyway. neither of lists or tuples are "more reliable" than the other. They both have perfectly well defined behaviour (which can be gleaned from reading the documentation) and reliably behave as documented. You just have to choose which fits better for the computation you're trying to implement. From lchaplin13 at gmail.com Sun Oct 23 07:32:00 2011 From: lchaplin13 at gmail.com (Lee) Date: Sun, 23 Oct 2011 04:32:00 -0700 (PDT) Subject: Exception Handling (C - extending python) References: Message-ID: <75930aea-ed09-44f8-b7ca-0fa9f72e6b12@g27g2000pro.googlegroups.com> Thanks Stefan, I am just interested to understand the mechanism inside python. If it points to an object that means I can defered it (through ob_type). >From there, how a function like PyErr_SetString knows what exception is? Where its value is kept? Lee On Oct 23, 10:06?pm, Stefan Behnel wrote: > Lee, 23.10.2011 06:09: > > > Where does PyExc_TypeError (and alike) points to? I can see its > > declaration - PyAPI_DATA(PyObject *) PyExc_TypeError; - in pyerrors.h > > but I cannot figure out what it is its value, where it is > > initialized. > > It gets initialised inside of the interpreter core and then points to a > Python object. > > > Any help is greatly appreciated. > > The question is: why do you ask? What exactly do you want to do? > > If you ask a more targeted question, you will get an answer that will help > you further. > > Stefan From darragh.ssa at gmail.com Sun Oct 23 07:38:54 2011 From: darragh.ssa at gmail.com (Kruptein) Date: Sun, 23 Oct 2011 04:38:54 -0700 (PDT) Subject: Deditor 0.3.1 Message-ID: <8d82dee9-7aa8-4e07-84e3-c81019bd4eeb@f36g2000vbm.googlegroups.com> Hey, I'm happy to announce a new release of Deditor version 0.3.1. What is Deditor? Deditor is a pythonic text-editor, written 100% in python and with the primary goal to ease python development. There is a python shell, codecompletion, code analyzing, instant code running and error checking and lots more. (Other languages are ofcourse also supported for syntax highlighting but don't have the other features) Deditor uses a very good plugin system DPlug which makes it easy to use a combination of plugins like a projects plugin to manage files, a network plugin to up-download stuff,... What's new in this version? The Projects plugin has been totally rewritten and is now a very usefull plugin which makes developing much easier if you have to work at multiple projects in short periods. Note that the network plugin is going to be totally rewritten for next release and is thus not that good atm, nevertheless enjoy! Download .deb/.tar.gz http://launchpad.net/deditor Download ppa: ppa:darragh-ssa/deditor and sudo apt-get install deditor Note: ppa is still in building proces but should be finished this afternoon pictures/videos of the new version are still in progress of creation but here is a short snapshot https://lh6.googleusercontent.com/-oopTygoo6o4/TqCwLY4EoRI/AAAAAAAAAbw/19J1jDq4yIU/deditor_project_0.3.1.png From lists at cheimes.de Sun Oct 23 08:12:18 2011 From: lists at cheimes.de (Christian Heimes) Date: Sun, 23 Oct 2011 14:12:18 +0200 Subject: Exception Handling (C - extending python) In-Reply-To: References: Message-ID: Am 23.10.2011 06:09, schrieb Lee: > Hi all, > > Where does PyExc_TypeError (and alike) points to? I can see its > declaration - PyAPI_DATA(PyObject *) PyExc_TypeError; - in pyerrors.h > but I cannot figure out what it is its value, where it is > initialized. It's initialized in Objects/exceptions.c SimpleExtendsException(PyExc_StandardError, TypeError, "Inappropriate argument type."); SimpleExtendsException() is a macro that defines a PyTypeObject and stores a cast to PyObject in PyExc_TypeError. Christian From stefan_ml at behnel.de Sun Oct 23 08:41:05 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 23 Oct 2011 14:41:05 +0200 Subject: Exception Handling (C - extending python) In-Reply-To: <75930aea-ed09-44f8-b7ca-0fa9f72e6b12@g27g2000pro.googlegroups.com> References: <75930aea-ed09-44f8-b7ca-0fa9f72e6b12@g27g2000pro.googlegroups.com> Message-ID: Hi, note that I reformatted your posting to get the replies back into order. Lee, 23.10.2011 13:32: > On Oct 23, 10:06 pm, Stefan Behnel wrote: >> Lee, 23.10.2011 06:09: >>> Where does PyExc_TypeError (and alike) points to? I can see its >>> declaration - PyAPI_DATA(PyObject *) PyExc_TypeError; - in pyerrors.h >>> but I cannot figure out what it is its value, where it is >>> initialized. >> >> It gets initialised inside of the interpreter core and then points to a >> Python object. > > If it points to an object that means I can defered it (through > ob_type). That will give you the "type" object, because PyExc_TypeError points to the type "TypeError". Note that types are also objects in Python. > From there, how a function like PyErr_SetString knows what exception > is? The type object that you pass in must inherit from the BaseException type. You can read the code in Python/errors.c, function PyErr_SetObject(). >>> Any help is greatly appreciated. >> >> The question is: why do you ask? What exactly do you want to do? >> >> If you ask a more targeted question, you will get an answer that will help >> you further. > > I am just interested to understand the mechanism inside python. That's just fine. If you are interested in the inner mechanics of the CPython runtime, reading the source is a very good way to start getting involved with the project. However, many extension module authors don't care about these inner mechanics and just use Cython instead. That keeps them from having to learn the C-API of CPython, and from tying their code too deeply into the CPython runtime itself. Stefan From 1248283536 at qq.com Sun Oct 23 09:15:08 2011 From: 1248283536 at qq.com (=?gbk?B?y66+ssH3ye4=?=) Date: Sun, 23 Oct 2011 21:15:08 +0800 Subject: python32 to write file Message-ID: code 1 can run in python2.6 #coding:utf-8 import urllib import lxml.html down='http://frux.wikispaces.com/' root=urllib.urlopen(down).read() root=lxml.html.fromstring(root) file=root.xpath('//a') for i in file: str1=i.text_content() if str1.find('pdf') >-1 : str2='http://frux.wikispaces.com/file/view/'+str1 myfile=urllib.urlopen(str2).read() book=open('/tmp/'+str1,'w') book.write(myfile) book.close() i usr command : 2to3-3.2 ~/xml.py -w to get code2 #coding:utf-8 import urllib.request, urllib.parse, urllib.error import lxml.html down='http://frux.wikispaces.com/' root=urllib.request.urlopen(down).read() root=lxml.html.fromstring(root) file=root.xpath('//a') for i in file: str1=i.text_content() if str1.find('pdf') >-1 : str2='http://frux.wikispaces.com/file/view/'+str1 myfile=urllib.request.urlopen(str2).read() book=open('c:\'+str1,'w') # i change it book.write(myfile) book.close() when i run it in python32,the output is : book=open('c:\'+str1,'w') invalid syntax,what is wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Oct 23 09:48:31 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Oct 2011 06:48:31 -0700 Subject: python32 to write file In-Reply-To: References: Message-ID: 2011/10/23 ???? <1248283536 at qq.com>: > ????? ? book=open('c:\'+str1,'w')? #? i? change it > when i run it? in? python32,the output is? : > book=open('c:\'+str1,'w') > invalid? syntax,what is wrong? Your problem is not at all Python 3-specific. Backslashes are used for escape sequences in string literals (e.g. "\n" is newline, "\t" is tab). For example, the string "c:\new\tally" contains both a newline and a tab, but not an N, nor a T, nor any backslashes (a literal backslash is written using the escape sequence "\\"; i.e. two backslashes). Similarly, "\'" is an escape sequence for apostrophe, and thus does not terminate the string literal, leading to a not entirely obvious SyntaxError. Use forward slashes (/) instead; Windows accepts them instead of backslashes as directory separators in path strings, and they have no such escaping issues. Cheers, Chris -- Damn you, CP/M! http://rebertia.com From 1248283536 at qq.com Sun Oct 23 09:59:19 2011 From: 1248283536 at qq.com (=?gbk?B?y66+ssH3ye4=?=) Date: Sun, 23 Oct 2011 21:59:19 +0800 Subject: =?gbk?B?u9i4tKO6IHB5dGhvbjMyIHRvIHdyaXRlIGZpbGU=?= Message-ID: i change my code into : import urllib.request, urllib.parse, urllib.error import lxml.html down='http://frux.wikispaces.com/' root=urllib.request.urlopen(down).read() root=lxml.html.fromstring(root) file=root.xpath('//a') for i in file: str1=i.text_content() if str1.find('pdf') >-1 : str2='http://frux.wikispaces.com/file/view/'+str1 myfile=urllib.request.urlopen(str2).read() book=open('c:/'+str1,'w') book.write(myfile) book.close() the new problem is : C:\Python32>python c:\xml.py Traceback (most recent call last): File "c:\xml.py", line 5, in root=lxml.html.fromstring(root) File "C:\Python32\lib\site-packages\lxml\html\__init__.py", line 630, in froms tring if start.startswith('; ????: 2011?10?23?(???) ??9:48 ???: "????"<1248283536 at qq.com>; ??: "python-list"; ??: Re: python32 to write file 2011/10/23 ???? <1248283536 at qq.com>: > book=open('c:\'+str1,'w') # i change it > when i run it in python32,the output is : > book=open('c:\'+str1,'w') > invalid syntax,what is wrong? Your problem is not at all Python 3-specific. Backslashes are used for escape sequences in string literals (e.g. "\n" is newline, "\t" is tab). For example, the string "c:\new\tally" contains both a newline and a tab, but not an N, nor a T, nor any backslashes (a literal backslash is written using the escape sequence "\\"; i.e. two backslashes). Similarly, "\'" is an escape sequence for apostrophe, and thus does not terminate the string literal, leading to a not entirely obvious SyntaxError. Use forward slashes (/) instead; Windows accepts them instead of backslashes as directory separators in path strings, and they have no such escaping issues. Cheers, Chris -- Damn you, CP/M! http://rebertia.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolftracks at invalid.com Sun Oct 23 10:57:02 2011 From: wolftracks at invalid.com (W. eWatson) Date: Sun, 23 Oct 2011 07:57:02 -0700 Subject: File Association for Python on XP Message-ID: Last night I thought I'd install Python on a friend's XP PC. I noticed he had declined to show extensions on any file. I thought the Control Panel might be the way to do it. I couldn't find anything that would do all files, doc, txt, py, etc. I was able to do it, I think, from a right-click on a py file. However, when I then clicked on the file, it seemed like the IDE was not going to come up. Instead it looked like it was headed directly for interpreter. His computer is quite slow. We went on to something else. Python doesn't yet need that much attention. So what should I have done, and how do I undo what I did? From mdanakodi16 at yahoo.com Sun Oct 23 11:48:11 2011 From: mdanakodi16 at yahoo.com (mdanakodi16 at yahoo.com) Date: Sun, 23 Oct 2011 08:48:11 -0700 (PDT) Subject: See Hot Sexy Star *Angelina Jolie* Nude Bathing Videos In All Angles Message-ID: See Hot Sexy Star *Angelina Jolie* Nude Bathing Videos In All Angles At http://angelina-health.co.cc Due to high sex content, i have hidden the videos in an image. in that website on Right side below search box click on image and watch videos in all angles. From mdanakodi16 at yahoo.com Sun Oct 23 11:49:46 2011 From: mdanakodi16 at yahoo.com (mdanakodi16 at yahoo.com) Date: Sun, 23 Oct 2011 08:49:46 -0700 (PDT) Subject: See Hot Sexy Star *Angelina Jolie* Nude Bathing Videos In All Angles Message-ID: See Hot Sexy Star *Angelina Jolie* Nude Bathing Videos In All Angles At http://angelina-health.co.cc Due to high sex content, i have hidden the videos in an image. in that website on Right side below search box click on image and watch videos in all angles. From ivo at webcrowd.net Sun Oct 23 11:50:54 2011 From: ivo at webcrowd.net (webcrowd.net) Date: Sun, 23 Oct 2011 17:50:54 +0200 Subject: Job Offer: 3 Python Backend Developer and other Positions in Berlin Message-ID: Hi Folks, hope it is okay to post job offers here. If not sorry for the spam and please let me know! One of our clients is looking for new and talented people to join their international, seven people strong, developers team in the heart of Berlin. You will join an awesome, nice and humble startup and you can enjoy the coffee and smoothie flatrate whilst playing a quick round of foosball in between. The team is working with Scrum and TDD so everybody stays involved and English is the language of choice. Furthermore they go out for a beer now and then and the company can even provide you with housing for the first couple of weeks in Berlin. Excited? Here are the job details: // Python Backend Developer You speak Python whilst dreaming and you do have experience with Django or RoR? You are not afraid of Javascript, HTML, CSS nor unit or functional testing (cucumber, lettuce) and github is your source codes living room? // Java Backend Developer You?ve worked on a professional Java (J2EE, J2SE 5/6) application at least for two years and you liked Spring and Hibernate on Facebook? Even the following technologies: Lucenel Solr, Tomcat, JBoss and GIT don?t make you sweat? // Technical QA Manager You mainly discuss about object oriented programming concepts with your friends? xUnit, TDD, BDD in combination with Scrum and XP raise your heartbeat? You call Ubuntu, Nginx, PostgreSQL as well as Python, Django and GIT your daily bread? // Frontend Developer (Javascript) You are a talent with Javascript in general and particularly with jQuery, Require.js and Backbone.js? You do testing and object orientated coding by heart and the user experience always comes in the first place for you? If so, request more details and apply: Tweet @webcrowdnet or email at hello at webcrowd.net or just reply here for further information. From mcepl at redhat.com Sun Oct 23 12:05:30 2011 From: mcepl at redhat.com (Matej Cepl) Date: Sun, 23 Oct 2011 18:05:30 +0200 Subject: help In-Reply-To: <4ea2db17$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <9f8pa1Fsh8U3@mid.individual.net> <4ea2db17$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: Dne 22.10.2011 17:02, Steven D'Aprano napsal(a): > Rather than assume malice, we should give X1 the benefit of the doubt and > assume he genuinely believed what he wrote but was merely mistaken. Sure, I didn't want to assume malice (sorry, English is my second language and sometimes it shows; would "libel" or "slander" fit the bill better?). I just wanted to slip in the information about repoquery which is an awesome tool, but not many people know about it. Mat?j From fraveydank at gmail.com Sun Oct 23 12:34:50 2011 From: fraveydank at gmail.com (David Riley) Date: Sun, 23 Oct 2011 12:34:50 -0400 Subject: help In-Reply-To: References: <9f8pa1Fsh8U3@mid.individual.net> <4ea2db17$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5ED19ED7-D7DC-4094-A685-BB1FB42D09F1@gmail.com> "Libel" and "slander" also generally indicate malice. Perhaps just "That's incorrect" might have come off a little less harsh. :-) - Dave On Oct 23, 2011, at 12:05 PM, Matej Cepl wrote: > Dne 22.10.2011 17:02, Steven D'Aprano napsal(a): >> Rather than assume malice, we should give X1 the benefit of the doubt and >> assume he genuinely believed what he wrote but was merely mistaken. > > Sure, I didn't want to assume malice (sorry, English is my second language and sometimes it shows; would "libel" or "slander" fit the bill better?). I just wanted to slip in the information about repoquery which is an awesome tool, but not many people know about it. > > Mat?j > -- > http://mail.python.org/mailman/listinfo/python-list From python at mrabarnett.plus.com Sun Oct 23 12:41:39 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 23 Oct 2011 17:41:39 +0100 Subject: File Association for Python on XP In-Reply-To: References: Message-ID: <4EA443C3.7050308@mrabarnett.plus.com> On 23/10/2011 15:57, W. eWatson wrote: > Last night I thought I'd install Python on a friend's XP PC. I noticed > he had declined to show extensions on any file. I thought the Control > Panel might be the way to do it. I couldn't find anything that would do > all files, doc, txt, py, etc. > > I was able to do it, I think, from a right-click on a py file. However, > when I then clicked on the file, it seemed like the IDE was not going to > come up. Instead it looked like it was headed directly for interpreter. > His computer is quite slow. We went on to something else. Python doesn't > yet need that much attention. > > So what should I have done, and how do I undo what I did? To show the extensions, in an Explorer window go to Tools->Folder Options... and look in the View tab. You can also look at the file associations in the File Types tab. From gherron at islandtraining.com Sun Oct 23 13:04:45 2011 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 23 Oct 2011 10:04:45 -0700 Subject: What is wrong with my code? In-Reply-To: References: <4EA3E68A.5010301@gmail.com> Message-ID: <4EA4492D.5080405@islandtraining.com> On 10/23/2011 03:08 AM, Chris Rebert wrote: > On Sun, Oct 23, 2011 at 3:03 AM, apometron > wrote: >> import os >> nome = sys.argv[1] > You did not `import sys`, so you'll get a NameError there. > >> final = nome >> for i in nome: >> print i >> if nome[i] = "_": >> final[i] = " " > Strings aren't mutable in Python; you can't assign to slices of them. > So you'll get a TypeError on the previous line. > > Cheers, > Chris Also, the statement for i in nome: does not loop through indices, but rather it loops through the actual characters of the string. Gary Herron From wolftracks at invalid.com Sun Oct 23 13:24:44 2011 From: wolftracks at invalid.com (W. eWatson) Date: Sun, 23 Oct 2011 10:24:44 -0700 Subject: File Association for Python on XP In-Reply-To: References: Message-ID: On 10/23/2011 9:41 AM, MRAB wrote: > To show the extensions, in an Explorer window go to Tools->Folder > Options... and look in the View tab. You can also look at the file > associations in the File Types tab. Thanks. From roy at panix.com Sun Oct 23 13:37:40 2011 From: roy at panix.com (Roy Smith) Date: Sun, 23 Oct 2011 13:37:40 -0400 Subject: argparse.ArgumentParser("blah") Message-ID: As I read the docs (http://tinyurl.com/3ww9scr), the following two calls should result in the same object: parser = argparse.ArgumentParser(description="blah") parser = argparse.ArgumentParser("blah") In the first case, I'm explicitly setting description to "blah", in the second case, I'm passing "blah" as a positional parameter so it should be taken as first parameter to the function, which happens to be description. Either way should end up the same. I don't, however, get the same behavior when run with "-h". The first gives what I would expect: ------------------------------------------------ usage: arg.py [-h] blah optional arguments: -h, --help show this help message and exit ------------------------------------------------ and the second gives: ------------------------------------------------ usage: blah [-h] optional arguments: -h, --help show this help message and exit ------------------------------------------------ Is this a bug, or am I just not reading the docs right? From __peter__ at web.de Sun Oct 23 14:06:14 2011 From: __peter__ at web.de (Peter Otten) Date: Sun, 23 Oct 2011 20:06:14 +0200 Subject: argparse.ArgumentParser("blah") References: Message-ID: Roy Smith wrote: > As I read the docs (http://tinyurl.com/3ww9scr), the following two calls > should result in the same object: > > parser = argparse.ArgumentParser(description="blah") > parser = argparse.ArgumentParser("blah") > > In the first case, I'm explicitly setting description to "blah", in the > second case, I'm passing "blah" as a positional parameter so it should > be taken as first parameter to the function, which happens to be > description. Either way should end up the same. > > I don't, however, get the same behavior when run with "-h". The first > gives what I would expect: > > ------------------------------------------------ > usage: arg.py [-h] > > blah > > optional arguments: > -h, --help show this help message and exit > ------------------------------------------------ > > and the second gives: > > ------------------------------------------------ > usage: blah [-h] > > optional arguments: > -h, --help show this help message and exit > ------------------------------------------------ > > Is this a bug, or am I just not reading the docs right? A quick look into the source code reveals the the documentation is not consistent with the actual implementation: http://hg.python.org/cpython/file/eef1027ab2f0/Lib/argparse.py#l1581 """ class ArgumentParser(_AttributeHolder, _ActionsContainer): [...] def __init__(self, prog=None, usage=None, description=None, epilog=None, version=None, parents=[], formatter_class=HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True): """ I suggest that you file a bug report. PS: My guess is that you are supposed to use keyword parameters only, but that the implementation doesn't enforce that (yet?). From wm at localhost.localdomain Sun Oct 23 14:25:34 2011 From: wm at localhost.localdomain (Waldek M.) Date: Sun, 23 Oct 2011 20:25:34 +0200 Subject: Job Offer: 3 Python Backend Developer and other Positions in Berlin References: Message-ID: <1b9shmovw2l6m$.dlg@localhost.localdomain> On Sun, 23 Oct 2011 17:50:54 +0200, webcrowd.net wrote: > hope it is okay to post job offers here. If not sorry for the spam and > please let me know! Not really. It's a newsgroup on Python *language*, not on Python-everything. You might want to post here instead, though: http://www.python.org/community/jobs/ Best regards, Waldek From roy at panix.com Sun Oct 23 14:33:50 2011 From: roy at panix.com (Roy Smith) Date: Sun, 23 Oct 2011 14:33:50 -0400 Subject: argparse.ArgumentParser("blah") References: Message-ID: In article , Roy Smith wrote: > As I read the docs (http://tinyurl.com/3ww9scr), the following two calls > should result in the same object: > > parser = argparse.ArgumentParser(description="blah") > parser = argparse.ArgumentParser("blah") Sigh. I should have dug deeper before posting. The docs don't match the code (they list the arguments in different orders). I've opened http://bugs.python.org/issue13249 on this. From tjreedy at udel.edu Sun Oct 23 14:50:54 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 23 Oct 2011 14:50:54 -0400 Subject: argparse.ArgumentParser("blah") In-Reply-To: References: Message-ID: On 10/23/2011 2:06 PM, Peter Otten wrote: > Roy Smith wrote: > >> As I read the docs (http://tinyurl.com/3ww9scr), the following two calls >> should result in the same object: >> >> parser = argparse.ArgumentParser(description="blah") >> parser = argparse.ArgumentParser("blah") >> >> In the first case, I'm explicitly setting description to "blah", in the >> second case, I'm passing "blah" as a positional parameter so it should >> be taken as first parameter to the function, which happens to be >> description. Either way should end up the same. >> >> I don't, however, get the same behavior when run with "-h". The first >> gives what I would expect: >> >> ------------------------------------------------ >> usage: arg.py [-h] >> >> blah >> >> optional arguments: >> -h, --help show this help message and exit >> ------------------------------------------------ >> >> and the second gives: >> >> ------------------------------------------------ >> usage: blah [-h] >> >> optional arguments: >> -h, --help show this help message and exit >> ------------------------------------------------ >> >> Is this a bug, or am I just not reading the docs right? > > A quick look into the source code reveals the the documentation is not > consistent with the actual implementation: > > http://hg.python.org/cpython/file/eef1027ab2f0/Lib/argparse.py#l1581 > > """ > class ArgumentParser(_AttributeHolder, _ActionsContainer): > [...] > def __init__(self, > prog=None, > usage=None, > description=None, > epilog=None, > version=None, > parents=[], > formatter_class=HelpFormatter, > prefix_chars='-', > fromfile_prefix_chars=None, > argument_default=None, > conflict_handler='error', > add_help=True): > """ I would call this a doc bug. The explanation of the parameters is in a different order yet. That should be changed too. help(ArgumentParser) gives them in the actual order. > I suggest that you file a bug report. > > PS: My guess is that you are supposed to use keyword parameters only, Parameters are just names local to the function. They are matched to argument objects by position or keyword, unless positional matching is disabled with the '*,' syntax, or unless the function is 'builtin' and keyword matching is not enabled. > but that the implementation doesn't enforce that (yet?). This would be an easy change in that adding '*, ' after 'self, ' in the parameter list would do it. It would be difficult in that it could break code that uses positional matching correctly, as given in the help message, and there is no way I know of to give a deprecation message. But there might be very little code that does so, given the mis-documentation in the manual. -- Terry Jan Reedy From tjreedy at udel.edu Sun Oct 23 15:52:28 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 23 Oct 2011 15:52:28 -0400 Subject: =?UTF-8?B?5Zue5aSN77yaIHB5dGhvbjMyIHRvIHdyaXRlIGZpbGU=?= In-Reply-To: References: Message-ID: On 10/23/2011 9:59 AM, ???? wrote: > i change my code into : Calling your file xml.py (as indicated below) is a potentially bad idea since the Python stdlib has a package named 'xml'. If you write 'import xml.xxx' in another file in the same directory, Python will try to find 'xxx' in your xml.py file. > import urllib.request, urllib.parse, urllib.error > import lxml.html Are you sure you have a version of lxml that works with Python 3? > down='http://frux.wikispaces.com/' > root=urllib.request.urlopen(down).read() What type of object is returned and bound to root? (print(type(root)) if doc not clear.) > root=lxml.html.fromstring(root) What type of object is root required to be (from lxml docs)? [snip] > the new problem is : > > C:\Python32>python c:\xml.py > Traceback (most recent call last): > File "c:\xml.py", line 5, in > root=lxml.html.fromstring(root) > File "C:\Python32\lib\site-packages\lxml\html\__init__.py", line 630, in > fromstring > if start.startswith(' TypeError: startswith first arg must be bytes or a tuple of bytes, not str This implies that the name 'start' is bound to bytes when it should be (for 3.2) bound to unicode, which would most likely mean that 'root' is the wrong type. Or that the above is the 2.x version of lxml where ' <75930aea-ed09-44f8-b7ca-0fa9f72e6b12@g27g2000pro.googlegroups.com> Message-ID: <14d4f626-0791-4608-aee3-fe29016cd593@p20g2000prm.googlegroups.com> For a moment, back to the basics... I am using the example provided by docs at 2.1.2 "Providing finer control...". Using say: mynoddy = noddy2.Noddy() mynoddy.first = "a" mynoddy.last = 0 the last line causes an ugly crash (on python 2.6.5 on winxp). No way to catch the exception. As I understand from the docs, all PyErr_SetString does is to set an exception, what one has to do to raise this exception (in C)? If I replace "return -1" in the Noddy_setlast() function with "return NULL" (well, the compiler will complain...) the program passes by without raising an exception. Any explanations?... Lee From d at davea.name Sun Oct 23 18:56:34 2011 From: d at davea.name (Dave Angel) Date: Sun, 23 Oct 2011 18:56:34 -0400 Subject: What is wrong with my code? In-Reply-To: <4EA3E68A.5010301@gmail.com> References: <4EA3E68A.5010301@gmail.com> Message-ID: <4EA49BA2.6080309@davea.name> On 10/23/2011 06:03 AM, apometron wrote: > import os > nome = sys.argv[1] > final = nome > for i in nome: > print i > if nome[i] = "_": > final[i] = " " > os.rename(nome, final) > What do you want to be wrong with it? There are so many things, it'd be fun to try to see who could come up with the most. 1) it's not a valid Fortran program. 2) it's missing a shebang line if we assume it's for Windows, or that you run it with an explicit bash line 3) if we pretend it's a python program, a few more 3a) It has a syntax error calling the print() function. (Python 3.2) If we assume it's a python 2.x program 4) it uses sys, without importing it 5) it uses second argument without checking if the user typed such an argument 6) it tries to change a character within a string, which is a non-mutable type 7) It creates two more references to the same string sys.argv[1], then tries to modify one of them, not realizing the others would change to. 8) it tries to subscript a string using a character. 9) it calls rename with two references to the same object. So nothing will ever actually happen, even if the other problems were fixed. Generally, you'll get the best answers here if you specify more of your environment (python version, OS), show what you tried (pasted from the command line), and the results you got (such as stack traces). HTH DaveA -- DaveA From skippy.hammond at gmail.com Sun Oct 23 19:42:23 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Mon, 24 Oct 2011 10:42:23 +1100 Subject: logging: warn() methods and function to be deprecated. In-Reply-To: References: Message-ID: <4EA4A65F.2090205@gmail.com> On 22/10/2011 11:09 PM, Vinay Sajip wrote: > In response to an issue (#13235) raised on the Python bug tracker, I'm going to > deprecate the warn() methods in the Logger and LoggerAdapter classes in the > stdlib logging package, as well the module-level warn() function. > > The warn() variants were synonyms for the warning() methods and function, and a > holdover from before the time that logging was added to Python.They were not > documented; it's probably time to retire them, so I've added a > DeprecationWarning to appear in 3.3, and they'll be completely removed in 3.4 > (along with the WARN synonym for WARNING). With this change, all the logging > levels are adjectives which apply to the logged message: DEBUG, INFO, WARNING, > ERROR and CRITICAL. > > I don't believe the WARN/warn variants were used much, if at all - but this is > just a heads up for anyone who might have used them. I think that is a real shame - it seems to be gratuitous breakage for almost zero benefit. That issue shows that Trac makes heavy use of .warn, I've use .warn almost exclusively for many years, and code.google.com shows it is used extensively in the wild. Is there still a chance to reconsider? Mark From 1248283536 at qq.com Sun Oct 23 21:06:12 2011 From: 1248283536 at qq.com (=?gbk?B?y66+ssH3ye4=?=) Date: Mon, 24 Oct 2011 09:06:12 +0800 Subject: getroot() problem Message-ID: C:\Documents and Settings\peng>cd c:\python32 C:\Python32>python Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> import lxml.html >>> sfile='http://finance.yahoo.com/q/op?s=A+Options' >>> root=lxml.html.parse(sfile).getroot() there is no problem to parse : http://finance.yahoo.com/q/op?s=A+Options' why i can not parse http://frux.wikispaces.com/ ?? >>> import lxml.html >>> sfile='http://frux.wikispaces.com/' >>> root=lxml.html.parse(sfile).getroot() Traceback (most recent call last): File "", line 1, in File "C:\Python32\lib\site-packages\lxml\html\__init__.py", line 692, in parse return etree.parse(filename_or_url, parser, base_url=base_url, **kw) File "lxml.etree.pyx", line 2942, in lxml.etree.parse (src/lxml/lxml.etree.c:5 4187) File "parser.pxi", line 1528, in lxml.etree._parseDocument (src/lxml/lxml.etre e.c:79485) File "parser.pxi", line 1557, in lxml.etree._parseDocumentFromURL (src/lxml/lx ml.etree.c:79768) File "parser.pxi", line 1457, in lxml.etree._parseDocFromFile (src/lxml/lxml.e tree.c:78843) File "parser.pxi", line 997, in lxml.etree._BaseParser._parseDocFromFile (src/ lxml/lxml.etree.c:75698) File "parser.pxi", line 564, in lxml.etree._ParserContext._handleParseResultDo c (src/lxml/lxml.etree.c:71739) File "parser.pxi", line 645, in lxml.etree._handleParseResult (src/lxml/lxml.e tree.c:72614) File "parser.pxi", line 583, in lxml.etree._raiseParseError (src/lxml/lxml.etr ee.c:71927) IOError: Error reading file 'b'http://frux.wikispaces.com/'': b'failed to load e xternal entity "http://frux.wikispaces.com/"' >>> -------------- next part -------------- An HTML attachment was scrubbed... URL: From d at davea.name Sun Oct 23 21:22:32 2011 From: d at davea.name (Dave Angel) Date: Sun, 23 Oct 2011 21:22:32 -0400 Subject: getroot() problem In-Reply-To: References: Message-ID: <4EA4BDD8.2070509@davea.name> On 10/23/2011 09:06 PM, ???????? wrote: > C:\Documents and Settings\peng>cd c:\python32 > > > > C:\Python32>python > > Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win > > 32 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> import lxml.html > >>>> sfile='http://finance.yahoo.com/q/op?s=A+Options' > >>>> root=lxml.html.parse(sfile).getroot() > there is no problem to parse : > > > http://finance.yahoo.com/q/op?s=A+Options' > > > > > why i can not parse > > http://frux.wikispaces.com/ ?? > >>>> import lxml.html > >>>> sfile='http://frux.wikispaces.com/' > >>>> root=lxml.html.parse(sfile).getroot() > > Traceback (most recent call last): > > File "", line 1, in > > File "C:\Python32\lib\site-packages\lxml\html\__init__.py", line 692, in parse > > > > return etree.parse(filename_or_url, parser, base_url=base_url, **kw) > > File "lxml.etree.pyx", line 2942, in lxml.etree.parse (src/lxml/lxml.etree.c:5 > > 4187) > > File "parser.pxi", line 1528, in lxml.etree._parseDocument (src/lxml/lxml.etre > > e.c:79485) > > File "parser.pxi", line 1557, in lxml.etree._parseDocumentFromURL (src/lxml/lx > > ml.etree.c:79768) > > File "parser.pxi", line 1457, in lxml.etree._parseDocFromFile (src/lxml/lxml.e > > tree.c:78843) > > File "parser.pxi", line 997, in lxml.etree._BaseParser._parseDocFromFile (src/ > > lxml/lxml.etree.c:75698) > > File "parser.pxi", line 564, in lxml.etree._ParserContext._handleParseResultDo > > c (src/lxml/lxml.etree.c:71739) > > File "parser.pxi", line 645, in lxml.etree._handleParseResult (src/lxml/lxml.e > > tree.c:72614) > > File "parser.pxi", line 583, in lxml.etree._raiseParseError (src/lxml/lxml.etr > > ee.c:71927) > > IOError: Error reading file 'b'http://frux.wikispaces.com/'': b'failed to load e > > xternal entity "http://frux.wikispaces.com/"' > >>> > Double-spacing makes your message much harder to read. I can only comment in a general way, in any case. most html is mal-formed, and not legal html. Although I don't have any experience with parsing it, I do with xml which has similar problems. The first thing I'd do is to separate the loading of the byte string from the website, from the parsing of those bytes. Further, I'd make a local copy of those bytes, so you can do testing repeatably. For example, you could run wget utility to copy the bytes locally and create a file. -- DaveA From dihedral88888 at googlemail.com Sun Oct 23 22:10:45 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Sun, 23 Oct 2011 19:10:45 -0700 (PDT) Subject: compare range objects In-Reply-To: <019dd721-055c-4aa3-aa03-6c355c2b3e18@k13g2000prg.googlegroups.com> References: <1319116780.86202.YahooMailNeo@web121517.mail.ne1.yahoo.com> <20111020162204.GA26505@Smoke> <453d196e-4516-47f3-9d33-caea70d33a8f@l12g2000vby.googlegroups.com> <4ea2557c$0$29968$c3e8da3$5496439d@news.astraweb.com> <57fe18d1-b66c-4b8c-bb83-a8994498d2cf@u13g2000vbx.googlegroups.com> <019dd721-055c-4aa3-aa03-6c355c2b3e18@k13g2000prg.googlegroups.com> Message-ID: <4393301.246.1319422245832.JavaMail.geo-discussion-forums@prng5> To compare two instances of objects defined by others in the same class or in derived classes from the same base class is an old problem in OOP. From aaabbb16 at hotmail.com Sun Oct 23 22:44:42 2011 From: aaabbb16 at hotmail.com (aaabbb16 at hotmail.com) Date: Sun, 23 Oct 2011 19:44:42 -0700 (PDT) Subject: How to use shell return value like $? In python? Message-ID: <9a377efb-7e18-46b8-902b-8fc40ab4d24b@m5g2000prg.googlegroups.com> exp: os.system('ls -al'? #I like to catch return value after this command. 0 or 1,2,3.... does python support to get "$?"? then I can use something like: If $?==0: ........ ................ TIA david From aaabbb16 at hotmail.com Sun Oct 23 22:51:47 2011 From: aaabbb16 at hotmail.com (aaabbb16 at hotmail.com) Date: Sun, 23 Oct 2011 19:51:47 -0700 (PDT) Subject: How to use shell return value like $? In python? References: <9a377efb-7e18-46b8-902b-8fc40ab4d24b@m5g2000prg.googlegroups.com> Message-ID: On Oct 23, 7:44?pm, aaabb... at hotmail.com wrote: > exp: > os.system('ls -al'? > #I like to catch return value after this command. 0 or 1,2,3.... > does python support to get "$?"? > then I can use something like: > ?If $?==0: > ? ? ?........ > ................ > TIA > david So for what I do is: r_number =os.system('ls -al') if r_number == 0 ......... ......... any other way? From clp2 at rebertia.com Sun Oct 23 22:58:37 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Oct 2011 19:58:37 -0700 Subject: How to use shell return value like $? In python? In-Reply-To: References: <9a377efb-7e18-46b8-902b-8fc40ab4d24b@m5g2000prg.googlegroups.com> Message-ID: On Sun, Oct 23, 2011 at 7:51 PM, wrote: > On Oct 23, 7:44?pm, aaabb... at hotmail.com wrote: >> exp: >> os.system('ls -al'? >> #I like to catch return value after this command. 0 or 1,2,3.... >> does python support to get "$?"? >> then I can use something like: >> ?If $?==0: > So for what I do is: > r_number =os.system('ls -al') > ? ? if r_number == 0 > ? ? ?......... > ? ? ?......... > any other way? I would recommend using the `subprocess` module instead: http://docs.python.org/library/subprocess.html#convenience-functions Cheers, Chris From fraveydank at gmail.com Sun Oct 23 23:00:22 2011 From: fraveydank at gmail.com (David Riley) Date: Sun, 23 Oct 2011 23:00:22 -0400 Subject: How to use shell return value like $? In python? In-Reply-To: <9a377efb-7e18-46b8-902b-8fc40ab4d24b@m5g2000prg.googlegroups.com> References: <9a377efb-7e18-46b8-902b-8fc40ab4d24b@m5g2000prg.googlegroups.com> Message-ID: <3A924B42-7BB4-4934-805C-87C2615832F5@gmail.com> On Oct 23, 2011, at 10:44 PM, aaabbb16 at hotmail.com wrote: > exp: > os.system('ls -al'? > #I like to catch return value after this command. 0 or 1,2,3.... > does python support to get "$?"? > then I can use something like: > If $?==0: > ........ > ................ From the manual (http://docs.python.org/library/os.html#os.system): "On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent." From the linked wait() documentation, the data returned is in a 16-bit integer, with the high byte indicating the exit status (the low byte is the signal that killed the process). So: status = os.system("foo") retval, sig = ((status >> 8) & 0xFF), (status & 0xFF) In the above example, your return status will end up in "retval". Of course, you probably ought to be using subprocess to run your subprocesses anyway; it's a lot more powerful and a lot harder to enable things like shell injection attacks. See: http://docs.python.org/library/subprocess.html#subprocess-replacements (which, of course, shows a direct replacement for os.system which is just as vulnerable to shell injection) - Dave From apometron.listas.cinco at gmail.com Sun Oct 23 23:21:49 2011 From: apometron.listas.cinco at gmail.com (apometron) Date: Mon, 24 Oct 2011 01:21:49 -0200 Subject: What is wrong with my code? In-Reply-To: <4EA49BA2.6080309@davea.name> References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> Message-ID: <4EA4D9CD.7010101@gmail.com> Sorry to continue discussing my thread on this list, I already subbed on the Tutor list but I need to reply and if possible, some ideas of why it dont works. Now it is another thing, entirely. Rename1.py and Rename2.py works, but why Rename3.py dont works? http://pastebin.com/dExFtTkp Thanks by the gentle support. []s Apometron On 10/23/2011 8:56 PM, Dave Angel wrote: > On 10/23/2011 06:03 AM, apometron wrote: >> import os >> nome = sys.argv[1] >> final = nome >> for i in nome: >> print i >> if nome[i] = "_": >> final[i] = " " >> os.rename(nome, final) >> > What do you want to be wrong with it? There are so many things, it'd > be fun to try to see who could come up with the most. > > 1) it's not a valid Fortran program. > 2) it's missing a shebang line > if we assume it's for Windows, or that you run it with an explicit > bash line > 3) if we pretend it's a python program, a few more > 3a) It has a syntax error calling the print() function. (Python 3.2) > If we assume it's a python 2.x program > 4) it uses sys, without importing it > 5) it uses second argument without checking if the user typed such an > argument > 6) it tries to change a character within a string, which is a > non-mutable type > 7) It creates two more references to the same string sys.argv[1], then > tries to modify one of them, not realizing the others would change to. > 8) it tries to subscript a string using a character. > 9) it calls rename with two references to the same object. So nothing > will ever actually happen, even if the other problems were fixed. > > Generally, you'll get the best answers here if you specify more of > your environment (python version, OS), show what you tried (pasted > from the command line), and the results you got (such as stack traces). > > HTH > > DaveA > > From nicholas.dokos at hp.com Sun Oct 23 23:23:12 2011 From: nicholas.dokos at hp.com (Nick Dokos) Date: Sun, 23 Oct 2011 23:23:12 -0400 Subject: How to use shell return value like $? In python? In-Reply-To: Message from David Riley of "Sun\, 23 Oct 2011 23\:00\:22 EDT." <3A924B42-7BB4-4934-805C-87C2615832F5@gmail.com> References: <9a377efb-7e18-46b8-902b-8fc40ab4d24b@m5g2000prg.googlegroups.com> <3A924B42-7BB4-4934-805C-87C2615832F5@gmail.com> Message-ID: <8800.1319426592@alphaville.dokosmarshall.org> David Riley wrote: > On Oct 23, 2011, at 10:44 PM, aaabbb16 at hotmail.com wrote: > > > exp: > > os.system('ls -al'? > > #I like to catch return value after this command. 0 or 1,2,3.... > > does python support to get "$?"? > > then I can use something like: > > If $?==0: > > ........ > > ................ > > From the manual (http://docs.python.org/library/os.html#os.system): > > "On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent." > > From the linked wait() documentation, the data returned is in a 16-bit integer, with the high byte indicating the exit status (the low byte is the signal that killed the process). So: > > > > > status = os.system("foo") > > retval, sig = ((status >> 8) & 0xFF), (status & 0xFF) > ... or retval, sig = os.WEXITSTATUS(status), os.WTERMSIG(status) for some insulation from low-level details. Nick > > > > In the above example, your return status will end up in "retval". > > Of course, you probably ought to be using subprocess to run your subprocesses anyway; it's a lot more powerful and a lot harder to enable things like shell injection attacks. See: http://docs.python.org/library/subprocess.html#subprocess-replacements (which, of course, shows a direct replacement for os.system which is just as vulnerable to shell injection) > > > - Dave > > -- > http://mail.python.org/mailman/listinfo/python-list From clp2 at rebertia.com Sun Oct 23 23:27:38 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Oct 2011 20:27:38 -0700 Subject: What is wrong with my code? In-Reply-To: <4EA4D9CD.7010101@gmail.com> References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> <4EA4D9CD.7010101@gmail.com> Message-ID: On Sun, Oct 23, 2011 at 8:21 PM, apometron wrote: > Sorry to continue discussing my thread on this list, I already subbed on the > Tutor list > but I need to reply and if possible, some ideas of why it dont works. Now it > is another > thing, entirely. Rename1.py and Rename2.py works, but why Rename3.py dont > works? You haven't specified in what way it's not working. What error are you getting, or what undesired/unexpected behavior are you observing? - Chris From 1248283536 at qq.com Mon Oct 24 00:02:45 2011 From: 1248283536 at qq.com (=?gbk?B?y66+ssH3ye4=?=) Date: Mon, 24 Oct 2011 12:02:45 +0800 Subject: install lxml Message-ID: there are two python versions in my computer, python2.7 is the default,python3.2 is the second install. for python2.7 ~$python Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import lxml >>> for python3.2 ~$python3.2 Python 3.2.2 (default, Oct 24 2011, 10:33:35) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import lxml Traceback (most recent call last): File "", line 1, in ImportError: No module named lxml i want to install lxml in python3.2. how can i do? -------------- next part -------------- An HTML attachment was scrubbed... URL: From apometron.listas.cinco at gmail.com Mon Oct 24 00:30:40 2011 From: apometron.listas.cinco at gmail.com (apometron) Date: Mon, 24 Oct 2011 02:30:40 -0200 Subject: What is wrong with my code? In-Reply-To: References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> <4EA4D9CD.7010101@gmail.com> Message-ID: <4EA4E9F0.4010600@gmail.com> The problem is that it is not reporting any error. The do something and quits silently. No rename action is done and no error. Running Python 2.7 on Windows Seven. I know that it is a bit tricky to help someone so, but I dont have any info to pass that be good to understand the situation. Thanks by the effort in help me. I appreciate every character of it. []s Apometron On 10/24/2011 1:27 AM, Chris Rebert wrote: > On Sun, Oct 23, 2011 at 8:21 PM, apometron > wrote: >> Sorry to continue discussing my thread on this list, I already subbed on the >> Tutor list >> but I need to reply and if possible, some ideas of why it dont works. Now it >> is another >> thing, entirely. Rename1.py and Rename2.py works, but why Rename3.py dont >> works? > You haven't specified in what way it's not working. What error are you > getting, or what undesired/unexpected behavior are you observing? > > - Chris From 1248283536 at qq.com Mon Oct 24 00:30:41 2011 From: 1248283536 at qq.com (=?gbk?B?y66+ssH3ye4=?=) Date: Mon, 24 Oct 2011 12:30:41 +0800 Subject: =?gbk?B?u9i4tKO6IGdldHJvb3QoKSAgIHByb2JsZW0=?= Message-ID: in my computer,there two os , 1.xp+python32 import lxml.html sfile='http://finance.yahoo.com/q/op?s=A+Options' root=lxml.html.parse(sfile).getroot() it is ok import lxml.html sfile='http://frux.wikispaces.com/' root=lxml.html.parse(sfile).getroot() there is problem Traceback (most recent call last): File "", line 1, in File "C:\Python32\lib\site-packages\lxml\html\__init__.py", line 692, in parse return etree.parse(filename_or_url, parser, base_url=base_url, **kw) File "lxml.etree.pyx", line 2942, in lxml.etree.parse (src/lxml/lxml.etree.c:5 4187) File "parser.pxi", line 1528, in lxml.etree._parseDocument (src/lxml/lxml.etre e.c:79485) File "parser.pxi", line 1557, in lxml.etree._parseDocumentFromURL (src/lxml/lx ml.etree.c:79768) File "parser.pxi", line 1457, in lxml.etree._parseDocFromFile (src/lxml/lxml.e tree.c:78843) File "parser.pxi", line 997, in lxml.etree._BaseParser._parseDocFromFile (src/ lxml/lxml.etree.c:75698) File "parser.pxi", line 564, in lxml.etree._ParserContext._handleParseResultDo c (src/lxml/lxml.etree.c:71739) File "parser.pxi", line 645, in lxml.etree._handleParseResult (src/lxml/lxml.e tree.c:72614) File "parser.pxi", line 583, in lxml.etree._raiseParseError (src/lxml/lxml.etr ee.c:71927) IOError: Error reading file 'b'http://frux.wikispaces.com/'': b'failed to load e xternal entity "http://frux.wikispaces.com/"' 2. ubuntu11.04+python2.6 import lxml.html sfile='http://frux.wikispaces.com/' root=lxml.html.parse(sfile).getroot() it is ok it is so strange thing for me to understand ------------------ ???? ------------------ ???: "Dave Angel"; ????: 2011?10?24?(???) ??9:22 ???: "1248283536"<1248283536 at qq.com>; ??: "lxml"; "python-list"; ??: Re: getroot() problem On 10/23/2011 09:06 PM, ???? wrote: > C:\Documents and Settings\peng>cd c:\python32 > > > > C:\Python32>python > > Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win > > 32 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> import lxml.html > >>>> sfile='http://finance.yahoo.com/q/op?s=A+Options' > >>>> root=lxml.html.parse(sfile).getroot() > there is no problem to parse : > > > http://finance.yahoo.com/q/op?s=A+Options' > > > > > why i can not parse > > http://frux.wikispaces.com/ ?? > >>>> import lxml.html > >>>> sfile='http://frux.wikispaces.com/' > >>>> root=lxml.html.parse(sfile).getroot() > > Traceback (most recent call last): > > File "", line 1, in > > File "C:\Python32\lib\site-packages\lxml\html\__init__.py", line 692, in parse > > > > return etree.parse(filename_or_url, parser, base_url=base_url, **kw) > > File "lxml.etree.pyx", line 2942, in lxml.etree.parse (src/lxml/lxml.etree.c:5 > > 4187) > > File "parser.pxi", line 1528, in lxml.etree._parseDocument (src/lxml/lxml.etre > > e.c:79485) > > File "parser.pxi", line 1557, in lxml.etree._parseDocumentFromURL (src/lxml/lx > > ml.etree.c:79768) > > File "parser.pxi", line 1457, in lxml.etree._parseDocFromFile (src/lxml/lxml.e > > tree.c:78843) > > File "parser.pxi", line 997, in lxml.etree._BaseParser._parseDocFromFile (src/ > > lxml/lxml.etree.c:75698) > > File "parser.pxi", line 564, in lxml.etree._ParserContext._handleParseResultDo > > c (src/lxml/lxml.etree.c:71739) > > File "parser.pxi", line 645, in lxml.etree._handleParseResult (src/lxml/lxml.e > > tree.c:72614) > > File "parser.pxi", line 583, in lxml.etree._raiseParseError (src/lxml/lxml.etr > > ee.c:71927) > > IOError: Error reading file 'b'http://frux.wikispaces.com/'': b'failed to load e > > xternal entity "http://frux.wikispaces.com/"' > >>> > Double-spacing makes your message much harder to read. I can only comment in a general way, in any case. most html is mal-formed, and not legal html. Although I don't have any experience with parsing it, I do with xml which has similar problems. The first thing I'd do is to separate the loading of the byte string from the website, from the parsing of those bytes. Further, I'd make a local copy of those bytes, so you can do testing repeatably. For example, you could run wget utility to copy the bytes locally and create a file. -- DaveA -------------- next part -------------- An HTML attachment was scrubbed... URL: From moijes12 at gmail.com Mon Oct 24 00:53:41 2011 From: moijes12 at gmail.com (moijes12) Date: Sun, 23 Oct 2011 21:53:41 -0700 (PDT) Subject: Books to lean Python 3 Web Programming? References: Message-ID: <2d15360d-ab41-49e6-be5a-38490e3f96c8@v8g2000pro.googlegroups.com> On Oct 23, 3:18?am, Jonathan Loescher wrote: > Can anyone recommend a good book to learn the web programming aspects > of Python 3? Hi You can check "Dive into Python 3" by Mark Pilgrim. It does cover some aspects of web programming. I haven't read it myself,but I've been reading "Dive into Python". I hope this helps. regards Alexander From tjreedy at udel.edu Mon Oct 24 00:58:24 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Oct 2011 00:58:24 -0400 Subject: install lxml In-Reply-To: References: Message-ID: On 10/24/2011 12:02 AM, ???? wrote: > there are two python versions in my computer, > python2.7 is the default,python3.2 is the second install. > for python2.7 > ~$python > Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import lxml > >>> > > for python3.2 > ~$python3.2 > Python 3.2.2 (default, Oct 24 2011, 10:33:35) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import lxml > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named lxml > > i want to install lxml in python3.2. > how can i do? Put a 3.2 version of lxml in the 3.2 Lib/site-packages directory. -- Terry Jan Reedy From moijes12 at gmail.com Mon Oct 24 01:09:44 2011 From: moijes12 at gmail.com (moijes12) Date: Sun, 23 Oct 2011 22:09:44 -0700 (PDT) Subject: Books to lean Python 3 Web Programming? References: Message-ID: On Oct 23, 3:18?am, Jonathan Loescher wrote: > Can anyone recommend a good book to learn the web programming aspects > of Python 3? Hi Try out "Dive into Python 3" for an introduction to HTTP services. regards Moses From jason.swails at gmail.com Mon Oct 24 01:18:46 2011 From: jason.swails at gmail.com (Jason Swails) Date: Mon, 24 Oct 2011 01:18:46 -0400 Subject: CSV writer question Message-ID: Hello, I have a question about a csv.writer instance. I have a utility that I want to write a full CSV file from lots of data, but due to performance (and memory) considerations, there's no way I can write the data sequentially. Therefore, I write the data in chunks to temporary files, then combine them all at the end. For convenience, I declare each writer instance via a statement like my_csv = csv.writer(open('temp.1.csv', 'wb')) so the open file object isn't bound to any explicit reference, and I don't know how to reference it inside the writer class (the documentation doesn't say, unless I've missed the obvious). Thus, the only way I can think of to make sure that all of the data is written before I start copying these files sequentially into the final file is to unbuffer them so the above command is changed to my_csv = csv.writer(open('temp.1.csv', 'wb', 0)) unless, of course, I add an explicit reference to track the open file object and manually close or flush it (but I'd like to avoid it if possible). My question is 2-fold. Is there a way to do that directly via the CSV API, or is the approach I'm taking the only way without binding the open file object to another reference? Secondly, if these files are potentially very large (anywhere from ~1KB to 20 GB depending on the amount of data present), what kind of performance hit will I be looking at by disabling buffering on these types of files? Tips, answers, comments, and/or suggestions are all welcome. Thanks a lot! Jason As an afterthought, I suppose I could always subclass the csv.writer class and add the reference I want to that, which I may do if there's no other convenient solution. -------------- next part -------------- An HTML attachment was scrubbed... URL: From 1248283536 at qq.com Mon Oct 24 01:31:19 2011 From: 1248283536 at qq.com (=?gbk?B?y66+ssH3ye4=?=) Date: Mon, 24 Oct 2011 13:31:19 +0800 Subject: =?gbk?B?u9i4tKO6IGluc3RhbGwgIGx4bWw=?= Message-ID: The latest version is lxml 2.3.1, released 2011-09-25, 1.download it 2.extract it ,put it in the /home/user/Python-3.2.2/libxml2-2.7.8 3.cd /home/user/Python-3.2.2/libxml2-2.7.8 4. ./configure 5.make 6.sudo make install when i finished ~$ python3.2 Python 3.2.2 (default, Oct 24 2011, 10:33:35) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import lxml Traceback (most recent call last): File "", line 1, in ImportError: No module named lxml there is still the problem!! ------------------ ???? ------------------ ???: "Terry Reedy"; ????: 2011?10?24?(???) ??12:58 ???: "python-list"; ??: "lxml"; ??: Re: install lxml On 10/24/2011 12:02 AM, ???? wrote: > there are two python versions in my computer, > python2.7 is the default,python3.2 is the second install. > for python2.7 > ~$python > Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import lxml > >>> > > for python3.2 > ~$python3.2 > Python 3.2.2 (default, Oct 24 2011, 10:33:35) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import lxml > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named lxml > > i want to install lxml in python3.2. > how can i do? Put a 3.2 version of lxml in the 3.2 Lib/site-packages directory. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Mon Oct 24 02:08:59 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Oct 2011 23:08:59 -0700 Subject: CSV writer question In-Reply-To: References: Message-ID: On Sun, Oct 23, 2011 at 10:18 PM, Jason Swails wrote: > Hello, > > I have a question about a csv.writer instance.? I have a utility that I want > to write a full CSV file from lots of data, but due to performance (and > memory) considerations, there's no way I can write the data sequentially. > Therefore, I write the data in chunks to temporary files, then combine them > all at the end.? For convenience, I declare each writer instance via a > statement like > > my_csv = csv.writer(open('temp.1.csv', 'wb')) > > so the open file object isn't bound to any explicit reference, and I don't > know how to reference it inside the writer class (the documentation doesn't > say, unless I've missed the obvious).? Thus, the only way I can think of to > make sure that all of the data is written before I start copying these files > sequentially into the final file is to unbuffer them so the above command is > changed to > > my_csv = csv.writer(open('temp.1.csv', 'wb', 0)) > > unless, of course, I add an explicit reference to track the open file object > and manually close or flush it > (but I'd like to avoid it if possible). Why? Especially when the performance cost is likely to be nontrivial... >?Is there a way to do that directly via the CSV API, Very doubtful; csv.writer (and reader for that matter) is implemented in C, doesn't expose a ._file or similar attribute, and has no .close() or .flush() methods. Cheers, Chris -- http://rebertia.com From rosuav at gmail.com Mon Oct 24 03:03:15 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 24 Oct 2011 18:03:15 +1100 Subject: CSV writer question In-Reply-To: References: Message-ID: On Mon, Oct 24, 2011 at 4:18 PM, Jason Swails wrote: > my_csv = csv.writer(open('temp.1.csv', 'wb')) > Have you confirmed, or can you confirm, whether or not the file gets closed automatically when the writer gets destructed? If so, all you need to do is: my_csv = something_else # or: del my_csv to unbind what I assume is the only reference to the csv.writer, upon which it should promptly clean itself up. ChrisA From stefan_ml at behnel.de Mon Oct 24 03:12:40 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Oct 2011 09:12:40 +0200 Subject: =?UTF-8?B?5Zue5aSN77yaIGluc3RhbGwgIGx4bWw=?= In-Reply-To: References: Message-ID: ????, 24.10.2011 07:31: > The latest version is lxml 2.3.1, released 2011-09-25, > 1.download it > 2.extract it ,put it in the /home/user/Python-3.2.2/libxml2-2.7.8 > 3.cd /home/user/Python-3.2.2/libxml2-2.7.8 > 4. ./configure > 5.make > 6.sudo make install Not libxml2. lxml. > when i finished > ~$ python3.2 > Python 3.2.2 (default, Oct 24 2011, 10:33:35) > [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import lxml > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named lxml > > there is still the problem!! You can get a binary build for Windows from PyPI: http://pypi.python.org/pypi/lxml/2.3 Oh, and please avoid cross-posting (and top-posting in replies). Stefan From __peter__ at web.de Mon Oct 24 03:28:11 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Oct 2011 09:28:11 +0200 Subject: shutil _isindir References: <4EA2BBF0.4050602@gmail.com> Message-ID: David Hoese wrote: > I was about to submit a bug report, but while testing I have figured out > that my specific problem has been solved in Python 2.7 (server that I > was using had 2.6 on it). You can see the differences here: > > 2.6: http://hg.python.org/cpython/file/b9a95ce2692c/Lib/shutil.py > 2.7: http://hg.python.org/cpython/file/d30482d51c25/Lib/shutil.py > > You'll notice that in move(), there is now a check for the same file, > which if they're not the same file you don't get unexpected deleted > files. If you still think I should submit a bug report let me know and > provide me with the test case...or just submit the bug yourself. Aren't there still problems that can be avoided with the change you propose? I think the bug report is worthwhile. From ivo at webcrowd.net Mon Oct 24 03:40:45 2011 From: ivo at webcrowd.net (webcrowd.net) Date: Mon, 24 Oct 2011 09:40:45 +0200 Subject: Job Offer: 3 Python Backend Developer and other Positions in Berlin In-Reply-To: <1b9shmovw2l6m$.dlg@localhost.localdomain> References: <1b9shmovw2l6m$.dlg@localhost.localdomain> Message-ID: Am 23.10.11 20:25, schrieb Waldek M.: > On Sun, 23 Oct 2011 17:50:54 +0200, webcrowd.net wrote: >> hope it is okay to post job offers here. If not sorry for the spam and >> please let me know! > > Not really. It's a newsgroup on Python *language*, not > on Python-everything. > > You might want to post here instead, though: > http://www.python.org/community/jobs/ > > Best regards, > Waldek Thanks Waldek, will do so in future! Best Regards, Ivo From vinay_sajip at yahoo.co.uk Mon Oct 24 04:28:28 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Mon, 24 Oct 2011 09:28:28 +0100 (BST) Subject: logging: warn() methods and function to be deprecated. In-Reply-To: <4EA4A65F.2090205@gmail.com> References: <4EA4A65F.2090205@gmail.com> Message-ID: <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> > I think that is a real shame - it seems to be gratuitous breakage for almost > zero benefit.? That issue shows that Trac makes heavy use of .warn, I've use > .warn almost exclusively for many years, and code.google.com shows it is used > extensively in the wild. Okay, but it's easy enough to change, and people are getting a reasonable amount of time to deal with it. > Is there still a chance to reconsider? I'm not dogmatic about things like this; warn() is just a hangover from a long time ago and bit of a nit, that's all. I suppose I should have removed it when 3.0 was released, but it went under my radar at that time. Hence my post here, to get feedback from logging users about this proposed change. Regards, Vinay Sajip From d at davea.name Mon Oct 24 08:18:28 2011 From: d at davea.name (Dave Angel) Date: Mon, 24 Oct 2011 08:18:28 -0400 Subject: What is wrong with my code? In-Reply-To: <4EA4E9F0.4010600@gmail.com> References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> <4EA4D9CD.7010101@gmail.com> <4EA4E9F0.4010600@gmail.com> Message-ID: <4EA55794.3050304@davea.name> (Don't top-post. Put your response after the part you're quoting from earlier messages. And include enough that somebody can help with minimal effort.) On 10/24/2011 12:30 AM, apometron wrote: > The problem is that it is not reporting any error. > > The do something and quits silently. > > No rename action is done and no error. > > Running Python 2.7 on Windows Seven. > Your link http://pastebin.com/dExFtTkp shows two copies of the code. I'm assuming they're identical, and using the second one. How do you know no rename action is done? Did you do a dir before and after running it? Were there any files that actually had underscores in them? Did you try adding a print to the innermost if statement to see if it ever ran? Did you try adding a print right after the os.rename that showed both nome and final? When I run it in CPython 2.7 on Linux, it successfully renamed the file (dumm_1.txt) I had supplied. davea at think:~/pytests$ ls dumm_1.txt itpone.itp~ lina.py~ pdbone.pdb~ prim.py~ itpone.itp lina.py pdbone.pdb prim.py whatswrong.py davea at think:~/pytests$ python whatswrong.py dumm_1.txt davea at think:~/pytests$ ls dumm 1.txt itpone.itp~ lina.py~ pdbone.pdb~ prim.py~ itpone.itp lina.py pdbone.pdb prim.py whatswrong.py davea at think:~/pytests$ (I had to delete the following part, since you put yours out of order) -- DaveA From npropadovic at googlemail.com Mon Oct 24 08:43:58 2011 From: npropadovic at googlemail.com (Propad) Date: Mon, 24 Oct 2011 05:43:58 -0700 (PDT) Subject: spawnl issues with Win 7 access rights Message-ID: Hello everybody, I have some trouble with a program I run both on a WinXP and on Win 7. It boils down to this several lines: import os vePath = r'C:\Programme\RA Consulting_Webservices\DiagRA-MCD \DiagRA_D.exe' #vePath = r'C:\Windows\notepad.exe' process_id = os.spawnl(os.P_NOWAIT, vePath) Under Win XP they open DiagRA just fine; under Win 7 I'm getting: OSError: [Errno 22] Invalid argument Needless to say, I checked the path under Win 7; it is correct. As you can see, I tried the same lines with notepad, just in case; same result. Works fine under XP, IOError under Win 7. So I'm pretty sure it's some kind of Win 7 access rights issue... Can anybody point me to a concise overview of the issues involved, and maybe even the known solutions? Again, it's os.spawnl in Python 2.2, under Win 7. Thank you very much in advance. Cheers, Nenad From mail at timgolden.me.uk Mon Oct 24 09:18:27 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 24 Oct 2011 14:18:27 +0100 Subject: spawnl issues with Win 7 access rights In-Reply-To: References: Message-ID: <4EA565A3.3030909@timgolden.me.uk> On 24/10/2011 13:43, Propad wrote: > Hello everybody, > I have some trouble with a program I run both on a WinXP and on Win 7. > It boils down to this several lines: > > import os > vePath = r'C:\Programme\RA Consulting_Webservices\DiagRA-MCD > \DiagRA_D.exe' > #vePath = r'C:\Windows\notepad.exe' > process_id = os.spawnl(os.P_NOWAIT, vePath) > > Under Win XP they open DiagRA just fine; under Win 7 I'm getting: > OSError: [Errno 22] Invalid argument > Needless to say, I checked the path under Win 7; it is correct. > > As you can see, I tried the same lines with notepad, just in case; > same result. Works fine under XP, IOError under Win 7. > > So I'm pretty sure it's some kind of Win 7 access rights issue... Can > anybody point me to a concise overview of the issues involved, and > maybe even the known solutions? Again, it's os.spawnl in Python 2.2, > under Win 7. That's impressive. I ran this (on Python 2.7 on Win7): import os os.spawnl (os.P_NOWAIT, r"c:\windows\notepad.exe") and Python crashed hard! Long time since I've seen that happen. This may or may not be related to what you're seeing but it's definitely a problem. I'll check the bugs database and/or file a bug. I *can* reproduce your problem running Python22 on Win7. Now, no-one's going to be applying patches to Python 2.2 at this stage: in the 2.x series, only 2.7 is getting anything other than urgent security fixes. And even 2.7's only getting clear bugfixes. Just so you know. Without checking the code, I'm going to assume that the 2.2 codebase is handing off to the MS C Runtime Library for posix-related calls such as the spawn* family. So it may not even be Python's code directly which is returning this error. TJG From alec.taylor6 at gmail.com Mon Oct 24 09:39:11 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 25 Oct 2011 00:39:11 +1100 Subject: Python as a replacement to PL/SQL Message-ID: Good morning, Is there a set of libraries for python which can be used as a complete replacement to PL/SQL? Alternatively, is there a python library for generating PL/SQL? (I am speaking from the context of Oracle DB, PL/Python only works with PostgreSQL) Thanks for all suggestions, Alec Taylor From npropadovic at googlemail.com Mon Oct 24 09:47:22 2011 From: npropadovic at googlemail.com (Propad) Date: Mon, 24 Oct 2011 06:47:22 -0700 (PDT) Subject: spawnl issues with Win 7 access rights References: Message-ID: Hello Tim, thanx for the fast answer. Sorry to hear there are such issues. I'm obviously not free to choose my version of Python, or I'would be using the latest'n'greatest. It's more like this: I'm obliged to use the version delivered with dSpace tools (which is HiL - ECU-testing software for the automotive and aerospace industries). I'just might be able to use 2.5, which dSpace delivered 2-3 years ago; but I'm not sure of that, and not sure it would help in any way. So some solution without tweaking the code or anything would be realy nice. I can't imagine anything of such importance was not tested at all during the beta phase - so it could be the tests were not run with such a tricky configuration of windows. Any hints are appreciated! Cheers, Nenad On 24 Okt., 15:18, Tim Golden wrote: > On 24/10/2011 13:43, Propad wrote: > > > > > > > Hello everybody, > > I have some trouble with a program I run both on a WinXP and on Win 7. > > It boils down to this several lines: > > > import os > > vePath = r'C:\Programme\RA Consulting_Webservices\DiagRA-MCD > > \DiagRA_D.exe' > > #vePath = r'C:\Windows\notepad.exe' > > process_id = os.spawnl(os.P_NOWAIT, vePath) > > > Under Win XP they ?open DiagRA just fine; under Win 7 I'm getting: > > OSError: [Errno 22] Invalid argument > > Needless to say, I checked the path under Win 7; it is correct. > > > As you can see, I tried the same lines with notepad, just in case; > > same result. Works fine under XP, IOError under Win 7. > > > So I'm pretty sure it's some kind of Win 7 access rights issue... Can > > anybody point me to a concise overview of the issues involved, and > > maybe even the known solutions? Again, it's os.spawnl in Python 2.2, > > under Win 7. > > That's impressive. I ran this (on Python 2.7 on Win7): > > > import os > > os.spawnl (os.P_NOWAIT, r"c:\windows\notepad.exe") > > > > and Python crashed hard! Long time since I've seen that happen. > > This may or may not be related to what you're seeing but it's > definitely a problem. I'll check the bugs database and/or > file a bug. > > I *can* reproduce your problem running Python22 on Win7. Now, > no-one's going to be applying patches to Python 2.2 at this > stage: in the 2.x series, only 2.7 is getting anything other > than urgent security fixes. And even 2.7's only getting clear > bugfixes. Just so you know. > > Without checking the code, I'm going to assume that the 2.2 codebase > is handing off to the MS C Runtime Library for posix-related calls > such as the spawn* family. So it may not even be Python's code directly > which is returning this error. > > TJG- Zitierten Text ausblenden - > > - Zitierten Text anzeigen - From mail at timgolden.me.uk Mon Oct 24 10:18:48 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 24 Oct 2011 15:18:48 +0100 Subject: spawnl issues with Win 7 access rights In-Reply-To: <4EA565A3.3030909@timgolden.me.uk> References: <4EA565A3.3030909@timgolden.me.uk> Message-ID: <4EA573C8.1080502@timgolden.me.uk> On 24/10/2011 14:18, Tim Golden wrote: I ran this (on Python 2.7 on Win7): > > > import os > > os.spawnl (os.P_NOWAIT, r"c:\windows\notepad.exe") > > > > and Python crashed hard! Long time since I've seen that happen. > > This may or may not be related to what you're seeing but it's > definitely a problem. I'll check the bugs database and/or > file a bug. > > I *can* reproduce your problem running Python22 on Win7. Now, > no-one's going to be applying patches to Python 2.2 at this > stage: in the 2.x series, only 2.7 is getting anything other > than urgent security fixes. And even 2.7's only getting clear > bugfixes. Just so you know. OK; the python 2.7 issues is http://bugs.python.org/issue8036 Let's see if I can get a fix in before the next release! Not quite sure whether the 2.2 issue is the same but it's looking like being a W7 / CRT-related issue. I'll keep looking TJG From jeanmichel at sequans.com Mon Oct 24 10:34:32 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 Oct 2011 16:34:32 +0200 Subject: logging: warn() methods and function to be deprecated. In-Reply-To: <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> References: <4EA4A65F.2090205@gmail.com> <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> Message-ID: <4EA57778.1030306@sequans.com> Vinay Sajip wrote: >> I think that is a real shame - it seems to be gratuitous breakage for almost >> > > >> zero benefit. That issue shows that Trac makes heavy use of .warn, I've use >> .warn almost exclusively for many years, and code.google.com shows it is used >> extensively in the wild. >> > > Okay, but it's easy enough to change, and people are getting a reasonable amount of time to deal with it. > > >> Is there still a chance to reconsider? >> > > I'm not dogmatic about things like this; warn() is just a hangover from a long time ago and bit of a nit, that's all. I suppose I should have removed it when 3.0 was released, but it went under my radar at that time. > > Hence my post here, to get feedback from logging users about this proposed change. > > Regards, > > Vinay Sajip > I'm not using python 3, I'm not sure my feedback matters, but I wouldn't mind refactoring warn into warning If I'd have to. It's better to use documented API anyway. JM PS : I also had an issue with my logging wrappers where I did not implement warn, quite confusing the first time I had this error. From mcfletch at vrplumber.com Mon Oct 24 10:38:55 2011 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Mon, 24 Oct 2011 10:38:55 -0400 Subject: logging: warn() methods and function to be deprecated. In-Reply-To: <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> References: <4EA4A65F.2090205@gmail.com> <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> Message-ID: <4EA5787F.1050906@vrplumber.com> On 11-10-24 04:28 AM, Vinay Sajip wrote: >> I think that is a real shame - it seems to be gratuitous breakage for almost >> zero benefit. That issue shows that Trac makes heavy use of .warn, I've use >> .warn almost exclusively for many years, and code.google.com shows it is used >> extensively in the wild. > Okay, but it's easy enough to change, and people are getting a reasonable amount of time to deal with it. I'd have to echo Mark's sentiment here. There is a *lot* of (fairly old) code around that uses .warn, and I'd wager even a lot of new code written by old programmers (such as myself) that uses it. Breaking it to avoid having an undocumented method seems wrong; suggest just adding documentation: "logger.warn(...) -- an alias to logger.warning provided for backward compatibility" >> Is there still a chance to reconsider? > I'm not dogmatic about things like this; warn() is just a hangover from a long time ago and bit of a nit, that's all. I suppose I should have removed it when 3.0 was released, but it went under my radar at that time. > > Hence my post here, to get feedback from logging users about this proposed change. I actually consider .warning() a nit :) . After all, it's 3 extra characters :) , and *who* actually reads documentation instead of just poking around and finding the shortest-named method in the instance? Anyway, I personally don't see this as worth the breakage. Just my $0.02, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From alain at dpt-info.u-strasbg.fr Mon Oct 24 10:45:08 2011 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Mon, 24 Oct 2011 16:45:08 +0200 Subject: Python as a replacement to PL/SQL References: Message-ID: <87bot6sb2j.fsf@dpt-info.u-strasbg.fr> Alec Taylor writes: > Is there a set of libraries for python which can be used as a complete > replacement to PL/SQL? This doesn't make much sense: PL/SQL lets you write server-side code, i.e., executed by the DBMS. Oracle can't execute python code directly, so python can only be used on the client side (I meant "client of the DBMS"), i.e., not to write stored procedures. There is no "complete replacement" of PL/SQL besides Java. This page shows you how to _call_ PL/SQL procedures from a python script: http://www.oracle.com/technetwork/articles/dsl/python-091105.html > (I am speaking from the context of Oracle DB, PL/Python only works > with PostgreSQL) PL/Python is a different beast, it lets you write stored functions in python. There is no such thing, afaik, with Oracle. -- Alain. From alec.taylor6 at gmail.com Mon Oct 24 10:59:07 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 25 Oct 2011 01:59:07 +1100 Subject: Python as a replacement to PL/SQL In-Reply-To: <87bot6sb2j.fsf@dpt-info.u-strasbg.fr> References: <87bot6sb2j.fsf@dpt-info.u-strasbg.fr> Message-ID: Hmm... What else is there besides PL/Python (for any DB) in the context of writing stored procedures in function? Thanks for all suggestions, Alec Taylor On Tue, Oct 25, 2011 at 1:45 AM, Alain Ketterlin wrote: > Alec Taylor writes: > >> Is there a set of libraries for python which can be used as a complete >> replacement to PL/SQL? > > This doesn't make much sense: PL/SQL lets you write server-side code, > i.e., executed by the DBMS. Oracle can't execute python code directly, > so python can only be used on the client side (I meant "client of the > DBMS"), i.e., not to write stored procedures. There is no "complete > replacement" of PL/SQL besides Java. > > This page shows you how to _call_ PL/SQL procedures from a python script: > > http://www.oracle.com/technetwork/articles/dsl/python-091105.html > >> (I am speaking from the context of Oracle DB, PL/Python only works >> with PostgreSQL) > > PL/Python is a different beast, it lets you write stored functions in > python. There is no such thing, afaik, with Oracle. > > -- Alain. > -- > http://mail.python.org/mailman/listinfo/python-list > From k.sahithi2862 at gmail.com Mon Oct 24 12:19:15 2011 From: k.sahithi2862 at gmail.com (SAHITHI) Date: Mon, 24 Oct 2011 09:19:15 -0700 (PDT) Subject: HOT ACTRESSES Message-ID: <17e12435-5ed4-4402-9e26-7c2c2133aec0@d33g2000prb.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html SAKUNI MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/sakuni-movie-stills.html 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html SNEHA ULLAL HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/sneha-ullal-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html From alec.taylor6 at gmail.com Mon Oct 24 12:30:41 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Tue, 25 Oct 2011 03:30:41 +1100 Subject: Convert DDL to ORM Message-ID: Good morning, I'm often generating DDLs from EER->Logical diagrams using tools such as PowerDesigner and Oracle Data Modeller. I've recently come across an ORM library (SQLalchemy), and it seems like a quite useful abstraction. Is there a way to convert my DDL to ORM code? Thanks for all suggestions, Alec Taylor From M.Komon at SiliconHill.cz Mon Oct 24 12:37:24 2011 From: M.Komon at SiliconHill.cz (=?UTF-8?B?TWFydGluIEtvbW/FiA==?=) Date: Mon, 24 Oct 2011 18:37:24 +0200 Subject: Python as a replacement to PL/SQL In-Reply-To: References: <87bot6sb2j.fsf@dpt-info.u-strasbg.fr> Message-ID: <4EA59444.60407@SiliconHill.cz> PostgreSQL supports PL/SQL, PL/TCL, PL/Python, PL/Perl and I've also seen PL/Java add on module. Martin On 10/24/2011 4:59 PM, Alec Taylor wrote: > Hmm... > > What else is there besides PL/Python (for any DB) in the context of > writing stored procedures in function? > > Thanks for all suggestions, > > Alec Taylor > > On Tue, Oct 25, 2011 at 1:45 AM, Alain Ketterlin > wrote: >> Alec Taylor writes: >> >>> Is there a set of libraries for python which can be used as a complete >>> replacement to PL/SQL? >> >> This doesn't make much sense: PL/SQL lets you write server-side code, >> i.e., executed by the DBMS. Oracle can't execute python code directly, >> so python can only be used on the client side (I meant "client of the >> DBMS"), i.e., not to write stored procedures. There is no "complete >> replacement" of PL/SQL besides Java. >> >> This page shows you how to _call_ PL/SQL procedures from a python script: >> >> http://www.oracle.com/technetwork/articles/dsl/python-091105.html >> >>> (I am speaking from the context of Oracle DB, PL/Python only works >>> with PostgreSQL) >> >> PL/Python is a different beast, it lets you write stored functions in >> python. There is no such thing, afaik, with Oracle. >> >> -- Alain. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> From M.Komon at SiliconHill.cz Mon Oct 24 12:43:05 2011 From: M.Komon at SiliconHill.cz (=?UTF-8?B?TWFydGluIEtvbW/FiA==?=) Date: Mon, 24 Oct 2011 18:43:05 +0200 Subject: Convert DDL to ORM In-Reply-To: References: Message-ID: <4EA59599.2040806@SiliconHill.cz> Hi, for the project I'm working on right now I've written a simple "SQL create script to ORM generator". I use SQLalchemy as well and this generator takes all tables and prepares classes, maps them to tables, introspects them and creates explicit attribute definitions in the classes. Contact me off-list for more details. Martin On 10/24/2011 6:30 PM, Alec Taylor wrote: > Good morning, > > I'm often generating DDLs from EER->Logical diagrams using tools such > as PowerDesigner and Oracle Data Modeller. > > I've recently come across an ORM library (SQLalchemy), and it seems > like a quite useful abstraction. > > Is there a way to convert my DDL to ORM code? > > Thanks for all suggestions, > > Alec Taylor From dmitrey15 at gmail.com Mon Oct 24 14:24:48 2011 From: dmitrey15 at gmail.com (dmitrey) Date: Mon, 24 Oct 2011 11:24:48 -0700 (PDT) Subject: [ANN] New free multifactor analysis tool for experiment planning Message-ID: Hi all, you may be interested in new free multifactor analysis tool for experiment planning (in physics, chemistry, biology etc). It is based on numerical optimization solver BOBYQA, released in 2009 by Michael J.D. Powell, and has easy and convenient GUI frontend, written in Python + tkinter. Maybe other (alternative) engines will be available in future. See its webpage for details: http://openopt.org/MultiFactorAnalysis Regards, Dmitrey. From candide at free.invalid Mon Oct 24 15:26:59 2011 From: candide at free.invalid (candide) Date: Mon, 24 Oct 2011 21:26:59 +0200 Subject: randrange exceptional behavior Message-ID: <4ea5bc04$0$6448$426a74cc@news.free.fr> Where is documented the behaviour of the standard function randrange in the case of an empty list ? for instance randrange(42,33) ? May I rely on an ValueError type error? From jason.swails at gmail.com Mon Oct 24 15:41:31 2011 From: jason.swails at gmail.com (Jason Swails) Date: Mon, 24 Oct 2011 15:41:31 -0400 Subject: CSV writer question In-Reply-To: References: Message-ID: On Mon, Oct 24, 2011 at 2:08 AM, Chris Rebert wrote: > On Sun, Oct 23, 2011 at 10:18 PM, Jason Swails > wrote: > > > unless, of course, I add an explicit reference to track the open file > object > > and manually close or flush it > > (but I'd like to avoid it if possible). > > Why? Especially when the performance cost is likely to be nontrivial... > Because if the CSV API exposed the file object, I wouldn't have to create that extra reference, and the class that is handling this stuff already has enough attributes without having to add a separate one for each CSV writer it instantiates. It's not a serious objection to creating it, just one I'd rather not do (it's less elegant IMO, whatever that's worth). > > Is there a way to do that directly via the CSV API, > > Very doubtful; csv.writer (and reader for that matter) is implemented > in C, doesn't expose a ._file or similar attribute, and has no > .close() or .flush() methods. > The machinery implemented in C, but they are wrapped in Python, and it's a Python file object being passed to the writer, so I thought maybe there was a 'standard' method of exposing file objects in these types of cases that I just wasn't aware of, but it appears not. Thanks for the info! Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From blueeagle2 at gmail.com Mon Oct 24 15:47:56 2011 From: blueeagle2 at gmail.com (blueeagle2 at gmail.com) Date: Mon, 24 Oct 2011 12:47:56 -0700 Subject: Gui Builder for Python an wxPython Message-ID: I am just getting into gui building in python and I am trying to find a designer that is easy to use. I tried wxGlade and though it looks promising I could not get anywhere with it. It would not let me create a simple dialog application. If I were using MonoDevelop it would be a snap, but there does not seem to be any descent tutorials anywhere that I can find. One would think it would be rather intuitive, but it is not or at least not for me. I have looked at wxFormBuilder and QT4 with python and they both looked better. I was just wondering what anyone else would consider a good wxPython designer. I would even be willing to buy one if it was not too expensive and had descent tutorials and documentation. -------------- next part -------------- An HTML attachment was scrubbed... URL: From candide at free.invalid Mon Oct 24 15:51:53 2011 From: candide at free.invalid (candide) Date: Mon, 24 Oct 2011 21:51:53 +0200 Subject: Importing a module from a non-cwd Message-ID: <4ea5c1da$0$3708$426a74cc@news.free.fr> Hi, It's easy to open a file not located in the current working directory (cwd). But how about importing a module? For instance, suppose I have a file, say my_file.py, located in the cwd, say /home/candide/ and suppose the module to be imported, say my_module.py, is located in the /home/candide/foo/ directory. How my_file.py can import the my_module.py module ? Thanks From python at mrabarnett.plus.com Mon Oct 24 16:09:16 2011 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 24 Oct 2011 21:09:16 +0100 Subject: randrange exceptional behavior In-Reply-To: <4ea5bc04$0$6448$426a74cc@news.free.fr> References: <4ea5bc04$0$6448$426a74cc@news.free.fr> Message-ID: <4EA5C5EC.40606@mrabarnett.plus.com> On 24/10/2011 20:26, candide wrote: > Where is documented the behaviour of the standard function randrange in > the case of an empty list ? for instance randrange(42,33) ? May I rely > on an ValueError type error? It's the same back to at least Python 2.5, so you can probably rely on that behaviour. Interestingly, the documentation says: """This is equivalent to choice(range(start, stop, step)), but doesn?t actually build a range object.""" but for choice(seq) it says: """If seq is empty, raises IndexError.""" so it's not entirely equivalent. From jason.swails at gmail.com Mon Oct 24 16:13:50 2011 From: jason.swails at gmail.com (Jason Swails) Date: Mon, 24 Oct 2011 16:13:50 -0400 Subject: CSV writer question In-Reply-To: References: Message-ID: On Mon, Oct 24, 2011 at 3:03 AM, Chris Angelico wrote: > On Mon, Oct 24, 2011 at 4:18 PM, Jason Swails > wrote: > > my_csv = csv.writer(open('temp.1.csv', 'wb')) > > > > Have you confirmed, or can you confirm, whether or not the file gets > closed automatically when the writer gets destructed? If so, all you > need to do is: > > my_csv = something_else > # or: > del my_csv > I'm not sure why I decided against this approach in the first place. This does work (at least with my test), so it's what I'll do. I probably wasn't confident that it would clean itself up properly, but that's probably rather un-pythonic and would not have made it into the stdlib if that was the case. Thanks! Jason -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at andros.org.uk Mon Oct 24 16:35:13 2011 From: lists at andros.org.uk (Andrew McLean) Date: Mon, 24 Oct 2011 21:35:13 +0100 Subject: CSV writer question In-Reply-To: References: Message-ID: <4EA5CC01.9040007@andros.org.uk> On 24/10/2011 08:03, Chris Angelico wrote: > On Mon, Oct 24, 2011 at 4:18 PM, Jason Swails wrote: >> my_csv = csv.writer(open('temp.1.csv', 'wb')) >> > Have you confirmed, or can you confirm, whether or not the file gets > closed automatically when the writer gets destructed? If so, all you > need to do is: > > my_csv = something_else > # or: > del my_csv > > to unbind what I assume is the only reference to the csv.writer, upon > which it should promptly clean itself up. My understanding is that in cpython the file does get closed when the writer is deleted, however, it's not guaranteed to happen in other Python implementations (e.g. IronPython, PyPy and Jython). Andrew From candide at free.invalid Mon Oct 24 16:35:28 2011 From: candide at free.invalid (candide) Date: Mon, 24 Oct 2011 22:35:28 +0200 Subject: randrange exceptional behavior In-Reply-To: References: <4ea5bc04$0$6448$426a74cc@news.free.fr> Message-ID: <4ea5cc11$0$18839$426a74cc@news.free.fr> Le 24/10/2011 22:09, MRAB a ?crit : > but for choice(seq) it says: > Ah of course, I should have checked there > """If seq is empty, raises IndexError.""" > Thanks From gordon at panix.com Mon Oct 24 16:38:34 2011 From: gordon at panix.com (John Gordon) Date: Mon, 24 Oct 2011 20:38:34 +0000 (UTC) Subject: Importing a module from a non-cwd References: <4ea5c1da$0$3708$426a74cc@news.free.fr> Message-ID: In <4ea5c1da$0$3708$426a74cc at news.free.fr> candide writes: > For instance, suppose I have a file, say my_file.py, located in the cwd, > say /home/candide/ and suppose the module to be imported, say > my_module.py, is located in the /home/candide/foo/ directory. > How my_file.py can import the my_module.py module ? If PYTHONPATH and/or sys.path contain /home/candide/foo/, then you should be able to: import my_module Or, if foo/ is a real module (i.e. it contains an __init__.py file), this should work: import foo.my_module -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From __peter__ at web.de Mon Oct 24 17:09:16 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Oct 2011 23:09:16 +0200 Subject: CSV writer question References: Message-ID: Jason Swails wrote: > Hello, > > I have a question about a csv.writer instance. I have a utility that I > want to write a full CSV file from lots of data, but due to performance > (and memory) considerations, there's no way I can write the data > sequentially. Therefore, I write the data in chunks to temporary files, > then combine them > all at the end. For convenience, I declare each writer instance via a > statement like > > my_csv = csv.writer(open('temp.1.csv', 'wb')) > > so the open file object isn't bound to any explicit reference, and I don't > know how to reference it inside the writer class (the documentation > doesn't > say, unless I've missed the obvious). Thus, the only way I can think of > to make sure that all of the data is written before I start copying these > files sequentially into the final file is to unbuffer them so the above > command is changed to > > my_csv = csv.writer(open('temp.1.csv', 'wb', 0)) > > unless, of course, I add an explicit reference to track the open file > object > and manually close or flush it (but I'd like to avoid it if possible). My > question is 2-fold. Is there a way to do that directly via the CSV API, > or is the approach I'm taking the only way without binding the open file > object > to another reference? Secondly, if these files are potentially very large > (anywhere from ~1KB to 20 GB depending on the amount of data present), > what kind of performance hit will I be looking at by disabling buffering > on these types of files? > > Tips, answers, comments, and/or suggestions are all welcome. > > Thanks a lot! > Jason > > As an afterthought, I suppose I could always subclass the csv.writer class > and add the reference I want to that, which I may do if there's no other > convenient solution. A contextmanager might help: import csv from contextlib import contextmanager @contextmanager def filewriter(filename): with open(filename, "wb") as outstream: yield csv.writer(outstream) if __name__ == "__main__": with filewriter("tmp.csv") as writer: writer.writerows([ ["alpha", "beta"], ["gamma", "delta"]]) From bahamutzero8825 at gmail.com Mon Oct 24 17:29:25 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Mon, 24 Oct 2011 16:29:25 -0500 Subject: Creating very similar functions with different parameters Message-ID: <4EA5D8B5.8040703@gmail.com> I want to create a decorator with two different (but very similar) versions of the wrapper function, but without copying giant chunks of similar code. The main difference is that one version takes extra parameters. def test_dec(func, extra=False): if extra: def wrapper(ex_param1, ex_param2, *args, **kwargs): print('bla bla') print('more bla') print(ex_param1) print(ex_param2) func(ex_param1, ex_param2, *args, **kwargs) else: def wrapper(*args, **kwargs): print('bla bla') print('more bla') func(*args, **kwargs) return wrapper If the function I'm wrapping takes ex_param1 and ex_param2 as parameters, then the decorator should print them and then execute the function, otherwise just execute the function. I'd rather not write separate wrappers that are mostly the same. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 From ben+python at benfinney.id.au Mon Oct 24 17:36:46 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 25 Oct 2011 08:36:46 +1100 Subject: Python as a replacement to PL/SQL References: <87bot6sb2j.fsf@dpt-info.u-strasbg.fr> Message-ID: <87sjmijclt.fsf@benfinney.id.au> Alec Taylor writes: > What else is there besides PL/Python (for any DB) in the context of > writing stored procedures in function? I know of no server-side language other than SQL which can reasonably be expected to work ?for any DB?. PostgreSQL supports PL/pgSQL, PL/Python, PL/tcl, PL/Perl, and others . -- \ Moriarty: ?Forty thousand million billion dollars? That money | `\ must be worth a fortune!? ?The Goon Show, _The Sale of | _o__) Manhattan_ | Ben Finney From tjreedy at udel.edu Mon Oct 24 18:14:31 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Oct 2011 18:14:31 -0400 Subject: spawnl issues with Win 7 access rights In-Reply-To: <4EA573C8.1080502@timgolden.me.uk> References: <4EA565A3.3030909@timgolden.me.uk> <4EA573C8.1080502@timgolden.me.uk> Message-ID: On 10/24/2011 10:18 AM, Tim Golden wrote: > On 24/10/2011 14:18, Tim Golden wrote: > I ran this (on Python 2.7 on Win7): >> >> >> import os >> >> os.spawnl (os.P_NOWAIT, r"c:\windows\notepad.exe") >> >> >> >> and Python crashed hard! Long time since I've seen that happen. Same with 3.2 and Win7, interpreter or IDLE. > OK; the python 2.7 issues is http://bugs.python.org/issue8036 The example there used P_WAIT instead of P_NOWAIT, but I added comment. -- Terry Jan Reedy From tjreedy at udel.edu Mon Oct 24 18:16:46 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Oct 2011 18:16:46 -0400 Subject: spawnl issues with Win 7 access rights In-Reply-To: References: Message-ID: On 10/24/2011 9:47 AM, Propad wrote: y > nice. I can't imagine anything of such importance was not tested at > all during the beta phase - so it could be the tests were not run with > such a tricky configuration of windows. The coverage of the test suite is still being improved as people volunteer to write more tests. This mostly happens as part of bug fixing. -- Terry Jan Reedy From miki.tebeka at gmail.com Mon Oct 24 20:21:02 2011 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Mon, 24 Oct 2011 17:21:02 -0700 (PDT) Subject: spawnl issues with Win 7 access rights In-Reply-To: References: Message-ID: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> Please use the subprocess module, it's the one who's actively maintained. http://docs.python.org/library/subprocess.html#replacing-the-os-spawn-family From philr at aspexconsulting.co.nz Mon Oct 24 20:30:41 2011 From: philr at aspexconsulting.co.nz (Phil Runciman) Date: Tue, 25 Oct 2011 13:30:41 +1300 Subject: Stack Architecture - was "Good books in computer science?" Message-ID: This was part of an earlier discussion in this forum. I want to correct the impression created by Lawrence D'Oliveiro that those who implemented stacks were not designing for efficiency. > What I can say is that for scientific/engineering calculations the RPN of > KDF9 was Great because assembler was no harder than using algol60 for the > calculations part of the problems I worked on. Lawrence D'Oliveiro ldo at geek-central.gen.new_zealand Mon Jun 22 03:52:55 CEST 2009 Unfortunately, we had to learn the hard way that machine instruction sets must be designed for efficiency of execution, not ease of use by humans. Stack-based architectures, for all their charm, cannot match register-based ones in this regard. FWIW: "Efficiency" is a slippery notion with contextual connotations. KDF9 had two stacks in its CPU. (The SJNS and the Nesting Store or Nest - see Eric's thesis.) I am not suggesting that you are ill-informed, but that stacks are insufficiently represented in the literature. The use of call return stacks to support subroutine returns is almost universal. For the evaluation of arithmetical expressions, the use of hardware stacks is the most efficient. From what I have read, it is compiler writers who find it hard to emulate the efficiencies achieved by assembler programmers. Are hardware designers considering the compiler writers' problems when they design their hardware? This would be heavy irony indeed. That is why stacks came into existence in the first place. Regards, Phil References: http://is.uwaterloo.ca/Eric_LaForest_Thesis.pdf discusses the confusion of first and second generation stack-based architectures. It includes a rebuttal of the arguments against stack computers, cited by Hennessy and Patterson, showing that they are applicable to the first generation of stack computers, but not the second. Christopher Bailey's "Optimisation Techniques for Stack-Based Processors", PhD thesis, University of Teesside, UK, July 1996, Amongst other things, analyzes the use of stack buffers to reduce memory traffic. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nvidhya01 at gmail.com Mon Oct 24 22:40:29 2011 From: nvidhya01 at gmail.com (n v) Date: Mon, 24 Oct 2011 19:40:29 -0700 (PDT) Subject: python royals @@@@@@@@@ Message-ID: http://123maza.com/48/silver424/ From wuwei23 at gmail.com Mon Oct 24 23:01:49 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 24 Oct 2011 20:01:49 -0700 (PDT) Subject: Creating very similar functions with different parameters References: Message-ID: <036b09e0-d404-4c1b-848b-e216316fa882@u10g2000prl.googlegroups.com> Guido wrote an article on a quick and easy multimethod implementation using a decorator: http://www.artima.com/weblogs/viewpost.jsp?thread=101605 From wuwei23 at gmail.com Mon Oct 24 23:34:46 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 24 Oct 2011 20:34:46 -0700 (PDT) Subject: revive a generator References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> Message-ID: <0ff5c9b6-1314-4553-8378-deec2520e0ab@j36g2000prh.googlegroups.com> On Oct 21, 11:46?am, Yingjie Lan wrote: > I am still not sure why should we enforce that? > a generator can not be reused after an explicit? > request to revive it? No one is "enforcing" anything, you're simply resisting implementing this yourself. Consider the following generator: import random def randgen(): for _ in xrange(10): yield random.choice(['Hi','Lo']) >>> [x for x in randgen()] ['Hi', 'Hi', 'Lo', 'Hi', 'Lo', 'Lo', 'Lo', 'Lo', 'Hi', 'Hi'] What would you expect when you reset that generator? A newly randomised set of values, or the _same_ set of values? What if the generator is reading from an external source, like temperature values? Once revived, should it return the exact same sequence it originally did, or should it retrieve new values? Now, no matter which decision you made, why is your expectation of behaviour the right one? Why should the generator protocol support your convience in particular? If you need your generator to be re-usable, make a factory that creates it. From wuwei23 at gmail.com Mon Oct 24 23:37:49 2011 From: wuwei23 at gmail.com (alex23) Date: Mon, 24 Oct 2011 20:37:49 -0700 (PDT) Subject: revive a generator References: <87botblot6.fsf@no-fixed-abode.cable.virginmedia.net> <1319161590.56446.YahooMailNeo@web121509.mail.ne1.yahoo.com> Message-ID: <1615ba72-2b64-4164-8beb-b8a1b2752802@d33g2000prb.googlegroups.com> On Oct 21, 12:09?pm, Yingjie Lan wrote: > Secondly, it would be nice to automatically revive it. Sure, it's always nice when your expectation of a language feature exactly matches with its capabilities. When it doesn't, you suck it up and code around it. Because at the very least it's a hell of a lot quicker than waiting for the language to change for you. From steve+comp.lang.python at pearwood.info Mon Oct 24 23:46:36 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 25 Oct 2011 03:46:36 GMT Subject: Creating very similar functions with different parameters References: Message-ID: <4ea6311b$0$29973$c3e8da3$5496439d@news.astraweb.com> On Mon, 24 Oct 2011 16:29:25 -0500, Andrew Berg wrote: > I want to create a decorator with two different (but very similar) > versions of the wrapper function, but without copying giant chunks of > similar code. The main difference is that one version takes extra > parameters. > > def test_dec(func, extra=False): > if extra: > def wrapper(ex_param1, ex_param2, *args, **kwargs): > print('bla bla') > print('more bla') > print(ex_param1) > print(ex_param2) > func(ex_param1, ex_param2, *args, **kwargs) > else: > def wrapper(*args, **kwargs): > print('bla bla') > print('more bla') > func(*args, **kwargs) > return wrapper > > If the function I'm wrapping takes ex_param1 and ex_param2 as > parameters, then the decorator should print them and then execute the > function, otherwise just execute the function. I'd rather not write > separate wrappers that are mostly the same. In principle you could inspect the function's calling signature using the inspect module, and then decide how to decorate it from that. But I recommend against that: it's too much like magic. This is how I would do it: from functools import wraps def decorator_factory(extras=None): """Factory function which returns a decorator. Usage: @decorator_factory(): # Note you need the parentheses. def spam(...): return ... @decorator_factory((extra1, extra2)): def spam(...): return ... """ # Inner function performing common functionality. def preamble(): print('bla bla') print('more bla') # Decide what sort of decorator is needed. if extras is None: # Create decorator style 1. def decorator(func): @wraps(func) def inner(*args, **kwargs): preamble() return func(*args, **kwargs) return inner else: # Create decorator style 2. extra1, extra2 = extras def decorator(func): @wraps(func) def inner(*args, **kwargs): preamble() print(extra1) print(extra2) return func(extra1, extra2, *args, **kwargs) return inner return decorator If you don't like nested functions inside nested functions, you can pull out the inner functions: def preamble(): print('bla bla') print('more bla') def plain_decorator(func): @wraps(func) def inner(*args, **kwargs): preamble() return func(*args, **kwargs) return inner def extra_decorator(func): @wraps(extra1, extra2, func) def inner(*args, **kwargs): preamble() print(extra1) print(extra2) return func(extra1, extra2, *args, **kwargs) return inner def decorator_factory(plain): if plain: return plain_decorator else: return extra_decorator -- Steven From ulrich.eckhardt at dominolaser.com Tue Oct 25 02:49:59 2011 From: ulrich.eckhardt at dominolaser.com (Ulrich Eckhardt) Date: Tue, 25 Oct 2011 08:49:59 +0200 Subject: Exception Handling (C - extending python) In-Reply-To: References: <75930aea-ed09-44f8-b7ca-0fa9f72e6b12@g27g2000pro.googlegroups.com> Message-ID: Am 23.10.2011 14:41, schrieb Stefan Behnel: > That's just fine. If you are interested in the inner mechanics of the > CPython runtime, reading the source is a very good way to start getting > involved with the project. > > However, many extension module authors don't care about these inner > mechanics and just use Cython instead. That keeps them from having to > learn the C-API of CPython, and from tying their code too deeply into > the CPython runtime itself. Could you elaborate a bit? What are the pros and cons of writing an extension module using the Cython API compared to using the CPyothon API? In particular, how portable is it? Can I compile a module in one and use it in the other? Don't I just tie myself to a different API, but tie myself nonetheless? Thank you! Uli From npropadovic at googlemail.com Tue Oct 25 03:01:13 2011 From: npropadovic at googlemail.com (Propad) Date: Tue, 25 Oct 2011 00:01:13 -0700 (PDT) Subject: spawnl issues with Win 7 access rights References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> Message-ID: <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> On 25 Okt., 02:21, Miki Tebeka wrote: > Please use the subprocess module, it's the one who's actively maintained.http://docs.python.org/library/subprocess.html#replacing-the-os-spawn... Thnx again for all the answers. As stated before, I'm limited in my options. One of them just might be to switch to Python 2.5, rewrite the code that crashes using the subprocess module, and then somehow patch the library I use (which I'm not suposed to do, but... oh well :-)). I can just hope subrocess was already mature adn offering the relevant functionality in 2.5. Cheers, Nenad From gilles.lenfant at gmail.com Tue Oct 25 03:13:50 2011 From: gilles.lenfant at gmail.com (Gilles Lenfant) Date: Tue, 25 Oct 2011 00:13:50 -0700 (PDT) Subject: [wanted] python-ldap for Python 2.3 / Win32 Message-ID: <16595266.1315.1319526830836.JavaMail.geo-discussion-forums@yqhp35> Hi, I have spent a couple of hours asking google, browsing Pypi, SF, and of course the official www.python-ldap.org site searching for a python-ldap installer for Python 2.3 on Windows 32 bits. Unsuccessfully :( As I need to add this to an ooold Plone site, it is not easy to upgrade to a newer Python version. So, please don't tell me to upgrade ;) Many thanks by advance to the people who will help me. You can send this package via mail to gillesDOTlenfantATgmailDOTcom. -- Gilles Lenfant From michael at stroeder.com Tue Oct 25 03:50:54 2011 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 25 Oct 2011 09:50:54 +0200 Subject: UnicodeError instead of UnicodeWarning Message-ID: HI! For tracking the cause of a UnicodeWarning I'd like to make the Python interpreter to raise an UnicodeError exception with full stack trace. Is there a short trick to achieve this? Many thanks in advance. Ciao, Michael. From ramapraba2653 at gmail.com Tue Oct 25 03:51:24 2011 From: ramapraba2653 at gmail.com (SUPREME) Date: Tue, 25 Oct 2011 00:51:24 -0700 (PDT) Subject: HOT HOT HOT Message-ID: <3a89a6d6-9628-4629-8b5c-fbc4bb0f129b@x16g2000prd.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html SAKUNI MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/sakuni-movie-stills.html 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html FOR ONLY HOT GUYS SEE THIS PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html SNEHA ULLAL HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/sneha-ullal-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html From as at sci.fi Tue Oct 25 04:11:02 2011 From: as at sci.fi (Anssi Saari) Date: Tue, 25 Oct 2011 11:11:02 +0300 Subject: What is wrong with my code? References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> Message-ID: apometron writes: > Now it is another > thing, entirely. Rename1.py and Rename2.py works, but why Rename3.py > dont works? Well, Rename3.py works for me, even in Windows 7. Maybe you should test it again? From clp2 at rebertia.com Tue Oct 25 04:11:39 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 25 Oct 2011 01:11:39 -0700 Subject: UnicodeError instead of UnicodeWarning In-Reply-To: References: Message-ID: 2011/10/25 Michael Str?der : > HI! > > For tracking the cause of a UnicodeWarning I'd like to make the Python > interpreter to raise an UnicodeError exception with full stack trace. Is there > a short trick to achieve this? from exceptions import UnicodeWarning from warnings import filterwarnings filterwarnings(action="error", category=UnicodeWarning) This will cause UnicodeWarnings to be raised as exceptions when they occur. Cheers, Chris -- http://rebertia.com From stefan_ml at behnel.de Tue Oct 25 04:22:04 2011 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 25 Oct 2011 10:22:04 +0200 Subject: Exception Handling (C - extending python) In-Reply-To: References: <75930aea-ed09-44f8-b7ca-0fa9f72e6b12@g27g2000pro.googlegroups.com> Message-ID: Ulrich Eckhardt, 25.10.2011 08:49: > Am 23.10.2011 14:41, schrieb Stefan Behnel: >> That's just fine. If you are interested in the inner mechanics of the >> CPython runtime, reading the source is a very good way to start getting >> involved with the project. >> >> However, many extension module authors don't care about these inner >> mechanics and just use Cython instead. That keeps them from having to >> learn the C-API of CPython, and from tying their code too deeply into >> the CPython runtime itself. > > Could you elaborate a bit? What are the pros and cons of writing an > extension module using the Cython API compared to using the CPyothon API? No cons. ;) Cython is not an API, it's a programming language. It's Python, but with extended support for talking to C/C++ code (and also Fortran). That means that you don't have to use the C-API yourself, because Cython will do it for you. > In particular, how portable is it? Can I compile a module in one and use it > in the other? They both use the CPython C-API internally. It's just that you are not using it explicitly in your code, so you (can) keep your own code free of CPython-isms. It's substantially more portable than the "usual" hand-written code, because it generates C code for you that compiles and works in CPython 2.4 up to the latest 3.3 in-development version, and also with all major C/C++ compilers, etc. It also generates faster glue code than you would write, e.g. for data type conversion and argument unpacking in function calls. So it speeds up thin wrappers automatically for you. That doesn't mean that you can't get the same level of speed and portability in hand-written code. It just means that you don't have to do it yourself. Saves a lot of time, both during development and later during the maintenance cycle. Basically, it allows you to focus on the functionality you want to implement, rather than the implementation details of CPython, and also keeps the maintenance overhead at that level for you. > Don't I just tie myself to a different API, but tie myself > nonetheless? There's a port to plain Python+ctypes underways, for example, which you could eventually use in PyPy. Try to do that at the C-API level. Stefan From __peter__ at web.de Tue Oct 25 04:22:11 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Oct 2011 10:22:11 +0200 Subject: UnicodeError instead of UnicodeWarning References: Message-ID: Michael Str?der wrote: > For tracking the cause of a UnicodeWarning I'd like to make the Python > interpreter to raise an UnicodeError exception with full stack trace. Is > there a short trick to achieve this? You can control warning behaviour with the -W commandline option: $ cat unicodewarning_demo.py # -*- coding: utf-8 -*- def g(): "?" == u"?" def f(n=3): if n: f(n-1) else: g() if __name__ == "__main__": f() $ python unicodewarning_demo.py unicodewarning_demo.py:4: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal "?" == u"?" $ python -W error::UnicodeWarning unicodewarning_demo.py Traceback (most recent call last): File "unicodewarning_demo.py", line 13, in f() File "unicodewarning_demo.py", line 8, in f f(n-1) File "unicodewarning_demo.py", line 8, in f f(n-1) File "unicodewarning_demo.py", line 8, in f f(n-1) File "unicodewarning_demo.py", line 10, in f g() File "unicodewarning_demo.py", line 4, in g "?" == u"?" UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal $ From apometron.listas.cinco at gmail.com Tue Oct 25 04:24:22 2011 From: apometron.listas.cinco at gmail.com (apometron) Date: Tue, 25 Oct 2011 06:24:22 -0200 Subject: What is wrong with my code? In-Reply-To: References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> Message-ID: <4EA67236.5040907@gmail.com> I did it very much times, Anssi. Beyond of run it on Python 2.7 latest build, what do you suggest? Do install Python 3.2 along the Python 2.7 installation could give me any problems? cheers, Apometron http://about.me/apometron On 10/25/2011 6:11 AM, Anssi Saari wrote: > apometron writes: > >> Now it is another >> thing, entirely. Rename1.py and Rename2.py works, but why Rename3.py >> dont works? > Well, Rename3.py works for me, even in Windows 7. Maybe you should test > it again? From michael at stroeder.com Tue Oct 25 04:36:35 2011 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Tue, 25 Oct 2011 10:36:35 +0200 Subject: [wanted] python-ldap for Python 2.3 / Win32 In-Reply-To: <16595266.1315.1319526830836.JavaMail.geo-discussion-forums@yqhp35> References: <16595266.1315.1319526830836.JavaMail.geo-discussion-forums@yqhp35> Message-ID: Gilles Lenfant wrote: > I have spent a couple of hours asking google, browsing Pypi, SF, and of > course the official www.python-ldap.org site searching for a python-ldap > installer for Python 2.3 on Windows 32 bits. Unsuccessfully :( In theory even recent python-ldap 2.4.3 should still work with Python 2.3. Please post your inquiry on the mailing-list python-ldap at python.org (subscribe before post). Maybe you can convince the maintainer of the Win32 packages there. Ciao, Michael. From d at davea.name Tue Oct 25 05:34:11 2011 From: d at davea.name (Dave Angel) Date: Tue, 25 Oct 2011 05:34:11 -0400 Subject: [Tutor] What is wrong with my code? In-Reply-To: <4EA67236.5040907@gmail.com> References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> <4EA67236.5040907@gmail.com> Message-ID: <4EA68293.9070805@davea.name> (Once again, please don't top-post. It makes your responses out of order) On 10/25/2011 04:24 AM, apometron wrote: > I did it very much times, Anssi. > > Beyond of run it on Python 2.7 latest build, what do you suggest? > > Do install Python 3.2 along the Python 2.7 installation could give me > any problems? > Why don't you say publicly that you aren't using cmd ? If your file manager is not running the equivalent of python yourprogram.py filename.txt then everyone here is chasing a wild goose. Switch to the command line, issue a sequence of commands that cause the failure, and paste them in a message here. Then if it works, but doesn't from your file manager, you/we/they can address the differences from the working command line. -- DaveA From apometron.listas.cinco at gmail.com Tue Oct 25 06:09:38 2011 From: apometron.listas.cinco at gmail.com (apometron) Date: Tue, 25 Oct 2011 08:09:38 -0200 Subject: [Tutor] What is wrong with my code? In-Reply-To: <4EA68293.9070805@davea.name> References: <4EA3E68A.5010301@gmail.com> <4EA49BA2.6080309@davea.name> <4EA67236.5040907@gmail.com> <4EA68293.9070805@davea.name> Message-ID: <4EA68AE2.2080309@gmail.com> On 10/25/2011 7:34 AM, Dave Angel wrote: > (Once again, please don't top-post. It makes your responses out of > order) > > On 10/25/2011 04:24 AM, apometron wrote: >> I did it very much times, Anssi. >> >> Beyond of run it on Python 2.7 latest build, what do you suggest? >> >> Do install Python 3.2 along the Python 2.7 installation could give me >> any problems? >> > > Why don't you say publicly that you aren't using cmd ? > > If your file manager is not running the equivalent of > > > python yourprogram.py filename.txt > > > then everyone here is chasing a wild goose. > > Switch to the command line, issue a sequence of commands that cause > the failure, and paste them in a message here. Then if it works, but > doesn't from your file manager, you/we/they can address the > differences from the working command line. > I found out what it is. It is the File Commander giving wrong informations to the script. In Take Command command line it works sweet. I will show all this to the File Commander author and ask him some way to solve this. It turns out do the thing in command line every time is not best way. I need do it by the file manager. But the file manager was puting stones in the way. Take Command has a script language also, but I would like do the things in Python, if possible. And this difficulty with File Commander makes use Python a thing less easy to do. Question solved. It was not Take Command the problem and I was sure it was not. Enter in command line to do things is a pain. =( I mean, e-ve-ry ti-me. But then, good news, all the three scripts works smoothly in the command line. Do you believe drag and drop in the Windows Explorer can be my salvation? Cool thing to try. []s Apometron http://about.me/apometron From fabiofz at gmail.com Tue Oct 25 07:09:28 2011 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Tue, 25 Oct 2011 09:09:28 -0200 Subject: Strange classmethod mock behavior Message-ID: I'm trying to mock a classmethod in a superclass but when restoring it a strange behavior happens in subclasses (tested on Python 2.5) Anyone knows why this happens? (see test case below for details) Is there any way to restore that original method to have the original behavior? import unittest class Test(unittest.TestCase): def testClassmethod(self): class Super(): @classmethod def GetCls(cls): return cls class Sub(Super): pass self.assertEqual(Sub.GetCls(), Sub) original = Super.GetCls #Mock Super.GetCls, and do tests... Super.GetCls = original #Restore the original classmethod self.assertEqual(Sub.GetCls(), Sub) #The call to the classmethod subclass returns the cls as Super and not Sub as expected! if __name__ == '__main__': unittest.main() From __peter__ at web.de Tue Oct 25 08:08:08 2011 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Oct 2011 14:08:08 +0200 Subject: Strange classmethod mock behavior References: Message-ID: Fabio Zadrozny wrote: > I'm trying to mock a classmethod in a superclass but when restoring it > a strange behavior happens in subclasses (tested on Python 2.5) > > Anyone knows why this happens? (see test case below for details) > Is there any way to restore that original method to have the original > behavior? > > import unittest > > class Test(unittest.TestCase): > > def testClassmethod(self): > class Super(): > @classmethod > def GetCls(cls): > return cls > > class Sub(Super): > pass > > self.assertEqual(Sub.GetCls(), Sub) > > original = Super.GetCls > #Mock Super.GetCls, and do tests... > Super.GetCls = original #Restore the original classmethod > self.assertEqual(Sub.GetCls(), Sub) #The call to the > classmethod subclass returns the cls as Super and not Sub as expected! > > if __name__ == '__main__': > unittest.main() [Not related to your problem] When working with descriptors it's a good idea to use newstyle classes, i. e. have Super inherit from object. The Super.GetCls attribute access is roughly equivalent to Super.__dict___["GetCls"].__get__(classmethod_instance, None, Super) and returns an object that knows about its class. So when you think you are restoring the original method you are actually setting the GetCls attribute to something else. You can avoid the problem by accessing the attribute explicitly: >>> class Super(object): ... @classmethod ... def m(cls): return cls ... >>> bad = Super.m >>> good = Super.__dict__["m"] >>> class Sub(Super): pass ... >>> Sub.m() >>> Super.m = bad >>> Sub.m() >>> Super.m = good >>> Sub.m() From mail at timgolden.me.uk Tue Oct 25 08:19:28 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 25 Oct 2011 13:19:28 +0100 Subject: spawnl issues with Win 7 access rights In-Reply-To: <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> Message-ID: <4EA6A950.6090706@timgolden.me.uk> On 25/10/2011 08:01, Propad wrote: > Thnx again for all the answers. As stated before, I'm limited in my > options. One of them just might be to switch to Python 2.5, rewrite > the code that crashes using the subprocess module, and then somehow > patch the library I use (which I'm not suposed to do, but... oh > well :-)). I can just hope subrocess was already mature adn offering > the relevant functionality in 2.5. I must admit I'm more than slightly surprised by this. My test case is to use os.spawnl to run c:/windows/notepad.exe. From the docs, I would expect to use os.spawnl (os.P_WAIT, "c:/windows/notepad.exe"). (I only want to open notepad.exe; there's no need for additional args). These are my test cases: (1) os.spawnl ( os.P_WAIT, "c:/windows/notepad.exe" ) (2) os.spawnl ( os.P_WAIT, "c:/windows/notepad.exe", "c:/windows/notepad.exe" ) (3) os.spawnl ( os.P_WAIT, "c:/windows/notepad.exe", "c:/windows/notepad.exe", "c:/temp.txt" ) And the results: ============================================================== Python | Platform | Case | Result -------------------------------------------------------------- 2.2.2 | WinXP | 1 | Works (empty notepad) 2.2.2 | WinXP | 2 | Works (empty notepad) 2.2.2 | WinXP | 3 | Works (notepad temp.txt) -------------------------------------------------------------- 2.2.2 | Win7 | 1 | OSError 2.2.2 | Win7 | 2 | Works (empty notepad) 2.2.2 | Win7 | 3 | Works (notepad temp.txt) -------------------------------------------------------------- 2.7.2 | WinXP | 1 | Crashes 2.7.2 | WinXP | 2 | Works (empty notepad) 2.7.2 | WinXP | 3 | Works (notepad temp.txt) -------------------------------------------------------------- 2.7.2 | Win7 | 1 | Crashes 2.7.2 | Win7 | 2 | Works (empty notepad) 2.7.2 | Win7 | 3 | Works (notepad temp.txt) ============================================================== Add to this a look at the mscrt source which ships with VS 2008 and the MSDN docs for spawnl: http://msdn.microsoft.com/en-us/library/wweek9sc%28v=vs.80%29.aspx and we see that the first args parameter must be the same as the path parameter. FWIW, at no extra cost, I went to the trouble of testing it on some flavour of Linux with Python 2.6 and got the same results as per 2.2.2 on WinXP. (Basically: everything works). Which leaves us with http://bugs.python.org/issue8036 in which recent versions of Python crash when the (arbitrary) second parameter isn't passed. And with an inexplicable behaviour change between the same version of Python running on WinXP and on Win7. It looks as though the workaround for your problem (or, possibly, your failure to fulfil some artificial parameter requirements) is to add the executable again as the third parameter. issue8036 (which also affects the execl family) has a patch waiting for review, which hopefully we can get round to fixing. As far as I can tell, the execl/spawnl family of functions isn't currently represented in the testsuite. TJG From gandalf at shopzeus.com Tue Oct 25 09:50:59 2011 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 25 Oct 2011 15:50:59 +0200 Subject: webapp development in pure python Message-ID: <4EA6BEC3.5010206@shopzeus.com> Hi, Anyone knows a framework for webapp development? I'm not talking about javascript/html compilers and ajax frameworks. I need something that does not require javascript knowledge, just pure Python. (So qooxdoo is not really an option, because it cannot be programmed in Python. You cannot even put out a window on the center of the screen without using javascript code, and you really have to be a javascript expert to write useful applications with qooxdoo.) What I need is a programmable GUI with windows, event handlers and extensible widgets, for creating applications that use http/https and a web browser for rendering. Is there something like this already available? Thanks, Laszlo From anurag.chourasia at gmail.com Tue Oct 25 10:12:28 2011 From: anurag.chourasia at gmail.com (Anurag Chourasia) Date: Tue, 25 Oct 2011 19:42:28 +0530 Subject: webapp development in pure python In-Reply-To: <4EA6BEC3.5010206@shopzeus.com> References: <4EA6BEC3.5010206@shopzeus.com> Message-ID: Have you considered Django ? http://www.djangoproject.com/ Regards, Anurag On Tue, Oct 25, 2011 at 7:20 PM, Laszlo Nagy wrote: > > Hi, > > Anyone knows a framework for webapp development? I'm not talking about > javascript/html compilers and ajax frameworks. I need something that does > not require javascript knowledge, just pure Python. (So qooxdoo is not > really an option, because it cannot be programmed in Python. You cannot even > put out a window on the center of the screen without using javascript code, > and you really have to be a javascript expert to write useful applications > with qooxdoo.) > > What I need is a programmable GUI with windows, event handlers and > extensible widgets, for creating applications that use http/https and a web > browser for rendering. > > Is there something like this already available? > > Thanks, > > Laszlo > > > > -- > http://mail.python.org/**mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at gmail.com Tue Oct 25 10:13:45 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Tue, 25 Oct 2011 15:13:45 +0100 Subject: webapp development in pure python In-Reply-To: <4EA6BEC3.5010206@shopzeus.com> References: <4EA6BEC3.5010206@shopzeus.com> Message-ID: On 25 October 2011 14:50, Laszlo Nagy wrote: > > ?Hi, > > Anyone knows a framework for webapp development? I'm not talking about > javascript/html compilers and ajax frameworks. I need something that does > not require javascript knowledge, just pure Python. (So qooxdoo is not > really an option, because it cannot be programmed in Python. You cannot even > put out a window on the center of the screen without using javascript code, > and you really have to be a javascript expert to write useful applications > with qooxdoo.) > > What I need is a programmable GUI with windows, event handlers and > extensible widgets, for creating applications that use http/https and a web > browser for rendering. So you're looking for something like Google Web Toolkit but using Python instead of Java... Do you know about pyjamas (http://pyjs.org/)? I've never used it, but I think it endeavours to be what you are looking for. HTH -- Arnaud From martin.hellwig at gmail.com Tue Oct 25 10:19:52 2011 From: martin.hellwig at gmail.com (Martin P. Hellwig) Date: Tue, 25 Oct 2011 15:19:52 +0100 Subject: webapp development in pure python In-Reply-To: References: <4EA6BEC3.5010206@shopzeus.com> Message-ID: On 10/25/11 15:13, Arnaud Delobelle wrote: > On 25 October 2011 14:50, Laszlo Nagy wrote: >> >> Hi, >> >> Anyone knows a framework for webapp development? I'm not talking about >> javascript/html compilers and ajax frameworks. I need something that does >> not require javascript knowledge, just pure Python. (So qooxdoo is not >> really an option, because it cannot be programmed in Python. You cannot even >> put out a window on the center of the screen without using javascript code, >> and you really have to be a javascript expert to write useful applications >> with qooxdoo.) >> >> What I need is a programmable GUI with windows, event handlers and >> extensible widgets, for creating applications that use http/https and a web >> browser for rendering. > > So you're looking for something like Google Web Toolkit but using > Python instead of Java... > > Do you know about pyjamas (http://pyjs.org/)? I've never used it, but > I think it endeavours to be what you are looking for. > > HTH > Second that, I use it for a couple of my projects for exactly that. -- mph From ian.g.kelly at gmail.com Tue Oct 25 10:40:48 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 25 Oct 2011 08:40:48 -0600 Subject: Creating very similar functions with different parameters In-Reply-To: <4EA5D8B5.8040703@gmail.com> References: <4EA5D8B5.8040703@gmail.com> Message-ID: On Mon, Oct 24, 2011 at 3:29 PM, Andrew Berg wrote: > I want to create a decorator with two different (but very similar) > versions of the wrapper function, but without copying giant chunks of > similar code. The main difference is that one version takes extra > parameters. > > def test_dec(func, extra=False): > ? ? ? ?if extra: > ? ? ? ? ? ? ? ?def wrapper(ex_param1, ex_param2, *args, **kwargs): > ? ? ? ? ? ? ? ? ? ? ? ?print('bla bla') > ? ? ? ? ? ? ? ? ? ? ? ?print('more bla') > ? ? ? ? ? ? ? ? ? ? ? ?print(ex_param1) > ? ? ? ? ? ? ? ? ? ? ? ?print(ex_param2) > ? ? ? ? ? ? ? ? ? ? ? ?func(ex_param1, ex_param2, *args, **kwargs) > ? ? ? ?else: > ? ? ? ? ? ? ? ?def wrapper(*args, **kwargs): > ? ? ? ? ? ? ? ? ? ? ? ?print('bla bla') > ? ? ? ? ? ? ? ? ? ? ? ?print('more bla') > ? ? ? ? ? ? ? ? ? ? ? ?func(*args, **kwargs) > ? ? ? ?return wrapper > > If the function I'm wrapping takes ex_param1 and ex_param2 as > parameters, then the decorator should print them and then execute the > function, otherwise just execute the function. I'd rather not write > separate wrappers that are mostly the same. Others have given more involved suggestions, but in this case you could just make the wrapper a closure and check the flag there: def test_dec(func, extra=False): def wrapper(*args, **kwargs): print('bla bla') print('more bla') if extra: ex_param1, ex_param2 = args[:2] print(ex_param1) print(ex_param2) func(*args, **kwargs) return wrapper Cheers, Ian From dihedral88888 at googlemail.com Tue Oct 25 11:39:09 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Tue, 25 Oct 2011 08:39:09 -0700 (PDT) Subject: Creating very similar functions with different parameters In-Reply-To: References: <4EA5D8B5.8040703@gmail.com> Message-ID: <22702775.328.1319557149527.JavaMail.geo-discussion-forums@prms22> Thanks for the debug modes in functional programing! Everything functional is true in CS at least in the theroy! From dihedral88888 at googlemail.com Tue Oct 25 11:39:09 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Tue, 25 Oct 2011 08:39:09 -0700 (PDT) Subject: Creating very similar functions with different parameters In-Reply-To: References: <4EA5D8B5.8040703@gmail.com> Message-ID: <22702775.328.1319557149527.JavaMail.geo-discussion-forums@prms22> Thanks for the debug modes in functional programing! Everything functional is true in CS at least in the theroy! From sidorenko.andrey at gmail.com Tue Oct 25 11:51:27 2011 From: sidorenko.andrey at gmail.com (spintronic) Date: Tue, 25 Oct 2011 08:51:27 -0700 (PDT) Subject: Data acquisition Message-ID: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Dear friends, I have a trouble with understanding the following. I have a very short script (shown below) which works fine if I "run" step by step (or line by line) in Python shell (type the first line/command -> press Enter, etc.). I can get all numbers (actually, there are no numbers but a long string, but this is not a problem) I need from a device: '0.3345098119,0.01069121274,0.02111624694,0.03833379529,0.02462816409,0.0774275008,0.06554297421,0.07366750919,0.08122602002,0.004018369318,0.03508462415,0.04829900696,0.06383554085, ...' However, when I start very the same list of commands as a script, it gives me the following, which is certainly wrong: [0.0, 0.0, 0.0, 0.0, 0.0,...] Any ideas? Why there is a difference when I run the script or do it command by command? =========================== from visa import * mw = instrument("GPIB0::20::INSTR", timeout = None) mw.write("*RST") mw.write("CALC1:DATA? FDATA") a=mw.read() print a =========================== (That is really all!) PS In this case I use Python Enthought for Windows, but I am not an expert in Windows (I work usually in Linux but now I need to run this data acquisition under Windows). From jeanmichel at sequans.com Tue Oct 25 12:15:22 2011 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 25 Oct 2011 18:15:22 +0200 Subject: Data acquisition In-Reply-To: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: <4EA6E09A.5000403@sequans.com> spintronic wrote: > Dear friends, > > I have a trouble with understanding the following. I have a very short > script (shown below) which works fine if I "run" step by step (or line > by line) in Python shell (type the first line/command -> press Enter, > etc.). I can get all numbers (actually, there are no numbers but a > long string, but this is not a problem) I need from a device: > > '0.3345098119,0.01069121274,0.02111624694,0.03833379529,0.02462816409,0.0774275008,0.06554297421,0.07366750919,0.08122602002,0.004018369318,0.03508462415,0.04829900696,0.06383554085, ...' > > However, when I start very the same list of commands as a script, it > gives me the following, which is certainly wrong: > > [0.0, 0.0, 0.0, 0.0, 0.0,...] > > Any ideas? Why there is a difference when I run the script or do it > command by command? > > =========================== > from visa import * > > mw = instrument("GPIB0::20::INSTR", timeout = None) > > mw.write("*RST") > mw.write("CALC1:DATA? FDATA") > > a=mw.read() > > print a > =========================== > (That is really all!) > > > PS In this case I use Python Enthought for Windows, but I am not an > expert in Windows (I work usually in Linux but now I need to run this > data acquisition under Windows). > Just in case you have a local installation of visa and it silently fails on some import, try to add at the begining of your script: import sys sys.path.append('') When using the python shell cmd line, '' is added to sys.path by the shell, that is one difference that can make relative imports fail in your script. If it's still not working, well, it means the problem is somewhere else. JM From nicholas.dokos at hp.com Tue Oct 25 12:29:45 2011 From: nicholas.dokos at hp.com (Nick Dokos) Date: Tue, 25 Oct 2011 12:29:45 -0400 Subject: Data acquisition In-Reply-To: Message from spintronic of "Tue, 25 Oct 2011 08:51:27 PDT." <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: <4784.1319560185@alphaville.dokosmarshall.org> spintronic wrote: > Dear friends, > > I have a trouble with understanding the following. I have a very short > script (shown below) which works fine if I "run" step by step (or line > by line) in Python shell (type the first line/command -> press Enter, > etc.). I can get all numbers (actually, there are no numbers but a > long string, but this is not a problem) I need from a device: > > '0.3345098119,0.01069121274,0.02111624694,0.03833379529,0.02462816409,0.0774275008,0.06554297421,0.07366750919,0.08122602002,0.004018369318,0.03508462415,0.04829900696,0.06383554085, ...' > > However, when I start very the same list of commands as a script, it > gives me the following, which is certainly wrong: > > [0.0, 0.0, 0.0, 0.0, 0.0,...] > > Any ideas? Why there is a difference when I run the script or do it > command by command? > > =========================== > from visa import * > > mw = instrument("GPIB0::20::INSTR", timeout = None) > > mw.write("*RST") > mw.write("CALC1:DATA? FDATA") > > a=mw.read() > > print a > =========================== > (That is really all!) > > > PS In this case I use Python Enthought for Windows, but I am not an > expert in Windows (I work usually in Linux but now I need to run this > data acquisition under Windows). > -- > http://mail.python.org/mailman/listinfo/python-list > Shot in the dark: could it be that you have to add delays to give the instrument time to adjust? When you do it from the python shell, line by line, there is a long delay between one line and the next. Nick From gandalf at shopzeus.com Tue Oct 25 12:33:30 2011 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 25 Oct 2011 18:33:30 +0200 Subject: webapp development in pure python In-Reply-To: References: <4EA6BEC3.5010206@shopzeus.com> Message-ID: <4EA6E4DA.2080307@shopzeus.com> >>> Anyone knows a framework for webapp development? I'm not talking about >>> javascript/html compilers and ajax frameworks. I need something that >>> does >>> not require javascript knowledge, just pure Python. (So qooxdoo is not >>> really an option, because it cannot be programmed in Python. You >>> cannot even >>> put out a window on the center of the screen without using >>> javascript code, >>> and you really have to be a javascript expert to write useful >>> applications >>> with qooxdoo.) >>> >>> What I need is a programmable GUI with windows, event handlers and >>> extensible widgets, for creating applications that use http/https >>> and a web >>> browser for rendering. >> >> So you're looking for something like Google Web Toolkit but using >> Python instead of Java... >> >> Do you know about pyjamas (http://pyjs.org/)? I've never used it, but >> I think it endeavours to be what you are looking for. As I told, I'm not talking about javascript/html compilers and ajax frameworks. Pyjamas is both a javascript compiler and an ajax framework. My Python module would connect to a database server and query some data, then display it in a grid. This cannot be compiled into javascript because of the database server connection. With pyjamas, I would have to create the server side part separately, the user interface separately, and hand-code the communication between the widets and the server side. I would like to use this theoretical web based framework just like pygtk or wxPython: create windows, place widgets on them, implement event handlers etc. and access the widgets and other server side resources (for example, a database connection) from the same source code. Transparently. So the web part would really just be the rendering part of the user inferface. This may not be possible at all.. My other idea was to use a freenx server and wxPython. Is it a better solution? Have anyone used this combination from an android tablet, for example? Would it work? Thanks, Laszlo From gordon at panix.com Tue Oct 25 12:43:42 2011 From: gordon at panix.com (John Gordon) Date: Tue, 25 Oct 2011 16:43:42 +0000 (UTC) Subject: Data acquisition References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: In <362e368f-829e-4477-bcfc-c0650d231029 at j7g2000yqi.googlegroups.com> spintronic writes: > Any ideas? Why there is a difference when I run the script or do it > command by command? Are you running the same python program in both cases? Are you in the same directory in both cases? Does PYTHONPATH and/or sys.path have the same value in both cases? Show us an exact transscript of both executions. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From sidorenko.andrey at gmail.com Tue Oct 25 13:22:39 2011 From: sidorenko.andrey at gmail.com (spintronic) Date: Tue, 25 Oct 2011 10:22:39 -0700 (PDT) Subject: Data acquisition References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: On Oct 25, 6:29?pm, Nick Dokos wrote: > Shot in the dark: could it be that you have to add delays to give the > instrument time to adjust? When you do it from the python shell, line by > line, there is a long delay between one line and the next. > > Nick Hi, Nick! Thanks! You are right but it was the first thing I thought about. So I have tried to delay using sleep(t) from the time module (I also sent "*OPC?" or "*WAI" commands to a device for synchronization). However, it does not help ... Best, AS From sidorenko.andrey at gmail.com Tue Oct 25 13:31:04 2011 From: sidorenko.andrey at gmail.com (spintronic) Date: Tue, 25 Oct 2011 10:31:04 -0700 (PDT) Subject: Data acquisition References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: <86e6bfb8-17e1-4544-97ba-7299db8a8140@p16g2000yqj.googlegroups.com> On Oct 25, 6:43?pm, John Gordon wrote: Thanks, John! > Are you running the same python program in both cases? Yes, the same. > Are you in the same directory in both cases? > Does PYTHONPATH and/or sys.path have the same value in both cases? It looks that yes but how can it matter? All I need it is to import the visa module and it works well. > Show us an exact transscript of both executions. There is nothing but "numbers". Or do you mean something else? I do not receive any errors, only different results ... Best, AS From sidorenko.andrey at gmail.com Tue Oct 25 13:35:42 2011 From: sidorenko.andrey at gmail.com (spintronic) Date: Tue, 25 Oct 2011 10:35:42 -0700 (PDT) Subject: Data acquisition References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: <8692a942-5e33-4063-a55f-7c02f3690b4a@hv4g2000vbb.googlegroups.com> On Oct 25, 6:15?pm, Jean-Michel Pichavant wrote: > spintronic wrote: > > Dear friends, > > > I have a trouble with understanding the following. I have a very short > > script (shown below) which works fine if I "run" step by step (or line > > by line) in Python shell (type the first line/command -> press Enter, > > etc.). I can get all numbers (actually, there are no numbers but a > > long string, but this is not a problem) I need from a device: > > > '0.3345098119,0.01069121274,0.02111624694,0.03833379529,0.02462816409,0.0774275008,0.06554297421,0.07366750919,0.08122602002,0.004018369318,0.03508462415,0.04829900696,0.06383554085, ...' > > > However, when I start very the same list of commands as a script, it > > gives me the following, which is certainly wrong: > > > [0.0, 0.0, 0.0, 0.0, 0.0,...] > > > Any ideas? Why there is a difference when I run the script or do it > > command by command? > > > =========================== > > from visa import * > > > mw = instrument("GPIB0::20::INSTR", timeout = None) > > > mw.write("*RST") > > mw.write("CALC1:DATA? FDATA") > > > a=mw.read() > > > print a > > =========================== > > (That is really all!) > > > PS In this case I use Python Enthought for Windows, but I am not an > > expert in Windows (I work usually in Linux but now I need to run this > > data acquisition under Windows). > > Just in case you have a local installation of visa and it silently fails > on some import, > > try to add at the begining of your script: > import sys > sys.path.append('') > > When using the python shell cmd line, '' is added to sys.path by the > shell, that is one difference that can make relative imports fail in > your script. > > If it's still not working, well, it means the problem is somewhere else. > > JM Hi! Thanks! I have just tried. Unfortunately, it does not work ... Best, AS From gordon at panix.com Tue Oct 25 14:34:41 2011 From: gordon at panix.com (John Gordon) Date: Tue, 25 Oct 2011 18:34:41 +0000 (UTC) Subject: Data acquisition References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> <86e6bfb8-17e1-4544-97ba-7299db8a8140@p16g2000yqj.googlegroups.com> Message-ID: In <86e6bfb8-17e1-4544-97ba-7299db8a8140 at p16g2000yqj.googlegroups.com> spintronic writes: > > Are you in the same directory in both cases? > > Does PYTHONPATH and/or sys.path have the same value in both cases? > It looks that yes but how can it matter? All I need it is to import > the visa module and it works well. If you run the two cases from different directories, and the current directory is in PYTHONPATH or sys.path, and one of the directories contains a python file named "visa.py" and the other doesn't, that culd account for the difference in output. Do you have access to the visa.py source code? Can you add a simple print statement near the top of the module so that we know the same visa.py module is being imported in both cases? > > Show us an exact transscript of both executions. > There is nothing but "numbers". Or do you mean something else? I do > not receive any errors, only different results ... I was more interested in the exact commands you used to run both cases, rather than the output. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From ameyer2 at yahoo.com Tue Oct 25 15:50:59 2011 From: ameyer2 at yahoo.com (Alan Meyer) Date: Tue, 25 Oct 2011 15:50:59 -0400 Subject: How to isolate a constant? In-Reply-To: References: Message-ID: <4EA71323.2030500@yahoo.com> On 10/22/2011 8:46 PM, MRAB wrote: > On 23/10/2011 01:26, Gnarlodious wrote: >> Say this: >> >> class tester(): >> _someList = [0, 1] >> def __call__(self): >> someList = self._someList >> someList += "X" >> return someList >> >> test = tester() >> >> But guess what, every call adds to the variable that I am trying to >> copy each time: >> test() >>> [0, 1, 'X'] >> test() >>> [0, 1, 'X', 'X'] ... > Python will copy something only when you tell it to copy. A simple way > of copying a list is to slice it: > > someList = self._someList[:] And another simple way: ... someList = list(self._someList) ... Alan From ian.g.kelly at gmail.com Tue Oct 25 16:05:49 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 25 Oct 2011 14:05:49 -0600 Subject: How to isolate a constant? In-Reply-To: <4EA71323.2030500@yahoo.com> References: <4EA71323.2030500@yahoo.com> Message-ID: On Tue, Oct 25, 2011 at 1:50 PM, Alan Meyer wrote: >> Python will copy something only when you tell it to copy. A simple way >> of copying a list is to slice it: >> >> someList = self._someList[:] > > And another simple way: > > ? ?... > ? ?someList = list(self._someList) > ? ?... I generally prefer the latter. It's clearer, and it guarantees that the result will be a list, which is usually what you want in these situations, rather than whatever unexpected type was passed in. Cheers, Ian From slc at publicus.net Tue Oct 25 17:18:07 2011 From: slc at publicus.net (Steven Clift) Date: Tue, 25 Oct 2011 16:18:07 -0500 Subject: Python developers interested in local communities, GroupServer Message-ID: My non-profit uses the GPL Python-based http://GroupServer.org platform to host local neighborhood online communities in the U.S., the UK, and New Zealand. We are users of GroupServer and not the owner of the project. We are plotting a future new features hackathon (in person in Minneapolis and perhaps simultaneously elsewhere) and are looking for python programmers with a particular interest in connecting people in local places. If you are interested in learning more, please contact us at team at e-democracy.org or http://e-democracy.org/contact Or join the GroupServer development group - http://groupserver.org/groups/development - where we will definitely making an announcement. We will also announce it here on the Local Labs online group: http://e-democracy.org/labs Thanks, Steven Clift E-Democracy.org P.S. GroupServer is probably the best open source hybrid e-mail list/web forum out there. Not the best e-mail list. And not the best web forum. But the best fully integrated approach. Example use with some customizations: http://e-democracy.org From waldemar.osuch at gmail.com Tue Oct 25 17:19:08 2011 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Tue, 25 Oct 2011 14:19:08 -0700 (PDT) Subject: [wanted] python-ldap for Python 2.3 / Win32 In-Reply-To: References: <16595266.1315.1319526830836.JavaMail.geo-discussion-forums@yqhp35> Message-ID: <4818553.676.1319577549027.JavaMail.geo-discussion-forums@yqnv12> I did try to build it using my current setup but it failed with some linking errors. Oh well. Google gods were nicer to me. Here is a couple alternative links. Maybe they will work for you. http://web.archive.org/web/20081101060042/http://www.agescibs.org/mauro/ http://old.zope.org/Members/volkerw/LdapWin32/ Waldemar From news at schwertberger.de Tue Oct 25 17:31:52 2011 From: news at schwertberger.de (Dietmar Schwertberger) Date: Tue, 25 Oct 2011 23:31:52 +0200 Subject: Data acquisition In-Reply-To: References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: Am 25.10.2011 19:22, schrieb spintronic: > On Oct 25, 6:29 pm, Nick Dokos wrote: >> Shot in the dark: could it be that you have to add delays to give the >> instrument time to adjust? When you do it from the python shell, line by >> line, there is a long delay between one line and the next. > Thanks! You are right but it was the first thing I thought about. So I > have tried to delay using sleep(t) from the time module (I also sent > "*OPC?" or "*WAI" commands to a device for synchronization). However, > it does not help ... RST is resetting all data and CALC is somehow calculating and returning data. Without a trigger between RST and CALC, I would not expect any data... Maybe the equipment is triggering continuously e.g. every second. When you were using the shell, you had a good chance to see a trigger between RST and CALC. With a script, it's not so likely. OPC won't help, as it would wait for completion of a measurement, but if you don't trigger, it won't wait. What kind of instrument are you using? Check for the trigger command. It may be something like INIT:IMM Regards, Dietmar From gilles.lenfant at gmail.com Tue Oct 25 17:56:26 2011 From: gilles.lenfant at gmail.com (Gilles Lenfant) Date: Tue, 25 Oct 2011 14:56:26 -0700 (PDT) Subject: [wanted] python-ldap for Python 2.3 / Win32 In-Reply-To: <4818553.676.1319577549027.JavaMail.geo-discussion-forums@yqnv12> References: <16595266.1315.1319526830836.JavaMail.geo-discussion-forums@yqhp35> <4818553.676.1319577549027.JavaMail.geo-discussion-forums@yqnv12> Message-ID: <10174006.847.1319579786925.JavaMail.geo-discussion-forums@yqlb4> So many thanks for your valuable help Waldemar, this is exactly what I needed. I have no Windows machine to compile with the source bundle all this, and must install this directly in a production server. I'll keep these precious links and files in a trunk. Many thanks again -- Gilles Lenfant From psimon at sonic.net Tue Oct 25 18:06:31 2011 From: psimon at sonic.net (Paul Simon) Date: Tue, 25 Oct 2011 15:06:31 -0700 Subject: Data acquisition References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: <4ea7331e$0$1715$742ec2ed@news.sonic.net> "spintronic" wrote in message news:362e368f-829e-4477-bcfc-c0650d231029 at j7g2000yqi.googlegroups.com... > Dear friends, > > I have a trouble with understanding the following. I have a very short > script (shown below) which works fine if I "run" step by step (or line > by line) in Python shell (type the first line/command -> press Enter, > etc.). I can get all numbers (actually, there are no numbers but a > long string, but this is not a problem) I need from a device: > > '0.3345098119,0.01069121274,0.02111624694,0.03833379529,0.02462816409,0.0774275008,0.06554297421,0.07366750919,0.08122602002,0.004018369318,0.03508462415,0.04829900696,0.06383554085, > ...' > > However, when I start very the same list of commands as a script, it > gives me the following, which is certainly wrong: > > [0.0, 0.0, 0.0, 0.0, 0.0,...] > > Any ideas? Why there is a difference when I run the script or do it > command by command? > > =========================== > from visa import * > > mw = instrument("GPIB0::20::INSTR", timeout = None) > > mw.write("*RST") > mw.write("CALC1:DATA? FDATA") > > a=mw.read() > > print a > =========================== > (That is really all!) > > > PS In this case I use Python Enthought for Windows, but I am not an > expert in Windows (I work usually in Linux but now I need to run this > data acquisition under Windows). I'm almost certain that there is a turnaround timing issue that is causing the problem. These are common problems in data aquisition systems. The simplest solution is to loop and wait for end of line from the sending end and if necessary put in a time delay. After receiving the data, check the received data for correct format, correct first and last characters, and if possible, check sum. I've worked through this problem with rs-485 data collection systems where there is no hand shaking and would not be surprised to expect the same even with rs-232. Paul Simon From invalid at invalid.invalid Tue Oct 25 18:50:57 2011 From: invalid at invalid.invalid (Grant Edwards) Date: Tue, 25 Oct 2011 22:50:57 +0000 (UTC) Subject: How to pretty-print ctypes composite data types? Message-ID: I'm using ctypes with a library that requires a handful of structure definitions. The actual definitions and usage aren't a problem. When it comes time to print out the values in a structure or array, there doesn't seem to be simple/general way to do that. Am I missing something? I presume one can recursively iterate through the fields in a structure and elements in an array, recursing on any composite types and printing the values when one finds a type, but I'm surprised that's not something that's already in the ctypes library somewhere -- the authors certainly seem to have thought of everything else. -- Grant Edwards grant.b.edwards Yow! I own seven-eighths of at all the artists in downtown gmail.com Burbank! From fabiofz at gmail.com Tue Oct 25 18:59:26 2011 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Tue, 25 Oct 2011 20:59:26 -0200 Subject: Strange classmethod mock behavior In-Reply-To: References: Message-ID: On Tue, Oct 25, 2011 at 10:08 AM, Peter Otten <__peter__ at web.de> wrote: > Fabio Zadrozny wrote: > >> I'm trying to mock a classmethod in a superclass but when restoring it >> a strange behavior happens in subclasses (tested on Python 2.5) >> >> Anyone knows why this happens? (see test case below for details) >> Is there any way to restore that original method to have the original >> behavior? >> >> import unittest >> >> class Test(unittest.TestCase): >> >> ? ? def testClassmethod(self): >> ? ? ? ? class Super(): >> ? ? ? ? ? ? @classmethod >> ? ? ? ? ? ? def GetCls(cls): >> ? ? ? ? ? ? ? ? return cls >> >> ? ? ? ? class Sub(Super): >> ? ? ? ? ? ? pass >> >> ? ? ? ? self.assertEqual(Sub.GetCls(), Sub) >> >> ? ? ? ? original = Super.GetCls >> ? ? ? ? #Mock Super.GetCls, and do tests... >> ? ? ? ? Super.GetCls = original #Restore the original classmethod >> ? ? ? ? self.assertEqual(Sub.GetCls(), Sub) #The call to the >> classmethod subclass returns the cls as Super and not Sub as expected! >> >> if __name__ == '__main__': >> ? ? unittest.main() > > [Not related to your problem] When working with descriptors it's a good idea > to use newstyle classes, i. e. have Super inherit from object. > > The Super.GetCls attribute access is roughly equivalent to > > Super.__dict___["GetCls"].__get__(classmethod_instance, None, Super) > > and returns an object that knows about its class. So when you think you are > restoring the original method you are actually setting the GetCls attribute > to something else. You can avoid the problem by accessing the attribute > explicitly: > >>>> class Super(object): > ... ? ? @classmethod > ... ? ? def m(cls): return cls > ... >>>> bad = Super.m >>>> good = Super.__dict__["m"] >>>> class Sub(Super): pass > ... >>>> Sub.m() > >>>> Super.m = bad >>>> Sub.m() > >>>> Super.m = good >>>> Sub.m() > > Hi Peter, thanks for the explanation. Printing it helped me understand it even better... print(Super.__dict__['GetCls']) print(Super.GetCls) > Cheers, Fabio From ian.g.kelly at gmail.com Tue Oct 25 20:30:32 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 25 Oct 2011 18:30:32 -0600 Subject: How to isolate a constant? In-Reply-To: References: <4EA71323.2030500@yahoo.com> Message-ID: On Tue, Oct 25, 2011 at 6:08 PM, Dennis Lee Bieber wrote: > Where's the line form to split those who'd prefer the first vs the > second result in this sample : > >>>> unExpected = "What about a string" >>>> firstToLast = unExpected[:] Strings are immutable. That doesn't suffice to copy them, even assuming you would want to do so in the first place. >>> unExpected is firstToLast True If you find yourself needing to make a copy, that usually means that you plan on modifying either the original or the copy, which in turn means that you need a type that supports modification operations, which usually means a list. If you pass in a string and then copy it with [:] and then try to modify it, you'll get an exception. If you don't try to modify it, then you probably didn't need to copy it in the first place. Cheers, Ian From tjreedy at udel.edu Tue Oct 25 21:11:15 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 Oct 2011 21:11:15 -0400 Subject: spawnl issues with Win 7 access rights In-Reply-To: <4EA6A950.6090706@timgolden.me.uk> References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> <4EA6A950.6090706@timgolden.me.uk> Message-ID: On 10/25/2011 8:19 AM, Tim Golden wrote: > On 25/10/2011 08:01, Propad wrote: >> Thnx again for all the answers. As stated before, I'm limited in my >> options. One of them just might be to switch to Python 2.5, rewrite >> the code that crashes using the subprocess module, and then somehow >> patch the library I use (which I'm not suposed to do, but... oh >> well :-)). I can just hope subrocess was already mature adn offering >> the relevant functionality in 2.5. > > I must admit I'm more than slightly surprised by this. My test case > is to use os.spawnl to run c:/windows/notepad.exe. From the docs, > I would expect to use os.spawnl (os.P_WAIT, "c:/windows/notepad.exe"). > (I only want to open notepad.exe; there's no need for additional args). > > These are my test cases: > > (1) > > os.spawnl ( > os.P_WAIT, > "c:/windows/notepad.exe" > ) > > (2) > > os.spawnl ( > os.P_WAIT, > "c:/windows/notepad.exe", > "c:/windows/notepad.exe" > ) > > (3) > > os.spawnl ( > os.P_WAIT, > "c:/windows/notepad.exe", > "c:/windows/notepad.exe", > "c:/temp.txt" > ) > > > And the results: > > ============================================================== > Python | Platform | Case | Result > -------------------------------------------------------------- > 2.2.2 | WinXP | 1 | Works (empty notepad) > 2.2.2 | WinXP | 2 | Works (empty notepad) > 2.2.2 | WinXP | 3 | Works (notepad temp.txt) > -------------------------------------------------------------- > 2.2.2 | Win7 | 1 | OSError > 2.2.2 | Win7 | 2 | Works (empty notepad) > 2.2.2 | Win7 | 3 | Works (notepad temp.txt) > -------------------------------------------------------------- > 2.7.2 | WinXP | 1 | Crashes > 2.7.2 | WinXP | 2 | Works (empty notepad) > 2.7.2 | WinXP | 3 | Works (notepad temp.txt) > -------------------------------------------------------------- > 2.7.2 | Win7 | 1 | Crashes > 2.7.2 | Win7 | 2 | Works (empty notepad) > 2.7.2 | Win7 | 3 | Works (notepad temp.txt) > ============================================================== > > > Add to this a look at the mscrt source which ships with VS 2008 > and the MSDN docs for spawnl: > > http://msdn.microsoft.com/en-us/library/wweek9sc%28v=vs.80%29.aspx > > and we see that the first args parameter must be the same as the > path parameter. > > FWIW, at no extra cost, I went to the trouble of testing it on some > flavour of Linux with Python 2.6 and got the same results > as per 2.2.2 on WinXP. (Basically: everything works). > > Which leaves us with http://bugs.python.org/issue8036 in which recent > versions of Python crash when the (arbitrary) second parameter isn't > passed. And with an inexplicable behaviour change between the same > version of Python running on WinXP and on Win7. OP reports 2.6 with XP works. Did that use VS 2005? Maybe C runtime changed (regressed). Also, could there be a 32 v. 64 bit issue? -- Terry Jan Reedy From mwilson at the-wire.com Tue Oct 25 22:48:12 2011 From: mwilson at the-wire.com (Mel) Date: Tue, 25 Oct 2011 22:48:12 -0400 Subject: How to isolate a constant? References: <4EA71323.2030500@yahoo.com> Message-ID: Dennis Lee Bieber wrote: > Where's the line form to split those who'd prefer the first vs the > second result in this sample : > >>>> unExpected = "What about a string" >>>> firstToLast = unExpected[:] >>>> repr(firstToLast) > "'What about a string'" >>>> explicitList = list(unExpected) >>>> repr(explicitList) > "['W', 'h', 'a', 't', ' ', 'a', 'b', 'o', 'u', 't', ' ', 'a', ' ', 's', > 't', 'r', 'i', 'n', 'g']" >>>> Well, as things stand, there's a way to get whichever result you need. The `list` constructor builds a single list from a single iterable. The list literal enclosed by `[`, `]` makes a list containing a bunch of items. Strings being iterable introduces a wrinkle, but `list('abcde')` doesn't create `['abcde']` just as `list(1)` doesn't create `[1]`. Mel. From fred.sells at adventistcare.org Tue Oct 25 23:00:52 2011 From: fred.sells at adventistcare.org (Sells, Fred) Date: Tue, 25 Oct 2011 23:00:52 -0400 Subject: webapp development in pure python In-Reply-To: <4EA6E4DA.2080307@shopzeus.com> References: <4EA6BEC3.5010206@shopzeus.com> <4EA6E4DA.2080307@shopzeus.com> Message-ID: Quixote may be what you want, but it's been years since I've used it and I don't know if it is still alive and kicking. It was from MEMS if I remember correctly. Using django and Flex is one way to avoid html and javascript and it works great for datagrids. Fred. From wuwei23 at gmail.com Tue Oct 25 23:15:21 2011 From: wuwei23 at gmail.com (alex23) Date: Tue, 25 Oct 2011 20:15:21 -0700 (PDT) Subject: webapp development in pure python References: <4EA6BEC3.5010206@shopzeus.com> Message-ID: <571a97cb-5ebc-4882-ad67-1ff7953383b7@u10g2000prl.googlegroups.com> Laszlo Nagy wrote: > My Python module would connect to a database server and query > some data, then display it in a grid. This cannot be compiled into > javascript because of the database server connection. So what you want is for everything to happen server-side, with html output sent to the client? Perhaps you could build on top of ToscaWidgets. They encapsulate HTML & JS, so you'll still need to work with them for custom widgets. > With pyjamas, I > would have to create the server side part separately, the user interface > separately, and hand-code the communication between the widets and the > server side. That's pretty much true of all non-trivial web development, though. There's a lot to be said for sucking it up and embracing traditional methods rather than flying against common wisdom and cobbling together something that works against web technologies rather than with them. From puntabluda at gmail.com Wed Oct 26 03:29:10 2011 From: puntabluda at gmail.com (Rebelo) Date: Wed, 26 Oct 2011 00:29:10 -0700 (PDT) Subject: webapp development in pure python In-Reply-To: References: <4EA6BEC3.5010206@shopzeus.com> Message-ID: <18902163.1637.1319614150053.JavaMail.geo-discussion-forums@yqp37> Try Pylons. Use html templates which get populated with data from your database and then just render them. If you just want to display data, with simple forms for editing and adding Pylons framework is more then enough. http://pylonsbook.com/en/1.1/ http://www.pylonsproject.org/ From puntabluda at gmail.com Wed Oct 26 03:29:10 2011 From: puntabluda at gmail.com (Rebelo) Date: Wed, 26 Oct 2011 00:29:10 -0700 (PDT) Subject: webapp development in pure python In-Reply-To: References: <4EA6BEC3.5010206@shopzeus.com> Message-ID: <18902163.1637.1319614150053.JavaMail.geo-discussion-forums@yqp37> Try Pylons. Use html templates which get populated with data from your database and then just render them. If you just want to display data, with simple forms for editing and adding Pylons framework is more then enough. http://pylonsbook.com/en/1.1/ http://www.pylonsproject.org/ From vinay_sajip at yahoo.co.uk Wed Oct 26 05:12:58 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Wed, 26 Oct 2011 09:12:58 +0000 (UTC) Subject: logging: warn() methods and function to be deprecated. References: <4EA4A65F.2090205@gmail.com> <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> <4EA5787F.1050906@vrplumber.com> Message-ID: Mike C. Fletcher vrplumber.com> writes: > I actually consider .warning() a nit :) . After all, it's 3 extra > characters :) , and *who* actually reads documentation instead of just > poking around and finding the shortest-named method in the instance? Readability counts :-) Are you saying there's no need to bother documenting stuff ??? ;-) > Anyway, I personally don't see this as worth the breakage. What breakage are we really talking about? Remember, Python 2.x will not change in this area - the proposed change is for Python 3.3 and later only, and will not be backported :-) As far as I know, Trac doesn't work with Python 3 anyway. Most of the code out there (which Mark found via Google Code Search) is Python 2.x. When porting from 2 to 3.3, it's just one extra little thing to deal with - small compared with other issues which come up when doing such ports. Regards, Vinay Sajip From amirouche.boubekki at gmail.com Wed Oct 26 05:14:02 2011 From: amirouche.boubekki at gmail.com (Amirouche Boubekki) Date: Wed, 26 Oct 2011 11:14:02 +0200 Subject: Forking simplejson Message-ID: H?llo, I would like to fork simplejson [1] and implement serialization rules based on protocols instead of types [2], plus special cases for protocol free objects, that breaks compatibility. The benefit will be a better API for json serialization of custom classes and in the case of iterable it will avoid a calls like: >>> simplejson.dumps(list(my_iterable)) The serialization of custom objects is documented in the class instead of the ``default`` function of current simplejson implementation [3]. The encoding algorithm works with a priority list that is summarized in the next table: +-------------------+---------------+ | Python protocol | JSON | | or special case | | +===================+===============+ | (?) __json__ | see (?) | +-------------------+---------------| | map | object | +-------------------+---------------+ | iterable | array | +-------------------+---------------+ | (*) float,int,long| number | +-------------------+---------------+ | (*) True | true | +-------------------+---------------+ | (*) False | false | +-------------------+---------------+ | (*) None | null | +-------------------+---------------+ | (?) unicode | see (?) | +-------------------+---------------+ (?) if the object implements a __json__ method, the returned value is used as the serialization of the object (*) special objects which are protocol free are serialized the same way it's done currently in simplejson (?) if the algorithm arrives here, call unicode (with proper encoding rule) on the object and use the result as json serialization As soon as an object match a rule, it's serialized. What do you think ? Do you find this API an improvement over simplejson ? Is it worth to code ? Where are documented the different protocols implemented by Python objects ? Regards, Amirouche [1] https://github.com/simplejson/simplejson [2] https://github.com/simplejson/simplejson/blob/master/simplejson/encoder.py#L75 [3] http://simplejson.readthedocs.org/en/latest/index.html#simplejson.JSONEncoder.default -------------- next part -------------- An HTML attachment was scrubbed... URL: From mcfletch at vrplumber.com Wed Oct 26 09:01:11 2011 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Wed, 26 Oct 2011 09:01:11 -0400 Subject: logging: warn() methods and function to be deprecated. In-Reply-To: References: <4EA4A65F.2090205@gmail.com> <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> <4EA5787F.1050906@vrplumber.com> Message-ID: <4EA80497.9050600@vrplumber.com> On 11-10-26 05:12 AM, Vinay Sajip wrote: > Mike C. Fletcher vrplumber.com> writes: > >> I actually consider .warning() a nit :) . After all, it's 3 extra >> characters :) , and *who* actually reads documentation instead of just >> poking around and finding the shortest-named method in the instance? > Readability counts :-) Are you saying there's no need to bother documenting > stuff ??? ;-) More: an undocumented entry point is not "deprecated" because, after all, it shows up in PyDoc as a regular method. > >> Anyway, I personally don't see this as worth the breakage. > > What breakage are we really talking about? Remember, Python 2.x will not change > in this area - the proposed change is for Python 3.3 and later only, and will > not be backported :-) > > As far as I know, Trac doesn't work with Python 3 anyway. Most of the code out > there (which Mark found via Google Code Search) is Python 2.x. When porting from > 2 to 3.3, it's just one extra little thing to deal with - small compared with > other issues which come up when doing such ports. Sure, but most of *everything* is Python 2.x, and porting to Python 3.x is already enough of a pain that key-stone projects like Trac still aren't there :) . This isn't going to be easily amenable to auto-translation via 2to3 (because you generally are calling log.warn() rather than logging.warning, but sometimes you are doing getattr( log, log_level ) and then passing that method around a few times), and it will often fall into the small percentage of untested code in most projects (coverage is often poor for logging messages in corner cases), so often won't get caught by test suites. Not a 3.x user, but expecting to have to be some day in the future, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From roy at panix.com Wed Oct 26 09:06:14 2011 From: roy at panix.com (Roy Smith) Date: Wed, 26 Oct 2011 09:06:14 -0400 Subject: webapp development in pure python References: <4EA6BEC3.5010206@shopzeus.com> <18902163.1637.1319614150053.JavaMail.geo-discussion-forums@yqp37> Message-ID: In article <18902163.1637.1319614150053.JavaMail.geo-discussion-forums at yqp37>, Rebelo wrote: > Try Pylons. Use html templates which get populated with data from your > database and then just render them. If you just want to display data, with > simple forms for editing and adding Pylons framework is more then enough. > > http://pylonsbook.com/en/1.1/ > http://www.pylonsproject.org/ If you're looking at web frameworks, you should also look at http://www.tornadoweb.org/. It's more of a HTTP engine than a application framework, but has some elements of both. We use it for lots of small HTTP tools we write. But, to go back to the OP's request: > What I need is a programmable GUI with windows, event handlers and > extensible widgets, for creating applications that use http/https and a web > browser for rendering. combined with: > I need something that does not require javascript knowledge, just pure Python. I'm not sure there's a good answer to that. If you're talking GUIs, windows, and extensible widgets, it really sounds like the kinds of things you're trying to do are going to require javascript. I'm not a huge fan of javascript, but the reality today is that for any kind of interactive UI in a web browser, you need to go there. Well, or Flash, but that's probably even more evil. You might want to look at [[Dart (programming language)]], but that's more of a research project than a tool at the moment. Check out that wikipedia page, however, it's got some pointers to other similar projects people are working on. From projetmbc at gmail.com Wed Oct 26 09:42:07 2011 From: projetmbc at gmail.com (projetmbc) Date: Wed, 26 Oct 2011 06:42:07 -0700 (PDT) Subject: Parsing using one gramar with contexts Message-ID: <28f0eeb3-da28-4738-8d1b-8e4e373c0e3e@f13g2000vbv.googlegroups.com> Hello, I'm seeking for one friendly library to parse one language with taking care of the context. For example, I would like to parse text in one docstring differently than the other code, or to add special keyword for the parsing when I'm in one class... Is there existing python tools for that ? From andrea.crotti.0 at gmail.com Wed Oct 26 10:22:00 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Wed, 26 Oct 2011 15:22:00 +0100 Subject: services/daemons Message-ID: <4EA81788.8080706@gmail.com> Running pypiserver as a service? I'm writing some scripts which in theory should be able to: - start up a local pypi server as a daemon (or well a service on Windows) - run "python setup.py develop" on a potentially very big set of eggs, possibly discovering automatically for changes. In theory using develop changes should be automatically seen, but if I move/rename something of course things might not work anymore. - run/debug/develop applications using this big set of eggs. On the distutils list it was suggested to use the "-m" option to easy_install, which avoids writing on the global easy_install.pth, which is one of the current problems. For the first one reading I thought I might use pypiserver (which ships also as a single file) and create a windows service/unix daemon from it. For the second I've seen watchdog: https://github.com/gorakhargosh/watchdog/ which looks interesting. As last thing the whole process should be as transparent and robust as possible, anyone did something similar or has suggestions? From mail at timgolden.me.uk Wed Oct 26 10:38:42 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 26 Oct 2011 15:38:42 +0100 Subject: spawnl issues with Win 7 access rights In-Reply-To: References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> <4EA6A950.6090706@timgolden.me.uk> Message-ID: <4EA81B72.7040008@timgolden.me.uk> On 26/10/2011 02:11, Terry Reedy wrote: > OP reports 2.6 with XP works. Where do you see that, Terry? (Or was there an offlist email?) > Did that use VS 2005? Maybe C runtime > changed (regressed). That's possible -- and is essentially my main guess (faute de mieux). I've got the same results on 32 & 64-bit machines. Hopefully the workaround I suggested -- doubling up the executable filepath -- will get round the user's particular issue. I'm not going to fight CRT changes, but if no-one else gets there, I will try to address issue8036 TJG From vinay_sajip at yahoo.co.uk Wed Oct 26 10:51:21 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Wed, 26 Oct 2011 14:51:21 +0000 (UTC) Subject: logging: warn() methods and function to be deprecated. References: <4EA4A65F.2090205@gmail.com> <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> <4EA5787F.1050906@vrplumber.com> <4EA80497.9050600@vrplumber.com> Message-ID: Mike C. Fletcher vrplumber.com> writes: > More: an undocumented entry point is not "deprecated" because, after > all, it shows up in PyDoc as a regular method. Deprecated methods also show up in PyDoc. Of course, if the deprecation is mentioned in the docstring, users would see this - but if it isn't, they wouldn't know until they got a DeprecationWarning. > auto-translation via 2to3 (because you generally are calling log.warn() > rather than logging.warning, but sometimes you are doing getattr( log, > log_level ) and then passing that method around a few times), and it That doesn't sound like a good usage pattern to me, especially as loggers have a log method which takes the logging level. There shouldn't be any need to pass a bound method around. Regards, Vinay Sajip From challb at gmail.com Wed Oct 26 11:51:44 2011 From: challb at gmail.com (Chris Hall) Date: Wed, 26 Oct 2011 08:51:44 -0700 (PDT) Subject: Review Python site with useful code snippets Message-ID: <98598900-8b72-4bb2-b21e-13666c9f823b@p16g2000yqd.googlegroups.com> I am looking to get reviews, comments, code snippet suggestions, and feature requests for my site. I intend to grow out this site with all kinds of real world code examples to learn from and use in everyday coding. The site is: http://www.pythonsnippet.com If you have anything to contribute or comment, please post it on the site or email me directly. Thanks, Chris From sidorenko.andrey at gmail.com Wed Oct 26 11:58:45 2011 From: sidorenko.andrey at gmail.com (spintronic) Date: Wed, 26 Oct 2011 08:58:45 -0700 (PDT) Subject: Data acquisition References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> Message-ID: <1059c1c4-4581-412d-ad08-6fba6289444d@l12g2000vby.googlegroups.com> Dear friends! Thank you for the discussion. It was really helpful. As mentioned, it was necessary to have a longer delay. Previously I have used a delay of 5 and 10 s but it was not long enough. Now it is 25 s and everything works fine. Thank you again! Best, AS From mcfletch at vrplumber.com Wed Oct 26 12:20:06 2011 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Wed, 26 Oct 2011 12:20:06 -0400 Subject: logging: warn() methods and function to be deprecated. In-Reply-To: References: <4EA4A65F.2090205@gmail.com> <1319444908.73851.YahooMailNeo@web25801.mail.ukl.yahoo.com> <4EA5787F.1050906@vrplumber.com> <4EA80497.9050600@vrplumber.com> Message-ID: <4EA83336.2020903@vrplumber.com> On 11-10-26 10:51 AM, Vinay Sajip wrote: ... > auto-translation via 2to3 (because you generally are calling log.warn() >> rather than logging.warning, but sometimes you are doing getattr( log, >> log_level ) and then passing that method around a few times), and it > That doesn't sound like a good usage pattern to me, especially as loggers have a > log method which takes the logging level. There shouldn't be any need to pass a > bound method around. Bound methods also pull along to *which* log you are going to send the message, but then I suppose you could just use the logging key as well as a piece of data. I'll withdraw the suggestion that it is not a trivial thing to add to 2to3, though I'll leave the implementation to someone else. Have fun, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From nathan.alexander.rice at gmail.com Wed Oct 26 13:34:04 2011 From: nathan.alexander.rice at gmail.com (Nathan Rice) Date: Wed, 26 Oct 2011 13:34:04 -0400 Subject: Forking simplejson In-Reply-To: References: Message-ID: Since this happily went off to the wrong recipient the first time... The python json module/simpljson are badly in need of an architecture update. The fact that you can't override the encode method of JSONEncoder and have it work reliably without monkey patching the pure python encoder is a sign that something is horribly wrong. On Wed, Oct 26, 2011 at 5:14 AM, Amirouche Boubekki wrote: > H?llo, > > I would like to fork simplejson [1] and implement serialization rules based > on protocols instead of types [2], plus special cases for protocol free > objects, that breaks compatibility. The benefit will be a better API for > json serialization of custom classes and in the case of iterable it will > avoid a calls like: > >>>> simplejson.dumps(list(my_iterable)) > > The serialization of custom objects is documented in the class instead of > the ``default`` function of current simplejson implementation [3]. > > The encoding algorithm works with a priority list that is summarized in the > next table: > > +-------------------+---------------+ > | Python protocol | JSON | > > > | or special case | | > +===================+===============+ > | (?) __json__ | see (?) | > > > +-------------------+---------------| > > | map | object | > > > +-------------------+---------------+ > | iterable | array | > +-------------------+---------------+ > | (*) float,int,long| number | > > > +-------------------+---------------+ > | (*) True | true | > +-------------------+---------------+ > | (*) False | false | > > > +-------------------+---------------+ > | (*) None | null | > +-------------------+---------------+ > | (?) unicode | see (?) | > > > +-------------------+---------------+ > > (?) if the object implements a __json__ method, the returned value is used > as the serialization of the object > > > (*) special objects which are protocol free are serialized the same way it's > done currently in simplejson > (?) if the algorithm arrives here, call unicode (with proper encoding rule) > on the object and use the result as json serialization > > > As soon as an object match a rule, it's serialized. > > What do you think ? Do you find this API an improvement over simplejson ? Is > it worth to code ? > > Where are documented the different protocols implemented by Python objects ? > > > > Regards, > > Amirouche > > [1] https://github.com/simplejson/simplejson > [2] > https://github.com/simplejson/simplejson/blob/master/simplejson/encoder.py#L75 > [3] > http://simplejson.readthedocs.org/en/latest/index.html#simplejson.JSONEncoder.default > > -- > http://mail.python.org/mailman/listinfo/python-list > > From news at schwertberger.de Wed Oct 26 13:35:03 2011 From: news at schwertberger.de (Dietmar Schwertberger) Date: Wed, 26 Oct 2011 19:35:03 +0200 Subject: Data acquisition In-Reply-To: <1059c1c4-4581-412d-ad08-6fba6289444d@l12g2000vby.googlegroups.com> References: <362e368f-829e-4477-bcfc-c0650d231029@j7g2000yqi.googlegroups.com> <1059c1c4-4581-412d-ad08-6fba6289444d@l12g2000vby.googlegroups.com> Message-ID: Am 26.10.2011 17:58, schrieb spintronic: > Thank you for the discussion. It was really helpful. As mentioned, it > was necessary to have a longer delay. Previously I have used a delay > of 5 and 10 s but it was not long enough. Now it is 25 s and > everything works fine. If you use the correct sequence of trigger and OPC/WAIT, I'm sure you can reduce the waiting time to the required minimum time and still your script will be more robust... Regards, Dietmar From tjreedy at udel.edu Wed Oct 26 15:20:12 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 Oct 2011 15:20:12 -0400 Subject: spawnl issues with Win 7 access rights In-Reply-To: <4EA81B72.7040008@timgolden.me.uk> References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> <4EA6A950.6090706@timgolden.me.uk> <4EA81B72.7040008@timgolden.me.uk> Message-ID: On 10/26/2011 10:38 AM, Tim Golden wrote: > On 26/10/2011 02:11, Terry Reedy wrote: >> OP reports 2.6 with XP works. > > Where do you see that, Terry? (Or was there an offlist email?) The first message of http://bugs.python.org/issue8036 "Python 2.6 is however happy and just reports invalid arg." -- Terry Jan Reedy From tjreedy at udel.edu Wed Oct 26 15:29:09 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 Oct 2011 15:29:09 -0400 Subject: Forking simplejson In-Reply-To: References: Message-ID: On 10/26/2011 5:14 AM, Amirouche Boubekki wrote: > H?llo, > > I would like to fork simplejson [1] and implement serialization rules > based on protocols instead of types [2], plus special cases for protocol > free objects, that breaks compatibility. The benefit will be a better > API for json serialization of custom classes and in the case of iterable > it will avoid a calls like: > > >>> simplejson.dumps(list(my_iterable)) > > The serialization of custom objects is documented in the class instead > of the ``default`` function of current simplejson implementation [3]. > > The encoding algorithm works with a priority list that is summarized in > the next table: > > +-------------------+---------------+ > | Python protocol | JSON | > | or special case | | > +===================+===============+ > | (?) __json__ | see (?) | > +-------------------+---------------| > | map | object | I am curious what you mean by the 'map' protocol. > Where are documented the different protocols implemented by Python objects ? Ref 3.3 special method names (and elsewhere ;-) http://docs.python.org/py3k/reference/datamodel.html#special-method-names --- Terry Jan Reedy From ross at biostat.ucsf.edu Wed Oct 26 15:48:01 2011 From: ross at biostat.ucsf.edu (Ross Boylan) Date: Wed, 26 Oct 2011 12:48:01 -0700 Subject: inserting \ in regular expressions Message-ID: <1319658482.13425.9.camel@corn.betterworld.us> I want to replace every \ and " (the two characters for backslash and double quotes) with a \ and the same character, i.e., \ -> \\ " -> \" I have not been able to figure out how to do that. The documentation for re.sub says "repl can be a string or a function; if it is a string, any backslash escapes in it are processed.That is, \n is converted to a single newline character, \r is converted to a carriage return, and so forth. Unknown escapes such as \j are left alone." \\ is apparently unknown, and so is left as is. So I'm unable to get a single \. Here are some tries in Python 2.5.2. The document suggested the result of a function might not be subject to the same problem, but it seems to be. >>> def f(m): ... return "\\"+m.group(1) ... >>> re.sub(r"([\\\"])", f, 'Silly " quote') 'Silly \\" quote' >>> re.sub(r"([\\\"])", r"\\1", 'Silly " quote') 'Silly \\1 quote' >>> re.sub(r"([\\\"])", "\\\\1", 'Silly " quote') 'Silly \\1 quote' >>> re.sub(r"([\\\"])", "\\\\\1", 'Silly " quote') 'Silly \\\x01 quote' >>> re.sub(r"([\\\"])", "\\\\\\1", 'Silly " quote') 'Silly \\" quote' Or perhaps I'm confused about what the displayed results mean. If a string has a literal \, does it get shown as \\? I'd appreciate it if you cc me on the reply. Thanks. Ross Boylan From michael at stroeder.com Wed Oct 26 15:48:46 2011 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 26 Oct 2011 21:48:46 +0200 Subject: ANN: python-ldap 2.4.4 Message-ID: Find a new release of python-ldap: http://pypi.python.org/pypi/python-ldap/2.4.4 python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). Project's web site: http://www.python-ldap.org/ Ciao, Michael. ---------------------------------------------------------------- Released 2.4.4 2011-10-26 Changes since 2.4.3: Modules/ * Format intermediate messages as 3-tuples instead of 4-tuples to match the format of other response messages. (thanks to Chris Mikkelson) * Fixes for memory leaks (thanks to Chris Mikkelson) Lib/ * New experimental(!) sub-module ldap.syncrepl implementing syncrepl consumer (see RFC 4533, thanks to Chris Mikkelson) Doc/ * Cleaned up rst files * Added missing classes From ian.g.kelly at gmail.com Wed Oct 26 16:26:45 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 26 Oct 2011 14:26:45 -0600 Subject: inserting \ in regular expressions In-Reply-To: <1319658482.13425.9.camel@corn.betterworld.us> References: <1319658482.13425.9.camel@corn.betterworld.us> Message-ID: On Wed, Oct 26, 2011 at 1:48 PM, Ross Boylan wrote: > Or perhaps I'm confused about what the displayed results mean. ?If a > string has a literal \, does it get shown as \\? In the repr, yes. If you try printing the string, you'll see that it only contains one \. By the way, regular expressions are overkill here. You can use the str.replace method for this: >>> print(r'Silly \ " quote'.replace('\\', '\\\\').replace('"', r'\"')) Silly \\ \" quote Cheers, Ian From michael at stroeder.com Wed Oct 26 16:34:19 2011 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 26 Oct 2011 22:34:19 +0200 Subject: [wanted] python-ldap for Python 2.3 / Win32 In-Reply-To: <4818553.676.1319577549027.JavaMail.geo-discussion-forums@yqnv12> References: <16595266.1315.1319526830836.JavaMail.geo-discussion-forums@yqhp35> <4818553.676.1319577549027.JavaMail.geo-discussion-forums@yqnv12> Message-ID: Waldemar Osuch wrote: > I did try to build it using my current setup but it failed with some linking errors. > Oh well. Waldemar, I really appreciate your Win32 support. > Google gods were nicer to me. Here is a couple alternative links. > Maybe they will work for you. > http://web.archive.org/web/20081101060042/http://www.agescibs.org/mauro/ > http://old.zope.org/Members/volkerw/LdapWin32/ Puh, this is really ancient stuff... For Python historians: http://python-ldap.cvs.sourceforge.net/python-ldap/python-ldap/CHANGES?view=markup Ciao, Michael. From d at davea.name Wed Oct 26 16:47:54 2011 From: d at davea.name (Dave Angel) Date: Wed, 26 Oct 2011 16:47:54 -0400 Subject: inserting \ in regular expressions In-Reply-To: <1319658482.13425.9.camel@corn.betterworld.us> References: <1319658482.13425.9.camel@corn.betterworld.us> Message-ID: <4EA871FA.2090804@davea.name> On 10/26/2011 03:48 PM, Ross Boylan wrote: > I want to replace every \ and " (the two characters for backslash and > double quotes) with a \ and the same character, i.e., > \ -> \\ > " -> \" > > I have not been able to figure out how to do that. The documentation > for re.sub says "repl can be a string or a function; if it is a string, > any backslash escapes in it are processed.That is, \n is converted to a > single newline character, \r is converted to a carriage return, and so > forth. Unknown escapes such as \j are left alone." > > \\ is apparently unknown, and so is left as is. So I'm unable to get a > single \. > > Here are some tries in Python 2.5.2. The document suggested the result > of a function might not be subject to the same problem, but it seems to > be. >>>> def f(m): > ... return "\\"+m.group(1) > ... >>>> re.sub(r"([\\\"])", f, 'Silly " quote') > 'Silly \\" quote' > >>> re.sub(r"([\\\"])", "\\\\\\1", 'Silly " quote') > 'Silly \\" quote' > > Or perhaps I'm confused about what the displayed results mean. If a > string has a literal \, does it get shown as \\? > > I'd appreciate it if you cc me on the reply. > > Thanks. > Ross Boylan > I can't really help on the regex aspect of your code, but I can tell you a little about backslashes, quote literals, the interpreter, and python. First, I'd scrap the interpreter and write your stuff to a file. Then test it by running that file. The reason for that is that the interpreter is helpfully trying to reconstruct the string you'd have to type in order to get that result. So while you may have successfully turned a double bacdkslash into a single one, the interpreter helpfully does the inverse, and you don't see whether you're right or not. Next, always assign to variables, and test those variables on a separate line with the regex. This is probably what your document meant when it mentioned the result of a function. Now some details about python. When python compiles/interprets a quote literal, the syntax parsing has to decide where the literal stops, so quotes are treated specially. Sometimes you can sidestep the problem of embedding quotes inside literals by using single quotes on the outside and double inside, or vice versa. As you did on the 'Silly " quote' example. But the more general way to put funny characters into a quote literal is to escape each with a backslash. So there a bunch of two-character escapes. backslash-quote is how you can put either kind of quote into a literal, regardless of what's being used to delimit it. backslash-n gets a newline, which would similarly be bad syntax. backslash-t and some others are usually less troublesome, but can be surprising. And backslash-backslash represents a single backslash. There are also backslash codes to represent arbitrary characters you might not have on your keyboard. And these may use multiple characters after the backslash. So write a bunch of lines like a = 'this is\'nt a surprise' print a and experiment. Notice that if you use \n in such a string, the print will put it on two lines. Likewise the tab is executed. Now for a digression. The interpreter uses repr() to display strings. You can experiment with that by doing print a print repr(a) Notice the latter puts quotes around the string. They are NOT part of the string object in a. And it re-escapes any embedded funny characters, sometimes differently than the way you entered them. Now, once you're confident that you can write a literal to express any possible string, try calling your regex. print re.sub(a, b, c) or whatever. Now, one way to cheat on the string if you know you'll want to put actual backslashes is to use the raw string. That works quite well unless you want the string to end with a backslash. There isn't a way to enter that as a single raw literal. You'd have to do something string like a = r"strange\literal\with\some\stuff" + "\\" My understanding is that no valid regex ends with a backslash, so this may not affect you. Now there are other ways to acquire a string object. If you got it from a raw_input() call, it doesn't need to be escaped, but it can't have an embedded newline, since the enter key is how the input is completed. If you read it from a file, it doesn't need to be escaped. Now you're ready to see what other funny requirements regex needs. You will be escaping stuff for their purposes, and sometimes that means your literal might have 4 or even more backslashes in a row. But hopefully now you'll see how to separate the different problems. -- DaveA From wallenpb at gmail.com Wed Oct 26 17:32:24 2011 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 26 Oct 2011 16:32:24 -0500 Subject: passing Python data to a javascript function Message-ID: I am writing a Python CGI and am needing to pass a data value from Python to a javascript function. My understanding is that I should use JSON as the middleman. However, I have not found a good example of doing this. The piece of data is a simple integer, but I converting that to a string first. Here is what I am trying, but unsuccessfully. I know this code is broken in at least two places. I may be going about this completely the wrong way. Any help would be appreciated. Thanks, Bill Allen #!/usr/bin/python import json import os import cgi import cgitb cgitb.enable() pid = [{'p':str(os.getpid())}] pid_data = json.dumps(pid) print "Content-type: text/html" print print """ showPID ####This is where I am not sure how to pass the value to the javascript function

Hello World!
""" -------------- next part -------------- An HTML attachment was scrubbed... URL: From ramit.prasad at jpmorgan.com Wed Oct 26 17:47:03 2011 From: ramit.prasad at jpmorgan.com (Prasad, Ramit) Date: Wed, 26 Oct 2011 17:47:03 -0400 Subject: webapp development in pure python In-Reply-To: <4EA6E4DA.2080307@shopzeus.com> References: <4EA6BEC3.5010206@shopzeus.com> <4EA6E4DA.2080307@shopzeus.com> Message-ID: <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF126AA8@EMARC112VS01.exchad.jpmchase.net> I am not really an expert web developer, so this is just my two cents. > My Python module would connect to a database server and query >some data, then display it in a grid. This cannot be compiled into >javascript because of the database server connection. You technically can connect to databases from JavaScript. It is a terrible idea, but achievable. Not really sure how it would get "compiled" into JavaScript, so it is possible that is the stumbling block. http://stackoverflow.com/questions/857670/how-to-connect-to-sql-server-database-from-javascript >I would have to create the server side part separately, the user interface separately, and hand-code the communication between the widets and the server side. As far as I know, this is the Right way to do a web/GUI apps; you may want to read about the MVC design pattern. >I would like to use this theoretical web based framework just like pygtk or wxPython Even in wxPython/pygtk, you should be using MVC pattern. Usually if your app is one class, you either have a trivial application or you are doing it wrong. Of course, that really applies to larger projects more than hacked together code for personal use. Apologies in advance if I misunderstood something. Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 -- This email is confidential and subject to important disclaimers and conditions including on offers for the purchase or sale of securities, accuracy and completeness of information, viruses, confidentiality, legal privilege, and legal entity disclaimers, available at http://www.jpmorgan.com/pages/disclosures/email. From wallenpb at gmail.com Wed Oct 26 18:18:36 2011 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 26 Oct 2011 17:18:36 -0500 Subject: passing Python data to a javascript function Message-ID: I am writing a Python CGI and am needing to pass a data value from Python to a javascript function. My understanding is that I should use JSON as the middleman. However, I have not found a good example of doing this. The piece of data is a simple integer, but I could easily covert that to a string first if necessary. Here is what I am trying, but unsuccessfully. I am sure that I have more than one issue in this code. #!/usr/bin/python import json, os, cgi, cgitb cgitb.enable() pid = [{'p':str(os.getpid())}] pid_data = json.dumps(pid) print "Content-type: text/html" print print """ Test Page

""".format(pid_data) -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Wed Oct 26 18:38:37 2011 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 26 Oct 2011 23:38:37 +0100 Subject: inserting \ in regular expressions In-Reply-To: <1319658482.13425.9.camel@corn.betterworld.us> References: <1319658482.13425.9.camel@corn.betterworld.us> Message-ID: <4EA88BED.7040706@mrabarnett.plus.com> On 26/10/2011 20:48, Ross Boylan wrote: > I want to replace every \ and " (the two characters for backslash and > double quotes) with a \ and the same character, i.e., > \ -> \\ > " -> \" > > I have not been able to figure out how to do that. The documentation > for re.sub says "repl can be a string or a function; if it is a string, > any backslash escapes in it are processed.That is, \n is converted to a > single newline character, \r is converted to a carriage return, and so > forth. Unknown escapes such as \j are left alone." > > \\ is apparently unknown, and so is left as is. So I'm unable to get a > single \. > [snip] The backspace character is also used for escaping in a regex, so you need to escape it with a backslash: >>> print('Silly " quote or \\ backslash') Silly " quote or \ backslash >>> print (re.sub(r'([\\\\"])', r"\\\1", 'Silly " quote or \\ backslash')) Silly \" quote or \\ backslash From benjamin.kaplan at case.edu Wed Oct 26 18:58:07 2011 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Wed, 26 Oct 2011 18:58:07 -0400 Subject: passing Python data to a javascript function In-Reply-To: References: Message-ID: On Wed, Oct 26, 2011 at 6:18 PM, Bill Allen wrote: > > I am writing a Python CGI and am needing to pass a data value from Python to a javascript function.?? My understanding is that I should use JSON as the middleman.? However, I have not found a good example of doing this.?? The piece of data is a simple integer, but I could easily covert that to a string first if necessary.?? Here is what I am trying, but unsuccessfully.? I am sure that I have more than one issue in this code. > > > > #!/usr/bin/python > > import json, os, cgi, cgitb > cgitb.enable() > > pid = [{'p':str(os.getpid())}] > pid_data = json.dumps(pid) > > print "Content-type: text/html" > print > > print """ > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> > > Test Page > > > > >

> > > """.format(pid_data) > You're making this much more difficult than it needs to be. JSON is used for sending data to JavaScript, meaning the JavaScript asks the server for a bunch of data, the server sends the client JSON, and everyone is happy. In your case, the information is available when the javascript is being generated so you can just pass in the number, no JSON needed. From web at naveed.net Wed Oct 26 22:06:16 2011 From: web at naveed.net (web at naveed.net) Date: Wed, 26 Oct 2011 19:06:16 -0700 (PDT) Subject: No more Python support in NetBeans 7.0 In-Reply-To: <4a98.4d8b560e.5ebee@altium.nl> References: <4a98.4d8b560e.5ebee@altium.nl> Message-ID: <4892437.584.1319681177024.JavaMail.geo-discussion-forums@yqp37> Sorry to comment on an old topic, but I wanted to clarify for others like me who might get the wrong idea. It looks like this is no longer true. Netbeans 7 might be supporting python after all. http://wiki.netbeans.org/Python70Roadmap From wallenpb at gmail.com Wed Oct 26 22:25:16 2011 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 26 Oct 2011 21:25:16 -0500 Subject: passing Python data to a javascript function In-Reply-To: References: Message-ID: Benjamin, I was afraid I was doing that. I have simplified it quite a bit, still not getting the output I am looking for. I am down to that I am not passing the value in the onload=showPID() call correctly. I know this is getting a bit far from a Python issue now, but if you have more insight on this, I would appreciate it. Is there another way of passing the data from the Python script to the javascript than what I am doing in this CGI? Thanks, Bill code now is: import os, cgi, cgitb cgitb.enable() pid_data = str(os.getpid()) print "Content-type: text/html" print print """ Test Page Hello World!


""" print "html: "+pid_data+"
" print """ """ If I use I get this for output: Hello World! html: 4900 If I use I get this for output: Hello World! js: pid_data html: 4708 On Wed, Oct 26, 2011 at 17:58, Benjamin Kaplan wrote: > On Wed, Oct 26, 2011 at 6:18 PM, Bill Allen wrote: > > > > I am writing a Python CGI and am needing to pass a data value from Python > to a javascript function. My understanding is that I should use JSON as > the middleman. However, I have not found a good example of doing this. > The piece of data is a simple integer, but I could easily covert that to a > string first if necessary. Here is what I am trying, but unsuccessfully. > I am sure that I have more than one issue in this code. > > > > > > > > #!/usr/bin/python > > > > import json, os, cgi, cgitb > > cgitb.enable() > > > > pid = [{'p':str(os.getpid())}] > > pid_data = json.dumps(pid) > > > > print "Content-type: text/html" > > print > > > > print """ > > > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> > > > > Test Page > > > > > > > > > >

> > > > > > """.format(pid_data) > > > > You're making this much more difficult than it needs to be. JSON is > used for sending data to JavaScript, meaning the JavaScript asks the > server for a bunch of data, the server sends the client JSON, and > everyone is happy. In your case, the information is available when the > javascript is being generated so you can just pass in the number, no > JSON needed. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed Oct 26 22:42:09 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 26 Oct 2011 19:42:09 -0700 Subject: passing Python data to a javascript function In-Reply-To: References: Message-ID: On Wed, Oct 26, 2011 at 7:25 PM, Bill Allen wrote: > > Benjamin, > > I was afraid I was doing that.?? I have simplified it quite a bit, still not > getting the output I am looking for.?? I am down to that I am not passing > the value in the onload=showPID() call correctly.? I know this is getting a > bit far from a Python issue now, but if you have more insight on this, I > would appreciate it.? Is there another way of passing the data from the > Python script to the javascript than what I am doing in this CGI? The problem is that you're not passing the data at all. You never interpolate the pid_data value into the string(s) constituting your embedded JavaScript (though you did do it just fine in the pure HTML). The Python variable `pid_data` is not somehow magically accessible to JavaScript; you must explicitly insert its value somewhere. > pid_data = str(os.getpid()) > print """ > Change that line to: As an example, if the PID happens to be 42, then the outputted fragment will end up being: As a sidenote, I would recommend using something higher-level than the `cgi` module. Python has an abundance of web frameworks and templating languages; take your pick. Cheers, Chris -- http://rebertia.com From rosuav at gmail.com Wed Oct 26 23:05:33 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 27 Oct 2011 14:05:33 +1100 Subject: webapp development in pure python In-Reply-To: <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF126AA8@EMARC112VS01.exchad.jpmchase.net> References: <4EA6BEC3.5010206@shopzeus.com> <4EA6E4DA.2080307@shopzeus.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF126AA8@EMARC112VS01.exchad.jpmchase.net> Message-ID: On Thu, Oct 27, 2011 at 8:47 AM, Prasad, Ramit wrote: > You technically can connect to databases from JavaScript. It is a terrible idea, but achievable. Not really sure how it would get "compiled" into JavaScript, so it is possible that is the stumbling block. > http://stackoverflow.com/questions/857670/how-to-connect-to-sql-server-database-from-javascript > Strongly recommend against this. I haven't confirmed, but by the look of it the code there is IE-only and MS SQL Server only. Also, remote database access is a major security concern. I would recommend keeping it all on the server (more efficient that way, too). ChrisA From wallenpb at gmail.com Wed Oct 26 23:51:34 2011 From: wallenpb at gmail.com (Bill Allen) Date: Wed, 26 Oct 2011 22:51:34 -0500 Subject: passing Python data to a javascript function In-Reply-To: References: Message-ID: Chris, Wow, that seems so simple now that I see it. I was dancing around that all day, but just not landing on it. Thanks so very much for the assist. --Bill Final code that works perfectly, passes the value from the Python script to the javascript correctly: #!/usr/bin/python import json, os, cgi, cgitb cgitb.enable() pid_data = str(os.getpid()) print "Content-type: text/html" print print """ Test Page Hello World!


""" print "html: "+pid_data+"
" print """ """ Output of above code is the following, which is just the PID of the Python CGI itself at runtime, displayed via javascript and via HTML. Hello World! js: 1308 html: 1308 On Wed, Oct 26, 2011 at 21:42, Chris Rebert wrote: > On Wed, Oct 26, 2011 at 7:25 PM, Bill Allen wrote: > > The problem is that you're not passing the data at all. You never > interpolate the pid_data value into the string(s) constituting your > embedded JavaScript (though you did do it just fine in the pure HTML). > The Python variable `pid_data` is not somehow magically accessible to > JavaScript; you must explicitly insert its value somewhere. > > > > pid_data = str(os.getpid()) > > > print """ > > > > > Change that line to: > > > As an example, if the PID happens to be 42, then the outputted > fragment will end up being: > > > As a sidenote, I would recommend using something higher-level than the > `cgi` module. Python has an abundance of web frameworks and templating > languages; take your pick. > > Cheers, > Chris > -- > http://rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Wed Oct 26 23:55:28 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 27 Oct 2011 14:55:28 +1100 Subject: passing Python data to a javascript function In-Reply-To: References: Message-ID: On Thu, Oct 27, 2011 at 2:51 PM, Bill Allen wrote: > Chris, > > Wow, that seems so simple now that I see it.? I was dancing around that all > day, but just not landing on it.?? Thanks so very much for the assist. > > --Bill > > Final code that works perfectly, passes the value from the Python script to > the javascript correctly: > > Congratulations! You've just written code that writes code. It takes a bit to get your head around it (especially when you start worrying about literal strings that might contain quotes, for instance), but it's really cool and seriously powerful stuff. Your server-side Python code can generate client-side Javascript code any way it likes... unlimited possibilities. ChrisA From dihedral88888 at googlemail.com Thu Oct 27 01:04:09 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Wed, 26 Oct 2011 22:04:09 -0700 (PDT) Subject: webapp development in pure python In-Reply-To: References: <4EA6BEC3.5010206@shopzeus.com> <4EA6E4DA.2080307@shopzeus.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF126AA8@EMARC112VS01.exchad.jpmchase.net> Message-ID: <3173882.1086.1319691849561.JavaMail.geo-discussion-forums@prlk36> I am thinking one has to distinguish between programs for database servers of the commercial applications in banks or insurance companies that cant be hacked in low costs, and experiments to chunk out database servers for games and videos all over the world! From dihedral88888 at googlemail.com Thu Oct 27 01:04:09 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Wed, 26 Oct 2011 22:04:09 -0700 (PDT) Subject: webapp development in pure python In-Reply-To: References: <4EA6BEC3.5010206@shopzeus.com> <4EA6E4DA.2080307@shopzeus.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF126AA8@EMARC112VS01.exchad.jpmchase.net> Message-ID: <3173882.1086.1319691849561.JavaMail.geo-discussion-forums@prlk36> I am thinking one has to distinguish between programs for database servers of the commercial applications in banks or insurance companies that cant be hacked in low costs, and experiments to chunk out database servers for games and videos all over the world! From rosuav at gmail.com Thu Oct 27 01:18:47 2011 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 27 Oct 2011 16:18:47 +1100 Subject: webapp development in pure python In-Reply-To: <3173882.1086.1319691849561.JavaMail.geo-discussion-forums@prlk36> References: <4EA6BEC3.5010206@shopzeus.com> <4EA6E4DA.2080307@shopzeus.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF126AA8@EMARC112VS01.exchad.jpmchase.net> <3173882.1086.1319691849561.JavaMail.geo-discussion-forums@prlk36> Message-ID: On Thu, Oct 27, 2011 at 4:04 PM, 88888 Dihedral wrote: > I am thinking one has to distinguish between programs for database servers of ? the commercial applications in banks or insurance companies that cant be hacked in low costs, and experiments to chunk out database servers for games and videos all over the world! I don't know about that. Best practices are often best for everyone; it's more critical for a bank than for a game server, but that doesn't mean the game server can afford to use swiss cheese as armor plate. Particularly if it's the livelihood of the game designer; in fact, that might even make it _more_ important than for a bank. ChrisA From dihedral88888 at googlemail.com Thu Oct 27 02:37:01 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Wed, 26 Oct 2011 23:37:01 -0700 (PDT) Subject: webapp development in pure python In-Reply-To: References: <4EA6BEC3.5010206@shopzeus.com> <4EA6E4DA.2080307@shopzeus.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF126AA8@EMARC112VS01.exchad.jpmchase.net> <3173882.1086.1319691849561.JavaMail.geo-discussion-forums@prlk36> Message-ID: <27201394.206.1319697421295.JavaMail.geo-discussion-forums@prng5> OK, lets start a framework in using python in the server side and the client side. (1). requirements of the server side first: 1. sending HTML, XML documents to be displayed in the browsers of the clients and receiving for user inputs are easy in modpython, django, and etc. 2. Data received in the server side has to be stored and verified for later accesses performed from client's requests 3. data and traffic amounts to be estimated for the server in order to process requests in terms of numbers of clients and costs per defined operation period, well, a slow database engine that consumes a lot CPU time in the server really sucks! (2). Lets check the client side, too! In scenario 1 the client side has the browser operating only via port 80. In scenario 2 the client side has an AP. that could be invoked in the browser, e.g. Adobe PDF reader or Apple's quick time engine In scenario 3 AP. can invoke the browser to a cyber page in the client side with multiple sockets via TCPIP/UDP of various ports in the AP., e.g. skype, msn, and etc.. Assuming that programmers can use a customized python package installed in the AP. of the client side with other tools is allowed. From dihedral88888 at googlemail.com Thu Oct 27 02:37:01 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Wed, 26 Oct 2011 23:37:01 -0700 (PDT) Subject: webapp development in pure python In-Reply-To: References: <4EA6BEC3.5010206@shopzeus.com> <4EA6E4DA.2080307@shopzeus.com> <0604E20B5F6F2F4784C9C8C71C5DD4DD2FDF126AA8@EMARC112VS01.exchad.jpmchase.net> <3173882.1086.1319691849561.JavaMail.geo-discussion-forums@prlk36> Message-ID: <27201394.206.1319697421295.JavaMail.geo-discussion-forums@prng5> OK, lets start a framework in using python in the server side and the client side. (1). requirements of the server side first: 1. sending HTML, XML documents to be displayed in the browsers of the clients and receiving for user inputs are easy in modpython, django, and etc. 2. Data received in the server side has to be stored and verified for later accesses performed from client's requests 3. data and traffic amounts to be estimated for the server in order to process requests in terms of numbers of clients and costs per defined operation period, well, a slow database engine that consumes a lot CPU time in the server really sucks! (2). Lets check the client side, too! In scenario 1 the client side has the browser operating only via port 80. In scenario 2 the client side has an AP. that could be invoked in the browser, e.g. Adobe PDF reader or Apple's quick time engine In scenario 3 AP. can invoke the browser to a cyber page in the client side with multiple sockets via TCPIP/UDP of various ports in the AP., e.g. skype, msn, and etc.. Assuming that programmers can use a customized python package installed in the AP. of the client side with other tools is allowed. From zapyon at gmx.net Thu Oct 27 04:11:15 2011 From: zapyon at gmx.net (Andreas Neudecker) Date: Thu, 27 Oct 2011 10:11:15 +0200 Subject: Philosophical Python: 2*b or not 2*b Message-ID: Not the answers I expected: ;-) >>> b = True >>> 2*b or not 2*b 2 >>> b = False >>> 2*b or not 2*b True It all becomes clear when you look at: >>> b = False >>> 2*b 0 >>> b = True >>> 2*b 2 No surprise there really. But fun anyway. Any more philsophical Python code out there? From zapyon at gmx.net Thu Oct 27 04:23:37 2011 From: zapyon at gmx.net (Andreas Neudecker) Date: Thu, 27 Oct 2011 10:23:37 +0200 Subject: Genehmigt vom Ministerium =?ISO-8859-15?Q?f=FCr_alberne_Gang?= =?ISO-8859-15?Q?arten?= Message-ID: http://blog.stuttgarter-zeitung.de/fundstucke/2011/10/27/genehmigt-vom-ministerium-fur-alberne-gangarten/ From mcepl at redhat.com Thu Oct 27 04:50:04 2011 From: mcepl at redhat.com (mcepl) Date: Thu, 27 Oct 2011 01:50:04 -0700 (PDT) Subject: Presenting recursive dict (json_diff) Message-ID: Hi, I have here a simple script (https://gitorious.org/json_diff/mainline) which makes a diff between two JSON files. So for JSON objects { "a": 1, "b": 2, "son": { "name": "Jano?ek" } } and { "a": 2, "c": 3, "daughter": { "name": "Maru?ka" } } it generates { "append": { "c": 3, "daughter": { "name": "Maru?ka" } }, "remove": { "b": 2, "son": { "name": "Jano?ek" } }, "update": { "a": 2 } } (obvious problems with name conflicts between internal keys and the investigated keys will be somehow addressed later; any simple Pythonic suggestions how?) Now, I would like to create a script (or class) to present such diff object in HTML (and mind you the diffs might be large, hopefully not too much deeply nested, by with many many keys). Any suggestions how to do it? Any libraries to use? I would love to use some templating language, but I am not sure which simple ones (e.g., I like pystache) could do recursive templating. So currently I am tending towards generating strings. I am currently tending towards something like (not cleaned to be CSS- only yet):
  'c' = 3
'b' = 2 --
'a' = 2
children
* son = 'Iv?nek'
* daughter = 'Maru?ka'
but I cannot say I like it. Any suggestions? Thank, Mat?j From faucheuses at gmail.com Thu Oct 27 04:57:55 2011 From: faucheuses at gmail.com (faucheuse) Date: Thu, 27 Oct 2011 01:57:55 -0700 (PDT) Subject: Problem using execvp Message-ID: <1c03dba0-3d9b-47ab-a4fc-b42210ed35ff@o15g2000yqj.googlegroups.com> Hi, I'm trying to launch my python program with another process name than "python.exe". In order to do that I'm trying to use the os.execvp function : os.execvp("./Launch.py", ["ProcessName"]) Launch.py is the file that Launch the program and ProcessName is the ... Process Name ^^ I get this error : OSError : [Errno 8] Exec format error. I searched and found many solutions like : os.execvp("./Launch.py", ["./Launch.py","ProcessName"]), but nothing worked so far. Can you help me plz ? From mcepl at redhat.com Thu Oct 27 05:24:42 2011 From: mcepl at redhat.com (mcepl) Date: Thu, 27 Oct 2011 02:24:42 -0700 (PDT) Subject: Presenting recursive dict (json_diff) References: Message-ID: On 27 ??j, 10:50, mcepl wrote: > Hi, > > I have here a simple script (https://gitorious.org/json_diff/mainline) > which makes a diff between two JSON files. So for JSON objects and I have completely burried to lead on this. The point is that the resulting object can be endlessly recursively nested. On each level I can have not only append/remove/update subobjects, but also number of subtrees. Something like this would be better picture: { "append": { "c": 3 }, "remove": { "b": 2 }, "update": { "a": 2, "children": { "update": { "son": "Iv?nek" }, "append": { "daughter": "Maru?ka" } } } } From hansmu at xs4all.nl Thu Oct 27 05:27:04 2011 From: hansmu at xs4all.nl (Hans Mulder) Date: Thu, 27 Oct 2011 11:27:04 +0200 Subject: Problem using execvp In-Reply-To: <1c03dba0-3d9b-47ab-a4fc-b42210ed35ff@o15g2000yqj.googlegroups.com> References: <1c03dba0-3d9b-47ab-a4fc-b42210ed35ff@o15g2000yqj.googlegroups.com> Message-ID: <4ea923e8$0$6863$e4fe514c@news2.news.xs4all.nl> On 27/10/11 10:57:55, faucheuse wrote: > I'm trying to launch my python program with another process name than > "python.exe". Which version of Python are you using? Which version of which operating system? > In order to do that I'm trying to use the os.execvp function : > > os.execvp("./Launch.py", ["ProcessName"]) > > Launch.py is the file that Launch the program and ProcessName is > the ... Process Name ^^ > > I get this error : OSError : [Errno 8] Exec format error. Maybe ./Lauch.py is not executable..... Can you run ./Launch.py from the command line? Does it have a valid shebang line? Is the 'x' bit set? What does "file ./Launch.py" report? > I searched and found many solutions like : os.execvp("./Launch.py", > ["./Launch.py","ProcessName"]), but nothing worked so far. This works for me: os.execvp("./Launch.py", ["ProcessName"]]) -- HansM From candide at free.invalid Thu Oct 27 06:08:45 2011 From: candide at free.invalid (candide) Date: Thu, 27 Oct 2011 12:08:45 +0200 Subject: __dict__ attribute for built-in types Message-ID: <4ea92dae$0$20639$426a74cc@news.free.fr> I realize that built-in types objects don't provide a __dict__ attribute and thereby i can't set an attribute to a such object, for instance >>> a=[42,421] >>> a.foo="bar" Traceback (most recent call last): File "", line 1, in AttributeError: 'list' object has no attribute 'foo' >>> a.__dict__ Traceback (most recent call last): File "", line 1, in AttributeError: 'list' object has no attribute '__dict__' >>> So, i was wondering : -- why this behaviour ? -- where the official documentation refers to this point ? From gelonida at gmail.com Thu Oct 27 06:09:29 2011 From: gelonida at gmail.com (Gelonida N) Date: Thu, 27 Oct 2011 12:09:29 +0200 Subject: python logging multiple processes to one file (via socket server) Message-ID: Hi, I have a rather 'simple' problem. Logging from multiple processes to the same file AND be sure, that no log message is lost, 1.) Log multiple processes to one file: ------------------------------------------ I have a python program, which I want to log, but which forks several times. Due to the forking logging to files with the default logging.FileHandler seems out of question. It seems, that I could use a SocketHandler, which collects data from all different processes and logs then to one file. Does anybody have a working example. 2.) Ensure, that no log message is lost. ------------------------------------------ If I understood the doc of the SocketHandler, then it will drop messages if the socket handler is not available. However for my current activity I would prefer, that it aborts if it cannot connect to the socket and that it blocks if the log server doesn't handle the sent data fast enough. Is this possible. Thanlks a lot in advance. What I found so far: http://docs.python.org/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes It states: "The following section documents this approach in more detail and includes a working socket receiver which can be used as a starting point for you to adapt in your own applications." Somehow I have a mental block though and fail to see the 'following section'. I also found http://code.google.com/p/python-loggingserver/ and ran first tests. However it seems, that this server stops logging my application after about 128 log entries. (the number varies and is not necessarily exactly 128), whereas the console loggier continues logging. I'm not really show why and would prefer a simpler example first. Thanks in advance for any code example, idea, link, comment. From npropadovic at googlemail.com Thu Oct 27 06:27:22 2011 From: npropadovic at googlemail.com (Propad) Date: Thu, 27 Oct 2011 03:27:22 -0700 (PDT) Subject: spawnl issues with Win 7 access rights References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> <4EA6A950.6090706@timgolden.me.uk> <4EA81B72.7040008@timgolden.me.uk> Message-ID: <98460dba-9e08-4d1a-8bf6-4e8fdbea2d0c@19g2000yqk.googlegroups.com> Hello Gentelmen, the suggestion to add the optional second parameter fixed the problem, spawnl now works on the Win 7 computer I'm responsible for (with Python 2.2). So the suggested cause seems to be right. Thank you for the great help! Cheers, Nenad On 26 Okt., 21:20, Terry Reedy wrote: > On 10/26/2011 10:38 AM, Tim Golden wrote: > > > On 26/10/2011 02:11, Terry Reedy wrote: > >> OP reports 2.6 with XP works. > > > Where do you see that, Terry? (Or was there an offlist email?) > > The first message ofhttp://bugs.python.org/issue8036 > "Python 2.6 is however happy and just reports invalid arg." > > -- > Terry Jan Reedy From james.e.m.housden at googlemail.com Thu Oct 27 06:35:47 2011 From: james.e.m.housden at googlemail.com (James Housden) Date: Thu, 27 Oct 2011 03:35:47 -0700 (PDT) Subject: Problem using execvp References: <1c03dba0-3d9b-47ab-a4fc-b42210ed35ff@o15g2000yqj.googlegroups.com> <4ea923e8$0$6863$e4fe514c@news2.news.xs4all.nl> Message-ID: <1b0cfe66-5b53-4294-a2cd-47e81e034c22@hj4g2000vbb.googlegroups.com> On Oct 27, 11:27?am, Hans Mulder wrote: > On 27/10/11 10:57:55, faucheuse wrote: > > > I'm trying to launch my python program with another process name than > > "python.exe". > > Which version of Python are you using? > Which version of which operating system? > > > In order to do that I'm trying to use the os.execvp function : > > > os.execvp("./Launch.py", ["ProcessName"]) > > > Launch.py is the file that Launch the program and ProcessName is > > the ... Process Name ^^ > > > I get this error : OSError : [Errno 8] Exec format error. > > Maybe ./Lauch.py is not executable..... > > Can you run ./Launch.py from the command line? > Does it have a valid shebang line? > Is the 'x' bit set? > What does "file ./Launch.py" report? > > > I searched and found many solutions like : os.execvp("./Launch.py", > > ["./Launch.py","ProcessName"]), but nothing worked so far. > > This works for me: > > ? ? ?os.execvp("./Launch.py", ["ProcessName"]]) > > -- HansM Hello, This worked for me: os.execvp("./Launch.py", ["python", "ProcessName"]) Best regards, James From mail at timgolden.me.uk Thu Oct 27 06:36:17 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 27 Oct 2011 11:36:17 +0100 Subject: spawnl issues with Win 7 access rights In-Reply-To: <98460dba-9e08-4d1a-8bf6-4e8fdbea2d0c@19g2000yqk.googlegroups.com> References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> <4EA6A950.6090706@timgolden.me.uk> <4EA81B72.7040008@timgolden.me.uk> <98460dba-9e08-4d1a-8bf6-4e8fdbea2d0c@19g2000yqk.googlegroups.com> Message-ID: <4EA93421.1090905@timgolden.me.uk> On 27/10/2011 11:27, Propad wrote: > the suggestion to add the optional second parameter fixed the problem, > spawnl now works on the Win 7 computer I'm responsible for (with > Python 2.2). So the suggested cause seems to be right. FWIW, although it's not obvious, the args parameter to spawnl is intended to become the sys.args (in Python terms) of the newly-spawned process. Which is why the first element is expected to be the name of the process. It took me some time to realise this myself :) Anyway, glad we could be of help. TJG From arnodel at gmail.com Thu Oct 27 06:36:54 2011 From: arnodel at gmail.com (Arnaud Delobelle) Date: Thu, 27 Oct 2011 11:36:54 +0100 Subject: __dict__ attribute for built-in types In-Reply-To: <4ea92dae$0$20639$426a74cc@news.free.fr> References: <4ea92dae$0$20639$426a74cc@news.free.fr> Message-ID: On 27 October 2011 11:08, candide wrote: > I realize that built-in types objects don't provide a __dict__ attribute and > thereby i can't set an attribute to a such object, for instance > > >>>> a=[42,421] >>>> a.foo="bar" > Traceback (most recent call last): > ?File "", line 1, in > AttributeError: 'list' object has no attribute 'foo' >>>> a.__dict__ > Traceback (most recent call last): > ?File "", line 1, in > AttributeError: 'list' object has no attribute '__dict__' >>>> Some built in types have a __dict__: >>> def foo(): pass ... >>> foo.__dict__ {} >>> import random >>> len(random.__dict__) 57 > > So, i was wondering : > > -- why this behaviour ? Performance reasons I guess. > -- where the official documentation refers to this point ? I don't know this one :) -- Arnaud From duncan.booth at invalid.invalid Thu Oct 27 07:03:17 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Oct 2011 11:03:17 GMT Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> Message-ID: candide wrote: > I realize that built-in types objects don't provide a __dict__ attribute > and thereby i can't set an attribute to a such object, for instance > > > >>> a=[42,421] > >>> a.foo="bar" > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'list' object has no attribute 'foo' > >>> a.__dict__ > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'list' object has no attribute '__dict__' > >>> > > > So, i was wondering : > > -- why this behaviour ? Types without a __dict__ use less memory. Also, if you couldn't have a type that didn't have a `__dict__` then any `dict` would also need its own `__dict__` which would either result in infinite memory use or recursive dictionaries. It isn't just built-in types, you can choose for any type you define whether or not to have a '__dict__' attribute >>> class Fixed(object): __slots__ = ('foo', 'bar') readonly = 42 >>> f = Fixed() >>> f.foo, f.bar = 1, 2 >>> f.foo, f.bar, f.readonly (1, 2, 42) >>> f.readonly = 24 Traceback (most recent call last): File "", line 1, in f.readonly = 24 AttributeError: 'Fixed' object attribute 'readonly' is read-only >>> f.baz = 'whatever' Traceback (most recent call last): File "", line 1, in f.baz = 'whatever' AttributeError: 'Fixed' object has no attribute 'baz' > -- where the official documentation refers to this point ? > See http://docs.python.org/reference/datamodel.html for the docs about __slots__ There is also the API documentation which describes at a low level how to control whether or not instances have a dict: http://docs.python.org/c-api/typeobj.html#tp_dictoffset I'm not sure though where you find a higher level statement of which builtin types have a __dict__. -- Duncan Booth http://kupuguy.blogspot.com From paul at subsignal.org Thu Oct 27 08:18:38 2011 From: paul at subsignal.org (=?ISO-8859-1?Q?Paul_K=F6lle?=) Date: Thu, 27 Oct 2011 14:18:38 +0200 Subject: Forking simplejson In-Reply-To: References: Message-ID: Am 26.10.2011 19:34, schrieb Nathan Rice: > Since this happily went off to the wrong recipient the first time... > > The python json module/simpljson are badly in need of an architecture > update. The fact that you can't override the encode method of > JSONEncoder and have it work reliably without monkey patching the pure > python encoder is a sign that something is horribly wrong. +1 I wonder why the builtin json didn't implemented the __json__ hook. Now you need to write encoders for possibly arbitrary (imported/third party) objects.... Looks like it's not so hard to extend json.JSONEncoder to look for __json__ though: >>> import json >>> from functools import partial >>> from types import MethodType >>> class Encoder(json.JSONEncoder): ... def default(self, obj): fn = getattr(obj, '__json__', None) ... if fn and type(fn) == MethodType: ... return obj.__json__() ... return json.JSONEncoder.default(self, obj) ... >>> class T(object): ... def __json__(self): ... return 'foo' ... >>> t = T() >>> dumps = partial(json.dumps, cls=Encoder) >>> dumps(dict([(1,1), (2,2), ('test',t)])) '{"test": "foo", "1": 1, "2": 2}' >>> cheers Paul [snip] From icanbob at gmail.com Thu Oct 27 08:41:18 2011 From: icanbob at gmail.com (bobicanprogram) Date: Thu, 27 Oct 2011 05:41:18 -0700 (PDT) Subject: python logging multiple processes to one file (via socket server) References: Message-ID: <7a3ebd15-5f65-4c3c-8fa0-2cf42bdf5972@i19g2000yqf.googlegroups.com> On Oct 27, 6:09 am, Gelonida N wrote: > Hi, > > I have a rather 'simple' problem. > Logging from multiple processes to the same file AND be sure, that no > log message is lost, > > 1.) Log multiple processes to one file: > ------------------------------------------ > > I have a python program, which I want to log, but which forks several times. > > Due to the forking logging to files with the default logging.FileHandler > seems out of question. > > It seems, that I could use a SocketHandler, which collects data from all > different processes and logs then to one file. > > Does anybody have a working example. > > 2.) Ensure, that no log message is lost. > ------------------------------------------ > If I understood the doc of the SocketHandler, then > it will drop messages if the socket handler is not available. > > However for my current activity I would prefer, that it aborts if it > cannot connect to the socket and that it blocks if the log server > doesn't handle the sent data fast enough. > > Is this possible. > > Thanlks a lot in advance. > > What I found so far:http://docs.python.org/howto/logging-cookbook.html#logging-to-a-singl... > > It states: > "The following section documents this approach in more detail and > includes a working socket receiver which can be used as a starting point > for you to adapt in your own applications." > > Somehow I have a mental block though and fail to see the 'following > section'. > > I also foundhttp://code.google.com/p/python-loggingserver/and ran > first tests. > > However it seems, that this server stops logging my application after > about 128 log entries. (the number varies and is not necessarily exactly > 128), whereas the console loggier continues logging. > > I'm not really show why and would prefer a simpler example first. > > Thanks in advance for any code example, idea, link, comment. You might want to check out the SIMPL toolkit (http:// www.icanprogram.com/06py/main.html). A SIMPL receiver will "naturally" queue and serialize messages from multiple senders. bob From rosuav at gmail.com Thu Oct 27 09:25:19 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Oct 2011 00:25:19 +1100 Subject: __dict__ attribute for built-in types In-Reply-To: References: <4ea92dae$0$20639$426a74cc@news.free.fr> Message-ID: On Thu, Oct 27, 2011 at 10:03 PM, Duncan Booth wrote: > Types without a __dict__ use less memory. Also, if you couldn't have a > type that didn't have a `__dict__` then any `dict` would also need its > own `__dict__` which would either result in infinite memory use or > recursive dictionaries. > Easy, just self-reference. a = {} a.__dict__ is a --> True Yeah, it's recursion, but no different from types: >>> type(type) is type True If you want this behavior, you can do it easily enough. >>> class dictdict(dict): def __init__(self): self.__dict__=self >>> a=dictdict() >>> a.__dict__ is a True However, the more compelling argument is that a __slots__ object can be WAY more efficient. ChrisA From amirouche.boubekki at gmail.com Thu Oct 27 09:55:15 2011 From: amirouche.boubekki at gmail.com (Amirouche Boubekki) Date: Thu, 27 Oct 2011 15:55:15 +0200 Subject: Forking simplejson In-Reply-To: References: Message-ID: > +-------------------+---------------+ >> | Python protocol | JSON | >> | or special case | | >> +===================+=========**======+ >> | (?) __json__ | see (?) | >> +-------------------+---------**------| >> | map | object | >> > > I am curious what you mean by the 'map' protocol. I mean dictionnary-like objects -------------- next part -------------- An HTML attachment was scrubbed... URL: From kwa at kuwata-lab.com Thu Oct 27 10:00:59 2011 From: kwa at kuwata-lab.com (Makoto Kuwata) Date: Thu, 27 Oct 2011 23:00:59 +0900 Subject: [ANN] pyKook 0.6.0 - task automation tool for Python, similar to Rake or Ant Message-ID: Hi, I have released pyKook 0.6.0. http://pypi.python.org/pypi/Kook/0.6.0 http://www.kuwata-lab.com/kook/ http://www.kuwata-lab.com/kook/pykook-users-guide.html In this release, a lot of enhancements are introduced. pyKook Overview --------------- pyKook is a task automation tool for Python, similar to Rake or Ant. (Kookbook.py): kookbook.default = 'build' @recipe(None, ['hello']) def build(c): """build all""" pass @recipe('hello', ['hello.o']) def file_hello(c): """build 'hello' from 'hello.o'""" system(c%'gcc -o $(product) $(ingred)') @recipe('*.o', ['$(1).c', '$(1).h']) def file_o(c): system(c%'gcc -c $(ingred)') Command-line: bash> kk # or pykook $ gcc -c hello.c ### *** hello.o (recipe=file_o) $ gcc -c hello.c ### ** hello (recipe=file_hello) $ gcc -o hello hello.o ### * build (recipe=build) See http://www.kuwata-lab.com/kook/pykook-users-guide.html for details. Enhancements in this release ---------------------------- * 'kookbook' variable is available in your cookbook to specify materials or default product. * Recipe meta-programming support. You can manipulate recipe objects directly. * Load other cookbooks by kookbook.load(). This enables you to split your Kookbook.py into several files. * Support some useful task recipes: clean, sweep, and all. * Namespace is now supported. It is called as 'Category' in Kook. * Concatenation supported. You can concatenate your cookbook and pyKook libraries into a file. Using concatenated file, user doesn't need to install pyKook at all. * Argument description is available. * Private spice option is available. * New command 'pushd()' provided. See http://www.kuwata-lab.com/kook/pykook-CHANGES.txt for details. Have fun! -- regards, makoto kuwata From candide at free.invalid Thu Oct 27 10:01:25 2011 From: candide at free.invalid (candide) Date: Thu, 27 Oct 2011 16:01:25 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: References: <4ea92dae$0$20639$426a74cc@news.free.fr> Message-ID: <4ea96437$0$24971$426a74cc@news.free.fr> Le 27/10/2011 13:03, Duncan Booth a ?crit : > >> -- where the official documentation refers to this point ? >> > See http://docs.python.org/reference/datamodel.html for the docs about > __slots__ > > There is also the API documentation which describes at a low level how > to control whether or not instances have a dict: > http://docs.python.org/c-api/typeobj.html#tp_dictoffset > > I'm not sure though where you find a higher level statement of which > builtin types have a __dict__. > OK, thanks for the information abouts the slots. Nevertheless, this cannot answer completely my question. Some builtin types like string, lists, integer, float, dictionaries, etc have the property that instances of those types don't provide a __dict__ attribute. I can't imagine the documentation lets pass silently this point. But beside this, how to recognise classes whose object doesn't have a __dict__ attribute ? From clp2 at rebertia.com Thu Oct 27 10:07:12 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 Oct 2011 07:07:12 -0700 Subject: Forking simplejson In-Reply-To: References: Message-ID: On Thu, Oct 27, 2011 at 6:55 AM, Amirouche Boubekki wrote: > >>> +-------------------+---------------+ >>> | Python protocol | JSON | >>> | or special case | | >>> +===================+===============+ >>> | (?) __json__ | see (?) | >>> +-------------------+---------------| >>> ? ? ?| map ? ? ? ? ? ? ? | object ? ? ? ?| >> >> I am curious what you mean by the 'map' protocol. > > I mean dictionnary-like objects How do you propose to detect such objects? isinstance(x, collections.Mapping) ? Cheers, Chris From clp2 at rebertia.com Thu Oct 27 10:16:46 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 Oct 2011 07:16:46 -0700 Subject: Forking simplejson In-Reply-To: References: Message-ID: On Wed, Oct 26, 2011 at 2:14 AM, Amirouche Boubekki wrote: > H?llo, > > I would like to fork simplejson [1] and implement serialization rules based > on protocols instead of types [2], plus special cases for protocol free > objects, that breaks compatibility. The benefit will be a better API for > json serialization of custom classes and in the case of iterable it will > avoid a calls like: > >>>> simplejson.dumps(list(my_iterable)) > > The serialization of custom objects is documented in the class instead of > the ``default`` function of current simplejson implementation [3]. > > The encoding algorithm works with a priority list that is summarized in the > next table: > > +-------------------+---------------+ > | Python protocol | JSON | > | or special case | | > +===================+===============+ > | (?) unicode | see (?) | > (?) if the algorithm arrives here, call unicode (with proper encoding rule) > on the object and use the result as json serialization I would prefer a TypeError in such cases, for the same reason str.join() doesn't do an implicit str() on its operands: - Explicit is better than implicit. - (Likely) errors should never pass silently. - In the face of ambiguity, refuse the temptation to guess. Cheers, Chris -- http://rebertia.com From johnroth1 at gmail.com Thu Oct 27 10:18:25 2011 From: johnroth1 at gmail.com (John Roth) Date: Thu, 27 Oct 2011 07:18:25 -0700 (PDT) Subject: inserting \ in regular expressions References: <1319658482.13425.9.camel@corn.betterworld.us> Message-ID: <4ffb88f5-eeb3-4eb8-a481-94f852be81f2@p20g2000prm.googlegroups.com> On Oct 26, 2:47?pm, Dave Angel wrote: > On 10/26/2011 03:48 PM, Ross Boylan wrote: > > > > > > > > > I want to replace every \ and " (the two characters for backslash and > > double quotes) with a \ and the same character, i.e., > > \ -> ?\\ > > " -> ?\" > > > I have not been able to figure out how to do that. ?The documentation > > for re.sub says "repl can be a string or a function; if it is a string, > > any backslash escapes in it are processed.That is, \n is converted to a > > single newline character, \r is converted to a carriage return, and so > > forth. Unknown escapes such as \j are left alone." > > > \\ is apparently unknown, and so is left as is. So I'm unable to get a > > single \. > > > Here are some tries in Python 2.5.2. ?The document suggested the result > > of a function might not be subject to the same problem, but it seems to > > be. > >>>> def f(m): > > ... ? ?return "\\"+m.group(1) > > ... > >>>> re.sub(r"([\\\"])", f, 'Silly " quote') > > 'Silly \\" quote' > > > >>> re.sub(r"([\\\"])", "\\\\\\1", 'Silly " quote') > > 'Silly \\" quote' > > > Or perhaps I'm confused about what the displayed results mean. ?If a > > string has a literal \, does it get shown as \\? > > > I'd appreciate it if you cc me on the reply. > > > Thanks. > > Ross Boylan > > I can't really help on the regex aspect of your code, but I can tell you > a little about backslashes, quote literals, the interpreter, and python. > > > ? Now, one way to cheat on the string if you know you'll want to put > actual backslashes is to use the raw string. That works quite well > unless you want the string to end with a backslash. ?There isn't a way > to enter that as a single raw literal. ?You'd have to do something > string like > ? ? ? a = r"strange\literal\with\some\stuff" + "\\" > > My understanding is that no valid regex ends with a backslash, so this > may not affect you. > > -- > > DaveA Dave's answer is excellent background. I've snipped everything except the part I want to emphasize, which is to use raw strings. They were put into Python specifically for your problem: that is, how to avoid the double and triple backslashes while writing regexes. John Roth From duncan.booth at invalid.invalid Thu Oct 27 10:36:19 2011 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Oct 2011 14:36:19 GMT Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> Message-ID: Chris Angelico wrote: > On Thu, Oct 27, 2011 at 10:03 PM, Duncan Booth > wrote: >> Types without a __dict__ use less memory. Also, if you couldn't have a >> type that didn't have a `__dict__` then any `dict` would also need its >> own `__dict__` which would either result in infinite memory use or >> recursive dictionaries. >> > > Easy, just self-reference. > a = {} > a.__dict__ is a --> True > > Yeah, it's recursion, but no different from types: > Try thinking that one through. Imagine you could set up a dictionary the way you describe: >>> class DictWithDict(dict): def __init__(self, *args, **kw): dict.__init__(self, *args, **kw) self.__dict__ = self >>> d = DictWithDict() >>> d.keys() dict_keys([]) >>> d = DictWithDict({'a': 42}) >>> d.keys() dict_keys(['a']) >>> d['keys'] = lambda: 'oops' >>> d.keys() 'oops' >>> A dict with itself as its own __dict__ becomes like a javascript object where subscripting and attribute access are mostly interchangeable. -- Duncan Booth http://kupuguy.blogspot.com From vinay_sajip at yahoo.co.uk Thu Oct 27 11:07:39 2011 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Thu, 27 Oct 2011 08:07:39 -0700 (PDT) Subject: python logging multiple processes to one file (via socket server) References: Message-ID: <15e35c86-588e-4da3-ad59-abaa5d7c25dd@g21g2000yqc.googlegroups.com> On Oct 27, 11:09?am, Gelonida N wrote: > "The following section documents this approach in more detail and > includes a working socket receiver which can be used as a starting point > for you to adapt in your own applications." > > Somehow I have a mental block though and fail to see the 'following > section'. You're right, the link got lost in a reorganisation of the documentation. Working example is here: http://docs.python.org/howto/logging-cookbook.html#sending-and-receiving-logging-events-across-a-network Regards, Vinay Sajip From amirouche.boubekki at gmail.com Thu Oct 27 11:24:24 2011 From: amirouche.boubekki at gmail.com (Amirouche Boubekki) Date: Thu, 27 Oct 2011 17:24:24 +0200 Subject: Forking simplejson In-Reply-To: References: Message-ID: 2011/10/27 Chris Rebert > On Wed, Oct 26, 2011 at 2:14 AM, Amirouche Boubekki > wrote: > > H?llo, > > > > I would like to fork simplejson [1] and implement serialization rules > based > > on protocols instead of types [2], plus special cases for protocol free > > objects, that breaks compatibility. The benefit will be a better API for > > json serialization of custom classes and in the case of iterable it will > > avoid a calls like: > > > >>>> simplejson.dumps(list(my_iterable)) > > > > The serialization of custom objects is documented in the class instead of > > the ``default`` function of current simplejson implementation [3]. > > > > The encoding algorithm works with a priority list that is summarized in > the > > next table: > > > > +-------------------+---------------+ > > | Python protocol | JSON | > > | or special case | | > > +===================+===============+ > > > | (?) unicode | see (?) | > > > (?) if the algorithm arrives here, call unicode (with proper encoding > rule) > > on the object and use the result as json serialization > > I would prefer a TypeError in such cases, for the same reason > str.join() doesn't do an implicit str() on its operands: > - Explicit is better than implicit. > - (Likely) errors should never pass silently. > - In the face of ambiguity, refuse the temptation to guess. > granted it's better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ladasky at my-deja.com Thu Oct 27 11:37:07 2011 From: ladasky at my-deja.com (John Ladasky) Date: Thu, 27 Oct 2011 08:37:07 -0700 (PDT) Subject: Philosophical Python: 2*b or not 2*b References: Message-ID: <7699e647-98fb-4a6e-aff4-1694d06fd705@h39g2000prh.googlegroups.com> On Oct 27, 1:11?am, Andreas Neudecker wrote: > Any more philsophical Python code out there? That is the question. From amirouche.boubekki at gmail.com Thu Oct 27 11:49:20 2011 From: amirouche.boubekki at gmail.com (Amirouche Boubekki) Date: Thu, 27 Oct 2011 17:49:20 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: <4ea92dae$0$20639$426a74cc@news.free.fr> References: <4ea92dae$0$20639$426a74cc@news.free.fr> Message-ID: 2011/10/27 candide > I realize that built-in types objects don't provide a __dict__ attribute > and thereby i can't set an attribute to a such object, for instance > > > >>> a=[42,421] > >>> a.foo="bar" > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'list' object has no attribute 'foo' > >>> a.__dict__ > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'list' object has no attribute '__dict__' > >>> > > > So, i was wondering : > > -- why this behaviour ? > performance > -- where the official documentation refers to this point ? > it's here and there in python documentation. I did not find specific documentation about the __dict__ property. Have a look at : - naming conventions in http://www.python.org/dev/peps/pep-0008/ - http://docs.python.org/library/stdtypes.html#modules __dict__ is similar to other __*__ properties and has a function that actually use it to do something usefull aka. dir http://docs.python.org/library/functions.html#dir The way I understand it is that it's for internal use but it's exposed for debugging (and learning ?) purpose. -------------- next part -------------- An HTML attachment was scrubbed... URL: From amirouche.boubekki at gmail.com Thu Oct 27 11:53:40 2011 From: amirouche.boubekki at gmail.com (Amirouche Boubekki) Date: Thu, 27 Oct 2011 17:53:40 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: <4ea96437$0$24971$426a74cc@news.free.fr> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> Message-ID: > But beside this, how to recognise classes whose object doesn't have a > __dict__ attribute ? > Why do you need to access __dict__ ? maybe dir is enough see the other message -------------- next part -------------- An HTML attachment was scrubbed... URL: From c.m.ackerman at gmail.com Thu Oct 27 12:29:10 2011 From: c.m.ackerman at gmail.com (quarterlife) Date: Thu, 27 Oct 2011 09:29:10 -0700 (PDT) Subject: xmlrpclib threadsafe? Message-ID: I need to talk to an xmlrpc server. I open one connection and then create a pile of threads communicating to that server. Based on some limited testing, it seems to work really well. The next step is to turn it into a pool. But before I continue, the question is: Does anyone know if the xmlrpclib is really threadsafe? From dihedral88888 at googlemail.com Thu Oct 27 13:35:37 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Thu, 27 Oct 2011 10:35:37 -0700 (PDT) Subject: python logging multiple processes to one file (via socket server) In-Reply-To: <15e35c86-588e-4da3-ad59-abaa5d7c25dd@g21g2000yqc.googlegroups.com> References: <15e35c86-588e-4da3-ad59-abaa5d7c25dd@g21g2000yqc.googlegroups.com> Message-ID: <25498691.487.1319736937890.JavaMail.geo-discussion-forums@prfp13> Well, please check the byte code compiled results. This is useful. I know that a lot people are working on increasing the speed of execution scripts written in python, say, psyco, pyrex for packages released! From missive at hotmail.com Thu Oct 27 15:38:29 2011 From: missive at hotmail.com (Lee Harr) Date: Fri, 28 Oct 2011 00:08:29 +0430 Subject: Need Windows user / developer to help with Pynguin Message-ID: I develop the free python-based turtle graphics application pynguin. http://pynguin.googlecode.com/ Lately I have been getting a lot of positive comments from people who use the program, but I am also getting a lot of feedback from people on Windows (mostly beginners) who are having trouble getting the program running. I don't use Windows myself, though I have found access occasionally to fix bugs. I just don't know enough about Windows culture to be able to make a reliable method for installing or running the program. The method that I wrote for Linux also works on Windows, but it has to be run from the command prompt. I am hoping someone can look at what is there and come up with a reliable method or a simple set of steps that people can follow to get up and running. Hopefully without having to resort to the command prompt. I started a wiki page here: http://code.google.com/p/pynguin/wiki/InstallingPynguinOnWindows but I can't even test if it actually works.... Thanks for any help. From bahamutzero8825 at gmail.com Thu Oct 27 15:47:35 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Thu, 27 Oct 2011 14:47:35 -0500 Subject: Need Windows user / developer to help with Pynguin In-Reply-To: References: Message-ID: <4EA9B557.20100@gmail.com> On 10/27/2011 2:38 PM, Lee Harr wrote: > I am hoping someone can look at what is there and come up with a > reliable method or a simple set of steps that people can follow to get > up and running. Hopefully without having to resort to the command > prompt. > > I started a wiki page here: > http://code.google.com/p/pynguin/wiki/InstallingPynguinOnWindows > but I can't even test if it actually works.... > > > Thanks for any help. Apparently, the US is a forbidden country and Google won't let me download. Otherwise, I'd test it for you. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 From tjreedy at udel.edu Thu Oct 27 15:49:47 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Oct 2011 15:49:47 -0400 Subject: Presenting recursive dict (json_diff) In-Reply-To: References: Message-ID: On 10/27/2011 4:50 AM, mcepl wrote: > Hi, > > I have here a simple script (https://gitorious.org/json_diff/mainline) > which makes a diff between two JSON files. So for JSON objects > > { > "a": 1, > "b": 2, > "son": { > "name": "Jano?ek" > } > } > > and > > { > "a": 2, > "c": 3, > "daughter": { > "name": "Maru?ka" > } > } > > it generates > > { > "append": { > "c": 3, > "daughter": { > "name": "Maru?ka" > } > }, > "remove": { > "b": 2, > "son": { > "name": "Jano?ek" > } > }, > "update": { > "a": 2 > } > } > > (obvious problems with name conflicts between internal keys and the > investigated keys will be somehow addressed later; any simple Pythonic > suggestions how?) Use '_append', etc, much like namedtuple does, for the same reason. -- Terry Jan Reedy From tjreedy at udel.edu Thu Oct 27 15:53:30 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Oct 2011 15:53:30 -0400 Subject: spawnl issues with Win 7 access rights In-Reply-To: <4EA93421.1090905@timgolden.me.uk> References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> <4EA6A950.6090706@timgolden.me.uk> <4EA81B72.7040008@timgolden.me.uk> <98460dba-9e08-4d1a-8bf6-4e8fdbea2d0c@19g2000yqk.googlegroups.com> <4EA93421.1090905@timgolden.me.uk> Message-ID: On 10/27/2011 6:36 AM, Tim Golden wrote: > On 27/10/2011 11:27, Propad wrote: >> the suggestion to add the optional second parameter fixed the problem, >> spawnl now works on the Win 7 computer I'm responsible for (with >> Python 2.2). So the suggested cause seems to be right. > > FWIW, although it's not obvious, the args parameter to spawnl > is intended to become the sys.args (in Python terms) of the > newly-spawned process. Which is why the first element is expected > to be the name of the process. It took me some time to realise > this myself :) > > Anyway, glad we could be of help. Can we make this fix automatic for Win7 to fix #8036? -- Terry Jan Reedy From dingbat at codesmiths.com Thu Oct 27 15:59:57 2011 From: dingbat at codesmiths.com (Andy Dingley) Date: Thu, 27 Oct 2011 12:59:57 -0700 (PDT) Subject: Dynamically creating properties? Message-ID: I have some XML, with a variable and somewhat unknown structure. I'd like to encapsulate this in a Python class and expose the text of the elements within as properties. How can I dynamically generate properties (or methods) and add them to my class? I can easily produce a dictionary of the required element names and their text values, but how do I create new properties at run time? Thanks, From gordon at panix.com Thu Oct 27 16:14:47 2011 From: gordon at panix.com (John Gordon) Date: Thu, 27 Oct 2011 20:14:47 +0000 (UTC) Subject: Dynamically creating properties? References: Message-ID: In Andy Dingley writes: > How can I dynamically generate properties (or methods) and add them to > my class? I can easily produce a dictionary of the required element > names and their text values, but how do I create new properties at run > time? You can set dynamic attributes on class objects without any special processing at all. Just do it, like so: class X(object): pass myx = X() myx.color = 'red' myx.food = 'french fries' myx.lucky_number = 7 Or, if you don't know the attribute name beforehand: setattr(myx, 'occupation', 'programmer') For methods, use an existing method name (without the trailing parentheses) as the attribute value, like so: myx.method = float # assigns the built-in method float() -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From pmaupin at gmail.com Thu Oct 27 16:34:28 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 27 Oct 2011 13:34:28 -0700 (PDT) Subject: Assigning generator expressions to ctype arrays Message-ID: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> Bug or misunderstanding? Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> x = 32 * [0] >>> x[:] = (x for x in xrange(32)) >>> from ctypes import c_uint >>> x = (32 * c_uint)() >>> x[:] = xrange(32) >>> x[:] = (x for x in xrange(32)) Traceback (most recent call last): File "", line 1, in ValueError: Can only assign sequence of same size >>> Thanks, Pat From mcepl at redhat.com Thu Oct 27 16:58:45 2011 From: mcepl at redhat.com (Matej Cepl) Date: Thu, 27 Oct 2011 22:58:45 +0200 Subject: Presenting recursive dict (json_diff) In-Reply-To: References: Message-ID: Dne 27.10.2011 21:49, Terry Reedy napsal(a): > Use '_append', etc, much like namedtuple does, for the same reason. Right, done. What about the presentation issue? Any ideas? Best, Mat?j From devplayer at gmail.com Thu Oct 27 17:48:54 2011 From: devplayer at gmail.com (DevPlayer) Date: Thu, 27 Oct 2011 14:48:54 -0700 (PDT) Subject: Dynamically creating properties? References: Message-ID: On Oct 27, 3:59?pm, Andy Dingley wrote: > I have some XML, with a variable and somewhat unknown structure. I'd > like to encapsulate this in a Python class and expose the text of the > elements within as properties. > > How can I dynamically generate properties (or methods) and add them to > my class? ?I can easily produce a dictionary of the required element > names and their text values, but how do I create new properties at run > time? > > Thanks, class MyX(object): pass myx = myx() xml_tag = parse( file.readline() ) # should be a valid python named-reference syntax, # although any object that can be a valid dict key is allowed. # generally valid python named reference would be the answer to your question attribute = validate( xml_tag ) # dynamicly named property setattr( myx, attribute, property(get_func, set_func, del_func, attr_doc) ) # "dynamicly named method" # really should be a valid python named-reference syntax myfunc_name = validate(myfunc_name) def somefunc(x): return x+x # or somefunc = lambda x: x + x setattr( myx, myfunc_name, somefunc ) So beaware of: # \\\\\\\\\\\\\\\\\\\\\\\\\ setattr(myx, '1', 'one') myx.1 File "", line 1 x.1 ^ SyntaxError: invalid syntax # \\\\\\\\\\\\\\\\\\\\\\\\\ x.'1' File "", line 1 x.'1' ^ SyntaxError: invalid syntax # \\\\\\\\\\\\\\\\\\\\\\\\\ x.__dict__['1'] # returns 'one' x.__dict__ # returns {'1': 'one'} So you should validate your variable names if you are getting them from somewhere. From steve+comp.lang.python at pearwood.info Thu Oct 27 18:19:18 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 27 Oct 2011 22:19:18 GMT Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> Message-ID: <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> On Thu, 27 Oct 2011 16:01:25 +0200, candide wrote: > OK, thanks for the information abouts the slots. Nevertheless, this > cannot answer completely my question. Some builtin types like string, > lists, integer, float, dictionaries, etc have the property that > instances of those types don't provide a __dict__ attribute. I can't > imagine the documentation lets pass silently this point. What, you think it goes against the laws of physics that nobody thought to mention it in the docs? > But beside this, how to recognise classes whose object doesn't have a > __dict__ attribute ? The same way as you would test for any other attribute. >>> hasattr(42, '__dict__') False -- Steven From steve+comp.lang.python at pearwood.info Thu Oct 27 18:31:45 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 27 Oct 2011 22:31:45 GMT Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> Message-ID: <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> On Thu, 27 Oct 2011 13:34:28 -0700, Patrick Maupin wrote: > Bug or misunderstanding? > > Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53) [GCC 4.5.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> x = 32 * [0] >>>> x[:] = (x for x in xrange(32)) >>>> from ctypes import c_uint >>>> x = (32 * c_uint)() >>>> x[:] = xrange(32) >>>> x[:] = (x for x in xrange(32)) > Traceback (most recent call last): > File "", line 1, in > ValueError: Can only assign sequence of same size >From the outside, you can't tell how big a generator expression is. It has no length: >>> g = (x for x in xrange(32)) >>> len(g) Traceback (most recent call last): File "", line 1, in TypeError: object of type 'generator' has no len() Since the array object has no way of telling whether the generator will have the correct size, it refuses to guess. I would argue that it should raise a TypeError with a less misleading error message, rather than a ValueError, so "bug". The simple solution is to use a list comp instead of a generator expression. If you have an arbitrary generator passed to you from the outside, and you don't know how long it is yourself, you can use itertools.islice to extract just the number of elements you want. Given g some generator expression, rather than doing this: # risky, if g is huge, the temporary list will also be huge x[:] = list(g)[:32] do this instead: # use lazy slices guaranteed not to be unexpectedly huge x[:] = list(itertools.islice(g, 32)) -- Steven From missive at hotmail.com Thu Oct 27 18:36:17 2011 From: missive at hotmail.com (Lee Harr) Date: Fri, 28 Oct 2011 03:06:17 +0430 Subject: Need Windows user / developer to help with Pynguin Message-ID: >> I started a wiki page here:????????????????????????????????????????????????????????????????????????????????????????????????? >> http://code.google.com/p/pynguin/wiki/InstallingPynguinOnWindows???????????????????????????????????????????????????????????? >> but I can't even test if it actually works....?????????????????????????????????????????????????????????????????????????????? > Apparently, the US is a forbidden country and Google won't let me????????????????????????????????????????????????????????????? > download. Otherwise, I'd test it for you. I don't understand. Where are you located? What message do you get when trying to download? From rosuav at gmail.com Thu Oct 27 18:39:34 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Oct 2011 09:39:34 +1100 Subject: __dict__ attribute for built-in types In-Reply-To: References: <4ea92dae$0$20639$426a74cc@news.free.fr> Message-ID: On Fri, Oct 28, 2011 at 1:36 AM, Duncan Booth wrote: > Try thinking that one through. Imagine you could set up a dictionary the > way you describe > > A dict with itself as its own __dict__ becomes like a javascript object > where subscripting and attribute access are mostly interchangeable. Yeah; I never said it was a good thing, just that it's possible. "Everything is permissible" - but not everything is beneficial. "Everything is permissible" - but not everything is constructive. (1 Corinthians 10:23, NIV translation.) ChrisA From candide at free.invalid Thu Oct 27 18:52:40 2011 From: candide at free.invalid (candide) Date: Fri, 28 Oct 2011 00:52:40 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4ea9e0ba$0$2261$426a74cc@news.free.fr> Le 28/10/2011 00:19, Steven D'Aprano a ?crit : > > What, you think it goes against the laws of physics that nobody thought > to mention it in the docs? No but I'm expecting from Python documentation to mention the laws of Python ... > >> But beside this, how to recognise classes whose object doesn't have a >> __dict__ attribute ? > > The same way as you would test for any other attribute. > >>>> hasattr(42, '__dict__') > False > > OK but I'm talking about classes, not instances : 42 has no __dict__ attribute but, may be, 43 _has_ such attribute, who knows in advance ? ;) Let'have a try : >>> hasattr(43, '__dict__') False >>> so we have proved by induction that no integer instance has a dictionnary attribute ;) From hniksic at xemacs.org Thu Oct 27 18:57:36 2011 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 28 Oct 2011 00:57:36 +0200 Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> Message-ID: <87pqhi2gbj.fsf@xemacs.org> candide writes: > But beside this, how to recognise classes whose object doesn't have a > __dict__ attribute ? str, list and others aren't classes, they are types. While all (new-style) classes are types, not all types are classes. It's instances of classes (types created by executing the "class" statement or its equivalent) that automatically get a __dict__, unless __slots__ was used at class definition time to suppress it. Built-in and extension types can choose whether to implement __dict__. (Mechanics of defining built-in and extension types are of course implementation-specific. CPython allows adding __dict__ to any extension type by setting the tp_dictoffset member of the type definition struct to the appropriate offset into the instance struct.) From devplayer at gmail.com Thu Oct 27 19:00:57 2011 From: devplayer at gmail.com (DevPlayer) Date: Thu, 27 Oct 2011 16:00:57 -0700 (PDT) Subject: Dynamically creating properties? References: Message-ID: Personally I like to use this function instead of a "try: except:" because try-except will allow names like __metaclass__. Remember, setattr(obj, attr_name, value) allows attr_name to be any valid str(). For example: '!@kdafk11', or '1_1', '1e-20', '0.0', '*one', '\n%%', etc. def isvalid_named_reference( astring ): # "varible name" is really a named_reference # import string # would be cleaner valid_first_char = '_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' valid_rest = '_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' # I think it's ok here for the rare type-check # as unicode named-references are not allowed if type(astring) is not str: return False if len(astring) == 0: return False if astring[0] not in valid_first_char: return False for c in astring[1:]: if c not in valid_rest: return False # Python keywords not allowed as named references (variable names) for astr in ['and', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'yield',]: if astring == astr: return False # valid names but bad idea if astring == '__builtins__': return None if astring == '__metaclass__': return None for astr in dir(__builtins__): if astring == astr: return None # use None as a warning # there might be more like __slots__, and other # module level effecting special names like '__metaclass__' return True Also when using dynamically created "varible names" to check if your objects have an attribute with that name already. From devplayer at gmail.com Thu Oct 27 19:15:01 2011 From: devplayer at gmail.com (DevPlayer) Date: Thu, 27 Oct 2011 16:15:01 -0700 (PDT) Subject: Dynamically creating properties? References: Message-ID: <43b77f11-fc3e-4e73-8e94-9ad43e2f6d49@a17g2000yqj.googlegroups.com> At least one error: change: > for astr in dir(__builtins__): to: for astr in __builtins__.__dict__: From candide at free.invalid Thu Oct 27 19:36:41 2011 From: candide at free.invalid (candide) Date: Fri, 28 Oct 2011 01:36:41 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: <87pqhi2gbj.fsf@xemacs.org> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <87pqhi2gbj.fsf@xemacs.org> Message-ID: <4ea9eb0b$0$637$426a34cc@news.free.fr> Le 28/10/2011 00:57, Hrvoje Niksic a ?crit : > was used at class definition time to suppress it. Built-in and > extension types can choose whether to implement __dict__. > Is it possible in the CPython implementation to write something like this : "foo".bar = 42 without raising an attribute error ? From python at mrabarnett.plus.com Thu Oct 27 20:02:52 2011 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 28 Oct 2011 01:02:52 +0100 Subject: __dict__ attribute for built-in types In-Reply-To: <4ea9eb0b$0$637$426a34cc@news.free.fr> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <87pqhi2gbj.fsf@xemacs.org> <4ea9eb0b$0$637$426a34cc@news.free.fr> Message-ID: <4EA9F12C.8030904@mrabarnett.plus.com> On 28/10/2011 00:36, candide wrote: > Le 28/10/2011 00:57, Hrvoje Niksic a ?crit : > >> was used at class definition time to suppress it. Built-in and >> extension types can choose whether to implement __dict__. >> > > Is it possible in the CPython implementation to write something like this : > > "foo".bar = 42 > > without raising an attribute error ? No, built-in classes written in C have certain limitations, but why would you want to do that anyway? From pmaupin at gmail.com Thu Oct 27 20:09:34 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 27 Oct 2011 17:09:34 -0700 (PDT) Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> On Oct 27, 5:31?pm, Steven D'Aprano wrote: > From the outside, you can't tell how big a generator expression is. It has no length: I understand that. > Since the array object has no way of telling whether the generator will have the correct size, it refuses to guess. It doesn't have to guess. It can assume that I, the programmer, know what the heck I am doing, and then validate that assumption -- trust, but verify. It merely needs to fill the slice and then ask for one more and check that StopIteration is raised. > I would argue that it should raise a TypeError > with a less misleading error message, rather > than a ValueError, so "bug". And I would argue that it should simply work, unless someone can present a more compelling reason why not. > The simple solution is to use a list comp > instead of a generator expression. I know how to work around the issue. I'm not sure I should have to. It violates the principle of least surprise for the ctypes array to not be able to interoperate with the iterator protocol in this fashion. Regards, Pat From devplayer at gmail.com Thu Oct 27 20:35:14 2011 From: devplayer at gmail.com (DevPlayer) Date: Thu, 27 Oct 2011 17:35:14 -0700 (PDT) Subject: Dynamically creating properties? References: <43b77f11-fc3e-4e73-8e94-9ad43e2f6d49@a17g2000yqj.googlegroups.com> Message-ID: Second error def isvalid_named_reference( astring ): # "varible name" is really a named_reference import __builtin__ # add line From stevenbird1 at gmail.com Thu Oct 27 21:21:10 2011 From: stevenbird1 at gmail.com (Steven Bird) Date: Fri, 28 Oct 2011 12:21:10 +1100 Subject: NLTK and package structure Message-ID: The Natural Language Toolkit (NLTK) is a suite of open source Python packages for natural language processing, available at http://nltk.org/, together with an O'Reilly book which is available online for free. Development is now hosted at http://github.com/nltk -- get it here: git at github.com:nltk/nltk.git I am seeking advice on how to speed up our import process. The contents of several sub-packages are made available at the top level, for the convenience of programmers and so that the examples published in the book are more concise. This has been done by having lots of "from subpackage import *" in the top-level __init__.py. Some of these imports are lazy. Unfortunately, any import of nltk leads to cascading imports which pull in most of the library, unacceptably slowing down the load time. https://github.com/nltk/nltk/blob/master/nltk/__init__.py I am looking for a solution that meets the following requirements: 1) import nltk is as fast as possible 2) published code examples are not broken (or are easily fixed by calling nltk.load_subpackages() before the rest of the code) 3) popular subpackage names are available at the top level (e.g. nltk.probability.ConditionalFreqDist as nltk.ConditionalFreqDist) The existing discussion of this issue amongst our developers is posted here: http://code.google.com/p/nltk/issues/detail?id=378 Our practice in structuring subpackages is described here: http://code.google.com/p/nltk/wiki/PackageStructure Thanks for any advice. -Steven Bird (NLTK Project coordinator) From nobody at nowhere.com Thu Oct 27 22:00:28 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 28 Oct 2011 03:00:28 +0100 Subject: Problem using execvp References: <1c03dba0-3d9b-47ab-a4fc-b42210ed35ff@o15g2000yqj.googlegroups.com> Message-ID: On Thu, 27 Oct 2011 01:57:55 -0700, faucheuse wrote: > I get this error : OSError : [Errno 8] Exec format error. The most likely reason for this error is a missing or invalid shebang, e.g.: #!/usr/bin/python or: #!/usr/bin/env python The "#!" must be the first two bytes in the file. Beware of text editors adding a Unicode BOM (byte order mark) at the beginning of the file. Forgetting to add execute permission would result in EPERM (errno=13, "Permission denied"). An invalid interpreter results in ENOENT (errno=2, "No such file or directory"). From tjreedy at udel.edu Thu Oct 27 22:44:26 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Oct 2011 22:44:26 -0400 Subject: __dict__ attribute for built-in types In-Reply-To: <4ea9e0ba$0$2261$426a74cc@news.free.fr> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> <4ea9e0ba$0$2261$426a74cc@news.free.fr> Message-ID: On 10/27/2011 6:52 PM, candide wrote: > No but I'm expecting from Python documentation to mention the laws of > Python ... The details of CPython builtin classes are not laws of Python. It *is* a 'law of Python' that classes can use 'slots = ' to restrict the attributes of instances. By implication, builtin classes in any implementation do not have to allow attribute assignment. I do not believe it would be a violation if some implementation did so. None of this is to say that we could not say something on the subject at the beginning of the 'built-in types' chapter of the lib manual. > OK but I'm talking about classes, not instances : Yes you are. The class determines whether its instances have assignable new attributes. > 42 has no __dict__ > attribute but, > may be, 43 _has_ such attribute, who knows in advance ? ;) True, in a sense, but if the class allowed a user to execute "42.__dict__ = {}" then you could safely assume that "43.xxx = z" should work also. -- Terry Jan Reedy From candide at free.invalid Thu Oct 27 22:46:17 2011 From: candide at free.invalid (candide) Date: Fri, 28 Oct 2011 04:46:17 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <87pqhi2gbj.fsf@xemacs.org> <4ea9eb0b$0$637$426a34cc@news.free.fr> Message-ID: <4eaa177c$0$25902$426a74cc@news.free.fr> Le 28/10/2011 02:02, MRAB a ?crit : > > No, built-in classes written in C have certain limitations, but why > would you want to do that anyway? Mainly for learning purpose and Python better understanding. Actually, I have a class of mine for drawing graphs with the Graphviz software. The nodes of the graph to be represented was supposed to have 2 attributes, say title and shortName. Now, I want to plot a graph whose nodes are pure string. So to fit the class interface, I was trying to add title and shortName attribute to every string node. From wuwei23 at gmail.com Thu Oct 27 22:48:32 2011 From: wuwei23 at gmail.com (alex23) Date: Thu, 27 Oct 2011 19:48:32 -0700 (PDT) Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> <4ea9e0ba$0$2261$426a74cc@news.free.fr> Message-ID: <761cb498-1193-4c33-a8e4-6c0adef7170b@d37g2000prg.googlegroups.com> On Oct 28, 8:52?am, candide wrote: > No but I'm expecting from Python documentation to mention the laws of > Python ... It's not a "law", it's an _implementation detail_. The docs don't tend to mention every such decision made because that's what the source is for. > But beside this, how to recognise classes whose object doesn't have a > __dict__ attribute ? The better question is: why do you need to be able to? > Is it possible in the CPython implementation to write something like this : > "foo".bar = 42 > without raising an attribute error ? Why are you trying to modify an immutible object? If you really want to assign attributes to string objects, subclass str. From huhai102 at gmail.com Thu Oct 27 22:50:06 2011 From: huhai102 at gmail.com (wholesale brand sunglasses) Date: Thu, 27 Oct 2011 19:50:06 -0700 (PDT) Subject: cheap air jordan shoes in www.nike-black.com Message-ID: <53a94ffc-9f41-4a81-bde0-492ea892ef3e@s32g2000prj.googlegroups.com> ? (www.nike-black.com) cheap wholesale nike air Jordan shoes , air force one shoes ? Air Jordan 2011 ? Air Jordan 1 I ? Air Jordan 2 II ? Air Jordan 3 III ? Air Jordan 4 IV ? Air Jordan 5 V ? Air Jordan 6 Rings(www.nike-black.com) ? Air Jordan 6 VI ? Air Jordan 7 VII ? Air Jordan 8 VIII ? Air Jordan 9 IX ? Air Jordan 10 X ? Air Jordan 11 XI ? Air Jordan 12 XII ? Air Jordan 13 XIII ? Air Jordan 14 XIV(www.nike-black.com) ? Air Jordan 15 XV ? Air Jordan 16 XVI ? Air Jordan 17 XVII ? Air Jordan 18 XVIII ? Air Jordan 19 XIX ? Air Jordan 20 XX ? Air Jordan 2009 ? Air Jordan 2010(www.nike-black.com) ? Air Jordan 21 XXI ? Air Jordan 22 XXII ? Air Jordan 23 Classic ? Air Jordan 23 XXIII ? Air Jordan Accolades ? Air Jordan All Day ? Air Jordan Alpha 1(www.nike-black.com) ? Air Jordan B Loyal ? Air Jordan Blase ? Air Jordan Chris Paul ? Air Jordan Classic 87 ? Air Jordan Dub Zero(www.nike-black.com) ? Air Jordan Esterno ? Air Jordan Flight 45 ? Air Jordan Flight 9 ? Air Jordan Fusions-> ? Air Jordan High Heels ? Air Jordan L'Style ? Air Jordan Melo M5 ? Air Jordan Nu Retro(www.nike-black.com) ? Air Jordan Ol School ? Air Jordan Ol School II ? Air Jordan Ol School III ? Air Jordan Olympia ? Air Jordan Phly ? Air Jordan Pro Classic(www.nike-black.com) ? Air Jordan Rare Air ? Air Jordan S.U. Trainer ? Air Jordan Spizikes ? Air Jordan Street Classic ? Air Jordan Team Elite ? Air Jordan Team Elite II(www.nike-black.com) ? Air Jordan Team ISO ? Air Jordan True Flight ? Air Jordan Women ? Jordan 1 Flight(www.nike-black.com) ? Jordan 25th Anniversary ? Jordan Big Fund ? Jordan Countdown ? Jordan Elements(www.nike-black.com) ? Jordan Sixty Plus 60+ ? Jordan Team-> ? Jordan Team Strong ? Jordan Trunner Q4 ? Jordan Winterized Spizike(www.nike-black.com) ? Nike Air Yeezy Website : http://www.nike-black.com From pmaupin at gmail.com Thu Oct 27 23:02:57 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Thu, 27 Oct 2011 20:02:57 -0700 (PDT) Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <87pqhi2gbj.fsf@xemacs.org> <4ea9eb0b$0$637$426a34cc@news.free.fr> <4eaa177c$0$25902$426a74cc@news.free.fr> Message-ID: <3aa6d44a-6015-485c-8745-d129941cb17a@g1g2000vbd.googlegroups.com> On Oct 27, 9:46?pm, candide wrote: > Le 28/10/2011 02:02, MRAB a crit : > > > > > No, built-in classes written in C have certain limitations, but why > > would you want to do that anyway? > > Mainly for learning purpose and Python better understanding. > > Actually, I have a class of mine for drawing graphs with the Graphviz > software. The nodes of the graph to be represented was supposed to have > 2 attributes, say title and shortName. Now, I want to plot a graph whose > nodes are pure string. So to fit the class interface, I was trying to > add title and shortName attribute to every string node. You can easily do that by subclassing a string: class AnnotatedStr(str): pass x = AnnotatedStr('Node1') x.title = 'Title for node 1' etc. The fact that you subclass it (unless your subclass uses __slots__) will give it a dict. From flt.johnson at gmail.com Thu Oct 27 23:05:13 2011 From: flt.johnson at gmail.com (Fletcher Johnson) Date: Thu, 27 Oct 2011 20:05:13 -0700 (PDT) Subject: Unicode literals and byte string interpretation. Message-ID: <8de0e9b7-aaac-44a4-8a07-9c1a20bfc3eb@s7g2000yqa.googlegroups.com> If I create a new Unicode object u'\x82\xb1\x82\xea\x82\xcd' how does this creation process interpret the bytes in the byte string? Does it assume the string represents a utf-16 encoding, at utf-8 encoding, etc...? For reference the string is ??? in the 'shift-jis' encoding. From huhai102 at gmail.com Thu Oct 27 23:06:12 2011 From: huhai102 at gmail.com (wholesale brand sunglasses) Date: Thu, 27 Oct 2011 20:06:12 -0700 (PDT) Subject: discount air jordan shoes in www.nike-black.com Message-ID: ? (www.nike-black.com) cheap wholesale nike air Jordan shoes , air force one shoes ? Air Jordan 2011 ? Air Jordan 1 I ? Air Jordan 2 II ? Air Jordan 3 III ? Air Jordan 4 IV ? Air Jordan 5 V ? Air Jordan 6 Rings(www.nike-black.com) ? Air Jordan 6 VI ? Air Jordan 7 VII ? Air Jordan 8 VIII ? Air Jordan 9 IX ? Air Jordan 10 X ? Air Jordan 11 XI ? Air Jordan 12 XII ? Air Jordan 13 XIII ? Air Jordan 14 XIV(www.nike-black.com) ? Air Jordan 15 XV ? Air Jordan 16 XVI ? Air Jordan 17 XVII ? Air Jordan 18 XVIII ? Air Jordan 19 XIX ? Air Jordan 20 XX ? Air Jordan 2009 ? Air Jordan 2010(www.nike-black.com) ? Air Jordan 21 XXI ? Air Jordan 22 XXII ? Air Jordan 23 Classic ? Air Jordan 23 XXIII Website : http://www.nike-black.com From tjreedy at udel.edu Thu Oct 27 23:23:04 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Oct 2011 23:23:04 -0400 Subject: Assigning generator expressions to ctype arrays In-Reply-To: <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> Message-ID: On 10/27/2011 8:09 PM, Patrick Maupin wrote: > x[:] = (x for x in xrange(32)) This translates to s.__setitem__(slice(None,None), generator_object) where 'generator_object' is completely opaque, except that it will yield 0 to infinity objects in response to next() before raising StopIteration. Given that a cytpe_array is a *fixed-length* array, *unlike* Python's extensible lists and arrays, failure is a possibility due to mis-matched lengths. So ctype_array can either look first, as it does, by calling len(value_object), or leap first and create a temporary array, see if it fills up exactly right, and if it does, copy it over. > I know how to work around the issue. I'm not sure I should have to. I do not think everyone else should suffer substantial increase in space and run time to avoid surprising you. > It violates the principle of least surprise for ctypes to do what is most efficient in 99.9% of uses? > for the ctypes array to > not be able to interoperate with the iterator protocol in this > fashion. It could, but at some cost. Remember, people use ctypes for efficiency, so the temp array path would have to be conditional. When you have a patch, open a feature request on the tracker. -- Terry Jan Reedy From fraveydank at gmail.com Thu Oct 27 23:37:01 2011 From: fraveydank at gmail.com (David Riley) Date: Thu, 27 Oct 2011 23:37:01 -0400 Subject: Unicode literals and byte string interpretation. In-Reply-To: <8de0e9b7-aaac-44a4-8a07-9c1a20bfc3eb@s7g2000yqa.googlegroups.com> References: <8de0e9b7-aaac-44a4-8a07-9c1a20bfc3eb@s7g2000yqa.googlegroups.com> Message-ID: On Oct 27, 2011, at 11:05 PM, Fletcher Johnson wrote: > If I create a new Unicode object u'\x82\xb1\x82\xea\x82\xcd' how does > this creation process interpret the bytes in the byte string? Does it > assume the string represents a utf-16 encoding, at utf-8 encoding, > etc...? > > For reference the string is ??? in the 'shift-jis' encoding. Try it and see! One test case is worth a thousand words. And Python has an interactive interpreter. :-) - Dave From rosuav at gmail.com Thu Oct 27 23:38:39 2011 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 28 Oct 2011 14:38:39 +1100 Subject: Unicode literals and byte string interpretation. In-Reply-To: <8de0e9b7-aaac-44a4-8a07-9c1a20bfc3eb@s7g2000yqa.googlegroups.com> References: <8de0e9b7-aaac-44a4-8a07-9c1a20bfc3eb@s7g2000yqa.googlegroups.com> Message-ID: On Fri, Oct 28, 2011 at 2:05 PM, Fletcher Johnson wrote: > If I create a new Unicode object u'\x82\xb1\x82\xea\x82\xcd' how does > this creation process interpret the bytes in the byte string? Does it > assume the string represents a utf-16 encoding, at utf-8 encoding, > etc...? > > For reference the string is ??? in the 'shift-jis' encoding. Encodings define how characters are represented in bytes. I think probably what you're looking for is a byte string with those hex values in it, which you can then turn into a Unicode string: >>> a=b'\x82\xb1\x82\xea\x82\xcd' >>> unicode(a,"shift-jis") # use 'str' instead of 'unicode' in Python 3 u'\u3053\u308c\u306f' The u'....' notation is for Unicode strings, which are not encoded in any way. The last line of the above is a valid way of entering that string in your source code, identifying Unicode characters by their codepoints. ChrisA From lie.1296 at gmail.com Thu Oct 27 23:42:34 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Fri, 28 Oct 2011 14:42:34 +1100 Subject: Dynamically creating properties? In-Reply-To: References: Message-ID: On 10/28/2011 08:48 AM, DevPlayer wrote: > On Oct 27, 3:59 pm, Andy Dingley wrote: >> I have some XML, with a variable and somewhat unknown structure. I'd >> like to encapsulate this in a Python class and expose the text of the >> elements within as properties. >> >> How can I dynamically generate properties (or methods) and add them to >> my class? I can easily produce a dictionary of the required element >> names and their text values, but how do I create new properties at run >> time? >> >> Thanks, > > class MyX(object): > pass > myx = myx() > > xml_tag = parse( file.readline() ) > > # should be a valid python named-reference syntax, > # although any object that can be a valid dict key is allowed. > # generally valid python named reference would be the answer to > your question > attribute = validate( xml_tag ) > > # dynamicly named property > setattr( myx, attribute, property(get_func, set_func, del_func, > attr_doc) ) > > # "dynamicly named method" > # really should be a valid python named-reference syntax > myfunc_name = validate(myfunc_name) > > def somefunc(x): > return x+x > # or > somefunc = lambda x: x + x > > setattr( myx, myfunc_name, somefunc ) > > > So beaware of: > # \\\\\\\\\\\\\\\\\\\\\\\\\ > setattr(myx, '1', 'one') > > myx.1 > File "", line 1 > x.1 > ^ > SyntaxError: invalid syntax > > # \\\\\\\\\\\\\\\\\\\\\\\\\ > x.'1' > File "", line 1 > x.'1' > ^ > SyntaxError: invalid syntax > > # \\\\\\\\\\\\\\\\\\\\\\\\\ > x.__dict__['1'] # returns > 'one' > > x.__dict__ # returns > {'1': 'one'} > > So you should validate your variable names if you are getting them > from somewhere. XML does not allow attribute names to start with a number, so I doubt you need to worry about that. In addition, if you also need to dynamically access attributes and you have zero control of the name, you can use getattr(). From tjreedy at udel.edu Fri Oct 28 00:16:30 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Oct 2011 00:16:30 -0400 Subject: Need Windows user / developer to help with Pynguin In-Reply-To: References: Message-ID: On 10/27/2011 3:38 PM, Lee Harr wrote: > > I develop the free python-based turtle graphics application pynguin. > > http://pynguin.googlecode.com/ > > > Lately I have been getting a lot of positive comments from people > who use the program, but I am also getting a lot of feedback from > people on Windows (mostly beginners) who are having trouble > getting the program running. > > I don't use Windows myself, though I have found access occasionally > to fix bugs. I just don't know enough about Windows culture to be > able to make a reliable method for installing or running the program. > > The method that I wrote for Linux also works on Windows, but it has > to be run from the command prompt. > > I am hoping someone can look at what is there and come up with a > reliable method or a simple set of steps that people can follow to get > up and running. Hopefully without having to resort to the command > prompt. > > I started a wiki page here: > http://code.google.com/p/pynguin/wiki/InstallingPynguinOnWindows > but I can't even test if it actually works.... In my experience, double clicking on x.zip should open the zip in the zip program (xp) but not actually extract. Win7, with zip built in, just treats x.zip as a directory in Explorer, with no external program required. You pynguin.zip contains one top level file -- a directory called pynguin that contains multiple files*. Extracting pynguin.zip to a pynguin directory in the same directory as pynguin.zip, the default behavior with Win7 at least, creates a new pynguin directory that contains the extracted pynguin directory. So one has to run pynguin/pynguin/setup.py. In other words, there is one level too many. People can erase 'pynguin' from the target list to avoid this. (I am not sure 7zip on xp has the same default.) *You would make things easier, at least for Windows users, if you added the proper extensions. pynguin => pynguin.py README => README.txt etc for other text files. If you are using setup.py, I do not know of any alternative to using a command prompt. But do tell people to find it with Start/All Programs/Accessories/Command Prompt. Then two choices that I know of. 1."cd dir", where dir is the path to the directory containing setup.py. Of course, for "python setup.py install" to work, people must have the Python installation path python-dir in the PATH environmental variable, which it will not be unless they put it there. Without that, "python-dir\python setup.py install" is required. 2. "cd python-dir" followed by "python pynguin-dir\setup.py install" I may have missed something, but I do not actually run many Python apps. One I have used (renpy) makes separate installers for Windows, *nix, and Mac. As I remember, is does a standard Windows installation with one of the free installers, asking where to put the files and if Start menu icons are wanted. I ran it with a desktop shortcup to the main program. The new disutiles2/distribute/packaging package plus a new python launcher for Windows should make things easier within a year, by the time 3.3 is out. For the occasion library package, I prefer to directly extract to site-packages. -- Terry Jan Reedy From tjreedy at udel.edu Fri Oct 28 00:18:30 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Oct 2011 00:18:30 -0400 Subject: Presenting recursive dict (json_diff) In-Reply-To: References: Message-ID: On 10/27/2011 4:58 PM, Matej Cepl wrote: > Dne 27.10.2011 21:49, Terry Reedy napsal(a): >> Use '_append', etc, much like namedtuple does, for the same reason. > > Right, done. What about the presentation issue? Any ideas? No. -- Terry Jan Reedy From nobody at nowhere.com Fri Oct 28 01:49:08 2011 From: nobody at nowhere.com (Nobody) Date: Fri, 28 Oct 2011 06:49:08 +0100 Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> Message-ID: On Thu, 27 Oct 2011 12:08:45 +0200, candide wrote: > I realize that built-in types objects don't provide a __dict__ attribute > and thereby i can't set an attribute to a such object, for instance Note that possession or absence of a __dict__ attribute doesn't necessarily mean that you can or can't set attributes, as the class can override __setattr__(). Ultimately, there is no guaranteed mechanism to determine in advance whether or not an attempt to set an attribute will succeed. From steve+comp.lang.python at pearwood.info Fri Oct 28 02:21:44 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 28 Oct 2011 06:21:44 GMT Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <87pqhi2gbj.fsf@xemacs.org> <4ea9eb0b$0$637$426a34cc@news.free.fr> Message-ID: <4eaa49f8$0$29968$c3e8da3$5496439d@news.astraweb.com> On Fri, 28 Oct 2011 01:36:41 +0200, candide wrote: > Le 28/10/2011 00:57, Hrvoje Niksic a ?crit : > >> was used at class definition time to suppress it. Built-in and >> extension types can choose whether to implement __dict__. >> >> > Is it possible in the CPython implementation to write something like > this : > > "foo".bar = 42 > > without raising an attribute error ? No, because built-in strings don't have a __dict__ and so you cannot add new attributes that didn't already exist. But you can subclass str and do whatever you like. class Str(str): pass Str("foo").bar = 42 -- Steven From steve+comp.lang.python at pearwood.info Fri Oct 28 03:06:08 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 28 Oct 2011 07:06:08 GMT Subject: Unicode literals and byte string interpretation. References: <8de0e9b7-aaac-44a4-8a07-9c1a20bfc3eb@s7g2000yqa.googlegroups.com> Message-ID: <4eaa545f$0$29968$c3e8da3$5496439d@news.astraweb.com> On Thu, 27 Oct 2011 20:05:13 -0700, Fletcher Johnson wrote: > If I create a new Unicode object u'\x82\xb1\x82\xea\x82\xcd' how does > this creation process interpret the bytes in the byte string? It doesn't, because there is no byte-string. You have created a Unicode object from a literal string of unicode characters, not bytes. Those characters are: Dec Hex Char 130 0x82 ? 177 0xb1 ? 130 0x82 ? 234 0xea ? 130 0x82 ? 205 0xcd ? Don't be fooled that all of the characters happen to be in the range 0-255, that is irrelevant. > Does it > assume the string represents a utf-16 encoding, at utf-8 encoding, > etc...? None of the above. It assumes nothing. It takes a string of characters, end of story. > For reference the string is ??? in the 'shift-jis' encoding. No it is not. The way to get a unicode literal with those characters is to use a unicode-aware editor or terminal: >>> s = u'???' >>> for c in s: ... print ord(c), hex(ord(c)), c ... 12371 0x3053 ? 12428 0x308c ? 12399 0x306f ? You are confusing characters with bytes. I believe that what you are thinking of is the following: you start with a byte string, and then decode it into unicode: >>> bytes = '\x82\xb1\x82\xea\x82\xcd' # not u'...' >>> text = bytes.decode('shift-jis') >>> print text ??? If you get the encoding wrong, you will get the wrong characters: >>> print bytes.decode('utf-16') ??? If you start with the Unicode characters, you can encode it into various byte strings: >>> s = u'???' >>> s.encode('shift-jis') '\x82\xb1\x82\xea\x82\xcd' >>> s.encode('utf-8') '\xe3\x81\x93\xe3\x82\x8c\xe3\x81\xaf' -- Steven From steve+comp.lang.python at pearwood.info Fri Oct 28 03:21:47 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 28 Oct 2011 07:21:47 GMT Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> Message-ID: <4eaa580a$0$29968$c3e8da3$5496439d@news.astraweb.com> On Thu, 27 Oct 2011 17:09:34 -0700, Patrick Maupin wrote: > On Oct 27, 5:31?pm, Steven D'Aprano +comp.lang.pyt... at pearwood.info> wrote: >> From the outside, you can't tell how big a generator expression is. It >> has no length: > > I understand that. > >> Since the array object has no way of telling whether the generator will >> have the correct size, it refuses to guess. > > It doesn't have to guess. It can assume that I, the programmer, know > what the heck I am doing, and then validate that assumption -- trust, > but verify. It merely needs to fill the slice and then ask for one more > and check that StopIteration is raised. Simple, easy, and wrong. It needs to fill in the slice, check that the slice has exactly the right number of elements (it may have fewer), and then check that the iterator is now empty. If the slice has too few elements, you've just blown away the entire iterator for no good reason. If the slice is the right length, but the iterator doesn't next raise StopIteration, you've just thrown away one perfectly good value. Hope it wasn't something important. >> I would argue that it should raise a TypeError with a less misleading >> error message, rather than a ValueError, so "bug". > > And I would argue that it should simply work, unless someone can present > a more compelling reason why not. I think that "the iterator protocol as it exists doesn't allow it to work the way you want" is a pretty compelling reason. >> The simple solution is to use a list comp instead of a generator >> expression. > > I know how to work around the issue. I'm not sure I should have to. It > violates the principle of least surprise for the ctypes array to not be > able to interoperate with the iterator protocol in this fashion. Perhaps you're too easily surprised by the wrong things. -- Steven From steve+comp.lang.python at pearwood.info Fri Oct 28 03:42:50 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 28 Oct 2011 07:42:50 GMT Subject: Dynamically creating properties? References: Message-ID: <4eaa5cfa$0$29968$c3e8da3$5496439d@news.astraweb.com> On Thu, 27 Oct 2011 16:00:57 -0700, DevPlayer wrote: > def isvalid_named_reference( astring ): > # "varible name" is really a named_reference > # import string # would be cleaner I don't understand the comment about "variable name". > valid_first_char = > '_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' > valid_rest = > '_0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' This would be better: import string valid_first_char = '_' + string.ascii_letters valid_rest = string.digits + valid_first_char > # I think it's ok here for the rare type-check > # as unicode named-references are not allowed > if type(astring) is not str: return False In Python 3 they are: http://www.python.org/dev/peps/pep-3131/ > if len(astring) == 0: return False > if astring[0] not in valid_first_char: return False > for c in astring[1:]: > if c not in valid_rest: return False > > # Python keywords not allowed as named references (variable names) > for astr in ['and', 'assert', 'break', 'class', 'continue', > 'def', 'del', 'elif', 'else', 'except', 'exec', > 'finally', 'for', 'from', 'global', 'if', 'import', > 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', > 'raise', 'return', 'try', 'while', 'yield',]: > if astring == astr: return False You missed 'as' and 'with'. And 'nonlocal' in Python 3. Possibly others. Try this instead: from keywords import iskeyword if iskeyword(astring): return False -- Steven From steve+comp.lang.python at pearwood.info Fri Oct 28 04:01:15 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 28 Oct 2011 08:01:15 GMT Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> <4ea9e0ba$0$2261$426a74cc@news.free.fr> Message-ID: <4eaa614b$0$29968$c3e8da3$5496439d@news.astraweb.com> On Fri, 28 Oct 2011 00:52:40 +0200, candide wrote: > Le 28/10/2011 00:19, Steven D'Aprano a ?crit : >> >> What, you think it goes against the laws of physics that nobody thought >> to mention it in the docs? > > > No but I'm expecting from Python documentation to mention the laws of > Python ... You seem to have missed my point. You said "I can't imagine" that the Python docs fail to mention that built-ins don't allow the addition of new attributes. I can, easily. The people writing the documentation are only human, and if they failed to mention it, oh well, perhaps they didn't think of it. This is hardly a surprise. Wanting to add arbitrary attributes to built-ins is not exactly an everyday occurrence. >>> But beside this, how to recognise classes whose object doesn't have a >>> __dict__ attribute ? >> >> The same way as you would test for any other attribute. >> >>>>> hasattr(42, '__dict__') >> False > > OK but I'm talking about classes, not instances : 42 has no __dict__ > attribute but, may be, 43 _has_ such attribute, who knows in advance ? > ;) True, it is theoretically possible that (say) only odd numbers get a __dict__, or primes, or the smallest multiple of seventeen larger than the natural logarithm of a googol (10**100). But it's a safe bet that nothing so arbitrary will happen. Dunder attributes ("Double UNDERscore") like __dict__ are reserved for use by Python, and __dict__ has known semantics. You can safely assume that either *all* instances of a type will have a __dict__, or *no* instances will have one. If some class violates that, oh well, your code can't be expected to support every badly-designed stupid class in the world. Also, keep in mind the difference between a *class* __dict__ and an *instance* __dict__. >>> hasattr(int, '__dict__') # Does the int class/type have a __dict__? True >>> hasattr(42, '__dict__') # Does the int instance have a __dict__? False -- Steven From tjreedy at udel.edu Fri Oct 28 04:19:26 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Oct 2011 04:19:26 -0400 Subject: Assigning generator expressions to ctype arrays In-Reply-To: <4eaa580a$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> <4eaa580a$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/28/2011 3:21 AM, Steven D'Aprano wrote: > If the slice has too few elements, you've just blown away the entire > iterator for no good reason. > If the slice is the right length, but the iterator doesn't next raise > StopIteration, you've just thrown away one perfectly good value. Hope it > wasn't something important. You have also over-written values that should be set back to what they were, before the exception is raised, which is why I said the test needs to be done with a temporary array. -- Terry Jan Reedy From mail at timgolden.me.uk Fri Oct 28 04:22:00 2011 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 28 Oct 2011 09:22:00 +0100 Subject: spawnl issues with Win 7 access rights In-Reply-To: References: <4308935.65.1319502062676.JavaMail.geo-discussion-forums@prfq1> <047ec741-9164-4b0e-bb24-f71e3ab1e39b@gk10g2000vbb.googlegroups.com> <4EA6A950.6090706@timgolden.me.uk> <4EA81B72.7040008@timgolden.me.uk> <98460dba-9e08-4d1a-8bf6-4e8fdbea2d0c@19g2000yqk.googlegroups.com> <4EA93421.1090905@timgolden.me.uk> Message-ID: <4EAA6628.4070309@timgolden.me.uk> On 27/10/2011 20:53, Terry Reedy wrote: > On 10/27/2011 6:36 AM, Tim Golden wrote: >> On 27/10/2011 11:27, Propad wrote: >>> the suggestion to add the optional second parameter fixed the problem, >>> spawnl now works on the Win 7 computer I'm responsible for (with >>> Python 2.2). So the suggested cause seems to be right. >> >> FWIW, although it's not obvious, the args parameter to spawnl >> is intended to become the sys.args (in Python terms) of the >> newly-spawned process. Which is why the first element is expected >> to be the name of the process. It took me some time to realise >> this myself :) >> >> Anyway, glad we could be of help. > > Can we make this fix automatic for Win7 to fix #8036? > It's tempting, but I think not. In principle, the caller can pass any value as the first arg of spawn: it'll simply end up as sys.argv[0] in Python terms. If spawnl were the way of the future, I'd be inclined to argue for the change. As it it, though, I'd simply apply the patch and, possibly, add a line to the docs indicating that the args must be non-empty. (I started to import the patch yesterday but something got in the way; I'll see if I can get it done today). TJG From hniksic at xemacs.org Fri Oct 28 05:08:13 2011 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 28 Oct 2011 11:08:13 +0200 Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <87pqhi2gbj.fsf@xemacs.org> <4ea9eb0b$0$637$426a34cc@news.free.fr> Message-ID: <87lis5jxfm.fsf@xemacs.org> candide writes: > Le 28/10/2011 00:57, Hrvoje Niksic a ?crit : > >> was used at class definition time to suppress it. Built-in and >> extension types can choose whether to implement __dict__. >> > > Is it possible in the CPython implementation to write something like this : > > "foo".bar = 42 > > without raising an attribute error ? No, and for good reason. Strings are immutable, so that you needn't care which particular instance of "foo" you're looking at, they're all equivalent. The interpreter uses that fact to cache instances of short strings such as Python identifiers, so that most places that look at a string like "foo" are in fact dealing with the same instance. If one could change an attribute of a particular instance of "foo", it would no longer be allowed for the interpreter to transparently cache them. The same goes for integers and other immutable built-in objects. If you really need to attach state to strings, subclass them as Steven explained. All code that accepts strings (including all built-ins) will work just fine, transparent caching will not happen, and attributes are writable. From moky.math at gmail.com Fri Oct 28 05:29:01 2011 From: moky.math at gmail.com (Laurent) Date: Fri, 28 Oct 2011 11:29:01 +0200 Subject: Entre local et global In-Reply-To: References: <7a7f1c9e-7a6e-42b6-8d53-023834f8b1a1@gk10g2000vbb.googlegroups.com> <4EA9736D.7040202@gmail.com> Message-ID: <4EAA75DD.2080200@gmail.com> Le 28/10/2011 10:43, ll.snark a ?crit : > On 27 oct, 17:06, Laurent Claessens wrote: >> > J'aimerais donc pouvoir indiquer dans fonca, que la variable lst est >> > celle d?finie dans fonc1. >> > Je ne veux pas d'une variable locale ? fonca, ni une variable globale >> > ? tout mon fichier (cf exemple ci-dessous) >> >> > Une id?e ? >> >> Je ne suis pas tr?s s?r que ?a r?ponse ? la question, mais une piste >> serait de faire de fonca une classe avec une m?thode __call__ et une >> variable de classe: >> >> class fonc2(object): >> fonc1.lst=[] >> def __call__(self,v): >> if len(fonc1.lst)<3: >> fonc1.lst=fonc1.lst+[v] >> print fonc1.lst >> > > > Effectivement, ?a r?pond en partie ? la question. > Il faudra que je vois si en faisant comme ?a, je peux r?soudre mon pb > de d?part sur les d?corateurs. MAis je suppose qu'entre une fonction > et une classe qui poss?de une > m?thode __call__, il n'y a pas tant de diff?rence que ?a... Moi je dirais que oui, il y a une diff?rence ?norme : dans une classe tu peux mettre beaucoup plus de choses ;) class Exemple(object): def __init__(self,a): self.a=a def __call__(self,x): return a+x f=Exemple(2) g=Exemple(10) f(1) # 3 g(1) # 11 f.a=6 f(1) # 7 Faire ?a avec une fonction, ?a me semblerait ardu, sauf ? faire comme tu faisais : une fonction qui contient une fonction et qui la retourne. (mais ? mon avis c'est moins lisible) > Merci pour la r?ponse en tous cas. Je suppose donc qu'il n'y a pas de > mot cl?, un peu comme global, mais qui > d?signe une port?e plus petite ? Je ne sais pas. > Je l'aurais sans doute vu dans la doc > ou dans des bouquin si ?a avait ?t? le cas, mais je trouve > que c'est bizarre. A priori, ?a ne me semble pas tellement bizarre. J'utiliserais une fonction seulement pour quelque chose qui a une entr?e et une sortie qui d?pend uniquement de l'entr?e. Pour quelque chose dont le comportement d?pend du contexte (c'est le cas de ce que tu demandes), j'utiliserais une classe dans les attributs de laquelle je mettrais les ?l?ments du contexte. Bon, je dis ?a, mais je ne suis pas assez fort pour pr?tendre ?tre certain de ce qui est "bizarre" ou non :) Bonne journ?e Laurent From candide at free.invalid Fri Oct 28 06:03:29 2011 From: candide at free.invalid (candide) Date: Fri, 28 Oct 2011 12:03:29 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: <4eaa614b$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> <4ea9e0ba$0$2261$426a74cc@news.free.fr> <4eaa614b$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4eaa7df3$0$16584$426a74cc@news.free.fr> Le 28/10/2011 10:01, Steven D'Aprano a ?crit : > didn't think of it. This is hardly a surprise. Wanting to add arbitrary > attributes to built-ins is not exactly an everyday occurrence. > Depends. Experimented programmers don't even think of it. But less advanced programmers can consider of it. It's is not uncommun to use a Python class like a C structure, for instance : class C:pass C.member1=foo C.member2=bar Why not with a built-in type instead of a custom class? > the natural logarithm of a googol (10**100). But it's a safe bet that > nothing so arbitrary will happen. betting when programming ? How curious! ;) > Also, keep in mind the difference between a *class* __dict__ and an > *instance* __dict__. > You mean this distinction >>> hasattr('', '__dict__') False >>> hasattr(''.__class__, '__dict__') True >>> ? From candide at free.invalid Fri Oct 28 06:04:14 2011 From: candide at free.invalid (candide) Date: Fri, 28 Oct 2011 12:04:14 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: <3aa6d44a-6015-485c-8745-d129941cb17a@g1g2000vbd.googlegroups.com> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <87pqhi2gbj.fsf@xemacs.org> <4ea9eb0b$0$637$426a34cc@news.free.fr> <4eaa177c$0$25902$426a74cc@news.free.fr> <3aa6d44a-6015-485c-8745-d129941cb17a@g1g2000vbd.googlegroups.com> Message-ID: <4eaa7e21$0$16584$426a74cc@news.free.fr> Le 28/10/2011 05:02, Patrick Maupin a ?crit : > You can easily do that by subclassing a string: > > class AnnotatedStr(str): > pass > > x = AnnotatedStr('Node1') > x.title = 'Title for node 1' > Less or more what I did. But requires to transport the string graph structure to the AnnotatedStr one. From candide at free.invalid Fri Oct 28 06:23:46 2011 From: candide at free.invalid (candide) Date: Fri, 28 Oct 2011 12:23:46 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: <87lis5jxfm.fsf@xemacs.org> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <87pqhi2gbj.fsf@xemacs.org> <4ea9eb0b$0$637$426a34cc@news.free.fr> <87lis5jxfm.fsf@xemacs.org> Message-ID: <4eaa82b5$0$8819$426a74cc@news.free.fr> Le 28/10/2011 11:08, Hrvoje Niksic a ?crit : > longer be allowed for the interpreter to transparently cache them. The > same goes for integers and other immutable built-in objects. On the other hand, immutability and optimization don't explain the whole thing because you can't do something like [].bar = 42. > > If you really need to attach state to strings, subclass them as Steven > explained. All code that accepts strings (including all built-ins) will > work just fine, transparent caching will not happen, and attributes are > writable. OK, thanks, I'll consider it seriously. Actually I have a directed graph whose nodes are given as string but it's oversimplistic to identify node and string (for nodes requiring specific methods). From moky.math at gmail.com Fri Oct 28 06:28:34 2011 From: moky.math at gmail.com (Laurent Claessens) Date: Fri, 28 Oct 2011 12:28:34 +0200 Subject: Entre local et global In-Reply-To: References: <7a7f1c9e-7a6e-42b6-8d53-023834f8b1a1@gk10g2000vbb.googlegroups.com> <4EA9736D.7040202@gmail.com> Message-ID: Woops. This was aimed to the french speaking python's usenet. Sorry. Laurent Le 28/10/2011 11:29, Laurent a ?crit : > Le 28/10/2011 10:43, ll.snark a ?crit : >> On 27 oct, 17:06, Laurent Claessens wrote: >>> > J'aimerais donc pouvoir indiquer dans fonca, que la variable lst est >>> > celle d?finie dans fonc1. >>> > Je ne veux pas d'une variable locale ? fonca, ni une variable globale >>> > ? tout mon fichier (cf exemple ci-dessous) >>> >>> > Une id?e ? [snip] From lists at cheimes.de Fri Oct 28 07:51:33 2011 From: lists at cheimes.de (Christian Heimes) Date: Fri, 28 Oct 2011 13:51:33 +0200 Subject: __dict__ attribute for built-in types In-Reply-To: <4eaa614b$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> <4ea9e0ba$0$2261$426a74cc@news.free.fr> <4eaa614b$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: Am 28.10.2011 10:01, schrieb Steven D'Aprano: >>>> hasattr(int, '__dict__') # Does the int class/type have a __dict__? > True >>>> hasattr(42, '__dict__') # Does the int instance have a __dict__? > False Also __dict__ doesn't have to be an instance of __dict__. Builtin types usually have a dictproxy instane as their __dict__. >>> type(int.__dict__) >>> int.__dict__["egg"] = "spam" Traceback (most recent call last): File "", line 1, in TypeError: 'dictproxy' object does not support item assignment From amirouche.boubekki at gmail.com Fri Oct 28 08:07:29 2011 From: amirouche.boubekki at gmail.com (Amirouche Boubekki) Date: Fri, 28 Oct 2011 14:07:29 +0200 Subject: Is Python in the browser a dead-end ? Message-ID: H?llo, There was a thread recently about the missed opportunity for Python to be a language that could replace Javascript in the browser. They are several attempts at doing something in this spirit here are the ones I'm aware of: - pyjamas aka. pyjs it is to Python what GWT is to Java : http://pyjs.org/ - py2js which compiles Python to Javascript without high level widget like pyjamas does https://github.com/qsnake/py2js - skulpt unlike py2js and pyjs there is no compilation phase http://www.skulpt.org/ And SubScript [1], which I am the creator, a Python-like language [2] and Sissi [3] which aims at being the stdlib of SubScript, currently it's implemented with py2js. It relies heavly on Google Closure tools [4]. I'm planning to add streamer [5] support if I can wrap my head around it. I'm done with self advertisement. Before starting SubScript I gave it some thoughts, and I think that it can bring value to web development. Here are articles that backs up my vision: - Javascript gurus claims that Javascript is indeed the "assembly" of the web [6], which means that Javascript is viable target for a compiler - Similar projects exists with Coffescript and ClojureScript which seems to have the lead and are gaining traction in web development community. Dart is another example. - The thing that makes Javascript development difficult is that it's hard to debug, but map JS [7] is making its way into Firefox which will help greatly Why do people think that this projects are doomed ? I ask this question to understand other point of views before commiting myself at finish SubScript & Sissi, I don't want to code something that will be useless. Thanks in advance, Amirouche [1] https://bitbucket.org/abki/subscript [2] currently Subscript code is parsed by Python parsing library the exact same syntax should be supported [3] https://bitbucket.org/abki/sissi/overview [4] http://code.google.com/intl/fr/closure/ [5] https://github.com/Gozala/streamer [6] http://www.hanselman.com/blog/JavaScriptIsAssemblyLanguageForTheWebSematicMarkupIsDeadCleanVsMachinecodedHTML.aspx [7] https://bugzilla.mozilla.org/show_bug.cgi?id=618650 -------------- next part -------------- An HTML attachment was scrubbed... URL: From billy.earney at gmail.com Fri Oct 28 11:03:10 2011 From: billy.earney at gmail.com (Billy Earney) Date: Fri, 28 Oct 2011 10:03:10 -0500 Subject: Is Python in the browser a dead-end ? In-Reply-To: References: Message-ID: I believe that python maybe had missed an opportunity to get in early and be able to take over a large market share from javascript. But that doesn't mean python is dead in the browser, it just means it will have more competition if it wants to replace javascript for Rich Internet Applications. there's also emscripten, which takes c code and compiles it into javascript. the c python compiler is one of its primary examples as you can see here: http://syntensity.com/static/python.html I've also contributed some code to Skupt so that a person can do something like Hopefully eventually, the code I submitted will be of use someday! :) On Fri, Oct 28, 2011 at 7:07 AM, Amirouche Boubekki < amirouche.boubekki at gmail.com> wrote: > H?llo, > > There was a thread recently about the missed opportunity for Python to be a > language that could replace Javascript in the browser. > > They are several attempts at doing something in this spirit here are the > ones I'm aware of: > > - pyjamas aka. pyjs it is to Python what GWT is to Java : http://pyjs.org/ > - py2js which compiles Python to Javascript without high level widget like > pyjamas does https://github.com/qsnake/py2js > - skulpt unlike py2js and pyjs there is no compilation phase > http://www.skulpt.org/ > > And SubScript [1], which I am the creator, a Python-like language [2] and > Sissi [3] which aims at being the stdlib of SubScript, currently it's > implemented with py2js. It relies heavly on Google Closure tools [4]. I'm > planning to add streamer [5] support if I can wrap my head around it. > > I'm done with self advertisement. > > Before starting SubScript I gave it some thoughts, and I think that it can > bring value to web development. > > Here are articles that backs up my vision: > > - Javascript gurus claims that Javascript is indeed the "assembly" of the > web [6], which means that Javascript is viable target for a compiler > > - Similar projects exists with Coffescript and ClojureScript which seems to > have the lead and are gaining traction in web development community. Dart is > another example. > > - The thing that makes Javascript development difficult is that it's hard > to debug, but map JS [7] is making its way into Firefox which will help > greatly > > Why do people think that this projects are doomed ? > > I ask this question to understand other point of views before commiting > myself at finish SubScript & Sissi, I don't want to code something that will > be useless. > > Thanks in advance, > > Amirouche > > [1] https://bitbucket.org/abki/subscript > [2] currently Subscript code is parsed by Python parsing library the exact > same syntax should be supported > [3] https://bitbucket.org/abki/sissi/overview > [4] http://code.google.com/intl/fr/closure/ > [5] https://github.com/Gozala/streamer > [6] > http://www.hanselman.com/blog/JavaScriptIsAssemblyLanguageForTheWebSematicMarkupIsDeadCleanVsMachinecodedHTML.aspx > [7] https://bugzilla.mozilla.org/show_bug.cgi?id=618650 > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ppearson at nowhere.invalid Fri Oct 28 11:52:49 2011 From: ppearson at nowhere.invalid (Peter Pearson) Date: 28 Oct 2011 15:52:49 GMT Subject: __dict__ attribute for built-in types References: <4ea92dae$0$20639$426a74cc@news.free.fr> <4ea96437$0$24971$426a74cc@news.free.fr> <4ea9d8e6$0$29968$c3e8da3$5496439d@news.astraweb.com> <4ea9e0ba$0$2261$426a74cc@news.free.fr> Message-ID: <9h01ehF8ogU1@mid.individual.net> On Fri, 28 Oct 2011 00:52:40 +0200, candide wrote: [snip] >>>>> hasattr(42, '__dict__') >> False [snip] > > Let'have a try : > > >>> hasattr(43, '__dict__') > False > >>> > > so we have proved by induction that no integer instance has a > dictionnary attribute ;) You left out an important step in this proof by induction. Observe: >>> n = 0 >>> hasattr(n, "__dict__") False >>> if hasattr(n, "__dict__") is False: ... hasattr(n+1, "__dict__") is False ... True There, now it's proven by induction. -- To email me, substitute nowhere->spamcop, invalid->net. From hanss at libero.it Fri Oct 28 13:03:35 2011 From: hanss at libero.it (Gabriele) Date: Fri, 28 Oct 2011 10:03:35 -0700 (PDT) Subject: getting columns attributes in declarative style with sqlalchemy Message-ID: <372ac973-575c-466a-9322-a879f099d86a@v5g2000vbh.googlegroups.com> Hi, I'm tryed to write my first application using SqlAlchemy. I'm using declarative style. I need to get the attributes of the columns of my table. This is an example of my very simple model-class: class Country(base): __tablename__ = "bookings_countries" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True) canceled = sqlalchemy.Column(sqlalchemy.Boolean, nullable=False, default=False) description = sqlalchemy.Column(Description) def __init__(self, canceled, description): self.canceled = canceled self.description = description def __repr__(self): return "" % (self.description) I want to populate a wx grid using the name of the fields as labels of the columns. I found three different solutions of my problem, but none satisfeid me: a) using column_descriptions in query object. col = (model.Country.canceled, model.Country.description) q = self.parent.session.query(*col).order_by(model.Country.description) l = [column["name"] for column in q.column_descriptions] in this way, l contains exactly what I need, but I don't like because I must execute an useless query only for having informations about the structure of my table. Ok, it's not so big problem, but IMO is not a very good solution b) reflecting the table c) using inspector lib from sqlachemy.engine I don't like because I have to use directly the name of the table in the database... It sounds me better and logical to use my class Country... but I can't find the simple way for doing that... maybe it's very simple, but... Someone can help me? Thanks Gabriele From nathan.alexander.rice at gmail.com Fri Oct 28 13:20:38 2011 From: nathan.alexander.rice at gmail.com (Nathan Rice) Date: Fri, 28 Oct 2011 13:20:38 -0400 Subject: Forking simplejson In-Reply-To: References: Message-ID: Just a random note, I actually set about the task of re-implementing a json encoder which can be subclassed, is highly extensible, and uses (mostly) sane coding techniques (those of you who've looked at simplejson's code will know why this is a good thing). So far preliminary tests show the json only subclass of the main encoder basically tied in performance with the python implementation of simplejson. The C version of simplejson does turn in a performance about 12x faster, but that's apples to oranges. The design of the encoder would also make a XML serializer pretty straight forward to implement as well (not that I care about XML, *blech*). I'm torn between just moving on to some of my other coding tasks and putting some time into this to make it pass the simplejson/std lib json tests. I really do think the standard lib json encoder is bad and I would like to see an alternative in there but I'm hesitant to get involved. Nathan On Thu, Oct 27, 2011 at 11:24 AM, Amirouche Boubekki wrote: > > > 2011/10/27 Chris Rebert >> >> On Wed, Oct 26, 2011 at 2:14 AM, Amirouche Boubekki >> wrote: >> > H?llo, >> > >> > I would like to fork simplejson [1] and implement serialization rules >> > based >> > on protocols instead of types [2], plus special cases for protocol free >> > objects, that breaks compatibility. The benefit will be a better API for >> > json serialization of custom classes and in the case of iterable it will >> > avoid a calls like: >> > >> >>>> simplejson.dumps(list(my_iterable)) >> > >> > The serialization of custom objects is documented in the class instead >> > of >> > the ``default`` function of current simplejson implementation [3]. >> > >> > The encoding algorithm works with a priority list that is summarized in >> > the >> > next table: >> > >> > ? ? +-------------------+---------------+ >> > ? ? | Python protocol ? | JSON ? ? ? ? ?| >> > ? ? | ?or special case ?| ? ? ? ? ? ? ? | >> > ? ? +===================+===============+ >> >> > ? ? | (?) unicode ? ? ? | see (?) ? ? ? | >> >> > (?) if the algorithm arrives here, call unicode (with proper encoding >> > rule) >> > on the object and use the result as json serialization >> >> I would prefer a TypeError in such cases, for the same reason >> str.join() doesn't do an implicit str() on its operands: >> - Explicit is better than implicit. >> - (Likely) errors should never pass silently. >> - In the face of ambiguity, refuse the temptation to guess. > > granted it's better. > > > -- > http://mail.python.org/mailman/listinfo/python-list > > From dhyams at gmail.com Fri Oct 28 13:34:35 2011 From: dhyams at gmail.com (dhyams) Date: Fri, 28 Oct 2011 10:34:35 -0700 (PDT) Subject: How to mix-in __getattr__ after the fact? Message-ID: <4630c4d0-86bc-4295-8bbb-6f58415191c8@v15g2000vbm.googlegroups.com> Python 2.7.2 I'm having trouble in a situation where I need to mix-in the functionality of __getattr__ after the object has already been created. Here is a small sample script of the situation: =============snip import types class Cow(object): pass # this __getattr__ works as advertised. #def __getattr__(self,a): # print "CAUGHT INCLASS: Attempting to get attribute ",a def attrgetter(self,a): print "CAUGHT: Attempting to get attribute ",a bessie = Cow() bessie.__getattr__ = types.MethodType(attrgetter,bessie,Cow) # here, I should see my printout "attempting to get attribute" # but I get an AttributeException print bessie.milk ======================snip If I call __getattr__ directly, as in bessie.__getattr__('foo'), it works as it should obviously; so the method is bound and ready to be called. But Python does not seem to want to call __getattr__ appropriately if I mix it in after the object is already created. Is there a workaround, or am I doing something wrongly? Thanks, From pmaupin at gmail.com Fri Oct 28 14:05:05 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 28 Oct 2011 11:05:05 -0700 (PDT) Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> Message-ID: <20aeed48-8d77-445a-a4b6-85f0309e714f@f36g2000vbm.googlegroups.com> On Oct 27, 10:23?pm, Terry Reedy wrote: > I do not think everyone else should suffer substantial increase in space > and run time to avoid surprising you. What substantial increase? There's already a check that winds up raising an exception. Just make it empty an iterator instead. > > It violates the principle of least surprise > > for ctypes to do what is most efficient in 99.9% of uses? It doesn't work at all with an iterator, so it's most efficient 100% of the time now. How do you know how many people would use iterators if it worked? > > It could, but at some cost. Remember, people use ctypes for efficiency, yes, you just made my argument for me. Thank you. It is incredibly inefficient to have to create a temp array. > so the temp array path would have to be conditional. I don't understand this at all. Right now, it just throws up its hands and says "I don't work with iterators." Why would it be a problem to change this? From michaelm at plumbersstock.com Fri Oct 28 14:10:14 2011 From: michaelm at plumbersstock.com (Michael McGlothlin) Date: Fri, 28 Oct 2011 12:10:14 -0600 Subject: Fast recursive generators? Message-ID: I'm trying to generate a list of values where each value is dependent on the previous value in the list and this bit of code needs to be repeatedly so I'd like it to be fast. It doesn't seem that comprehensions will work as each pass needs to take the result of the previous pass as it's argument. map() doesn't seem likely. filter() or reduce() seem workable but not very clean. Is there a good way to do this? About the best I can get is this: l = [ func ( start ) ] f = lambda a: func ( l[-1] ) or a filter ( f, range ( big_number, -1, -1 ) ) I guess I'm looking for something more like: l = do ( lambda a: func ( a ), big_number, start ) Thanks, Michael McGlothlin From malaclypse2 at gmail.com Fri Oct 28 14:14:34 2011 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 28 Oct 2011 14:14:34 -0400 Subject: How to mix-in __getattr__ after the fact? In-Reply-To: <4630c4d0-86bc-4295-8bbb-6f58415191c8@v15g2000vbm.googlegroups.com> References: <4630c4d0-86bc-4295-8bbb-6f58415191c8@v15g2000vbm.googlegroups.com> Message-ID: On Fri, Oct 28, 2011 at 1:34 PM, dhyams wrote: > If I call __getattr__ directly, as in bessie.__getattr__('foo'), it > works as it should obviously; so the method is bound and ready to be > called. ?But Python does not seem to want to call __getattr__ > appropriately if I mix it in after the object is already created. ?Is > there a workaround, or am I doing something wrongly? Python looks up special methods on the class, not the instance (see http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes). It seems like you ought to be able to delegate the special attribute access from the class to the instance somehow, but I couldn't figure out how to do it in a few minutes of fiddling at the interpreter. -- Jerry From ethan at stoneleaf.us Fri Oct 28 14:20:20 2011 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 28 Oct 2011 11:20:20 -0700 Subject: How to mix-in __getattr__ after the fact? In-Reply-To: <4630c4d0-86bc-4295-8bbb-6f58415191c8@v15g2000vbm.googlegroups.com> References: <4630c4d0-86bc-4295-8bbb-6f58415191c8@v15g2000vbm.googlegroups.com> Message-ID: <4EAAF264.1050307@stoneleaf.us> dhyams wrote: > Python 2.7.2 > > I'm having trouble in a situation where I need to mix-in the > functionality of __getattr__ after the object has already been > created. Here is a small sample script of the situation: > > =============snip > > import types > > class Cow(object): > pass > # this __getattr__ works as advertised. > #def __getattr__(self,a): > # print "CAUGHT INCLASS: Attempting to get attribute ",a > > > def attrgetter(self,a): > print "CAUGHT: Attempting to get attribute ",a > > bessie = Cow() > > bessie.__getattr__ = types.MethodType(attrgetter,bessie,Cow) > > # here, I should see my printout "attempting to get attribute" > # but I get an AttributeException > print bessie.milk > ======================snip > > If I call __getattr__ directly, as in bessie.__getattr__('foo'), it > works as it should obviously; so the method is bound and ready to be > called. But Python does not seem to want to call __getattr__ > appropriately if I mix it in after the object is already created. Is > there a workaround, or am I doing something wrongly? > > Thanks, Python only looks up __xxx__ methods in new-style classes on the class itself, not on the instances. So this works: 8<---------------------------------------------------------------- class Cow(object): pass def attrgetter(self, a): print "CAUGHT: Attempting to get attribute", a bessie = Cow() Cow.__getattr__ = attrgetter print bessie.milk 8<---------------------------------------------------------------- ~Ethan~ From tjreedy at udel.edu Fri Oct 28 16:24:02 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Oct 2011 16:24:02 -0400 Subject: Assigning generator expressions to ctype arrays In-Reply-To: <20aeed48-8d77-445a-a4b6-85f0309e714f@f36g2000vbm.googlegroups.com> References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> <20aeed48-8d77-445a-a4b6-85f0309e714f@f36g2000vbm.googlegroups.com> Message-ID: On 10/28/2011 2:05 PM, Patrick Maupin wrote: > On Oct 27, 10:23 pm, Terry Reedy wrote: >> I do not think everyone else should suffer substantial increase in space >> and run time to avoid surprising you. > > What substantial increase? of time and space, as I said, for the temporary array that I think would be needed and which I also described in the previous paragraph that you clipped > There's already a check that winds up > raising an exception. Just make it empty an iterator instead. It? I have no idea what you intend that to refer to. >>> It violates the principle of least surprise >> for ctypes to do what is most efficient in 99.9% of uses? > > It doesn't work at all with an iterator, so it's most efficient 100% > of the time now. How do you know how many people would use iterators > if it worked? I doubt it would be very many because it is *impossible* to make it work in the way that I think people would want it to. >> It could, but at some cost. Remember, people use ctypes for efficiency, > yes, you just made my argument for me. Thank you. It is incredibly > inefficient to have to create a temp array. But necessary to work with blank box iterators. Now you are agreeing with my argument. >> so the temp array path would have to be conditional. > I don't understand this at all. Right now, it just throws up its > hands and says "I don't work with iterators." If ctype_array slice assignment were to be augmented to work with iterators, that would, in my opinion (and see below), require use of temporary arrays. Since slice assignment does not use temporary arrays now (see below), that augmentation should be conditional on the source type being a non-sequence iterator. > Why would it be a problem to change this? CPython comes with immutable fixed-length arrays (tuples) that do not allow slice assignment and mutable variable-length arrays (lists) that do. The definition is 'replace the indicated slice with a new slice built from all values from an iterable'. Point 1: This works for any properly functioning iterable that produces any finite number of items. Iterators are always exhausted. Replace can be thought of as delete follewed by add, but the implementation is not that naive. Point 2: If anything goes wrong and an exception is raised, the list is unchanged. This means that there must be temporary internal storage of either old or new references. An example that uses an improperly functioning generator. >>> a [0, 1, 2, 3, 4, 5, 6, 7] >>> def g(): yield None raise ValueError >>> a[3:6]=g() Traceback (most recent call last): File "", line 1, in a[3:6]=g() File "", line 3, in g raise ValueError ValueError >>> a [0, 1, 2, 3, 4, 5, 6, 7] A c_uint array is a new kind of beast: a fixed-length mutable array. So it has to have a different definition of slice assignment than lists. Thomas Heller, the ctypes author, apparently chose 'replacement by a sequence with exactly the same number of items, else raise an exception'. though I do not know what the doc actually says. An alternative definition would have been to replace as much of the slice as possible, from the beginning, while ignoring any items in excess of the slice length. This would work with any iterable. However, partial replacement of a slice would be a surprising innovation to most. The current implementation assumes that the reported length of a sequence matches the valid indexes and dispenses with temporary storage. This is shown by the following: from ctypes import c_uint n = 20 class Liar: def __len__(self): return n def __getitem__(self, index): if index < 10: return 1 else: raise ValueError() x = (n * c_uint)() print(list(x)) x[:] = range(n) print(list(x)) try: x[:] = Liar() except: pass print(list(x)) >>> [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] I consider such unintended partial replacement to be a glitch. An exception could be raised, but without adding temp storage, the array could not be restored. And making a change *and* raising an exception would be a different sort of glitch. (One possible with augmented assignment involving a mutable member of a tuple.) So I would leave this as undefined behavior for an input outside the proper domain of the function. Anyway, as I said before, you are free to propose a specific change ('work with iterators' is too vague) and provide a corresponding patch. -- Terry Jan Reedy From tjreedy at udel.edu Fri Oct 28 16:45:21 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Oct 2011 16:45:21 -0400 Subject: Fast recursive generators? In-Reply-To: References: Message-ID: On 10/28/2011 2:10 PM, Michael McGlothlin wrote: > I'm trying to generate a list of values Better to think of a sequence of values, whether materialized as a 'list' or not. > where each value is dependent > on the previous value in the list and this bit of code needs to be > repeatedly so I'd like it to be fast. It doesn't seem that > comprehensions will work as each pass needs to take the result of the > previous pass as it's argument. map() doesn't seem likely. filter() or Comprehensions combine map and filter, both of which conceptually work on each item of a pre-existing list independently. (I am aware that the function passed can stash away values to create dependence. > reduce() seem workable but not very clean. Is there a good way to do > this? About the best I can get is this: > > l = [ func ( start ) ] > f = lambda a: func ( l[-1] ) or a > filter ( f, range ( big_number, -1, -1 ) ) > > > I guess I'm looking for something more like: > > l = do ( lambda a: func ( a ), big_number, start ) Something like def do(func, N, value): yield value for i in range(1,N): value = func(value) yield value ? For more generality, make func a function of both value and i. If you need a list, "l = list(do(f,N,x))", but if you do not, you can do "for item in do(f,N,x):" and skip making the list. -- Terry Jan Reedy From gelonida at gmail.com Fri Oct 28 16:47:42 2011 From: gelonida at gmail.com (Gelonida N) Date: Fri, 28 Oct 2011 22:47:42 +0200 Subject: save tuple of simple data types to disk (low memory foot print) Message-ID: Hi, I would like to save many dicts with a fixed amount of keys tuples to a file in a memory efficient manner (no random, but only sequential access is required) As the keys are the same for each entry I considered converting them to tuples. The tuples contain only strings, ints (long ints) and floats (double) and the data types for each position within the tuple are fixed. The fastest and simplest way is to pickle the data or to use json. Both formats however are not that optimal. I could store ints and floats with pack. As strings have variable length I'm not sure how to save them efficiently (except adding a length first and then the string. Is there already some 'standard' way or standard library to store such data efficiently? Thanks in advance for any suggestion. From tjreedy at udel.edu Fri Oct 28 16:52:43 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Oct 2011 16:52:43 -0400 Subject: Forking simplejson In-Reply-To: References: Message-ID: On 10/28/2011 1:20 PM, Nathan Rice wrote: > Just a random note, I actually set about the task of re-implementing a > json encoder which can be subclassed, is highly extensible, and uses > (mostly) sane coding techniques (those of you who've looked at > simplejson's code will know why this is a good thing). So far > preliminary tests show the json only subclass of the main encoder > basically tied in performance with the python implementation of > simplejson. The C version of simplejson does turn in a performance > about 12x faster, but that's apples to oranges. The design of the > encoder would also make a XML serializer pretty straight forward to > implement as well (not that I care about XML, *blech*). > > I'm torn between just moving on to some of my other coding tasks and > putting some time into this to make it pass the simplejson/std lib > json tests. I really do think the standard lib json encoder is bad Python is the result of people who thought *something* was 'bad' > and I would like to see an alternative in there and volunteered the effort to make something better. > but I'm hesitant to get involved. As someone who is involved and tries to encourage others, I am curious why. -- Terry Jan Reedy From pmaupin at gmail.com Fri Oct 28 17:51:19 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 28 Oct 2011 14:51:19 -0700 (PDT) Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> <4eaa580a$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1e1764c6-d49d-468b-a0bd-cec3033acfee@t8g2000yql.googlegroups.com> On Oct 28, 3:19?am, Terry Reedy wrote: > On 10/28/2011 3:21 AM, Steven D'Aprano wrote: > > > If the slice has too few elements, you've just blown away the entire > > iterator for no good reason. > > If the slice is the right length, but the iterator doesn't next raise > > StopIteration, you've just thrown away one perfectly good value. Hope it > > wasn't something important. > > You have also over-written values that should be set back to what they > were, before the exception is raised, which is why I said the test needs > to be done with a temporary array. > Sometimes when exceptions happen, data is lost. You both make a big deal out of simultaneously (a) not placing burden on the normal case and (b) defining the normal case by way of what happens during an exception. Iterators are powerful and efficient, and ctypes are powerful and efficient, and the only reason you've managed to give why I shouldn't be able to fill a ctype array slice from an iterator is that, IF I SCREW UP and the iterator doesn't produce the right amount of data, I will have lost some data. Regards, Pat From nathan.alexander.rice at gmail.com Fri Oct 28 18:49:05 2011 From: nathan.alexander.rice at gmail.com (Nathan Rice) Date: Fri, 28 Oct 2011 18:49:05 -0400 Subject: Forking simplejson In-Reply-To: References: Message-ID: I've found that in a lot of cases getting a patch submitted is only half about good engineering. The other half is politics. I like one of those things, I don't like the other, and I don't want to take time out of my coding schedule to write something if in the end a reviewer shoots down my patch for contrived reasons. I don't know what the python committers are like but I guess you could say I'm once bitten twice shy. Nathan On Fri, Oct 28, 2011 at 4:52 PM, Terry Reedy wrote: > On 10/28/2011 1:20 PM, Nathan Rice wrote: >> >> Just a random note, I actually set about the task of re-implementing a >> json encoder which can be subclassed, is highly extensible, and uses >> (mostly) sane coding techniques (those of you who've looked at >> simplejson's code will know why this is a good thing). ?So far >> preliminary tests show the json only subclass of the main encoder >> basically tied in performance with the python implementation of >> simplejson. ?The C version of simplejson does turn in a performance >> about 12x faster, but that's apples to oranges. ?The design of the >> encoder would also make a XML serializer pretty straight forward to >> implement as well (not that I care about XML, *blech*). >> >> I'm torn between just moving on to some of my other coding tasks and >> putting some time into this to make it pass the simplejson/std lib >> json tests. ?I really do think the standard lib json encoder is bad > > Python is the result of people who thought *something* was 'bad' > >> and I would like to see an alternative in there > > and volunteered the effort to make something better. > >> but I'm hesitant to get involved. > > As someone who is involved and tries to encourage others, I am curious why. > > -- > Terry Jan Reedy > > -- > http://mail.python.org/mailman/listinfo/python-list > From roy at panix.com Fri Oct 28 19:08:42 2011 From: roy at panix.com (Roy Smith) Date: Fri, 28 Oct 2011 19:08:42 -0400 Subject: save tuple of simple data types to disk (low memory foot print) References: Message-ID: In article , Gelonida N wrote: > I would like to save many dicts with a fixed amount of keys > tuples to a file in a memory efficient manner (no random, but only > sequential access is required) There's two possible scenarios here. One, which you seem to be exploring, is to carefully study your data and figure out the best way to externalize it which reduces volume. The other is to just write it out in whatever form is most convenient (JSON is a reasonable thing to try first), and compress the output. Let the compression algorithms worry about extracting the entropy. You may be surprised at how well it works. It's also an easy experiment to try, so if it doesn't work well, at least it didn't cost you much to find out. From pmaupin at gmail.com Fri Oct 28 19:27:37 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 28 Oct 2011 16:27:37 -0700 (PDT) Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> <4eaa580a$0$29968$c3e8da3$5496439d@news.astraweb.com> <1e1764c6-d49d-468b-a0bd-cec3033acfee@t8g2000yql.googlegroups.com> Message-ID: <88b69248-5faf-473b-b12c-543973fbb8a0@f36g2000vbm.googlegroups.com> On Oct 28, 4:51?pm, Patrick Maupin wrote: > On Oct 28, 3:19?am, Terry Reedy wrote: > > > On 10/28/2011 3:21 AM, Steven D'Aprano wrote: > > > > If the slice has too few elements, you've just blown away the entire > > > iterator for no good reason. > > > If the slice is the right length, but the iterator doesn't next raise > > > StopIteration, you've just thrown away one perfectly good value. Hope it > > > wasn't something important. > > > You have also over-written values that should be set back to what they > > were, before the exception is raised, which is why I said the test needs > > to be done with a temporary array. > > Sometimes when exceptions happen, data is lost. You both make a big > deal out of simultaneously (a) not placing burden on the normal case > and (b) defining the normal case by way of what happens during an > exception. ?Iterators are powerful and efficient, and ctypes are > powerful and efficient, and the only reason you've managed to give why > I shouldn't be able to fill a ctype array slice from an iterator is > that, IF I SCREW UP and the iterator doesn't produce the right amount > of data, I will have lost some data. > > Regards, > Pat And, BTW, the example you give of, e.g. a,b,c = (some generator expression) ALREADY LOSES DATA if the iterator isn't the right size and it raises an exception. It doesn't overwrite a or b or c, but you're deluding yourself if you think that means it hasn't altered the system state. From michaelm at plumbersstock.com Fri Oct 28 20:49:15 2011 From: michaelm at plumbersstock.com (Michael McGlothlin) Date: Fri, 28 Oct 2011 18:49:15 -0600 Subject: Fast recursive generators? In-Reply-To: References: Message-ID: >> I'm trying to generate a list of values > > Better to think of a sequence of values, whether materialized as a 'list' or > not. The final value will actually be a string but it seems it is usually faster to join a list of strings than to concat them one by one. >> where each value is dependent >> on the previous value in the list and this bit of code needs to be >> repeatedly so I'd like it to be fast. It doesn't seem that >> comprehensions will work as each pass needs to take the result of the >> previous pass as it's argument. map() doesn't seem likely. filter() or > > Comprehensions combine map and filter, both of which conceptually work on > each item of a pre-existing list independently. (I am aware that the > function passed can stash away values to create dependence. The problem is I don't really have a pre-existing list. I just want a tight loop to generate the list from the initial value. Probably I could do something similar to my filter() method below but it seems really convoluted. I thought maybe there was a better way I just didn't know about. Python is full of neat tricks but it can be hard to remember them all. >> reduce() seem workable but not very clean. Is there a good way to do >> this? About the best I can get is this: >> >> l = [ func ( start ) ] >> f = lambda a: func ( l[-1] ) or a >> filter ( f, range ( big_number, -1, -1 ) ) >> >> >> I guess I'm looking for something more like: >> >> l = do ( lambda a: func ( a ), big_number, start ) > > Something like > > def do(func, N, value): > ? ?yield value > ? ?for i in range(1,N): > ? ? ? ?value = func(value) > ? ? ? ?yield value > > ? > For more generality, make func a function of both value and i. > If you need a list, "l = list(do(f,N,x))", but if you do not, you can do > "for item in do(f,N,x):" and skip making the list. Generators seem considerably slower than using comprehension or map/filter/reduce. I have tons of memory to work in (~100GB actual RAM) and the resulting data isn't that big so I'm more concerned about CPU. Thanks. From steve+comp.lang.python at pearwood.info Fri Oct 28 21:00:17 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 29 Oct 2011 01:00:17 GMT Subject: save tuple of simple data types to disk (low memory foot print) References: Message-ID: <4eab5021$0$29968$c3e8da3$5496439d@news.astraweb.com> On Fri, 28 Oct 2011 22:47:42 +0200, Gelonida N wrote: > Hi, > > I would like to save many dicts with a fixed amount of keys tuples to a > file in a memory efficient manner (no random, but only sequential > access is required) What do you call "many"? Fifty? A thousand? A thousand million? How many items in each dict? Ten? A million? What do you mean "keys tuples"? > As the keys are the same for each entry I considered converting them to > tuples. I don't even understand what that means. You're going to convert the keys to tuples? What will that accomplish? > The tuples contain only strings, ints (long ints) and floats (double) > and the data types for each position within the tuple are fixed. > > The fastest and simplest way is to pickle the data or to use json. Both > formats however are not that optimal. How big are your JSON files? 10KB? 10MB? 10GB? Have you tried using pickle's space-efficient binary format instead of text format? Try using protocol=2 when you call pickle.Pickler. Or have you considered simply compressing the files? > I could store ints and floats with pack. As strings have variable length > I'm not sure how to save them efficiently (except adding a length first > and then the string. This isn't 1980 and you're very unlikely to be using 720KB floppies. Premature optimization is the root of all evil. Keep in mind that when you save a file to disk, even if it contains only a single bit of data, the actual space used will be an entire block, which on modern hard drives is very likely to be 4KB. Trying to compress files smaller than a single block doesn't actually save you any space. > Is there already some 'standard' way or standard library to store such > data efficiently? Yes. Pickle and JSON plus zip or gzip. -- Steven From steve+comp.lang.python at pearwood.info Fri Oct 28 21:01:56 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 29 Oct 2011 01:01:56 GMT Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> <4eaa580a$0$29968$c3e8da3$5496439d@news.astraweb.com> <1e1764c6-d49d-468b-a0bd-cec3033acfee@t8g2000yql.googlegroups.com> <88b69248-5faf-473b-b12c-543973fbb8a0@f36g2000vbm.googlegroups.com> Message-ID: <4eab5084$0$29968$c3e8da3$5496439d@news.astraweb.com> On Fri, 28 Oct 2011 16:27:37 -0700, Patrick Maupin wrote: > And, BTW, the example you give of, e.g. > > a,b,c = (some generator expression) > > ALREADY LOSES DATA if the iterator isn't the right size and it raises an > exception. Yes. What's your point? This fact doesn't support your proposal in the slightest. You have argued against using a temporary array. I quote: "It is incredibly inefficient to have to create a temp array." [Aside: how do you know this is not just inefficient but *incredibly* so?] But that's exactly what happens in tuple unpacking: the generator on the right hand side is unpacked into a temporary tuple, and then assigned to the targets on the left hand side. If the number of elements on both sides aren't the same, the assignment fails. That is, tuple unpacking behaves like this pseudo-code: targets = left hand side values = tuple(right hand side) if len(targets) != len(values): fail otherwise: for each pair target, value: target = value This has the important property that the assignment is atomic: it either succeeds in full, or it doesn't occur. The only side-effect is to exhaust the generator, which is unavoidable given that generators don't have a length. Without temporary storage for the right hand side, you lose the property of atomicism. That would be unacceptable. In the case of the ctypes array, the array slice assignment is also treated as atomic: it either succeeds in full, or it fails in full. This is an important property. Unlike tuple unpacking, the array is even more conservative about what is on the right hand size: it doesn't accept iterators at all, only sequences. This is a sensible default, because it is *easy* to work around: if you want to unpack the iterator, just make a temporary list: array[:] = list(x+1 for x in range(32)) Assignment remains atomic, and the generator will be unpacked into a temporary list at full C speed. If you don't care about assignment being atomic -- and it's your right to weaken the array contract in your own code -- feel free to write your own helper function based on your earlier suggestion: "It merely needs to fill the slice and then ask for one more and check that StopIteration is raised." def array_assign(array, values): try: if len(values) == len(array): array[:] = values # runs at full C speed except TypeError: try: for i in xrange(len(array)): array[i] = next(values) # or values.next in Python 2.5 except StopIteration: raise TypeError('too few items') try: next(values) except StopIteration: pass else: raise TypeError('too many values') But this non-atomic behaviour would be entirely inappropriate as the default behaviour for a ctypes array. -- Steven From bahamutzero8825 at gmail.com Fri Oct 28 21:25:24 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Fri, 28 Oct 2011 20:25:24 -0500 Subject: Need Windows user / developer to help with Pynguin In-Reply-To: References: Message-ID: <4EAB5604.6000509@gmail.com> On 10/27/2011 5:36 PM, Lee Harr wrote: > What message do you get when trying to download? It said something like "You're trying to download from a forbidden country. That's all we know." Anyway, I was able to get the files. Once everything is set up, it seems to work. I haven't done any serious testing, but it opens and I can move the penguin and use the examples. BTW, you may want to look into py2exe or cx_Freeze to make Windows binaries. Also, the Python installer associates .py and .pyw files with python.exe and pythonw.exe respectively, so if you add the extension as Terry mentioned, it should work. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 From pmaupin at gmail.com Fri Oct 28 22:14:18 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Fri, 28 Oct 2011 19:14:18 -0700 (PDT) Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> <4eaa580a$0$29968$c3e8da3$5496439d@news.astraweb.com> <1e1764c6-d49d-468b-a0bd-cec3033acfee@t8g2000yql.googlegroups.com> <88b69248-5faf-473b-b12c-543973fbb8a0@f36g2000vbm.googlegroups.com> <4eab5084$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <6452ce55-bf89-4c30-87f2-bc651763667a@r2g2000vbj.googlegroups.com> On Oct 28, 8:01?pm, Steven D'Aprano > > ALREADY LOSES DATA if the iterator isn't the right size and it raises an > > exception. > > Yes. What's your point? This fact doesn't support your proposal in the > slightest. You earlier made the argument that "If the slice has too few elements, you've just blown away the entire iterator for no good reason. If the slice is the right length, but the iterator doesn't next raise StopIteration, you've just thrown away one perfectly good value. Hope it wasn't something important." In other words, you WERE arguing that it's very important not to lose information. Now that I show that information is ALREADY LOST in a similar scenario, you are arguing that's irrelevant. Whatever. > You have argued against using a temporary array. I quote: > > [Aside: how do you know this is not just inefficient but *incredibly* so?] By profiling my app, looking for places to save time without having to resort to C. > But that's exactly what happens in tuple unpacking: > the generator on the right hand side is unpacked into > a temporary tuple, and then assigned to the targets > on the left hand side. Agreed. But Terry was making the (correct) argument that people using ctypes are often looking for efficiency. > If the number of elements on both sides aren't the same, > the assignment fails. That is, tuple unpacking behaves > like (snip) Yes, and that loses information from the right hand side if it fails and the right hand side happens to be an iterator. For some reason you're OK with that in this case, but it was the worst thing in the world a few messages ago. > This has the important property that the > assignment is atomic: it either succeeds in full, > or it doesn't occur. Not right at all. >The only side-effect is to exhaust the generator, > which is unavoidable given that generators don't have a > length. Yes. But earlier you were acting like it would be problematic for me to lose information out of the generator if there were a failure, and now the sanctity of the information on the LHS is so much more than on the RHS. Frankly, that's all a crock. In your earlier email, you argued that my proposal loses information, when in fact, in some cases it PRESERVES information (the very information you are trying to transfer) that ISN'T preserved when this temp array is tossed, and the only information it LOSES is information the programmer declared his clear intent to kill. But that's an edge case anyway. > Without temporary storage for the right hand side, > you lose the property of atomicism. That would be > unacceptable. As if the temporary storage workaround exhibited the "necessary" atomicity, or as if you have even showed a valid argument why the atomicity is important for this case. > In the case of the ctypes array, the array slice assignment is also > treated as atomic: it either succeeds in full, or it fails in full. > This is an important property. Unlike tuple unpacking, the array is even more > conservative about what is on the right hand size: it doesn't accept > iterators at all, only sequences. This is a sensible default, How it works is not a bad start, but it's arguably unfinished. > because it is *easy* to work around: if you want to unpack the iterator, just make a temporary list: (snip) I already said I know the workaround. I don't know why you can't believe that. But one of the purposes of the iterator protocol is to reduce the number of cases where you have to create huge lists. > Assignment remains atomic, and the generator will be unpacked into a > temporary list at full C speed. Which can be very slow if your list has several million items in it. > If you don't care about assignment being atomic -- and it's your right to > weaken the array contract in your own code Currently, there IS no contract between ctype arrays and generators. I'm suggesting that it would be useful to create one, and further suggesting that if a programmer attempts to load a ctypes array from a generator of the wrong size, it is certainly important to let the programmer know he screwed up, but it is not at all important that some elements of the ctypes array, that the programmer was in fact trying to replace, were in fact correctly replaced before the size error was noticed. > -- feel free to write your own > helper function based on your earlier suggestion: (snip) Doing this in Python is also slow and painful, and the tradeoff of this vs the temp list depends on the system, the caching, the amount of memory available, and the size of the data to be transferred. I could do it in C, but that defeats my whole purpose of using ctypes to avoid having to ship C code to customers. > But this non-atomic behaviour would be entirely inappropriate as the > default behaviour for a ctypes array. That's obviously your opinion, but your supporting arguments are quite weak. Regards, Pat From lie.1296 at gmail.com Fri Oct 28 22:26:31 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Sat, 29 Oct 2011 13:26:31 +1100 Subject: How to mix-in __getattr__ after the fact? In-Reply-To: <4EAAF264.1050307@stoneleaf.us> References: <4630c4d0-86bc-4295-8bbb-6f58415191c8@v15g2000vbm.googlegroups.com> <4EAAF264.1050307@stoneleaf.us> Message-ID: On 10/29/2011 05:20 AM, Ethan Furman wrote: > > Python only looks up __xxx__ methods in new-style classes on the class > itself, not on the instances. > > So this works: > > 8<---------------------------------------------------------------- > class Cow(object): > pass > > def attrgetter(self, a): > print "CAUGHT: Attempting to get attribute", a > > bessie = Cow() > > Cow.__getattr__ = attrgetter > > print bessie.milk > 8<---------------------------------------------------------------- a minor modification might be useful: bessie = Cow() bessie.__class__.__getattr__ = attrgetter From tjreedy at udel.edu Fri Oct 28 22:27:40 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Oct 2011 22:27:40 -0400 Subject: Fast recursive generators? In-Reply-To: References: Message-ID: On 10/28/2011 8:49 PM, Michael McGlothlin wrote: >> Better to think of a sequence of values, whether materialized as a 'list' or >> not. > > The final value will actually be a string but it seems it is usually > faster to join a list of strings than to concat them one by one. .join() takes an iterable of strings as its argument >> Comprehensions combine map and filter, both of which conceptually work on >> each item of a pre-existing list independently. (I am aware that the >> function passed can stash away values to create dependence. > > The problem is I don't really have a pre-existing list. So, as I said, map, filter, and comprehensions are not applicable to your problem. >> def do(func, N, value): >> yield value >> for i in range(1,N): >> value = func(value) >> yield value >> >> For more generality, make func a function of both value and i. >> If you need a list, "l = list(do(f,N,x))", but if you do not, you can do >> "for item in do(f,N,x):" and skip making the list. > > Generators seem considerably slower than using comprehension or > map/filter So what? A saw may cut faster than a hammer builds, but I hope you don't grab a saw when you need a hammer. > /reduce. Do you actually have an example where ''.join(reduce(update, N, start)) is faster than ''.join(update_gen(N, start))? Resuming a generator n times should be *faster* than n calls to the update function of reduce (which will actually have to build a list). --- Terry Jan Reedy From gagsl-py2 at yahoo.com.ar Fri Oct 28 23:18:04 2011 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Oct 2011 00:18:04 -0300 Subject: Fast recursive generators? References: Message-ID: En Fri, 28 Oct 2011 15:10:14 -0300, Michael McGlothlin escribi?: > I'm trying to generate a list of values where each value is dependent > on the previous value in the list and this bit of code needs to be > repeatedly so I'd like it to be fast. It doesn't seem that > comprehensions will work as each pass needs to take the result of the > previous pass as it's argument. map() doesn't seem likely. filter() or > reduce() seem workable but not very clean. Is there a good way to do > this? About the best I can get is this: > > l = [ func ( start ) ] > f = lambda a: func ( l[-1] ) or a > filter ( f, range ( big_number, -1, -1 ) ) > > > I guess I'm looking for something more like: > > l = do ( lambda a: func ( a ), big_number, start ) What about a generator function? def my_generator(): prev = 1 yield prev while True: this = 2*prev yield this prev = this print list(itertools.islice(my_generator(), 10)) -- Gabriel Genellina From patx44 at gmail.com Sat Oct 29 01:54:52 2011 From: patx44 at gmail.com (patx) Date: Sat, 29 Oct 2011 01:54:52 -0400 Subject: Introducing pickleDB; a simple, lightweight, and fast key-value database. Message-ID: Hello I have recently started work on a new project called pickleDB. It is a lightweight key-value database engine (inspired by redis). Check it out at http://packages.python.org/pickleDB -- Harrison Erd -------------- next part -------------- An HTML attachment was scrubbed... URL: From dihedral88888 at googlemail.com Sat Oct 29 05:10:27 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Sat, 29 Oct 2011 02:10:27 -0700 (PDT) Subject: Fast recursive generators? In-Reply-To: References: Message-ID: <31591999.1755.1319879427800.JavaMail.geo-discussion-forums@prlk36> I am thinking the bye code compiler in python can be faster if all known immutable instances up to the execution are compiled immutable objects to be assigned. From dihedral88888 at googlemail.com Sat Oct 29 05:10:27 2011 From: dihedral88888 at googlemail.com (88888 Dihedral) Date: Sat, 29 Oct 2011 02:10:27 -0700 (PDT) Subject: Fast recursive generators? In-Reply-To: References: Message-ID: <31591999.1755.1319879427800.JavaMail.geo-discussion-forums@prlk36> I am thinking the bye code compiler in python can be faster if all known immutable instances up to the execution are compiled immutable objects to be assigned. From ramapraba2653 at gmail.com Sat Oct 29 05:19:35 2011 From: ramapraba2653 at gmail.com (SUPREME) Date: Sat, 29 Oct 2011 02:19:35 -0700 (PDT) Subject: `********AMAZING HOT PHOTOS & VIDEOS ******** Message-ID: <125f9a4d-4a56-47e2-a941-2b35fa27b388@x16g2000prd.googlegroups.com> FOR GOOD JOBS SITES TO YOU http://goodjobssites.blogspot.com/ HOT KATRINA KAIF PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/katrina-kaif.html AISHWARYA RAI HOT HQ PHOTO STILLS http://actressgallery-kalyani.blogspot.com/2011/09/aishwarya-rai.html ASIN HOT PHOTO GALLERY http://actressgallery-kalyani.blogspot.com/2011/09/asin.html SAKUNI MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/sakuni-movie-stills.html 7TH SENSE MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/10/7th-sense-movie-stills.html MOGUDU MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/mogudu-movie-stills.html HANSIKA MATOWNI LATEST HOT STILLS http://actressgallery-kalyani.blogspot.com/2011/09/hansika-motwani.html KAJAL AGARWAL HOT PHOTOS http://actressgallery-kalyani.blogspot.com/2011/09/kajal-agarwal.html TAMANNA SIRUTHAI HOT MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/siruthai-movie-stills.html SNEHA HOT GOA MOVIE STILLS http://actressgallery-kalyani.blogspot.com/2011/09/goa-movie-stills.html FOR ONLY HOT GUYS SEE THIS TRISHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/trisha-hot.html TAMANNA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/tamanna-hot.html PRIYAMANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/priyamani-hot.html KAJAL AGARWAL LATEST HOT WITHOUT TOP http://hotactress-kalyani.blogspot.com/2011/08/kajal-agarwal-hot-photos.html SAMANTHA LATEST HOT STILLS http://hotactress-kalyani.blogspot.com/2011/09/samantha-hot.html SNEHA ULLAL HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/sneha-ullal-hot.html ANJALI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/anjali-hot.html HANSIKA MOTWANI HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/10/hansika-motwani-hot.html PRANITHA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/pranitha-hot.html HOT KATRINAKAIF WALLPAPERS http://hotactress-kalyani.blogspot.com/2011/08/katrina-kaif-hot.html HOT MALLU ACTRESS BHAMA http://hotactress-kalyani.blogspot.com/2011/09/bhama-hot.html TOLLYWOOD HOT ACTRESSES http://hotactress-kalyani.blogspot.com/2011/08/hot-actrsess.html SONAKSHI SINHA HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/09/sonakshi-sinha-hot.html PRIYANKA CHOPRA LATEST HOT PHOTOS http://hotactress-kalyani.blogspot.com/2011/08/priyanka-chopra-hot.html LATEST AMISHA PATEL HOT PICS http://hotactress-kalyani.blogspot.com/2011/08/amisha-patel-hot.html TAPSEE DIFFERENT STILLS http://hotactress-kalyani.blogspot.com/2011/08/tapsee-hot.html From g.rodola at gmail.com Sat Oct 29 06:15:18 2011 From: g.rodola at gmail.com (=?ISO-8859-1?Q?Giampaolo_Rodol=E0?=) Date: Sat, 29 Oct 2011 12:15:18 +0200 Subject: ANN: psutil 0.4.0 released Message-ID: Hi folks, I'm pleased to announce the 0.4.0 release of psutil: http://code.google.com/p/psutil === About === psutil is a module providing an interface for retrieving information on all running processes and system utilization (CPU, disk, memory, network) in a portable way by using Python, implementing many functionalities offered by command line tools such as ps, top, free, lsof and others. It works on Linux, Windows, OSX and FreeBSD, both 32-bit and 64-bit, with Python versions from 2.4 to 3.3 by using a single code base. === Major enhancements === Aside from fixing different high priority bugs this release introduces two new important features: disks and network IO counters. With these, you can monitor disks usage and network traffic. 2 scripts were added to provide an example of what kind of applications can be written with these two hooks: http://code.google.com/p/psutil/source/browse/trunk/examples/iotop.py http://code.google.com/p/psutil/source/browse/trunk/examples/nettop.py ...and here you can see some screenshots: http://code.google.com/p/psutil/#Example_applications === Other enhancements == - Process.get_connections() has a new 'kind' parameter to filters for connections by using different criteria. - timeout=0 parameter can now be passed to Process.wait() to make it return immediately (non blocking). - Python 3.2 installer for Windows 64 bit is now provided in downloads section. - (FreeBSD) addeed support for Process.getcwd() - (FreeBSD) Process.get_open_files() has been rewritten in C and no longer relies on lsof. - various crashes on module import across differnt platforms were fixed. For a complete list of features and bug fixes see: http://psutil.googlecode.com/svn/trunk/HISTORY === New features by example === >>> import psutil >>> >>> psutil.disk_io_counters() iostat(read_count=8141, write_count=2431, read_bytes=290203, write_bytes=537676, read_time=5868, write_time=94922) >>> >>> psutil.disk_io_counters(perdisk=True) {'sda1' :iostat(read_count=8141, write_count=2431, read_bytes=290203, write_bytes=537676, read_time=5868, write_time=94922), 'sda2' :iostat(read_count=811241, write_count=31, read_bytes=1245, write_bytes=11246, read_time=768008, write_time=922)} >>> >>> >>> psutil.network_io_counters() iostat(bytes_sent=1270374, bytes_recv=7828365, packets_sent=9810, packets_recv=11794) >>> >>> psutil.network_io_counters(pernic=True) {'lo': iostat(bytes_sent=800251705, bytes_recv=800251705, packets_sent=455778, packets_recv=455778), 'eth0': iostat(bytes_sent=813731756, bytes_recv=4183672213, packets_sent=3771021, packets_recv=4199213)} >>> >>> >>> import os >>> p = psutil.Process(os.getpid()) >>> p.get_connections(kind='tcp') [connection(fd=115, family=2, type=1, local_address=('10.0.0.1', 48776), remote_address=('93.186.135.91', 80), status='ESTABLISHED')] >>> p.get_connections(kind='udp6') [] >>> p.get_connections(kind='inet6') [] >>> === Links === * Home page: http://code.google.com/p/psutil * Source tarball: http://psutil.googlecode.com/files/psutil-0.4.0.tar.gz * Api Reference: http://code.google.com/p/psutil/wiki/Documentation As a final note I'd like to thank Jeremy Whitlock, who kindly contributed disk/network io counters code for OSX and Windows. Please try out this new release and let me know if you experience any problem by filing issues on the bug tracker. Thanks in advance. --- Giampaolo Rodola' http://code.google.com/p/pyftpdlib/ http://code.google.com/p/psutil/ From missive at hotmail.com Sat Oct 29 10:43:13 2011 From: missive at hotmail.com (Lee Harr) Date: Sat, 29 Oct 2011 19:13:13 +0430 Subject: Need Windows user / developer to help with Pynguin Message-ID: Thanks to all those who tested and replied! > For Windows users who want to just run Pyguin (not modify or tinker > with the source code), it would be best to bundle Pynguin up with > Py2exe I considered that, but I agree that licensing issues would make it problematic. > the Python installer associates .py and .pyw files with > python.exe and pythonw.exe respectively, so if you add the extension as > Terry mentioned, it should work. I think this is the best way to go. > pynguin => pynguin.py Would it be better to go with pynguin.pyw ? Actually, I was thinking of just copying that script to something like run_pynguin.pyw Anyone able to test if just making that single change makes it so that a user can just unpack the .zip file and double click on run_pynguin.pyw to run the app? > Win7, with zip built in, just > treats x.zip as a directory in Explorer So, is that going to be a problem? The user just sees it as a folder, goes in and double-clicks on run_pynguin.pyw and once python is running what does it see? Are the contents of the virtually "unpacked" folder going to be available to the script? > You pynguin.zip contains one top level file -- a directory called > pynguin that contains multiple files I feel that this is the correct way to create a .zip file. I have run in to so many poorly formed .zip files (ones that extract all of their files to the current directory) that when extracting any .zip I always create a dummy folder and put the .zip in there before extracting. Mine is actually called pynguin-0.12.zip and extracts to a folder called pynguin-0.12 > Extracting pynguin.zip to a > pynguin directory in the same directory as pynguin.zip, the default > behavior with Win7 at least, creates a new pynguin directory that > contains the extracted pynguin directory. So, windows now creates the dummy folder automatically? Is the problem that the .zip has the same name (minus the extension)? Would it solve the problem to just change the name of the archive to something like pynguin012.zip ? > README => README.txt Just out of curiosity, what happens if you double-click the README sans .txt? Does it make you choose which app to open with? From pmaupin at gmail.com Sat Oct 29 10:43:34 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Sat, 29 Oct 2011 07:43:34 -0700 (PDT) Subject: Assigning generator expressions to ctype arrays References: <32ee8e3e-4d42-4d2e-bdc7-087970c2736e@hv4g2000vbb.googlegroups.com> <4ea9dbd0$0$29968$c3e8da3$5496439d@news.astraweb.com> <43aea5ad-bc9f-4e82-a9d5-74a06553a2ad@q16g2000yqn.googlegroups.com> <20aeed48-8d77-445a-a4b6-85f0309e714f@f36g2000vbm.googlegroups.com> Message-ID: <4eaa454d-d1cd-4518-8476-96e06580ebfa@hj4g2000vbb.googlegroups.com> On Oct 28, 3:24?pm, Terry Reedy wrote: > On 10/28/2011 2:05 PM, Patrick Maupin wrote: > > > On Oct 27, 10:23 pm, Terry Reedy ?wrote: > >> I do not think everyone else should suffer substantial increase in space > >> and run time to avoid surprising you. > > > What substantial increase? > > of time and space, as I said, for the temporary array that I think would > be needed and which I also described in the previous paragraph that you > clipped That's because I don't think it needs a temporary array. A temporary array would provide some invariant guarantees that are nice but not necessary in a lot of real-world cases. > > > ?There's already a check that winds up > > raising an exception. ?Just make it empty an iterator instead. > > It? I have no idea what you intend that to refer to. Sorry, code path. There is already a "code path" that says "hey I can't handle this." To modify this code path to handle the case of a generic iterable would add a tiny bit of code, but would not add any appreciable space (no temp array needed for my proposal) and would not add any runtime to people who are not passing in iterables or doing other things that currently raise exceptions. > I doubt it would be very many because it is *impossible* to make it work > in the way that I think people would want it to. How do you know? I have a use case that I really don't think is all that rare. I know exactly how much data I am generating, but I am generating it piecemeal using iterators. > >> It could, but at some cost. Remember, people use ctypes for efficiency, > > yes, you just made my argument for me. ?Thank you. ?It is incredibly > > inefficient to have to create a temp array. No, I don't think I did "make your argument for you." I am currently making a temp list because I have to, and am proposing that with a small change to the ctypes library, that wouldn't always need to be done. > But necessary to work with blank box iterators. With your own preconceived set of assumptions. (Which I will admit, you have given quite a bit of thought to, which I appreciate.) > Now you are agreeing with my argument. Nope, still not doing that. > If ctype_array slice assignment were to be augmented to work with > iterators, that would, in my opinion (and see below), That's better for not being absolute. Thank you for admitting other possibilities. > require use of > temporary arrays. Since slice assignment does not use temporary arrays > now (see below), that augmentation should be conditional on the source > type being a non-sequence iterator. I don't think any temporary array is required, but in any case, yes the code path through the ctypes array library __setslice__ would have to be modified where it gives up now, in order to decide to do something different if it is passed an iterable. > CPython comes with immutable fixed-length arrays (tuples) that do not > allow slice assignment and mutable variable-length arrays (lists) that > do. The definition is 'replace the indicated slice with a new slice > built from all values from an iterable'. Point 1: This works for any > properly functioning iterable that produces any finite number of items. Agreed. > Iterators are always exhausted. And my proposal would continue to exhaust iterators, or would raise an exception if the iterator wasn't exhausted. > Replace can be thought of as delete follewed by add, but the > implementation is not that naive. Sure, on a mutable length item. > Point 2: If anything goes wrong and an > exception is raised, the list is unchanged. This may be true on lists, and is quite often true (and is nice when it happens), but it isn't always true in general. For example, with the current tuple packing/unpacking protocol across an assignment, the only real guarantee is that everything is gathered up into a single object before the assignment is done. It is not the case that nothing will be unpacked unless everything can be unpacked. For example: >>> >>> a,b,c,d,e,f,g,h,i = range(100,109) >>> (a,b,c,d), (e,f), (g,h,i) = (1,2,3,4), (5,6,7), (8,9) Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack >>> a,b,c,d,e,f,g,h,i (1, 2, 3, 4, 104, 105, 106, 107, 108) >>> > This means that there must > be temporary internal storage of either old or new references. As I show with the tuple unpacking example, it is not an inviolate law that Python won't unpack a little unless it can unpack everything. > An > example that uses an improperly functioning generator. (snip) Yes, I agree that lists are wondrously robust. But one of the reasons for this is the "flexible" interpretation of slice start and end points, that can be as surprising to a beginner as anything I'm proposing. > A c_uint array is a new kind of beast: a fixed-length mutable > array. So it has to have a different definition of slice > assignment than lists. Thomas Heller, the ctypes author, > apparently chose 'replacement by a sequence with exactly > the same number of items, else raise an exception'. though > I do not know what the doc actually says. Yes, but ctypes was designed and developed before generator expressions were available, and before or contemporaneously with the first cut of itertools. We arguably use Python differently than we did in those days. > An alternative definition would have been to replace as much of the > slice as possible, from the beginning, while ignoring any items in > excess of the slice length. This would work with any iterable. I think that an iterable that doesn't match the slice length should be an error condition and raise an exception. Both for too much data and too little data. > However, partial replacement of a slice would be a surprising innovation to most. Yes, but when an exception is raised it doesn't always mean that nothing got replaced. See my tuple unpacking example earlier. > The current implementation assumes that the reported length of a > sequence matches the valid indexes and dispenses with temporary storage. This is shown by the following: (snip) > I consider such unintended partial replacement to be a glitch. Now that's actually interesting. I agree with you that it's not desired behavior to not raise an exception. OTOH, exploiting this misfeature might actually increase performance for my specific case. > An > exception could be raised, but without adding temp storage, the array > could not be restored. And making a change *and* raising an exception > would be a different sort of glitch. (One possible with augmented > assignment involving a mutable member of a tuple.) It's also possible with non-augmented assignments with immutable tuples, as I showed above. > So I would leave this as undefined behavior for an input > outside the proper domain of the function. Not sure what you mean by "this." I don't think that the interpreter should always paternalistically say "no, you can't assign an item that doesn't have a __len__ attribute because you obviously don't know what you're doing if you're trying to do that." I think the interpreter should do the same as it does on my tuple unpacking example -- try to do the right thing, and raise an exception if it fails during the process. > Anyway, as I said before, you are free to propose a specific change > ('work with iterators' is too vague) and provide a corresponding patch. I will try to see if I can do that some time in the next few months, if I ever get out of crunch mode. Thanks, Pat From bahamutzero8825 at gmail.com Sat Oct 29 11:01:42 2011 From: bahamutzero8825 at gmail.com (Andrew Berg) Date: Sat, 29 Oct 2011 10:01:42 -0500 Subject: Need Windows user / developer to help with Pynguin In-Reply-To: References: Message-ID: <4EAC1556.8060307@gmail.com> On 10/29/2011 9:43 AM, Lee Harr wrote: > So, windows now creates the dummy folder automatically? That is the default choice, but users are given a prompt to choose an arbitrary directory. Note that this only applies to the ZIP extractor in Explorer; other archive programs have their own behavior. I agree with you on having a top-level directory in an archive, but MS figures users are more likely to be annoyed with files scattered around the current directory than a nested directory. Unfortunately, many archives out in the wild have a top-level directory while many others don't, so one can rarely ever be certain how a given archive is organized without opening it. > Is the problem that the .zip has the same name (minus the extension)? Not at all. > Just out of curiosity, what happens if you double-click the > README sans .txt? Does it make you choose which app to open with? Typically, that is the case because files without extensions are not registered by default. -- CPython 3.2.2 | Windows NT 6.1.7601.17640 | Thunderbird 7.0 From gelonida at gmail.com Sat Oct 29 12:44:14 2011 From: gelonida at gmail.com (Gelonida N) Date: Sat, 29 Oct 2011 18:44:14 +0200 Subject: save tuple of simple data types to disk (low memory foot print) In-Reply-To: <4eab5021$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <4eab5021$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/29/2011 03:00 AM, Steven D'Aprano wrote: > On Fri, 28 Oct 2011 22:47:42 +0200, Gelonida N wrote: > >> Hi, >> >> I would like to save many dicts with a fixed amount of keys tuples to a >> file in a memory efficient manner (no random, but only sequential >> access is required) > > What do you mean "keys tuples"? Corrected phrase: I would like to save many dicts with a fixed (and known) amount of keys in a memory efficient manner (no random, but only sequential access is required) to a file (which can later be sent over a slow expensive network to other machines) Example: Every dict will have the keys 'timestamp', 'floatvalue', 'intvalue', 'message1', 'message2' 'timestamp' is an integer 'floatvalue' is a float 'intvalue' an int 'message1' is a string with a length of max 2000 characters, but can often be very short 'message2' the same as message1 so a typical dict will look like { 'timetamp' : 12, 'floatvalue': 3.14159, 'intvalue': 42, 'message1' : '', 'message2' : '=' * 1999 } > > What do you call "many"? Fifty? A thousand? A thousand million? How many > items in each dict? Ten? A million? File size can be between 100kb and over 100Mb per file. Files will be accumulated over months. I just want to use the smallest possible space, as the data is collected over a certain time (days / months) and will be transferred via UMTS / EDGE / GSM network, where the transfer takes already for quite small data sets several minutes. I want to reduce the transfer time, when requesting files on demand (and the amount of data in order to not exceed the monthly quota) >> As the keys are the same for each entry I considered converting them to >> tuples. > > I don't even understand what that means. You're going to convert the keys > to tuples? What will that accomplish? >> As the keys are the same for each entry I considered converting them (the before mentioned dicts) to tuples. so the dict { 'timetamp' : 12, 'floatvalue': 3.14159, 'intvalue': 42, 'message1' : '', 'message2' : '=' * 1999 } would become [ 12, 3.14159, 42, '', ''=' * 1999 ] > > >> The tuples contain only strings, ints (long ints) and floats (double) >> and the data types for each position within the tuple are fixed. >> >> The fastest and simplest way is to pickle the data or to use json. Both >> formats however are not that optimal. > > How big are your JSON files? 10KB? 10MB? 10GB? > > Have you tried using pickle's space-efficient binary format instead of > text format? Try using protocol=2 when you call pickle.Pickler. No. This is probably already a big step forward. As I know the data types if each element in the tuple I would however prefer a representation, which is not storing the data types for each typle over and over again (as they are the same for each dict / tuple) > > Or have you considered simply compressing the files? Compression makes sense but the inital file format should be already rather 'compact' > >> I could store ints and floats with pack. As strings have variable length >> I'm not sure how to save them efficiently (except adding a length first >> and then the string. > > This isn't 1980 and you're very unlikely to be using 720KB floppies. > Premature optimization is the root of all evil. Keep in mind that when > you save a file to disk, even if it contains only a single bit of data, > the actual space used will be an entire block, which on modern hard > drives is very likely to be 4KB. Trying to compress files smaller than a > single block doesn't actually save you any space. > > >> Is there already some 'standard' way or standard library to store such >> data efficiently? > > Yes. Pickle and JSON plus zip or gzip. > pickle protocol-2 + gzip of the tuple derived from the dict, might be good enough for the start. I have to create a little more typical data in order to see how many percent of my payload would consist of repeating the data types for each tuple. From gelonida at gmail.com Sat Oct 29 12:47:57 2011 From: gelonida at gmail.com (Gelonida N) Date: Sat, 29 Oct 2011 18:47:57 +0200 Subject: save tuple of simple data types to disk (low memory foot print) In-Reply-To: References: Message-ID: On 10/29/2011 01:08 AM, Roy Smith wrote: > In article , > Gelonida N wrote: > >> I would like to save many dicts with a fixed amount of keys >> tuples to a file in a memory efficient manner (no random, but only >> sequential access is required) > > There's two possible scenarios here. One, which you seem to be > exploring, is to carefully study your data and figure out the best way > to externalize it which reduces volume. > > The other is to just write it out in whatever form is most convenient > (JSON is a reasonable thing to try first), and compress the output. Let > the compression algorithms worry about extracting the entropy. You may > be surprised at how well it works. It's also an easy experiment to try, > so if it doesn't work well, at least it didn't cost you much to find out. Yes I have to make some more tests to see the defference between just compressing aplain format (JSON / pickle) and compressing the 'optimized' representation. From python.list at tim.thechases.com Sat Oct 29 13:47:42 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 29 Oct 2011 12:47:42 -0500 Subject: save tuple of simple data types to disk (low memory foot print) In-Reply-To: References: <4eab5021$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4EAC3C3E.3030309@tim.thechases.com> On 10/29/11 11:44, Gelonida N wrote: > I would like to save many dicts with a fixed (and known) amount of keys > in a memory efficient manner (no random, but only sequential access is > required) to a file (which can later be sent over a slow expensive > network to other machines) > > Example: > Every dict will have the keys 'timestamp', 'floatvalue', 'intvalue', > 'message1', 'message2' > 'timestamp' is an integer > 'floatvalue' is a float > 'intvalue' an int > 'message1' is a string with a length of max 2000 characters, but can > often be very short > 'message2' the same as message1 > > so a typical dict will look like > { 'timetamp' : 12, 'floatvalue': 3.14159, 'intvalue': 42, > 'message1' : '', 'message2' : '=' * 1999 } > > >> >> What do you call "many"? Fifty? A thousand? A thousand million? How many >> items in each dict? Ten? A million? > > File size can be between 100kb and over 100Mb per file. Files will be > accumulated over months. If Steven's pickle-protocol2 solution doesn't quite do what you need, you can do something like the code below. Gzip is pretty good at addressing... >> Or have you considered simply compressing the files? > Compression makes sense but the inital file format should be > already rather 'compact' ...by compressing out a lot of the duplicate aspects. Which also mitigates some of the verbosity of CSV. It serializes the data to a gzipped CSV file then unserializes it. Just point it at the appropriate data-source, adjust the column-names and data-types -tkc from gzip import GzipFile from csv import writer, reader data = [ # use your real data here { 'timestamp': 12, 'floatvalue': 3.14159, 'intvalue': 42, 'message1': 'hello world', 'message2': '=' * 1999, }, ] * 10000 f = GzipFile('data.gz', 'wb') try: w = writer(f) for row in data: w.writerow([ row[name] for name in ( # use your real col-names here 'timestamp', 'floatvalue', 'intvalue', 'message1', 'message2', )]) finally: f.close() output = [] for row in reader(GzipFile('data.gz')): d = dict(( (name, f(row[i])) for i, (f,name) in enumerate(( # adjust for your column-names/data-types (int, 'timestamp'), (float, 'floatvalue'), (int, 'intvalue'), (str, 'message1'), (str, 'message2'), )))) output.append(d) # or output = [ dict(( (name, f(row[i])) for i, (f,name) in enumerate(( # adjust for your column-names/data-types (int, 'timestamp'), (float, 'floatvalue'), (int, 'intvalue'), (str, 'message1'), (str, 'message2'), )))) for row in reader(GzipFile('data.gz')) ] From geoff.bache at gmail.com Sat Oct 29 17:06:12 2011 From: geoff.bache at gmail.com (Geoff Bache) Date: Sat, 29 Oct 2011 14:06:12 -0700 (PDT) Subject: Customizing class attribute access in classic classes Message-ID: Hi, I'm wondering if there is any way to customize class attribute access on classic classes? So this works: class Meta(type): def __getattr__(cls, name): return "Customized " + name class A: __metaclass__ = Meta print A.blah but it turns A into a new-style class. If "Meta" does not inherit from type, the customization works but A ends up not being a class at all, severely restricting its usefulness. I then hoped I could get "Meta" to inherit from types.ClassType but that wasn't allowed either. Is there any way to do this or is it just a limitation of classic classes? Regards, Geoff Bache From jason at powerpull.net Sat Oct 29 17:15:52 2011 From: jason at powerpull.net (Jason Friedman) Date: Sat, 29 Oct 2011 21:15:52 +0000 Subject: Review Python site with useful code snippets In-Reply-To: <98598900-8b72-4bb2-b21e-13666c9f823b@p16g2000yqd.googlegroups.com> References: <98598900-8b72-4bb2-b21e-13666c9f823b@p16g2000yqd.googlegroups.com> Message-ID: On Wed, Oct 26, 2011 at 3:51 PM, Chris Hall wrote: > I am looking to get reviews, comments, code snippet suggestions, and > feature requests for my site. > I intend to grow out this site with all kinds of real world code > examples to learn from and use in everyday coding. > The site is: > > http://www.pythonsnippet.com > > If you have anything to contribute or comment, please post it on the > site or email me directly. Great sentiment, but there is already http://code.activestate.com/, http://code.google.com/p/python-code-snippets/ and http://stackoverflow.com/questions/2032462/python-code-snippets. Pretty site you put up, though. From ben+python at benfinney.id.au Sat Oct 29 22:16:24 2011 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 30 Oct 2011 13:16:24 +1100 Subject: Customizing class attribute access in classic classes References: Message-ID: <87wrbnmdfr.fsf@benfinney.id.au> Geoff Bache writes: > I'm wondering if there is any way to customize class attribute access > on classic classes? Why do that? What is it you're hoping to achieve, and why limit it to classic classes only? > So this works: > > class Meta(type): > def __getattr__(cls, name): > return "Customized " + name > > class A: > __metaclass__ = Meta > > print A.blah > > but it turns A into a new-style class. Yes, A is a new-style class *because* it inherits from ?type? . Why does that not meet your needs? -- \ Contentsofsignaturemaysettleduringshipping. | `\ | _o__) | Ben Finney From lie.1296 at gmail.com Sun Oct 30 01:15:07 2011 From: lie.1296 at gmail.com (Lie Ryan) Date: Sun, 30 Oct 2011 16:15:07 +1100 Subject: Convert DDL to ORM In-Reply-To: References: Message-ID: On 10/25/2011 03:30 AM, Alec Taylor wrote: > Good morning, > > I'm often generating DDLs from EER->Logical diagrams using tools such > as PowerDesigner and Oracle Data Modeller. > > I've recently come across an ORM library (SQLalchemy), and it seems > like a quite useful abstraction. > > Is there a way to convert my DDL to ORM code? It's called reverse engineering. Some ORMs, e.g. Django's ORM can reverse engineer the database into Django Models by using `./manage.py inspectdb`. I believe the equivalent in SQLalchemy would be SQL Autocode, see http://turbogears.org/2.1/docs/main/Utilities/sqlautocode.html and http://code.google.com/p/sqlautocode/ From geoff.bache at gmail.com Sun Oct 30 05:05:09 2011 From: geoff.bache at gmail.com (Geoff Bache) Date: Sun, 30 Oct 2011 02:05:09 -0700 (PDT) Subject: Customizing class attribute access in classic classes References: <87wrbnmdfr.fsf@benfinney.id.au> Message-ID: <0128c52e-1e20-453a-881c-0abe3f7a09a0@y36g2000yqm.googlegroups.com> On Oct 30, 4:16?am, Ben Finney wrote: > Geoff Bache writes: > > I'm wondering if there is any way to customize class attribute access > > on classic classes? > > Why do that? What is it you're hoping to achieve, and why limit it to > classic classes only? > I'm building a mocking tool, CaptureMock, which works by intercepting and capturing particular calls, recording and replaying them. A user can just say "intercept httplib for me" and it will record all the interactions with httplib and allow a test that can be run without doing anything via http or writing any handcrafted "mock-code". So I need to be able to intercept also static attribute access, say httplib.HTTPConnection.request. httplib.HTTPConnection is a classic class. I can make my intercepting version of it into a new-style class but the risk is that that will change its behaviour in subtle ways, negating the point of the tool. As for limiting it to classic classes only, I obviously need to do it on new-style classes also. But I know how to do that... Regards, Geoff Bache From steve+comp.lang.python at pearwood.info Sun Oct 30 05:23:26 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 30 Oct 2011 09:23:26 GMT Subject: Customizing class attribute access in classic classes References: Message-ID: <4ead178e$0$29968$c3e8da3$5496439d@news.astraweb.com> On Sat, 29 Oct 2011 14:06:12 -0700, Geoff Bache wrote: > Hi, > > I'm wondering if there is any way to customize class attribute access on > classic classes? > > So this works: > > class Meta(type): > def __getattr__(cls, name): > return "Customized " + name > > class A: > __metaclass__ = Meta > > print A.blah > > but it turns A into a new-style class. And why is this a problem? In any case, metaclasses work for classic classes. Metaclasses go back to pre-Python 1.5, long before new-style classes and type unification. http://www.python.org/doc/essays/metaclasses/ You just have to do a lot more work: class Meta: def __init__(self, name, bases, namespace): self.__name__ = name self.__bases__ = bases self.__dict__ = namespace def __str__(self): return "" __repr__ = __str__ def __getattr__(self, name): return "Customized " + name def __call__(self): return self (The purpose of the __str__ and __repr__ methods is to make it possible to experiment in the interactive interpreter, without a lot of mysterious and puzzling "str object is not callable" TypeErrors. Trust me on this.) And in use: >>> class Spam: ... __metaclass__ = Meta ... a = 1 ... >>> Spam.b 'Customized b' But note that using classic classes, there is no equivalent of __getattribute__ or descriptors, so there is no way to customize access of an attribute which actually does exist: >>> Spam.a 1 -- Steven From geoff.bache at gmail.com Sun Oct 30 06:02:35 2011 From: geoff.bache at gmail.com (Geoff Bache) Date: Sun, 30 Oct 2011 03:02:35 -0700 (PDT) Subject: Customizing class attribute access in classic classes References: <4ead178e$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9ccffb27-a8d0-4fc2-b308-ba9239dc2c13@p16g2000yqd.googlegroups.com> Thanks for this Steven. I'm however gettings some pretty odd effects, both on method access and inheritance. I expanded your example a bit... class Meta: def __init__(self, name, bases, namespace): self.__name__ = name self.__bases__ = bases self.__dict__ = namespace def __str__(self): return "" __repr__ = __str__ def __getattr__(self, name): return "Customized " + name def __call__(self): return self class Base: def basemethod(self): return "base" class A(Base): __metaclass__ = Meta def method(self): return "answer" The effect seems to be to make all methods of A into static methods, and to ignore its base classes altogether: >>> a = A() >>> print a.blah2 Customized blah2 >>> print a.method() Traceback (most recent call last): File "", line 1, in TypeError: method() takes exactly 1 argument (0 given) >>> print a.method(1) answer >>> print A.method(1) answer >>> print a.basemethod() Traceback (most recent call last): File "", line 1, in TypeError: 'str' object is not callable >>> isinstance(a, Base) False Regards, Geoff Bache From skippy.hammond at gmail.com Sun Oct 30 07:03:08 2011 From: skippy.hammond at gmail.com (Mark Hammond) Date: Sun, 30 Oct 2011 22:03:08 +1100 Subject: Need Windows user / developer to help with Pynguin In-Reply-To: References: Message-ID: <4EAD2EEC.5050707@gmail.com> On 30/10/2011 1:43 AM, Lee Harr wrote: >> For Windows users who want to just run Pyguin (not modify or tinker >> with the source code), it would be best to bundle Pynguin up with >> Py2exe > > I considered that, but I agree that licensing issues would make it > problematic. What licensing issues concern you? The py2exe license shouldn't be a problem and py2exe or something like it is good advice. Mark From devplayer at gmail.com Sun Oct 30 10:11:25 2011 From: devplayer at gmail.com (DevPlayer) Date: Sun, 30 Oct 2011 07:11:25 -0700 (PDT) Subject: Dynamically creating properties? References: <4eaa5cfa$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4382a97c-0517-4fca-be14-181d480038a6@4g2000yqu.googlegroups.com> To be honest, I was hoping someone would have posted a link to a well known and tested recipe. You'd think this function would be in the standard library or a specific Exception tied directly with setattr() and getattr() (and possibly __getattr__(), __getattribute__(), __setattr__()) The main thing I wanted to point out though is when you start using dynamically named references, there's more to it then just letting a dynamic file define it. If there's a way to reference a set of data, it really shouldn't be with a "dynamically named reference" too often. Databases are a good example. Perhaps this is a better way for example: If you have a bunch of tables in your DB -is- it better to get the table def and create a Python class with dynamically named "fields"? Or is it better to create a Table class with name attribute and a Field class with a name attribute (named "name") SO instead of : field_name = xml_parse.get_next_field_name(xml_table_definition) my_table = Table() setattr(my_table, field_name, empty_list_to_later_contain_field_data) Perhaps: field_name = xml_parse.get_next_field_name(xml_table_definition) my_table = Table() my_table.fields[field_name] = empty_list_to_later_contain_field_data # or my_table.add_field( Field(field_name) ) From boyee118 at gmail.com Sun Oct 30 10:49:16 2011 From: boyee118 at gmail.com (Korobase) Date: Sun, 30 Oct 2011 22:49:16 +0800 Subject: [Help] python ctypes to process C pointer! Message-ID: A c code snippet,the c file compiled to a dll file named libxxx.dll: typedef void* HND; typedef unsigned char UCHAR; typedef short int SWORD; ....... int Connect( HND* hnd, UCHAR* ipaddr, SWORD port){ ...... return 1; } then How to handle function Connect using python and ctypes. especially the parameter hnd? My python code: from ctypes import * xxx = cdll.libxxx xxx.Connect.restype=c_int xxx.Connect.argstype=[c_wchar_p,c_wchar_p,c_int] hnd=c_char_p() buf=create_string_buffer("127.0.0.1\0") ipaddr=cast(buf,POINTER(c_char)) xxx.Connect(byref(hnd),ipaddr,8000) But I always result a error: WindowsError: exception: access violation writing 0x00000000 How to fix this problem? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gnarlodious at gmail.com Sun Oct 30 11:02:22 2011 From: gnarlodious at gmail.com (Gnarlodious) Date: Sun, 30 Oct 2011 08:02:22 -0700 (PDT) Subject: __init__ with multiple list values Message-ID: <1acb0d4c-069b-4356-8a9e-cd5640023c2b@g27g2000pre.googlegroups.com> Initializing a list of objects with one value: class Order: def __init__(self, ratio): self.ratio=ratio def __call__(self): return self.ratio ratio=[1, 2, 3, 4, 5] Orders=[Order(x) for x in ratio] But now I want to __init__ with 3 values: class Order: def __init__(self, ratio, bias, locus): self.ratio=ratio self.bias=bias self.locus=locus def __call__(self): return self.ratio, self.bias, self.locus ratio=[1, 2, 3, 4, 5] bias=[True, False, True, False, True] locus=['A', 'B', 'C', 'D', 'E'] Orders=[Order(x,y,z) for x,y,z in [ratio, bias, locus]] >>> ValueError: too many values to unpack (expected 3) How to do it? -- Gnarlie From i.mehrzad at gmail.com Sun Oct 30 11:14:38 2011 From: i.mehrzad at gmail.com (Mehrzad Irani) Date: Sun, 30 Oct 2011 08:14:38 -0700 (PDT) Subject: Review Python site with useful code snippets In-Reply-To: <98598900-8b72-4bb2-b21e-13666c9f823b@p16g2000yqd.googlegroups.com> References: <98598900-8b72-4bb2-b21e-13666c9f823b@p16g2000yqd.googlegroups.com> Message-ID: <29976477.1418.1319987678361.JavaMail.geo-discussion-forums@prep8> Considering that the site is going to grow over time, putting the snippets in a drop-down menu isn't a wise idea in my opinion. Snippets on a separate page like activestate python would make it more convenient. Nice initiative, and would be very helpful when it grows over time. From rosuav at gmail.com Sun Oct 30 11:15:21 2011 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 31 Oct 2011 02:15:21 +1100 Subject: __init__ with multiple list values In-Reply-To: <1acb0d4c-069b-4356-8a9e-cd5640023c2b@g27g2000pre.googlegroups.com> References: <1acb0d4c-069b-4356-8a9e-cd5640023c2b@g27g2000pre.googlegroups.com> Message-ID: On Mon, Oct 31, 2011 at 2:02 AM, Gnarlodious wrote: > Orders=[Order(x,y,z) for x,y,z in [ratio, bias, locus]] > Assuming that you intend to take the first element of each list, then the second, and so on, you'll want to use zip(): Orders=[Order(x,y,z) for x,y,z in zip(ratio, bias, locus)] With your syntax, Python iterates over a three-element list. The first iteration, it looks at 'ratio' and tries to unpack that into x,y,z; this doesn't work, because ratio has five elements. The second iteration would try to unpack 'bias', and the third would go for 'locus'. The zip function returns tuples of (ratio[N], bias[N], locus[N]) for successive Ns: >>> list(zip(ratio,bias,locus)) [(1, True, 'A'), (2, False, 'B'), (3, True, 'C'), (4, False, 'D'), (5, True, 'E')] ChrisA From irmen.NOSPAM at xs4all.nl Sun Oct 30 11:46:38 2011 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 30 Oct 2011 16:46:38 +0100 Subject: [ANN] Pyrolite 1.3 - native Pyro and Pickle library for Java and .NET Message-ID: <4ead715e$0$6847$e4fe514c@news2.news.xs4all.nl> Hello, I'd like to announce Pyrolite 1.3, a tiny (~50k) Pyro client library for Java and .NET. Q: "what is a java/.net library doing in this newsgroup?" A.1: This library is meant to connect a Java or .NET program to Python in a very simple way, using the Pyro protocol. Pyro is my remote object library or Python. A.2: Pyrolite contains an almost feature complete native implementation of Python's pickle protocol. This can be useful by itself to read/write pickles from Java or .NET programs. Download Pyrolite here: http://irmen.home.xs4all.nl/pyrolite/ More info on Pyrolite: http://irmen.home.xs4all.nl/pyrolite/README.txt More info on Pyro: http://irmen.home.xs4all.nl/pyro/ Enjoy, Irmen de Jong From gnarlodious at gmail.com Sun Oct 30 12:08:24 2011 From: gnarlodious at gmail.com (Gnarlodious) Date: Sun, 30 Oct 2011 09:08:24 -0700 (PDT) Subject: __init__ with multiple list values References: <1acb0d4c-069b-4356-8a9e-cd5640023c2b@g27g2000pre.googlegroups.com> Message-ID: On Oct 30, 9:15?am, Chris Angelico wrote: > Orders=[Order(x,y,z) for x,y,z in zip(ratio, bias, locus)] Brilliant, thanks! -- Gnarlie From missive at hotmail.com Sun Oct 30 12:33:30 2011 From: missive at hotmail.com (Lee Harr) Date: Sun, 30 Oct 2011 21:03:30 +0430 Subject: Need Windows user / developer to help with Pynguin In-Reply-To: <4EAD2EEC.5050707@gmail.com> References: , <4EAD2EEC.5050707@gmail.com> Message-ID: >>> Py2exe >> >> I considered that, but I agree that licensing issues would make it >> problematic. > > What licensing issues concern you? The py2exe license shouldn't be a > problem and py2exe or something like it is good advice. I think PyQt 4 would be the biggest issue. It is GPL 2 / 3. I think if this were just for my own use, or just for use in getting the program on to computers in my own school's labs then py2exe would be fine. I don't think I could post a py2exe'd version on the google code site for general distribution. Of course this is only my own personal (non-legal) opinion. From alec.taylor6 at gmail.com Sun Oct 30 14:48:33 2011 From: alec.taylor6 at gmail.com (Alec Taylor) Date: Mon, 31 Oct 2011 05:48:33 +1100 Subject: Need Windows user / developer to help with Pynguin In-Reply-To: References: Message-ID: Maybe push something onto pip or easy_install? On Fri, Oct 28, 2011 at 6:38 AM, Lee Harr wrote: > > I develop the free python-based turtle graphics application pynguin. > > http://pynguin.googlecode.com/ > > > Lately I have been getting a lot of positive comments from people > who use the program, but I am also getting a lot of feedback from > people on Windows (mostly beginners) who are having trouble > getting the program running. > > I don't use Windows myself, though I have found access occasionally > to fix bugs. I just don't know enough about Windows culture to be > able to make a reliable method for installing or running the program. > > > The method that I wrote for Linux also works on Windows, but it has > to be run from the command prompt. > > > I am hoping someone can look at what is there and come up with a > reliable method or a simple set of steps that people can follow to get > up and running. Hopefully without having to resort to the command > prompt. > > I started a wiki page here: > http://code.google.com/p/pynguin/wiki/InstallingPynguinOnWindows > but I can't even test if it actually works.... > > > Thanks for any help. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From python at mrabarnett.plus.com Sun Oct 30 15:30:38 2011 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 30 Oct 2011 19:30:38 +0000 Subject: __init__ with multiple list values In-Reply-To: <1acb0d4c-069b-4356-8a9e-cd5640023c2b@g27g2000pre.googlegroups.com> References: <1acb0d4c-069b-4356-8a9e-cd5640023c2b@g27g2000pre.googlegroups.com> Message-ID: <4EADA5DE.6090302@mrabarnett.plus.com> On 30/10/2011 15:02, Gnarlodious wrote: > Initializing a list of objects with one value: > > class Order: > def __init__(self, ratio): > self.ratio=ratio > def __call__(self): > return self.ratio > > ratio=[1, 2, 3, 4, 5] > Orders=[Order(x) for x in ratio] > > > But now I want to __init__ with 3 values: > > class Order: > def __init__(self, ratio, bias, locus): > self.ratio=ratio > self.bias=bias > self.locus=locus > def __call__(self): > return self.ratio, self.bias, self.locus > > ratio=[1, 2, 3, 4, 5] > bias=[True, False, True, False, True] > locus=['A', 'B', 'C', 'D', 'E'] > Orders=[Order(x,y,z) for x,y,z in [ratio, bias, locus]] > >>>> ValueError: too many values to unpack (expected 3) > > How to do it? > Use 'zip': Orders=[Order(x,y,z) for x,y,z in zip(ratio, bias, locus)] From anders at flauntkit.com Sun Oct 30 16:33:29 2011 From: anders at flauntkit.com (Anders Gunnarsson) Date: Sun, 30 Oct 2011 13:33:29 -0700 (PDT) Subject: Calling JavaScript inside the webbrowser module Message-ID: <7045835.701.1320006809939.JavaMail.geo-discussion-forums@yqnx19> Hi! Is there anyway to communicate with JavaScript inside a website opened via the webbrowser module? | import webbrowser | webbrowser.open('http://python.org') Here I'd like to do something like webbrowser.call('alert(1)') and I'd like to be able to call the python app from javascript too. I've looked at pywebkitgtk, but it's messy running on win32. From darren at dvhart.com Sun Oct 30 17:04:30 2011 From: darren at dvhart.com (Darren Hart) Date: Sun, 30 Oct 2011 14:04:30 -0700 Subject: Appending to sys.path during module install with distutils Message-ID: I'm trying to use distutils to install a collection of modules in /usr/local/lib/python2.7/site-packages. My distribution (Fedora 15) doesn't include any /usr/local paths in sys.path, so the import fails when running the program. The distutils documentation suggests adding a $NAME.pth file to an existing site-packages directory in sys.path. Is there a preferred/accepted method of doing this? I considered just adding some code to my setup.py to generate a braindump.pth file containing something like: PREFIX/lib/pythonMAJOR.MINOR/site-packages and then walking the existing sys.path and picking one of those site-packages directories to install braindump.pth to. I'm not sure how to determine which is the appropriate path. Maybe I'm going about this completely wrong as well - anyone care to help steer me in the right direction? The project is located here: http://braindump.dvhart.com in case anyone wants it for reference. Thanks, -- Darren Hart From electronixtar at gmail.com Sun Oct 30 23:13:00 2011 From: electronixtar at gmail.com (est) Date: Mon, 31 Oct 2011 11:13:00 +0800 Subject: SSE4a with ctypes in python? (gcc __builtin_popcount) In-Reply-To: References: Message-ID: Hi guys, Here is the sample code http://stackoverflow.com/questions/6389841/efficiently-find-binary-strings-with-low-hamming-distance-in-large-set/6390606#6390606 static inline int distance(unsigned x, unsigned y) { return __builtin_popcount(x^y); } Is it possible to rewrite the above gcc code in python using ctypes (preferably Win/*nix compatible)? TIA! -------------- next part -------------- An HTML attachment was scrubbed... URL: From Ric at rdo Mon Oct 31 00:37:01 2011 From: Ric at rdo (Ric at rdo) Date: Sun, 30 Oct 2011 23:37:01 -0500 Subject: ttk Listbox Message-ID: What would be an equivalent widget in ttk like a Listbox and if possible a small example? I tried to look here http://docs.python.org/library/ttk.html but did not see anything. Maybe I did not look in the right place? tia From electronixtar at gmail.com Mon Oct 31 04:39:47 2011 From: electronixtar at gmail.com (est) Date: Mon, 31 Oct 2011 01:39:47 -0700 (PDT) Subject: SSE4a with ctypes in python? (gcc __builtin_popcount) Message-ID: Hi guys, Here is the sample code http://stackoverflow.com/questions/6389841/efficiently-find-binary-strings-with-low-hamming-distance-in-large-set/6390606#6390606 static inline int distance(unsigned x, unsigned y) { return __builtin_popcount(x^y); } Is it possible to rewrite the above gcc code in python using ctypes (preferably Win/*nix compatible)? TIA! From modelnine at modelnine.org Mon Oct 31 04:41:17 2011 From: modelnine at modelnine.org (Heiko Wundram) Date: Mon, 31 Oct 2011 09:41:17 +0100 Subject: SSE4a with ctypes in python? (gcc __builtin_popcount) In-Reply-To: References: Message-ID: <4EAE5F2D.9070804@modelnine.org> Am 31.10.2011 04:13, schrieb est: > Is it possible to rewrite the above gcc code in python using ctypes > (preferably Win/*nix compatible)? No; the (gcc-injected) functions starting with __builtin_* are not "real" functions in the sense that they can be called by calling into a library, but rather are converted to a series of assembler instructions by the compiler directly. Wrapping this (distance) primitive by writing a C-module for Python, thus exposing the respective gcc-generated assembler code to Python through a module, won't yield any relevant speedups either, because most of the time will be spent in the call sequence for calling the function, and not in the actual computation. -- --- Heiko. From __peter__ at web.de Mon Oct 31 04:53:00 2011 From: __peter__ at web.de (Peter Otten) Date: Mon, 31 Oct 2011 09:53 +0100 Subject: Introducing pickleDB; a simple, lightweight, and fast key-value database. References: Message-ID: patx wrote: > Hello I have recently started work on a new project called pickleDB. It is > a lightweight key-value database engine (inspired by redis). > > Check it out at http://packages.python.org/pickleDB > > import json as pickle # ;) > > def load(location): > global db > try: > db = pickle.load(open(location, 'rb')) > except IOError: > db = {} > global loco > loco = location > return True > > def set(key, value): > db[key] = value > pickle.dump(db, open(loco, 'wb')) > return True > > def get(key): > return db[key] Hmm, I don't think that will scale... From pennerandpen at web.de Mon Oct 31 06:00:26 2011 From: pennerandpen at web.de (user1024) Date: Mon, 31 Oct 2011 11:00:26 +0100 Subject: ttk Listbox In-Reply-To: References: Message-ID: hi http://www.tkdocs.com/tutorial/index.html remember that you have to import line from tkinter import ttk (at "from tkinter import *" ttk in not included) From pennerandpen at web.de Mon Oct 31 06:01:42 2011 From: pennerandpen at web.de (user1024) Date: Mon, 31 Oct 2011 11:01:42 +0100 Subject: ttk Listbox In-Reply-To: References: Message-ID: hi http://www.tkdocs.com/tutorial/index.html remember that you have to import like from tkinter import ttk (at "from tkinter import *" ttk in not included) From home3 at faustballmanager.de.vu Mon Oct 31 06:05:35 2011 From: home3 at faustballmanager.de.vu (autofelge) Date: Mon, 31 Oct 2011 11:05:35 +0100 Subject: ttk Listbox In-Reply-To: References: Message-ID: <4eae72f0$0$4151$6e1ede2f@read.cnntp.org> hi http://www.tkdocs.com/tutorial/index.html remember that you have to import like from tkinter import ttk (at "from tkinter import *" ttk in not included) From home3 at faustballmanager.de.vu Mon Oct 31 06:07:07 2011 From: home3 at faustballmanager.de.vu (autofelge) Date: Mon, 31 Oct 2011 11:07:07 +0100 Subject: ttk Listbox In-Reply-To: References: Message-ID: <4eae734b$0$4151$6e1ede2f@read.cnntp.org> hi http://www.tkdocs.com/tutorial/index.html remember that you have to import like from tkinter import ttk (at "from tkinter import *" ttk in not included) From user at 1024.de Mon Oct 31 06:10:53 2011 From: user at 1024.de (user1024) Date: Mon, 31 Oct 2011 11:10:53 +0100 Subject: ttk Listbox In-Reply-To: References: Message-ID: hi http://www.tkdocs.com/tutorial/index.html remember that you have to import like from tkinter import ttk (at "from tkinter import *" ttk in not included) From dhyams at gmail.com Mon Oct 31 08:01:40 2011 From: dhyams at gmail.com (dhyams) Date: Mon, 31 Oct 2011 05:01:40 -0700 (PDT) Subject: How to mix-in __getattr__ after the fact? References: <4630c4d0-86bc-4295-8bbb-6f58415191c8@v15g2000vbm.googlegroups.com> <4EAAF264.1050307@stoneleaf.us> Message-ID: <8bc11029-860e-4d3a-8770-062e16e31514@j39g2000yqc.googlegroups.com> Thanks for all of the responses; everyone was exactly correct, and obeying the binding rules for special methods did work in the example above. Unfortunately, I only have read-only access to the class itself (it was a VTK class wrapped with SWIG), so I had to find another way to accomplish what I was after. On Oct 28, 10:26?pm, Lie Ryan wrote: > On 10/29/2011 05:20 AM, Ethan Furman wrote: > > > > > > > > > > > > > Python only looks up __xxx__ methods in new-style classes on the class > > itself, not on the instances. > > > So this works: > > > 8<---------------------------------------------------------------- > > class Cow(object): > > pass > > > def attrgetter(self, a): > > print "CAUGHT: Attempting to get attribute", a > > > bessie = Cow() > > > Cow.__getattr__ = attrgetter > > > print bessie.milk > > 8<---------------------------------------------------------------- > > a minor modification might be useful: > > bessie = Cow() > bessie.__class__.__getattr__ = attrgetter From andrea.crotti.0 at gmail.com Mon Oct 31 10:00:03 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Mon, 31 Oct 2011 14:00:03 +0000 Subject: locate executables for different platforms Message-ID: <4EAEA9E3.50409@gmail.com> Suppose that I have a project which (should be)/is multiplatform in python, which, however, uses some executables as black-boxes. These executables are platform-dependent and at the moment they're just thrown inside the same egg, and using pkg_resources to get the path. I would like to rewrite this thing being able to: - detect the OS - find the right executable version - get the path and run it It would be nice to still be able to use pkg_resources, but at that point I think I would need to store all the executables in another egg, is that correct? Is there already something available to manage external multi-platform executables? Thanks, Andrea From kw at codebykevin.com Mon Oct 31 10:00:22 2011 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 31 Oct 2011 10:00:22 -0400 Subject: ttk Listbox In-Reply-To: References: Message-ID: On 10/31/11 12:37 AM, Ric at rdo wrote: > > What would be an equivalent widget in ttk like a Listbox and if > possible a small example? I tried to look here > http://docs.python.org/library/ttk.html but did not see anything. > > Maybe I did not look in the right place? > > tia The listbox isn't part of the themed ttk widgets. The ttk::treview is, and that can be set up as a single-column list display. There may be an example of how to do this in the docs or source code tree (I don't use the widget myself so I don't have any sample code to share). --Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From andrea.crotti.0 at gmail.com Mon Oct 31 10:24:40 2011 From: andrea.crotti.0 at gmail.com (Andrea Crotti) Date: Mon, 31 Oct 2011 14:24:40 +0000 Subject: locate executables for different platforms In-Reply-To: <4EAEA9E3.50409@gmail.com> References: <4EAEA9E3.50409@gmail.com> Message-ID: <4EAEAFA8.80305@gmail.com> On 10/31/2011 02:00 PM, Andrea Crotti wrote: > Suppose that I have a project which (should be)/is multiplatform in > python, > which, however, uses some executables as black-boxes. > > These executables are platform-dependent and at the moment they're just > thrown inside the same egg, and using pkg_resources to get the path. > > I would like to rewrite this thing being able to: > - detect the OS > - find the right executable version > - get the path and run it > > It would be nice to still be able to use pkg_resources, but at that > point I think > I would need to store all the executables in another egg, is that > correct? > Is there already something available to manage external multi-platform > executables? > > Thanks, > Andrea The most simple possible way I can think of to solve this problem would be, to create a directory for each executable, and in each directory the executable with the platform in the name, like: - exec1: + exec1-linux2 + exec1-darwin ... And to look up would be very simple (as below), but I feel that is not very smart... import sys from os import path BASE_DIR = '.' exec_name = sys.argv[1] assert path.isdir(exec_name) plat = sys.platform name_ex = "%s-%s" % (exec_name, plat) if plat == 'win32': name_ex += '.exe' res_ex = path.join(exec_name, name_ex) assert path.isfile(res_ex) print path.abspath(res_ex) From devplayer at gmail.com Mon Oct 31 10:39:23 2011 From: devplayer at gmail.com (DevPlayer) Date: Mon, 31 Oct 2011 07:39:23 -0700 (PDT) Subject: Review Python site with useful code snippets References: <98598900-8b72-4bb2-b21e-13666c9f823b@p16g2000yqd.googlegroups.com> Message-ID: <7c5576ff-d4bf-47e7-8b18-9ed1893ef924@r2g2000vbj.googlegroups.com> When visitors visit your site to post their code; often such posts ask for username and email address; consider adding additional fields to generate some Python documenting feature like Sphinx or epydoc. and let your site inject the docstring (module string) into the snippet; primarily, author, url=YOUR url if not provided by them, date, python version, os, etc... See reStructuRE for possible fields to inject. From roland at catalogix.se Mon Oct 31 10:52:39 2011 From: roland at catalogix.se (Roland Hedberg) Date: Mon, 31 Oct 2011 15:52:39 +0100 Subject: Support for Galois/Counter Mode (GCM) ? Message-ID: <282F3AA8-AD7B-4499-93DF-8E617267EEC1@catalogix.se> Hi ! Is there a crypto library for Python that has support for GCM ?? -- Roland From pierre.quentel at gmail.com Mon Oct 31 10:55:36 2011 From: pierre.quentel at gmail.com (Pierre Quentel) Date: Mon, 31 Oct 2011 07:55:36 -0700 (PDT) Subject: [ANN] Karrigell-4.3.6 released Message-ID: <0d65a4a3-4eb8-4508-8153-7ef2f5fdb6e1@v5g2000vbh.googlegroups.com> Hi, A new version of the Karrigell web framework for Python 3.2+ has just been released on http://code.google.com/p/karrigell/ One of the oldest Python web frameworks around (the first version was released back in 2002), it now has 2 main versions, one for Python 2 and another one for Python 3. The Python 2.x version is available at http://karrigell.sf.net ; this branch is maintained, but no new feature is going to be developed All the development work is now focused on the version for Python 3. The first release was published in February and we are already at the 10th release Karrigell's design is about simplicity for the programmer and integration of all the web environment in the scripts namespace. For instance, the "Hello world" script requires 2 lines : def index(): return "Hello world" All the HTML tags are available as classes in the scripts namespace : def index(): return HTML(BODY("Hello world")) To build an HTML document as a tree, the HTML tags objects support the operators + (add brother) and <= (add child) : def index(): form = FORM(action="insert",method="post") form <= INPUT(name="foo")+BR()+INPUT(name="bar") form <= INPUT(Type="submit",value="Ok") return HTML(BODY(form)) The scripts can be served by a built-in web server, or through the Apache server, either on CGI mode or using the WSGI interface The package obvioulsy has built-in support for usual features such as cookie and session management, localization, user login/logout/role management. It also includes a complete documentation, with a tutorial and a set of how-to's A helpful and friendly community welcomes users at http://groups.google.com/group/karrigell Enjoy ! Pierre From devplayer at gmail.com Mon Oct 31 11:01:19 2011 From: devplayer at gmail.com (DevPlayer) Date: Mon, 31 Oct 2011 08:01:19 -0700 (PDT) Subject: locate executables for different platforms References: Message-ID: On Oct 31, 10:00?am, Andrea Crotti wrote: > Suppose that I have a project which (should be)/is multiplatform in python, > which, however, uses some executables as black-boxes. > > These executables are platform-dependent and at the moment they're just > thrown inside the same egg, and using pkg_resources to get the path. > > I would like to rewrite this thing being able to: > - detect the OS > - find the right executable version > - get the path and run it > > It would be nice to still be able to use pkg_resources, but at that > point I think > I would need to store all the executables in another egg, is that correct? > Is there already something available to manage external multi-platform > executables? > > Thanks, > Andrea While this doesn't answer your question fully, here is a beta snippet I wrote in Python, that returns a list of full pathnames, for a set of specified filenames, found in paths specified by PATH environment variable. Only tested on WIN32. Note on WIN32 systems the snippet tries to find filenames with extensions specified by the environment varible PATHEXT. On Unix it will also try with no extension, of cource (not tested). Enjoy. From devplayer at gmail.com Mon Oct 31 11:02:24 2011 From: devplayer at gmail.com (DevPlayer) Date: Mon, 31 Oct 2011 08:02:24 -0700 (PDT) Subject: locate executables for different platforms References: Message-ID: <32cd7f28-744e-414d-bedb-3268f66df5fe@k10g2000yqn.googlegroups.com> Oh forgot the link: http://pastebin.com/kFp0dJdS From rick.mansilla at gmail.com Mon Oct 31 12:18:24 2011 From: rick.mansilla at gmail.com (Ricardo Mansilla) Date: Mon, 31 Oct 2011 10:18:24 -0600 Subject: Tweepy: Invalid arguments at function call (tweepy.Stream()) Message-ID: Hi i'm trying to fetch realtime data from twitter using tweepy.Stream(). So I have tried the following... After successfully authenticate using oauth: auth = tweepy.OAuthHandler(...) (it works fine, i have my access_token.key and secret) i did: streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout='90') and: streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout='90') none of this works, it keeps giving me the same error: Traceback (most recent call last): File "", line 1, in streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), timeout='60') TypeError: *init*() takes at least 4 arguments (4 given) then i have searched for the parameters of the function: tweedy.streaming.Stream(login,password,Listener(),...etc) but i thought this login and pass was the authentication method using in the basic authentication not in the oauth case. Now i'm really confused, a little help please? pd: As you can see, i'm trying to get realtime data from twitter (and make some further NLP with it), i have chose tweepy because the dev.twitter.compage recommended it, but if you have any other suggestion for doing this, it will be welcomed -------------- next part -------------- An HTML attachment was scrubbed... URL: From ckaynor at zindagigames.com Mon Oct 31 14:34:31 2011 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Mon, 31 Oct 2011 11:34:31 -0700 Subject: C API: Making a context manager Message-ID: I am currently rewritting a class using the Python C API to improve performance of it, however I have not been able to find any documentation?about how to make a context manager using the C API. The code I am working to produce is the following (its a method of a class): @contextlib.contextmanager def connected(self, *args, **kwargs): connection = self.connect(*args, **kwargs) try: yield finally: connection.disconnect() For this, my first question is: is there any built-in method to make this type of method in the C API? If not, is there a slot on the type object I am missing for __enter__ and __exit__, or should just be defined using the PyMethodDef struct on the class (presumably named the same as the Python functions)? Chris From brian.curtin at gmail.com Mon Oct 31 15:15:37 2011 From: brian.curtin at gmail.com (Brian Curtin) Date: Mon, 31 Oct 2011 14:15:37 -0500 Subject: C API: Making a context manager In-Reply-To: References: Message-ID: On Mon, Oct 31, 2011 at 13:34, Chris Kaynor wrote: > I am currently rewritting a class using the Python C API to improve > performance of it, however I have not been able to find any > documentation?about how to make a context manager using the C API. > > The code I am working to produce is the following (its a method of a class): > > @contextlib.contextmanager > def connected(self, *args, **kwargs): > ? ? ? ?connection = self.connect(*args, **kwargs) > ? ? ? ?try: > ? ? ? ? ? ? ? ?yield > ? ? ? ?finally: > ? ? ? ? ? ? ? ?connection.disconnect() > > For this, my first question is: is there any built-in method to make > this type of method in the C API? If not, is there a slot on the type > object I am missing for __enter__ and __exit__, or should just be > defined using the PyMethodDef struct on the class (presumably named > the same as the Python functions)? You'd just add "__enter__" and "__exit__" in the PyMethodDef. If you have the CPython source, we do it in there in a few places. Off the top of my head, PC\winreg.c contains at least one class that works as a context manager (PyHKEY), although there are a few others scattered around the source. From ckaynor at zindagigames.com Mon Oct 31 15:18:05 2011 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Mon, 31 Oct 2011 12:18:05 -0700 Subject: C API: Making a context manager In-Reply-To: References: Message-ID: On Mon, Oct 31, 2011 at 12:15 PM, Brian Curtin wrote: > > You'd just add "__enter__" and "__exit__" in the PyMethodDef. If you > have the CPython source, we do it in there in a few places. Off the > top of my head, PC\winreg.c contains at least one class that works as > a context manager (PyHKEY), although there are a few others scattered > around the source. > That is what I figured. I was just hoping there was some helper class similar to the contextmanager decorator that would make it easier to use, however at the same time it makes sense that there is not. Thanks, Chris From Ric at rdo Mon Oct 31 15:34:26 2011 From: Ric at rdo (Ric at rdo) Date: Mon, 31 Oct 2011 14:34:26 -0500 Subject: ttk Listbox References: Message-ID: On Mon, 31 Oct 2011 10:00:22 -0400, Kevin Walzer wrote: >On 10/31/11 12:37 AM, Ric at rdo wrote: >> >> What would be an equivalent widget in ttk like a Listbox and if >> possible a small example? I tried to look here >> http://docs.python.org/library/ttk.html but did not see anything. >> >> Maybe I did not look in the right place? >> >> tia > >The listbox isn't part of the themed ttk widgets. The ttk::treview is, >and that can be set up as a single-column list display. There may be an >example of how to do this in the docs or source code tree (I don't use >the widget myself so I don't have any sample code to share). > >--Kevin Thank you for the information. From python at bdurham.com Mon Oct 31 15:43:44 2011 From: python at bdurham.com (python at bdurham.com) Date: Mon, 31 Oct 2011 15:43:44 -0400 Subject: Experience with ActivateState Stackato or PiCloud SaaS/PaaS offerings? Message-ID: <1320090224.3316.140660992863349@webmail.messagingengine.com> Looking for feedback from anyone who has tried or is using ActiveState Stackato, PiCloud or other Python orientated SaaS/PaaS offerings? Pros, cons, advice, lessons learned? Thank you, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at bdurham.com Mon Oct 31 15:54:34 2011 From: python at bdurham.com (python at bdurham.com) Date: Mon, 31 Oct 2011 15:54:34 -0400 Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? Message-ID: <1320090874.6062.140660992866273@webmail.messagingengine.com> Wondering if there's a fast/efficient built-in way to determine if a string has non-ASCII chars outside the range ASCII 32-127, CR, LF, or Tab? I know I can look at the chars of a string individually and compare them against a set of legal chars using standard Python code (and this works fine), but I will be working with some very large files in the 100's Gb to several Tb size range so I'd thought I'd check to see if there was a built-in in C that might handle this type of check more efficiently. Does this sound like a use case for cython or pypy? Thanks, Malcolm -------------- next part -------------- An HTML attachment was scrubbed... URL: From Ric at rdo Mon Oct 31 16:03:58 2011 From: Ric at rdo (Ric at rdo) Date: Mon, 31 Oct 2011 15:03:58 -0500 Subject: ttk Listbox References: Message-ID: On Mon, 31 Oct 2011 10:00:22 -0400, Kevin Walzer wrote: >On 10/31/11 12:37 AM, Ric at rdo wrote: >> >> What would be an equivalent widget in ttk like a Listbox and if >> possible a small example? I tried to look here >> http://docs.python.org/library/ttk.html but did not see anything. >> >> Maybe I did not look in the right place? >> >> tia > >The listbox isn't part of the themed ttk widgets. The ttk::treview is, >and that can be set up as a single-column list display. There may be an >example of how to do this in the docs or source code tree (I don't use >the widget myself so I don't have any sample code to share). > >--Kevin Quick question: Then why is it mentioned here http://www.tkdocs.com/tutorial/morewidgets.html? Listboxes are created using the Listbox function: l = Listbox(parent, height=10) From pauldavidmena at gmail.com Mon Oct 31 16:16:25 2011 From: pauldavidmena at gmail.com (extraspecialbitter) Date: Mon, 31 Oct 2011 13:16:25 -0700 (PDT) Subject: How do I pass a variable to os.popen? Message-ID: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> I'm trying to write a simple Python script to print out network interfaces (as found in the "ifconfig -a" command) and their speed ("ethtool "). The idea is to loop for each interface and print out its speed. os.popen seems to be the right solution for the ifconfig command, but it doesn't seem to like me passing the interface variable as an argument. Code snippet is below: ============ #!/usr/bin/python # Quick and dirty script to print out available interfaces and their speed # Initializations output = " Interface: %s Speed: %s" import os, socket, types fp = os.popen("ifconfig -a") dat=fp.read() dat=dat.split('\n') for line in dat: if line[10:20] == "Link encap": interface=line[:9] cmd = 'ethtool %interface' print cmd gp = os.popen(cmd) fat=gp.read() fat=fat.split('\n') ============= I'm printing out "cmd" in an attempt to debug, and "interface" seems to be passed as a string and not a variable. Obviously I'm a newbie, and I'm hoping this is a simple syntax issue. Thanks in advance! From catdude at gmail.com Mon Oct 31 16:40:20 2011 From: catdude at gmail.com (Dan M) Date: 31 Oct 2011 20:40:20 GMT Subject: How do I pass a variable to os.popen? References: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> Message-ID: <9h8fdkFvt1U6@mid.individual.net> On Mon, 31 Oct 2011 13:16:25 -0700, extraspecialbitter wrote: > cmd = 'ethtool %interface' Do you perhaps mean: cmd = 'ethtool %s' % (interface, ) From ian.g.kelly at gmail.com Mon Oct 31 16:41:11 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 31 Oct 2011 14:41:11 -0600 Subject: How do I pass a variable to os.popen? In-Reply-To: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> References: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> Message-ID: On Mon, Oct 31, 2011 at 2:16 PM, extraspecialbitter wrote: > ? ?cmd = 'ethtool %interface' That is not Python syntax for string interpolation. Try: cmd = 'ethtool %s' % interface On a side note, os.popen is deprecated. You should look into using the higher-level subprocess.check_output instead. Cheers, Ian From dreadpiratejeff at gmail.com Mon Oct 31 16:46:09 2011 From: dreadpiratejeff at gmail.com (J) Date: Mon, 31 Oct 2011 16:46:09 -0400 Subject: How do I pass a variable to os.popen? In-Reply-To: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> References: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> Message-ID: On Mon, Oct 31, 2011 at 16:16, extraspecialbitter wrote: > ? ?if line[10:20] == "Link encap": > ? ? ? interface=line[:9] > ? ?cmd = 'ethtool %interface' > ? ?print cmd > ? ?gp = os.popen(cmd) because you're saying that cmd is 'ethtool %interface' as you pointed out later on... how about: cmd = 'ethtool %s' % interface note the spaces there... that tells it to convert the contents of interface to a string and insert them into the string you're assigning to cmd... assuming interface is things like eth0, you shoud now see "ethtool eth0" when the print statement runs. From clp2 at rebertia.com Mon Oct 31 16:48:02 2011 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 31 Oct 2011 13:48:02 -0700 Subject: How do I pass a variable to os.popen? In-Reply-To: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> References: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> Message-ID: On Mon, Oct 31, 2011 at 1:16 PM, extraspecialbitter wrote: > I'm trying to write a simple Python script to print out network > interfaces (as found in the "ifconfig -a" command) and their speed > ("ethtool "). ?The idea is to loop for each interface and > print out its speed. ?os.popen seems to be the right solution for the os.popen() is somewhat deprecated. Use the subprocess module instead. > ifconfig command, but it doesn't seem to like me passing the interface > variable as an argument. ?Code snippet is below: > > ============ > > #!/usr/bin/python > > # Quick and dirty script to print out available interfaces and their > speed > > # Initializations > > output = " Interface: %s Speed: %s" > > import os, socket, types > > fp = os.popen("ifconfig -a") > dat=fp.read() > dat=dat.split('\n') > for line in dat: > ? ?if line[10:20] == "Link encap": > ? ? ? interface=line[:9] > ? ?cmd = 'ethtool %interface' cmd will literally contain a percent-sign and the word "interface". If your shell happens to use % as a prefix to indicate a variable, note that Python variables are completely separate from and not accessible from the shell. So either ethtool will get the literal string "%interface" as its argument, or since there is no such shell variable, after expansion it will end up getting no arguments at all. Perhaps you meant: cmd = "ethtool %s" % interface Which could be more succinctly written: cmd = "ethtool " + interface > ? ?print cmd > ? ?gp = os.popen(cmd) > ? ?fat=gp.read() The subprocess equivalent is: fat = subprocess.check_output(["ethtool", interface]) > ? ?fat=fat.split('\n') > > ============= > > I'm printing out "cmd" in an attempt to debug, and "interface" seems > to be passed as a string and not a variable. ?Obviously I'm a newbie, > and I'm hoping this is a simple syntax issue. ?Thanks in advance! Cheers, Chris -- http://rebertia.com From pauldavidmena at gmail.com Mon Oct 31 17:25:59 2011 From: pauldavidmena at gmail.com (Paul David Mena) Date: Mon, 31 Oct 2011 17:25:59 -0400 Subject: How do I pass a variable to os.popen? In-Reply-To: References: <4aba51d5-987f-4b65-a661-a9cb38b0e6e2@t38g2000prg.googlegroups.com> Message-ID: This was exactly what I was looking for. Thanks! On Mon, Oct 31, 2011 at 4:48 PM, Chris Rebert wrote: > On Mon, Oct 31, 2011 at 1:16 PM, extraspecialbitter > wrote: > > I'm trying to write a simple Python script to print out network > > interfaces (as found in the "ifconfig -a" command) and their speed > > ("ethtool "). The idea is to loop for each interface and > > print out its speed. os.popen seems to be the right solution for the > > os.popen() is somewhat deprecated. Use the subprocess module instead. > > > ifconfig command, but it doesn't seem to like me passing the interface > > variable as an argument. Code snippet is below: > > > > ============ > > > > #!/usr/bin/python > > > > # Quick and dirty script to print out available interfaces and their > > speed > > > > # Initializations > > > > output = " Interface: %s Speed: %s" > > > > import os, socket, types > > > > fp = os.popen("ifconfig -a") > > dat=fp.read() > > dat=dat.split('\n') > > for line in dat: > > if line[10:20] == "Link encap": > > interface=line[:9] > > cmd = 'ethtool %interface' > > cmd will literally contain a percent-sign and the word "interface". If > your shell happens to use % as a prefix to indicate a variable, note > that Python variables are completely separate from and not accessible > from the shell. So either ethtool will get the literal string > "%interface" as its argument, or since there is no such shell > variable, after expansion it will end up getting no arguments at all. > Perhaps you meant: > cmd = "ethtool %s" % interface > Which could be more succinctly written: > cmd = "ethtool " + interface > > > print cmd > > gp = os.popen(cmd) > > fat=gp.read() > > The subprocess equivalent is: > fat = subprocess.check_output(["ethtool", interface]) > > > fat=fat.split('\n') > > > > ============= > > > > I'm printing out "cmd" in an attempt to debug, and "interface" seems > > to be passed as a string and not a variable. Obviously I'm a newbie, > > and I'm hoping this is a simple syntax issue. Thanks in advance! > > Cheers, > Chris > -- > http://rebertia.com > -- Paul David Mena -------------------- pauldavidmena at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon Oct 31 17:32:04 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 31 Oct 2011 17:32:04 -0400 Subject: Tweepy: Invalid arguments at function call (tweepy.Stream()) In-Reply-To: References: Message-ID: On 10/31/2011 12:18 PM, Ricardo Mansilla wrote: > Hi i'm trying to fetch realtime data from twitter using tweepy.Stream(). A reference to your source for tweepy would help. The link below gives https://github.com/tweepy/tweepy for the current source. http://pypi.python.org/pypi/tweepy/1.7.1 has versions for 2.4,5,6 from May 2010. You neglected to mention which version of Python you are using > streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), > timeout='90') > and: > streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), > timeout='90') These look identical. > none of this works, it keeps giving me the same error: > > Traceback (most recent call last): > File "", line 1, in > streaming_api = tweepy.streaming.Stream(auth, CustomStreamListener(), > timeout='60') > TypeError: *init*() takes at least 4 arguments (4 given) 3.2 prints the proper method name: __init__. I do not remember that older versions did that conversion, but maybe so. In any case, the error message us screwed up. It has been improved in current Python. > then i have searched for the parameters of the function: > > tweedy.streaming.Stream(login,password,Listener(),...etc) > but i thought this login and pass was the authentication method using in > the basic authentication not in the oauth case. > Now i'm really confused, a little help please? The current tweepy/streaming.py source code from the site above says: class Stream(object): def __init__(self, auth, listener, **options): self.auth = auth self.listener = listener self.running = False self.timeout = options.get("timeout", 300.0) According to this, __init__ takes 3 positional params, which is what you gave it. Perhaps, this was different in an earlier version. Look at the code you are running. > i have chose tweepy because the > dev.twitter.com page recommended it, That page mentions no libraries. Perhaps you meant https://dev.twitter.com/docs/twitter-libraries -- Terry Jan Reedy From d at davea.name Mon Oct 31 17:47:06 2011 From: d at davea.name (Dave Angel) Date: Mon, 31 Oct 2011 17:47:06 -0400 Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? In-Reply-To: <1320090874.6062.140660992866273@webmail.messagingengine.com> References: <1320090874.6062.140660992866273@webmail.messagingengine.com> Message-ID: <4EAF175A.6060508@davea.name> On 10/31/2011 03:54 PM, python at bdurham.com wrote: > Wondering if there's a fast/efficient built-in way to determine > if a string has non-ASCII chars outside the range ASCII 32-127, > CR, LF, or Tab? > > I know I can look at the chars of a string individually and > compare them against a set of legal chars using standard Python > code (and this works fine), but I will be working with some very > large files in the 100's Gb to several Tb size range so I'd > thought I'd check to see if there was a built-in in C that might > handle this type of check more efficiently. > > Does this sound like a use case for cython or pypy? > > Thanks, > Malcolm > How about doing a .replace() method call, with all those characters turning into '', and then see if there's anything left? -- DaveA From d at davea.name Mon Oct 31 18:08:00 2011 From: d at davea.name (Dave Angel) Date: Mon, 31 Oct 2011 18:08:00 -0400 Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? In-Reply-To: <4EAF175A.6060508@davea.name> References: <1320090874.6062.140660992866273@webmail.messagingengine.com> <4EAF175A.6060508@davea.name> Message-ID: <4EAF1C40.6030202@davea.name> On 10/31/2011 05:47 PM, Dave Angel wrote: > On 10/31/2011 03:54 PM, python at bdurham.com wrote: >> Wondering if there's a fast/efficient built-in way to determine >> if a string has non-ASCII chars outside the range ASCII 32-127, >> CR, LF, or Tab? >> >> I know I can look at the chars of a string individually and >> compare them against a set of legal chars using standard Python >> code (and this works fine), but I will be working with some very >> large files in the 100's Gb to several Tb size range so I'd >> thought I'd check to see if there was a built-in in C that might >> handle this type of check more efficiently. >> >> Does this sound like a use case for cython or pypy? >> >> Thanks, >> Malcolm >> > How about doing a .replace() method call, with all those characters > turning into '', and then see if there's anything left? > > > I was wrong once again. But a simple combination of translate() and split() methods might do it. Here I'm suggesting that the table replace all valid characters with space, so the split() can use its default behavior. -- DaveA From ian.g.kelly at gmail.com Mon Oct 31 18:52:53 2011 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 31 Oct 2011 16:52:53 -0600 Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? In-Reply-To: <4EAF1C40.6030202@davea.name> References: <1320090874.6062.140660992866273@webmail.messagingengine.com> <4EAF175A.6060508@davea.name> <4EAF1C40.6030202@davea.name> Message-ID: On Mon, Oct 31, 2011 at 4:08 PM, Dave Angel wrote: > I was wrong once again. ?But a simple combination of ?translate() and > split() methods might do it. ?Here I'm suggesting that the table replace all > valid characters with space, so the split() can use its default behavior. That sounds overly complicated and error-prone. For instance, split() will split on vertical tab, which is not one of the characters the OP wanted. I would probably use a regular expression for this. import re if re.search(r'[^\r\n\t\040-\177]', string_to_test): print("Invalid!") Cheers, Ian From steve+comp.lang.python at pearwood.info Mon Oct 31 19:02:15 2011 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: 31 Oct 2011 23:02:15 GMT Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? References: <1320090874.6062.140660992866273@webmail.messagingengine.com> Message-ID: <4eaf28f7$0$29968$c3e8da3$5496439d@news.astraweb.com> On Mon, 31 Oct 2011 17:47:06 -0400, Dave Angel wrote: > On 10/31/2011 03:54 PM, python at bdurham.com wrote: >> Wondering if there's a fast/efficient built-in way to determine if a >> string has non-ASCII chars outside the range ASCII 32-127, CR, LF, or >> Tab? >> >> I know I can look at the chars of a string individually and compare >> them against a set of legal chars using standard Python code (and this >> works fine), but I will be working with some very large files in the >> 100's Gb to several Tb size range so I'd thought I'd check to see if >> there was a built-in in C that might handle this type of check more >> efficiently. >> >> Does this sound like a use case for cython or pypy? >> >> Thanks, >> Malcolm >> > How about doing a .replace() method call, with all those characters > turning into '', and then see if there's anything left? No offense Dave, but do you really think that making a copy of as much as a terabyte of data is *more* efficient than merely scanning the data and stopping on the first non-ASCII character you see? There is no way of telling whether a string includes non-ASCII characters without actually inspecting each character. So in the event that the string *is* fully ASCII text, you have to check every character, there can be no shortcuts. However, there is a shortcut if the string isn't fully ASCII text: once you've found a single non-text character, stop. So the absolute least amount of work you can do is: # Define legal characters: LEGAL = ''.join(chr(n) for n in range(32, 128)) + '\n\r\t\f' # everybody forgets about formfeed... \f # and are you sure you want to include chr(127) as a text char? def is_ascii_text(text): for c in text: if c not in LEGAL: return False return True Algorithmically, that's as efficient as possible: there's no faster way of performing the test, although one implementation may be faster or slower than another. (PyPy is likely to be faster than CPython, for example.) But can we get better in Python? Yes, I think so. First off, CPython is optimized for local variable lookups over globals, and since you are looking up the global LEGAL potentially 1000000000000 times, even a 1% saving per lookup will help a lot. So the first step is to make a local reference, by adding this line just above the for loop: legal = LEGAL But we can do even better still. Each time we test for "c not in legal", we do a linear search of 100 characters. On average, that will mean comparing 50 characters for equality at best. We can do better by using a set or frozenset, which gives us approximately constant time lookups: legal = frozenset(LEGAL) Finally, we can try to do as much work as possible in fast C code and as little as necessary in relatively slow Python: def is_ascii_text(text): legal = frozenset(LEGAL) return all(c in legal for c in text) Since all() is guaranteed to keep short-cut semantics, that will be as fast as possible in Python, and quite possibly just as fast as any C extension you might write. If that's still too slow, use smaller files or get a faster computer :) -- Steven From tjreedy at udel.edu Mon Oct 31 19:10:02 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 31 Oct 2011 19:10:02 -0400 Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? In-Reply-To: <1320090874.6062.140660992866273@webmail.messagingengine.com> References: <1320090874.6062.140660992866273@webmail.messagingengine.com> Message-ID: On 10/31/2011 3:54 PM, python at bdurham.com wrote: > Wondering if there's a fast/efficient built-in way to determine if a > string has non-ASCII chars outside the range ASCII 32-127, CR, LF, or Tab? I presume you also want to disallow the other ascii control chars? > I know I can look at the chars of a string individually and compare them > against a set of legal chars using standard Python code (and this works If, by 'string', you mean a string of bytes 0-255, then I would, in Python 3, where bytes contain ints in [0,255], make a byte mask of 256 0s and 1s (not '0's and '1's). Example: mask = b'\0\1'*121 for c in b'\0\1help': print(mask[c]) 1 0 1 0 1 1 In your case, use \1 for forbidden and replace the print with "if mask[c]: ; break" In 2.x, where iterating byte strings gives length 1 byte strings, you would need ord(c) as the index, which is much slower. > fine), but I will be working with some very large files in the 100's Gb > to several Tb size range so I'd thought I'd check to see if there was a > built-in in C that might handle this type of check more efficiently. > Does this sound like a use case for cython or pypy? Cython should get close to c speed, especially with hints. Make sure you compile something like the above as Py 3 code. -- Terry Jan Reedy From kw at codebykevin.com Mon Oct 31 20:00:13 2011 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 31 Oct 2011 20:00:13 -0400 Subject: ttk Listbox In-Reply-To: References: Message-ID: On 10/31/11 4:03 PM, Ric at rdo wrote: > On Mon, 31 Oct 2011 10:00:22 -0400, Kevin Walzer > wrote: > >> On 10/31/11 12:37 AM, Ric at rdo wrote: >>> >>> What would be an equivalent widget in ttk like a Listbox and if >>> possible a small example? I tried to look here >>> http://docs.python.org/library/ttk.html but did not see anything. >>> >>> Maybe I did not look in the right place? >>> >>> tia >> >> The listbox isn't part of the themed ttk widgets. The ttk::treview is, >> and that can be set up as a single-column list display. There may be an >> example of how to do this in the docs or source code tree (I don't use >> the widget myself so I don't have any sample code to share). >> >> --Kevin > > Quick question: > > Then why is it mentioned here > http://www.tkdocs.com/tutorial/morewidgets.html? > > Listboxes are created using the Listbox function: > > l = Listbox(parent, height=10) The listbox is a Tk widget, not a ttk widget. It's one of the original Tk/Tkinter widgets, and has no themed equivalent. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From python.list at tim.thechases.com Mon Oct 31 20:01:14 2011 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 31 Oct 2011 19:01:14 -0500 Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? In-Reply-To: <4eaf28f7$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <1320090874.6062.140660992866273@webmail.messagingengine.com> <4eaf28f7$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4EAF36CA.5040409@tim.thechases.com> On 10/31/11 18:02, Steven D'Aprano wrote: > # Define legal characters: > LEGAL = ''.join(chr(n) for n in range(32, 128)) + '\n\r\t\f' > # everybody forgets about formfeed... \f > # and are you sure you want to include chr(127) as a text char? > > def is_ascii_text(text): > for c in text: > if c not in LEGAL: > return False > return True > > > Algorithmically, that's as efficient as possible: there's no faster way > of performing the test, although one implementation may be faster or > slower than another. (PyPy is likely to be faster than CPython, for > example.) Additionally, if one has some foreknowledge of the character distribution, one might be able to tweak your > def is_ascii_text(text): > legal = frozenset(LEGAL) > return all(c in legal for c in text) with some if/else chain that might be faster than the hashing involved in a set lookup (emphasis on the *might*, not being an expert on CPython internals) such as def is_ascii_text(text): return all( (' ' <= c <= '\x7a') or c == '\n' or c == '\t' for c in text) But Steven's main points are all spot on: (1) use an O(1) lookup; (2) return at the first sign of trouble; and (3) push it into the C implementation rather than a for-loop. (and the "locals are faster in CPython" is something I didn't know) -tkc From pmaupin at gmail.com Mon Oct 31 20:32:34 2011 From: pmaupin at gmail.com (Patrick Maupin) Date: Mon, 31 Oct 2011 17:32:34 -0700 (PDT) Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? References: <1320090874.6062.140660992866273@webmail.messagingengine.com> <4EAF175A.6060508@davea.name> <4EAF1C40.6030202@davea.name> Message-ID: <3bd5234e-dbbe-4f67-84fb-e654650decb6@hv4g2000vbb.googlegroups.com> On Mon, Oct 31, 2011 at 4:08 PM, Dave Angel wrote: Yes. Actually, you don't even need the split() -- you can pass an optional deletechars parameter to translate(). On Oct 31, 5:52?pm, Ian Kelly wrote: > That sounds overly complicated and error-prone. Not really. >?For instance, split() will split on vertical tab, > which is not one of the characters the OP wanted. That's just the default behavior. You can explicitly specify the separator to split on. But it's probably more efficient to just use translate with deletechars. > I would probably use a regular expression for this. I use 'em all the time, but not for stuff this simple. Regards, Pat From tjreedy at udel.edu Mon Oct 31 20:44:45 2011 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 31 Oct 2011 20:44:45 -0400 Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? In-Reply-To: <4eaf28f7$0$29968$c3e8da3$5496439d@news.astraweb.com> References: <1320090874.6062.140660992866273@webmail.messagingengine.com> <4eaf28f7$0$29968$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/31/2011 7:02 PM, Steven D'Aprano wrote: > On Mon, 31 Oct 2011 17:47:06 -0400, Dave Angel wrote: > >> On 10/31/2011 03:54 PM, python at bdurham.com wrote: >>> Wondering if there's a fast/efficient built-in way to determine if a >>> string has non-ASCII chars outside the range ASCII 32-127, CR, LF, or >>> Tab? >>> >>> I know I can look at the chars of a string individually and compare >>> them against a set of legal chars using standard Python code (and this >>> works fine), but I will be working with some very large files in the >>> 100's Gb to several Tb size range so I'd thought I'd check to see if >>> there was a built-in in C that might handle this type of check more >>> efficiently. >>> >>> Does this sound like a use case for cython or pypy? >>> >>> Thanks, >>> Malcolm >>> >> How about doing a .replace() method call, with all those characters >> turning into '', and then see if there's anything left? > > > No offense Dave, but do you really think that making a copy of as much as > a terabyte of data is *more* efficient than merely scanning the data and > stopping on the first non-ASCII character you see? > > > There is no way of telling whether a string includes non-ASCII characters > without actually inspecting each character. So in the event that the > string *is* fully ASCII text, you have to check every character, there > can be no shortcuts. However, there is a shortcut if the string isn't > fully ASCII text: once you've found a single non-text character, stop. So > the absolute least amount of work you can do is: > > # Define legal characters: > LEGAL = ''.join(chr(n) for n in range(32, 128)) + '\n\r\t\f' > # everybody forgets about formfeed... \f > # and are you sure you want to include chr(127) as a text char? > > def is_ascii_text(text): > for c in text: > if c not in LEGAL: > return False > return True If text is 3.x bytes, this does not work ;-). OP did not specify bytes or unicode or Python version. > > > Algorithmically, that's as efficient as possible: This is a bit strange since you go on to explain that it is inefficient -- O(n*k) where n = text length and k = legal length -- whereas below is O(n). > there's no faster way > of performing the test, although one implementation may be faster or > slower than another. (PyPy is likely to be faster than CPython, for > example.) > > But can we get better in Python? Yes, I think so. First off, CPython is > optimized for local variable lookups over globals, and since you are > looking up the global LEGAL potentially 1000000000000 times, even a 1% > saving per lookup will help a lot. So the first step is to make a local > reference, by adding this line just above the for loop: > > legal = LEGAL > > But we can do even better still. Each time we test for "c not in legal", > we do a linear search of 100 characters. On average, that will mean > comparing 50 characters for equality at best. We can do better by using a > set or frozenset, which gives us approximately constant time lookups: > > legal = frozenset(LEGAL) > > Finally, we can try to do as much work as possible in fast C code and as > little as necessary in relatively slow Python: > > def is_ascii_text(text): > legal = frozenset(LEGAL) > return all(c in legal for c in text) > > Since all() is guaranteed to keep short-cut semantics, that will be as > fast as possible in Python, A dangerous statement to make. 'c in legal' has to get hash(c) and look that up in the hash table, possible skipping around a bit if t If text is byte string rather than unicode, a simple lookup 'mask[c]', where mask is a 0-1 byte array, should be faster (see my other post). On my new Pentium Win 7 machine, it is -- by albout 5%. For 100,000,000 legal bytes, a minimum of 8.69 versus 9.17 seconds. from time import clock legal_set = frozenset(range(32, 128)) legal_ray = 128 * b'\1' illegal = 128 * b'\0' # only testing legal char 'a' text = b'a' * 100000000 print(clock()) print(all(c in legal_set for c in text), clock()) # min 9.17 t = clock() print(all(legal_ray[c] for c in text), clock()-t) # min 8.69 ##for c in text: ## if illegal[c]: print(False); break # slower, about 9.7 ##print(True, clock()) The explicit loop took about 9.7 seconds. It is more flexible as it could detect the position of the first bad character, or of all of them. -- Terry Jan Reedy From d at davea.name Mon Oct 31 22:12:26 2011 From: d at davea.name (Dave Angel) Date: Mon, 31 Oct 2011 22:12:26 -0400 Subject: Efficient, built-in way to determine if string has non-ASCII chars outside ASCII 32-127, CRLF, Tab? In-Reply-To: <3bd5234e-dbbe-4f67-84fb-e654650decb6@hv4g2000vbb.googlegroups.com> References: <1320090874.6062.140660992866273@webmail.messagingengine.com> <4EAF175A.6060508@davea.name> <4EAF1C40.6030202@davea.name> <3bd5234e-dbbe-4f67-84fb-e654650decb6@hv4g2000vbb.googlegroups.com> Message-ID: <4EAF558A.7080602@davea.name> On 10/31/2011 08:32 PM, Patrick Maupin wrote: > On Mon, Oct 31, 2011 at 4:08 PM, Dave Angel wrote: > > Yes. Actually, you don't even need the split() -- you can pass an > optional deletechars parameter to translate(). > > > On Oct 31, 5:52 pm, Ian Kelly wrote: > >> That sounds overly complicated and error-prone. > Not really. > >> For instance, split() will split on vertical tab, >> which is not one of the characters the OP wanted. > That's just the default behavior. You can explicitly specify the > separator to split on. But it's probably more efficient to just use > translate with deletechars. > >> I would probably use a regular expression for this. > I use 'em all the time, but not for stuff this simple. > > Regards, > Pat I would claim that a well-written (in C) translate function, without using the delete option, should be much quicker than any python loop, even if it does copy the data. Incidentally, on the Pentium family, there's a machine instruction for that, to do the whole loop in one instruction (with rep prefix). I don't know if the library version is done so. And with the delete option, it wouldn't be copying anything, if the data is all legal. As for processing a gig of data, I never said to do it all in one pass. Process it maybe 4k at a time, and quit the first time you encounter a character not in the table. But I didn't try to post any code, since the OP never specified Python version, nor the encoding of the data. He just said string. And we all know that without measuring, it's all speculation. DaveA -- DaveA From rick.mansilla at gmail.com Mon Oct 31 22:36:23 2011 From: rick.mansilla at gmail.com (Ricardo Mansilla) Date: Mon, 31 Oct 2011 20:36:23 -0600 Subject: Tweepy: Invalid arguments at function call (tweepy.Stream()) (Terry Reedy) Message-ID: Thanks a lot for your answer. I'm using python 2.7.2 and tweetpy 1.7 >>> help(tweepy) Help on package tweepy: NAME tweepy - Tweepy Twitter API library (...) VERSION 1.7.1 and probably that is the problem, the link that you gave me refers to the 1.2 version page... Anyway, i already have their IRC direction and i think it would be easier to find support there. Thanks again. Ricardo Mansilla ps: sometimes i get lazy about writing the whole link to a precise direction which lacks of importance in my point; please, don't judge me for my exquisite way of keep the attention in the correct place... :) -------------- next part -------------- An HTML attachment was scrubbed... URL: