Re: How to Teach Python "Variables"
"J. Clifford Dyer" wrote: > This thread is bleedin' demised. No, you have stunned it. Delicate threads stun easily. To get back to the original question, namely how to teach the concept of a python variable, I would probably take a harder look at the "wandering names" analogy. I think it was first mentioned some time ago in a similar context by Dennis. Heinz = 42 Heinz = [1,2,3,4] Where is Heinz now? He is masquerading as a list, after having been an integer... But he suffers from amnesia, he can't remember his integer days. And what about the 42? It is still lurking in limbo, waiting to be Garbage Collected or resurrected by a new assignment. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Science list
It is true that suggestions may arrive from all directions. Nonetheless, this extremely useful list is so crowded that if checking email is not carried out every few hours, it is difficult to detect other messages in the plethora of pythons and spams arrived. What happens if email is disregarded for a few days? Therefore, I support a recent suggestion to establish a "science list", where python-solving problems arising from scientific use of software should appear. Something will be missed by users of the "science list", though things will become manageable. On the present list they are not. Thanks francesco pietra Get easy, one-click access to your favorites. Make Yahoo! your homepage. http://www.yahoo.com/r/hs -- http://mail.python.org/mailman/listinfo/python-list
How do I not make a list?
It may sound like a strange question but that's probably only because I don't know the proper terminology. I have an iterable object, like a list, and I want to perform a transform on it (do an operation on each of the elements) and then pass it onto something else that expects and iterable. I'm pretty sure this something else doesn't need a list, either, and just wants to iterate over elements. Now, I could just make a list, using a list comprehension, performing my operation on each element, and then pass that list on, knowing that it is iterable. However, I was wondering if there was a way I can do virtually this without having to actually allocate the memory for a list. Creating a stock iterator or generator or whatever it's called, with a passed in operation? I hope I've described this adequately. Thank you... -- http://mail.python.org/mailman/listinfo/python-list
Re: Bundling Python on Mac
Benjamin schrieb: > Hello, I'm writing a Python/PyQt application. For my Mac distribution. > I would like to include all the needed libraries in the Mac bundle. > How should I go about doing this? The py2app distutils extension should do that for you. It works flawless for PyObjc-apps for me - it _should_ do so for Qt as well, but I have to admit that it sometimes had errors related to Qt when creating bundles - so maybe you need to tweak the support a bit. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I not make a list?
On 11/29/07, Just Another Victim of the Ambient Morality <[EMAIL PROTECTED]> wrote: > It may sound like a strange question but that's probably only because I > don't know the proper terminology. I have an iterable object, like a list, > and I want to perform a transform on it (do an operation on each of the > elements) and then pass it onto something else that expects and iterable. > I'm pretty sure this something else doesn't need a list, either, and just > wants to iterate over elements. > Now, I could just make a list, using a list comprehension, performing my > operation on each element, and then pass that list on, knowing that it is > iterable. However, I was wondering if there was a way I can do virtually > this without having to actually allocate the memory for a list. Creating a > stock iterator or generator or whatever it's called, with a passed in > operation? Well I think what you want is to use "()" instead of "[]" >>> l = (i for i in range(1,20)) >>> l Cheers, -- Amit Khemka -- http://mail.python.org/mailman/listinfo/python-list
Determine whether program was started by clicking icon or command line
Hi! I wonder whether there might be a way to find out how a Python program was started (in my case in Windows): By double clicking the file or by calling it on the "DOS" command line prompt. Background: I would like to have the program run in an "interactive mode" if double clicked, and silently in a "batch mode" when started otherwise. Any hints? Thank you! Ben -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I not make a list?
Just Another Victim of the Ambient Morality schrieb: > It may sound like a strange question but that's probably only because I > don't know the proper terminology. I have an iterable object, like a list, > and I want to perform a transform on it (do an operation on each of the > elements) and then pass it onto something else that expects and iterable. > I'm pretty sure this something else doesn't need a list, either, and just > wants to iterate over elements. > Now, I could just make a list, using a list comprehension, performing my > operation on each element, and then pass that list on, knowing that it is > iterable. However, I was wondering if there was a way I can do virtually > this without having to actually allocate the memory for a list. Creating a > stock iterator or generator or whatever it's called, with a passed in > operation? You want a generator expression. Or a generator. res = (apply_something(e) for e in my_iterable) or def g(mit): for e in mit: yield apply_something(e) Both only get evaluated step by step during the iteration, reducing memory consumption. Diez -- http://mail.python.org/mailman/listinfo/python-list
X/Linux mouse_event (like in win32api)
Hello everyone. I would like to be able to emit a mouse click on my xgl/compiz desktop, like I used to do in Windows: win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0) I installed Python and pywin32 in wine and they both work, but I cannot extend the mouse emulation to my X desktop. Is there a way to interact directly with the X server (or with the kernel?) to simulate a click? And if it can't be done in Python, where should I go? Thank you in advance for your replies. -- http://mail.python.org/mailman/listinfo/python-list
Re: Science list
Francesco Pietra wrote: > It is true that suggestions may arrive from all directions. Nonetheless, this > extremely useful list is so crowded that if checking email is not carried out > every few hours, it is difficult to detect other messages in the plethora of > pythons and spams arrived. What happens if email is disregarded for a few > days? > > Therefore, I support a recent suggestion to establish a "science list", where > python-solving problems arising from scientific use of software should appear. > > Something will be missed by users of the "science list", though things will > become manageable. On the present list they are not. Isn't that called the SciPy list ;-) ([EMAIL PROTECTED]) cheers, Stef -- http://mail.python.org/mailman/listinfo/python-list
Re: Very basic, sorting a list ???
Peter Decker wrote: > On Nov 28, 2007 7:22 PM, stef mientki <[EMAIL PROTECTED]> wrote: >> print 'xx3',ordered_list.sort() > > The sort() method returns None. It sorts the list in place; it doesn't > return a copy of the sorted list. > Thank you all for the answers, I do understand now, although I find it rather non-intuitive. I didn't expect a copy, but a reference to itself wouldn't be asked too much ? Why does it return None, instead of the sorted object itself ? I guess it would cost almost exactly the same processing power. cheers, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list
Re: Very basic, sorting a list ???
On Nov 29, 10:40 am, Stef Mientki <[EMAIL PROTECTED]> wrote: > Peter Decker wrote: > > On Nov 28, 2007 7:22 PM, stef mientki <[EMAIL PROTECTED]> wrote: > >> print 'xx3',ordered_list.sort() > > > The sort() method returns None. It sorts the list in place; it doesn't > > return a copy of the sorted list. > > Thank you all for the answers, > I do understand now, > although I find it rather non-intuitive. > I didn't expect a copy, but a reference to itself wouldn't be asked too much ? > Why does it return None, instead of the sorted object itself ? > I guess it would cost almost exactly the same processing power. > > cheers, > Stef Mientki >From the Docs; The sort() and reverse() methods modify the list in place for economy of space when sorting or reversing a large list. To remind you that they operate by side effect, they don't return the sorted or reversed list. -- http://mail.python.org/mailman/listinfo/python-list
Re: Very basic, sorting a list ???
Stef Mientki <[EMAIL PROTECTED]> writes: > although I find it rather non-intuitive. > I didn't expect a copy, but a reference to itself wouldn't be asked > too much ? If you didn't expect a copy, why rely on the return value? You could simply continue using the sorted list. Your first post says "I'm trying to sort a list, using the same list at the commandline works, but in a program it doesn't." > Why does it return None, instead of the sorted object itself ? > I guess it would cost almost exactly the same processing power. It's not about processing power at all, it's about clarity. Code that says: foo = [5, 2, 3, 1] bar = foo.sort() might run into a nasty surprise upon finding that both foo and bar point to the same (sorted) list. Returning None ensures that the error is detected as early as possible. Returning a list strongly indicates that a copy is being made. For example, the following Perl code: @foo = (3, 2, 1); @bar = sort @foo; makes @bar sorted, but leaves @foo alone. -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine whether program was started by clicking icon or command line
On Nov 29, 9:51 am, Benjamin Hell <[EMAIL PROTECTED]> wrote: > Hi! > > I wonder whether there might be a way to find out how a Python > program was started (in my case in Windows): By double clicking the > file or by calling it on the "DOS" command line prompt. I think it's not possible (or very tricky) to do that. > Background: I would like to have the program run in an "interactive > mode" if double clicked, and silently in a "batch mode" when started > otherwise. > > Any hints? Why don't you just create a desktop icon that calls "myprog.py -- interactive-mode" and then check in sys.argv for the actual argument? Or, if you prefer not to use arguments, you could just change the working directory of the shortcut and then check os.getcwd()? Though it's a weird thing to do... Hope I could. aatiis -- http://mail.python.org/mailman/listinfo/python-list
Does changing a Tkinter Variable bound to a widget invoke its 'command' callback function?
I am writing a simple (maybe a bit conveluded, but I just started learning Tkinter) program that uses a 'notebook' code snippet from a python cookbook. It creates a customizable frame and radio button for each 'tab' and uses .forget to hide the frames that aren't 'current'. I modified it to use a Scale slider bar instead of radio buttons. What my program does is create a parent notebook object, and in each notebook frame, child notebooks are created. All the sliders are created with: command=lambda x: self.display(int(x)) Which displays the contents of the associated notebook frame (via forget/pack). All of this also works fine, but I wanted it to be a little more user-friendly by linking all the sliders on the child notebooks using a control IntVar so that each child notebook can be on the same page while scrolling through them. The problem is that when the currently displayed slider is moved, it updates the current child notebook, but not the notebooks of the hidden frames. Their sliders are moved when they are next displayed, but the associated frames are not updated, so there is a mismatch between slider and frame until that specific slider is moved. I can't find much information on control variables with respect to Scale widgets, so any insight, hints, or suggestions would be greatly appreciated. Some snippets of the involved routines: def __init__(self, master, size, start=0, side=LEFT, choice=None): self.active_fr = start self.size = size if(choice): self.choice = choice else: self.choice = IntVar(value=start) ... # create slider self.slide = Scale(self.rb_fr, variable=self.choice, orient=self.orient, from_=start, to=(size-start+1), length=200, command=lambda x: self.display(int(x))) ... def display(self, fr): self.frames[self.active_fr].forget() self.frames[fr].pack(fill=BOTH, expand=1) self.active_fr = fr -- http://mail.python.org/mailman/listinfo/python-list
Re: Very basic, sorting a list ???
Hrvoje Niksic wrote: > Stef Mientki <[EMAIL PROTECTED]> writes: > >> although I find it rather non-intuitive. >> I didn't expect a copy, but a reference to itself wouldn't be asked >> too much ? > > If you didn't expect a copy, why rely on the return value? You could > simply continue using the sorted list. Your first post says "I'm > trying to sort a list, using the same list at the commandline works, > but in a program it doesn't." > >> Why does it return None, instead of the sorted object itself ? >> I guess it would cost almost exactly the same processing power. > > It's not about processing power at all, it's about clarity. Code that > says: > > foo = [5, 2, 3, 1] > bar = foo.sort() > > might run into a nasty surprise upon finding that both foo and bar > point to the same (sorted) list. Returning None ensures that the > error is detected as early as possible. Aha, that might be a valid reasoning. thanks, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list
wxPython and Tkinter
Hi all, I migrate some code from tkinter to wxpython. I need the equivalent Tkinter method Tkinter.Tk.after in wxPython, but I'm not able to find it. It exist or there are other trick to emulate it? thank you w -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython and Tkinter
On 29 Nov, 11:50, whatazor <[EMAIL PROTECTED]> wrote: > Hi all, > I migrate some code from tkinter to wxpython. I need the equivalent > Tkinter method Tkinter.Tk.after > in wxPython, but I'm not able to find it. It exist or there are other > trick to emulate it? > > thank you > w "after" in Tk method allows to all a function every X milliseconds. -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython and Tkinter
Hello, take a look here [1]. I think its a got place to start. br Mathias [1] http://sebsauvage.net/python/gui/#import 2007/11/29, whatazor <[EMAIL PROTECTED]>: > > Hi all, > I migrate some code from tkinter to wxpython. I need the equivalent > Tkinter method Tkinter.Tk.after > in wxPython, but I'm not able to find it. It exist or there are other > trick to emulate it? > > thank you > w > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Try/Except/Yield/Finally...I'm Lost :-}
2007/11/28, Victor Subervi <[EMAIL PROTECTED]>: > > Hi; > I am trying to find words in a document that are identical to any word in > a vocabulary list, to replace that word with special markup. Let's say the > word is "dharma". I don't want to replace the first few letters of, say > "dharmawuhirfuhi". Also, to make matters more difficult, if the word > "adharma" is found in the document, I need to replace that with special > markup, too. (In Sanskrit, "a" preceding a word negates the word.) But I > don't want to replace "adharma" and then go off and replace the "dharma" in > "adharma", thus having nested markup. Now, I tried separating out all the > words in the line (I go through the doc line by line), but then, of course, > I lost all the punctuation! So now I have this code: > > for word in vocab: > aword = "a" + word > try: > line = re.sub(aword, pu_four + aword + > pu_five + aword + pu_six, line) > except: > pass > try: > line = re.sub(word, pu_one + word + pu_two > + word + pu_three, line) > except: > pass > > which, of course, ends up breaking all the above! Can someone send me a > shovel to dig my way out of this mess? > TIA, > Victor > > -- > http://mail.python.org/mailman/listinfo/python-list Hi, I'm not quite sure, what the try - else clauses are expected to catch (if there is no match, the replace function simply leaves the original string; there would be at least exceptions with invalid patterns), but if I understand the problem correctly, I would use the usual regexp means to match whole words only. It would be the \b metacharacter indicating word boundary; e.g.the patern \bdharma\b should only match a complete word "dharma" but not "adharma " or "dharmawuhirfuhi" see http://docs.python.org/lib/re-syntax.html for details about the re patterns (especially \b can be unicode or locale dependent, but it seems, that you are using a basic latin transcription, so it wouldn't matter). However I don't know what is the content of pu_one, pu_two ... pu_five, pu_six ... in your code; are there maybe some inflexion affixes? in that case the pattern for such a compound word can be \bPrefixStemSuffix1Suffix2Ending1\b etc. However, it could get quite complicated, if you try to deal with some specificities of natural languages with such straightforward approaches. Hope this helps a bit; Vlasta -- http://mail.python.org/mailman/listinfo/python-list
PIL image.getcolors
I have an RGBA .png which PIL is able to read and I would like to convert the image to a simple RGB image with a single colour reserved for transparent as the A channel is either all on or all off. I thought I could use the the im.getcolors method to find the colours used by the image, but it sometimes returns None. Is there a smart way to find out an unused colour or the least used colour in my image? Additionally can PIL change a specified colour quickly. I'm guessing I might be able to do it using the composite mechanism > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] > on win32 > Type "help", "copyright", "credits" or "license" for more information. import Image im0 = Image.open('trans.png') im0.mode > 'RGBA' im0.getcolors() > [(55367, (255, 1, 25, 255)), (24104, (24, 79, 235, 255)), (46529, (0, 0, 0, > 0))] im1 = Image.open('400px-Wiki_letter_w.svg.png') im1.mode > 'RGBA' im1.getcolors() im1.getcolors() is None > True -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
GUI builder tool
Hi All, Please help me in selecting the best tool for developing wxPython GUIs. I'm preparing a tool that has explorer,editor and log window using wxPython.. I've heard some namely wxGlade,Boa,etc.. Which one would be the best. Thanks in Advance Regards, Tarun -- http://mail.python.org/mailman/listinfo/python-list
Variables and their domain
Hi all, I have one doubt, in my applciation I have a method (Method1) which has other method (Method2) inside of it. Ok, in my first method I define a variable "lista" which is an array, an other one, "lb", which is a listbox with some elements inserted from lista. Then, when I do a double click on a lb element, I go to Method 2, where I can continue inserting elements in lb and reading lista, but if I do "lista=..." I get an error of local variable referenced. The problem is that if I do lb and lista global variables, I have to declare them outside any method, haven't I?. If someone could help me I would be very pleased. Resume: Main Method1 Lista=a,b,c,d. Lb=listbox Method2 Lista=e,f,g.. -->error! Thanks in advance Best Regars, Naxo -- http://mail.python.org/mailman/listinfo/python-list
Re: Tuning question
On Nov 28, 3:15 pm, Wally Lepore <[EMAIL PROTECTED]> wrote: > Hi Graham > > Is this email still good? Not anymore. You just gave it out to millions of spammers on Usenet. > Its been awhile since we spoke last on the tuning list. Are you still on > Yahoo messenger? > Also, what is your email address please. You told me to email you when I had > questions that seemed too basic for the tuning list. Thanks Graham. My > email is [EMAIL PROTECTED] > > Stay well > Walter (Wally) Lepore -- http://mail.python.org/mailman/listinfo/python-list
Monkey patching new style classes
Is it possible to add an attribute to a new style class where the name of that attribute is determined at runtime? In other words, is there an new style class alternative to adding items to a classes __dict__ ? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Lib for audio?
I need to read microphone input and determine frequency. Is there a lib for that? Thanks, Dave -- http://mail.python.org/mailman/listinfo/python-list
PyPubSub module version 3 usage
Hello, I just recently found out that wx.lib.pubsub has finally moved away from wx, and now lives at: http://pubsub.wiki.sourceforge.net I'm trying to use pubsub3, which is the third version and now the default one, but I'm having a hard time creating topics and messages for sending: class Topic: __init__(self, _name, _description, _parent=None, **kwargs) | Specify the name, description, and parent of | this Topic, and the list of kwargs allowed on listeners | of this topic. The non-kwargs all start with a '_' to | minimize the chance of conflict with a kwargs key. from pubsub import pub class Test(pub.Topic): def __init__(self): pub.Topic.__init__(self, 'Topic.Test', 'This is a test topic') class Msg(pub.Message): pass pub.sendMessage(Test()) Traceback (most recent call last): File "topics.py", line 80, in pub.sendMessage(Test()) File "build/bdist.linux-i686/egg/pubsub/pubsub3.py", line 421, in sendMessage File "build/bdist.linux-i686/egg/pubsub/pubsub3.py", line 195, in sendMessage File "/home/frank/test/topics.py", line 155, in getTopic File "/home/frank/test/topics.py", line 162, in __getTopic TypeError: iteration over non-sequence. pub.sendMessage(Msg()) Traceback (most recent call last): File "topics.py", line 80, in pub.sendMessage(Test()) File "build/bdist.linux-i686/egg/pubsub/pubsub3.py", line 421, in sendMessage File "build/bdist.linux-i686/egg/pubsub/pubsub3.py", line 195, in sendMessage File "/home/frank/test/topics.py", line 155, in getTopic File "/home/frank/test/topics.py", line 162, in __getTopic TypeError: iteration over non-sequence. The variable in question for class Test() contains: Topic 'T.o.p.i.c...T.e.s.t': This is a test topic. Listeners that have 'topic=pub.AUTO_PASS_TOPIC' as a kwarg will get the topic name as value of topic (ie 'T.o.p.i.c...T.e.s.t'). Listeners must otherwise be callable with no args. No listeners are currently subscribed. There are currently no subtopics. which of course is non-iterable. Same for class Msg(), So obviously my Topic and Message class constructors are wrong. The code on the wiki is for pubsub2, and seems to be outdated compared to pubsub3 API. pubsub1 is the same as wx.lib.pubsub btw. Basically I'm looking for example code to get me kickstarted using pubsub3. Best regards, Frank -- http://mail.python.org/mailman/listinfo/python-list
any Templating system help
Hi, I am stuck a little. I am working on a demo site to propose for the my company. Using mod_python and several python technologies. But the website is simply using publisher handler, i dont want to use any framework such as DJango etc. so the main idea is, i made many python files which has several defs inside, such as index, getList, submitForm etc now everything is working nice, means calling them in url. I need a templating system now. But not slow and complex. The only things in templating system i need is: fetching all the names of variables/placeholder in template. (i can then call the suitable defs from files and apply the wrapper on it and return to main caller) setting the values Please suggest some ideas. -- -=Ravi=- -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython and Tkinter
On Nov 29, 7:56 am, whatazor <[EMAIL PROTECTED]> wrote: > On 29 Nov, 11:50, whatazor <[EMAIL PROTECTED]> wrote: > > > Hi all, > > I migrate some code from tkinter to wxpython. I need the equivalent > > Tkinter method Tkinter.Tk.after > > in wxPython, but I'm not able to find it. It exist or there are other > > trick to emulate it? > > > thank you > > w > > "after" in Tk method allows to all a function every X milliseconds. I think you need to setup an wx.Timer object. self.timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) where the self.OnTimer is the method you want to call. You need to start the timer: self.timer.Start() That's it, I think. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I not make a list?
On 2007-11-29, Just Another Victim of the Ambient Morality <[EMAIL PROTECTED]> wrote: > It may sound like a strange question but that's probably only > because I don't know the proper terminology. I have an > iterable object, like a list, and I want to perform a transform > on it (do an operation on each of the elements) and then pass > it onto something else that expects and iterable. I'm pretty > sure this something else doesn't need a list, either, and just > wants to iterate over elements. Try itertools.imap. something_else(imap(do_operation, an_iterable)) -- Neil Cerutti You've got to take the sour with the bitter. --Samuel Goldwyn -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter, wxPython, PyGtk, or PyQt...
On Nov 28, 7:34 pm, "John Jameson" <[EMAIL PROTECTED]> wrote: > hi carl, > > I'm totally new with graphics for python. I'm using windows, but you > make it sound like I need to know how to program with MFC to use them? > Is this true? Can't you just stay in python? > best, > John > > I would like like to start doing some GUI-programming in Python, but don't > know which library to choose. > > Tkinter seems a bit old. Correct me if I am wrong! The layout doesn't look > as nice as for the others. I've seen some powerful stuff done in Tkinter. While I prefer wxPython, it's still a valid choice. If you browse the list, you'll notice that Tk is going to be (or just has been) upgraded, so Tkinter should start looking better soon. > > wxPython seems to be the first-hand choice for people doing W32-programming > (with MFC-experience). This one changes too often to be included in the official Python distro. But the changes are also beneficial. If you have a C++ background, then this one should be extremely easy to pick up. I use it in all my GUI apps now. >From what I've read and seen, wxPython uses the native widgets on whatever platform it is deployed on, so it should have the native "look and feel" most of the time. > > PyGtk seems to be a modern, very clean and nice approach, but with poor > W32-support. Is PyGtk a mature library with respect to version stability > and documentation. > > PyQt is a huge library (thanks to Qt), but not free on W32, or? > > Is there any possibility that any of the above-mentioned libraries will be > included as a standard library in any of the near-future Python > distributions? Tkinter is already included with Python and has been for quite some time. > > I myself program on W32 at work, but use Linux at home. So, which one should > I start with in order to reduce the effort of learning something new and to > be productive in the shortest time possible? > > By the way, how do I most easily include plotting capabilities to my > Python-apps? The people on the wxPython user's group usually mention matplot for this sort of thing. I think they combine it with wxPython's drawing/ blitting capabilities, but since I don't do that myself, I am not completely sure of the implementation. > > Carl Hope that helps some! Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython and Tkinter
On Nov 29, 7:14 am, imbunche <[EMAIL PROTECTED]> wrote: > On Nov 29, 7:56 am, whatazor <[EMAIL PROTECTED]> wrote: > > > On 29 Nov, 11:50, whatazor <[EMAIL PROTECTED]> wrote: > > > > Hi all, > > > I migrate some code from tkinter to wxpython. I need the equivalent > > > Tkinter method Tkinter.Tk.after > > > in wxPython, but I'm not able to find it. It exist or there are other > > > trick to emulate it? > > > > thank you > > > w > > > "after" in Tk method allows to all a function every X milliseconds. > > I think you need to setup an wx.Timer object. > self.timer = wx.Timer(self) > self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) > > where the self.OnTimer is the method you want to call. > You need to start the timer: > self.timer.Start() > > That's it, I think. That should definitely work. For documentation, see the following links: http://wiki.wxpython.org/Timer http://www.wxpython.org/docs/api/wx.Timer-class.html http://www.onlamp.com/pub/a/python/excerpts/chpt20/wxpython.html?page=3 Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Lib for audio?
This should do the trick: http://www.libsdl.org/ Dave wrote: > I need to read microphone input and determine frequency. Is there a lib > for that? > > Thanks, > Dave > -- Shane Geiger IT Director National Council on Economic Education [EMAIL PROTECTED] | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -- http://mail.python.org/mailman/listinfo/python-list
Re: Science list
Francesco Pietra wrote: > Nonetheless, this extremely useful list is so crowded that if > checking email is not carried out every few hours, it is difficult > to detect other messages in the plethora of pythons and spams > arrived. Why don't you use a newsreader to access comp.lang.python? It's suited much better for tracking long and many threads. Regards, Björn -- BOFH excuse #357: I'd love to help you -- it's just that the Boss won't let me near the computer. -- http://mail.python.org/mailman/listinfo/python-list
Re: Control mouse position and clicking
Tony wrote: [place mouse programmatically] > well, you can do it from Java, Are you absolutely positive? IIRC the Mac UI guidelines forbid such things, and there's no API function for it; so Java wouldn't have any chance. Regards, Björn -- BOFH excuse #136: Daemons loose in system. -- http://mail.python.org/mailman/listinfo/python-list
Re: Lib for audio?
>> I need to read microphone input and determine frequency. Is there a lib >> for that? Yet one more possibility includes the OpenAL Python bindings: http://home.gna.org/oomadness/en/pyopenal/index.html -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: any Templating system help
On Thu, Nov 29, 2007 at 06:48:10PM +0530, Ravi Kumar wrote: > Hi, > I am stuck a little. I am working on a demo site to propose for the my > company. Using mod_python and several python technologies. But the website > is simply using publisher handler, i dont want to use any framework such as > DJango etc. > > so the main idea is, i made many python files which has several defs inside, > such as index, getList, submitForm etc > now everything is working nice, means calling them in url. I need a > templating system now. But not slow and complex. The only things in > templating system i need is: > > fetching all the names of variables/placeholder in template. (i can then > call the suitable defs from files and apply the wrapper on it and return to > main caller) > setting the values > > Please suggest some ideas. > > > > -- > -=Ravi=- > -- > http://mail.python.org/mailman/listinfo/python-list Well, I personally like Genshi (http://genshi.edgewall.org/), but offcourse there are others (myghty, cheetah) and I know you can use the Django templating system apart from the framework (never did this though. But personally, when I only need a templating system and nothing more (for some html-reports for instance) I tend to use genshi. Yoram signature.asc Description: Digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython and Tkinter
On Nov 29, 2007 7:54 AM, <[EMAIL PROTECTED]> wrote: > > On Nov 29, 7:14 am, imbunche <[EMAIL PROTECTED]> wrote: > > On Nov 29, 7:56 am, whatazor <[EMAIL PROTECTED]> wrote: > > > > > On 29 Nov, 11:50, whatazor <[EMAIL PROTECTED]> wrote: > > > > > > Hi all, > > > > I migrate some code from tkinter to wxpython. I need the equivalent > > > > Tkinter method Tkinter.Tk.after > > > > in wxPython, but I'm not able to find it. It exist or there are other > > > > trick to emulate it? > > > > > > thank you > > > > w > > > > > "after" in Tk method allows to all a function every X milliseconds. > > > > I think you need to setup an wx.Timer object. > > self.timer = wx.Timer(self) > > self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer) > > > > where the self.OnTimer is the method you want to call. > > You need to start the timer: > > self.timer.Start() > > > > That's it, I think. > > That should definitely work. For documentation, see the following > links: > > http://wiki.wxpython.org/Timer > http://www.wxpython.org/docs/api/wx.Timer-class.html > http://www.onlamp.com/pub/a/python/excerpts/chpt20/wxpython.html?page=3 For a one-shot call, you can just use wx.CallLater. wx.CallAfter may be useful too, depending on what you were using after() for. -- http://mail.python.org/mailman/listinfo/python-list
Re: Lib for audio?
On Nov 29, 6:04 am, Dave <[EMAIL PROTECTED]> wrote: > I need to read microphone input and determine frequency. Is there a lib > for that? > > Thanks, > Dave You might take a look at the ossaudiodev module (note: it's #nix only): http://docs.python.org/lib/module-ossaudiodev.html http://docs.python.org/lib/mixer-device-objects.html If you're on Windows, looking at the source for the above module still might be enlightening. I also found the following which may or may not be helpful: http://py.vaults.ca/parnassus/apyllo.py/63131194 Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Science list
I was trying to suggest a more specific mail-list in order not to be floaded. I am the opinion that python-list@python.org is very informative and useful, though it is hard to find the time for so many mails. f. --- Bjoern Schliessmann <[EMAIL PROTECTED]> wrote: > Francesco Pietra wrote: > > Nonetheless, this extremely useful list is so crowded that if > > checking email is not carried out every few hours, it is difficult > > to detect other messages in the plethora of pythons and spams > > arrived. > > Why don't you use a newsreader to access comp.lang.python? It's > suited much better for tracking long and many threads. > > Regards, > > > Björn > > > -- > BOFH excuse #357: > > I'd love to help you -- it's just that the Boss won't let me near > the computer. > > -- > http://mail.python.org/mailman/listinfo/python-list > Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs -- http://mail.python.org/mailman/listinfo/python-list
Re: Lib for audio?
Dave a écrit : > I need to read microphone input and determine frequency. Is there a lib > for that? > > Thanks, > Dave Another possible solution, the PortAudio binding (pyportaudio). http://people.csail.mit.edu/hubert/pyaudio/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Python web frameworks
On Nov 22, 11:22 pm, SamFeltus <[EMAIL PROTECTED]> wrote: > """Perhaps we need a pythonic FRONTEND. """ > > Should have happened years ago. It did. Mark Hammond embedded Python under MSIE about the same time javascript and java applets came along (94, maybe?) It didn't fly because of political and marketing problems, I think. One technical killer was that C-Python can be crashed relatively easily by malicious code, and browser providers don't like that too much. Also, the stuff you need to do to make it crash proof would make the interpreter a lot slower (which may be why javascript is pretty slow). -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=msie+de-facto+recognized+dim -- http://mail.python.org/mailman/listinfo/python-list
How to suggest a new Python list? Was: Science list
Francesco Pietra wrote: > I was trying to suggest a more specific mail-list in order not to be floaded. > I > am the opinion that python-list@python.org is very informative and useful, > though it is hard to find the time for so many mails. > f. > I agree with Francesco: Python is increasingly used in sciences (or, at least, I use it increasingly :-) and it would be of some use to have a communication channel focused on this: there are a few mailing lists for specific niche topics (CAD, XML) already, so sciences could be one more. There are mailing lists for numpy/scipy, f2py, VTK and the rest of it, but nothing quite like what Francesco suggests, as far as I know. Some folks that do not want to be flooded by 200 posts/day are going to pop up there and explain how they replaced 60,000 lines of FORTRAN by 100 lines of Python in one afternoon (before the tea break), surely that can't hurt. Anyway, I do not see how to suggest a new mailing list on http://www.python.org/community/lists/ - does anyone know? cheers, J. -- http://mail.python.org/mailman/listinfo/python-list
Re: Books on Python
I've read "Begining Python" written by Hetland from Apress. I enjoyed it a lot. I also liked reading "Dive into Python" (also from Apress) for those who already know a language. A free edition is at diveintopython.org. -- http://mail.python.org/mailman/listinfo/python-list
Re: Science list
Do you know if "free" yahoo.com allows threaded view for python only? I was unable to set that. This also means that there are mailing lists I am interested to view all that is going on (which is two orders less that python), so that i can't sett threated viw for all mailing lists. f. --- nmp <[EMAIL PROTECTED]> wrote: > Bjoern Schliessmann wrote: > > > Francesco Pietra wrote: > >> Nonetheless, this extremely useful list is so crowded that if checking > >> email is not carried out every few hours, it is difficult to detect > >> other messages in the plethora of pythons and spams arrived. > > > > Why don't you use a newsreader to access comp.lang.python? It's suited > > much better for tracking long and many threads. > > Or switch to threaded view in your mail program, most mailers can do it > nowadays. > -- > http://mail.python.org/mailman/listinfo/python-list > Get easy, one-click access to your favorites. Make Yahoo! your homepage. http://www.yahoo.com/r/hs -- http://mail.python.org/mailman/listinfo/python-list
Re: Control mouse position and clicking
I am running ubuntu. :) -- http://mail.python.org/mailman/listinfo/python-list
PIL image.filter -> boundaries
Hi, I'm filtering an image with a custom kernel. It works fine, except for the boundaries. image.filter() seems to add a 1px zero-border to the image to process the pixels at the boundaries of the image.I'd rather have it replicate the values of the boundary pixels. Is this an option and where can I set it? thanks, Pieter ps, the code: img = Image.open('cell.tif') kernelX = ImageFilter.Kernel(size=(3,3),kernel=[1,0,-1,2,0,-2,1,0,-1],scale=8) gradientX = im.filter(kernelX) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to suggest a new Python list? Was: Science list
On 2007-11-29, J. Robertson <[EMAIL PROTECTED]> wrote: > Francesco Pietra wrote: >> I was trying to suggest a more specific mail-list in order not to be >> floaded. I >> am the opinion that python-list@python.org is very informative and useful, >> though it is hard to find the time for so many mails. >> f. >> > > I agree with Francesco: Python is increasingly used in sciences (or, at > least, I use it increasingly :-) and it would be of some use to have a > communication channel focused on this: there are a few mailing lists for > specific niche topics (CAD, XML) already, so sciences could be one more. So what is the focus in the list? I think 'science' is both too broad and in many cases not at all relevant for the problem at hand. For example, Should I be a scientist before I can post there? (If yes, what about: I work as supporting staff, am a PhD student, am a regular student, have a home work question, think of going to college, just learning Python that I may need at school). Any particular brand of science (CS, Math, Physics, Bio, Chemistry, other)? Should I use Python for programming a science problem? Should I have a problem in science and want to use Python for solving it? How are science problems any different from 'normal' problems? I am writing a parser for a language used in science, can I put it there? (and if yes, how is that different from writing a language for a non-science problem?) I am trying to run program XYZ as a sub-shell, or in a thread, or distributed. Does it make any difference whether XYZ solves a science problem or not? I don't see a clear useful line called 'science', but YMMV. > Some folks that do not want to be flooded by 200 posts/day are going to > pop up there and explain how they replaced 60,000 lines of FORTRAN by > 100 lines of Python in one afternoon (before the tea break), surely that > can't hurt. If the sheer number of posts is a problem, skip subjects that you don't like, just like everybody else. If your mailinglist idea fails you have a nicely quiet corner (but is otherwise useless). That is however more easily achieved by not reading c.l.p. If it succeeds, you may easily get the same amount of traffic as you have now here. So how is 'science' here a good criterium? > Anyway, I do not see how to suggest a new mailing list on > http://www.python.org/community/lists/ - does anyone know? Ask at c.l.p. ? :) Albert -- http://mail.python.org/mailman/listinfo/python-list
Re: looking for ocbc example
On Nov 28, 2:43 am, Tim Golden <[EMAIL PROTECTED]> wrote: > Carl K wrote: > > jay graves wrote: > >> On Sep 21, 2:43 am, Tim Golden <[EMAIL PROTECTED]> wrote: > >>> Carl K wrote: > It seems there are 2 odbc modules - pyOdbc and mxOdbc - anyone know the > difference? > >>> In short, pyodbc is open source; mxOdbc requires a commercial license. > >>> pyodbc is a newcomer, but appears to work for everything I've thrown > >>> at it (which is not much). mxOdbc has been around longer, and is sure > >>> to be a more mature product. It may offer more features & functionality. > >> There is also a brand new module 'ceODBC'. > >>http://ceodbc.sourceforge.net/ > > >> I haven't used it yet but I want to give it a try. > > > I tried it, and it worked better than pyodbc. (better is not exactly right. > > there was some weird bug in the ctree odbc driver, and the author of ceODBC > > gave > > me a workaround.) > > All right, I'm a little perplexed as to whether "better" here > refers to the admirable response of the ceOBDC author or to > some other factors which demonstrate ceODBC's superiority. > > I've not really got the opportunity to pit them against each > other so to speak, but I'd love to hear from someone who had. > > TJ Just tried ceODBC the other day (on XP), and it worked like a charm connecting SqlServer and DB2. Here's SqlServer: >>> import ceODBC >>> db=ceODBC.connect('DSN=Wells') >>> c=db.cursor() >>> c.execute('select wellname, latitudedecimal, longitudedecimal from >>> dbo.wells where wellid in (11587,11194,11157)') >>> for each in c.fetchall(): ... print each ... ('GILL #1-18', 33.095599, -92.38563) ('HOW #2-7', 35.10155, -91.48824) ('JKK #11-13', 34.09130, -93.45256) Simple! Very similar syntax to mxODBC. -- http://mail.python.org/mailman/listinfo/python-list
Building Python 2.5.0 on AIX 5.3 - Undefined symbol: .__floor
Hi, We have also many problems compiling Python on AIX 5.3 with same erros, could be kind enough to tell us ohw to solve the problem ou the right parameters to compil python. Many thanks in advance. Nicolas-- http://mail.python.org/mailman/listinfo/python-list
Re: Python web frameworks
On Nov 29, 3:15 pm, Aaron Watters <[EMAIL PROTECTED]> wrote: > On Nov 22, 11:22 pm, SamFeltus <[EMAIL PROTECTED]> wrote: > > > """Perhaps we need a pythonic FRONTEND. """ > > > Should have happened years ago. > > It did. Mark Hammond embedded Python under MSIE about > the same time javascript and java applets came along (94, maybe?) > It didn't fly because of political and marketing problems, > I think. One technical killer was that C-Python can > be crashed relatively easily by malicious code, and > browser providers don't like that too much. Also, the > stuff you need to do to make it crash proof would make > the interpreter a lot slower (which may be why javascript > is pretty slow). > > -- Aaron Watters > > ===http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=msie+de-facto+... Time for another go, perhaps, seeing as the web has become the world's default user interface? -- http://mail.python.org/mailman/listinfo/python-list
Re: Very basic, sorting a list ???
On 29 nov, 04:11, Hrvoje Niksic <[EMAIL PROTECTED]> wrote: > Stef Mientki <[EMAIL PROTECTED]> writes: > > although I find it rather non-intuitive. > > I didn't expect a copy, but a reference to itself wouldn't be asked > > too much ? > > If you didn't expect a copy, why rely on the return value? You could > simply continue using the sorted list. Your first post says "I'm > trying to sort a list, using the same list at the commandline works, > but in a program it doesn't." > > > Why does it return None, instead of the sorted object itself ? > > I guess it would cost almost exactly the same processing power. > > It's not about processing power at all, it's about clarity. Code that > says: > > foo = [5, 2, 3, 1] > bar = foo.sort() > > might run into a nasty surprise upon finding that both foo and bar > point to the same (sorted) list. Returning None ensures that the > error is detected as early as possible. > > Returning a list strongly indicates that a copy is being made. For > example, the following Perl code: > > @foo = (3, 2, 1); > @bar = sort @foo; > > makes @bar sorted, but leaves @foo alone. try >>> foo = [5, 2, 3, 1] >>> bar = sorted(foo) >>> foo [5, 2, 3, 1] >>> bar [1, 2, 3, 5] -- http://mail.python.org/mailman/listinfo/python-list
SMTPLIB & email.MIMEText : Certain charaters in the body stop mail from arriving. Why?
Hello Sending mail with certain characters in the body causes mail never to arrive. Why? e.g if body text has a fullstop "." mail never arrives. I'm using python 4.2 on windows. Harvey # import smtplib from email.MIMEText import MIMEText def mail(serverURL=None, sender='', to='', subject='', text=''): COMMASPACE = ', ' to = COMMASPACE.join(to) msg = MIMEText(text) msg['Subject'] = subject msg['From'] = sender msg['To'] = to mailServer = smtplib.SMTP(serverURL, 25) mailServer.sendmail(sender, to, msg.as_string()) mailServer.quit() print msg.as_string() # Output Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: "Information from ost-cs-emma" From: [EMAIL PROTECTED] To: [EMAIL PROTECTED] Some text Some more text in body - Information in this email including any attachments may be privileged, confidential and is intended exclusively for the addressee. The views expressed may not be official policy, but the personal views of the originator. If you have received it in error, please notify the sender by return e-mail and delete it from your system. You should not reproduce, distribute, store, retransmit, use or disclose its contents to anyone. Please note we reserve the right to monitor all e-mail communication through our internal and external networks. SKY and the SKY marks are trade marks of British Sky Broadcasting Group plc and are used under licence. British Sky Broadcasting Limited (Registration No. 2906991), Sky Interactive Limited (Registration No. 3554332), Sky-In-Home Service Limited (Registration No. 2067075) and Sky Subscribers Services Limited (Registration No. 2340150) are direct or indirect subsidiaries of British Sky Broadcasting Group plc (Registration No. 2247735). All of the companies mentioned in this paragraph are incorporated in England and Wales and share the same registered office at Grant Way, Isleworth, Middlesex TW7 5QD. -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter, wxPython, PyGtk, or PyQt...
is PyQt related to Qt? I presume so. is Qt needed for PyQt? is PyQt usable in all platforms Python is available and is it GPLed, too? I read TrollTech webpage on QT and the Windows version is not free for in-house development in the private industry; licenses start around $6000 for the first year and $2000-$3000 from then on. gsal -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter, wxPython, PyGtk, or PyQt...
gsal schrieb: > is PyQt related to Qt? I presume so. > > is Qt needed for PyQt? Sure. > is PyQt usable in all platforms Python is available and is it GPLed, > too? Yes. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Any Pythonista knowing Estonian on this list?
Two nice Python fans (Pearu and Raul) have contacted me about this. Thanks! On Nov 28, 10:39 pm, "André" <[EMAIL PROTECTED]> wrote: > Some of the tasks that are part of Google's H.O.P. involved > translation (i18n) of some well-known ... and some lesser known > projects. I have received a translation in Estonian for Crunchy - > probably of the order of a 100 phrases. I just want to make sure that > no practical joke has been played in doing the translations ... my > Estonian is None. > > Anyone with basic reading knowledge of Estonian is more than welcome > to contact me. > > André -- http://mail.python.org/mailman/listinfo/python-list
Re: Control mouse position and clicking
Bjoern Schliessmann wrote: > Tony wrote: > > [place mouse programmatically] >> well, you can do it from Java, > > Are you absolutely positive? IIRC the Mac UI guidelines forbid such > things, and there's no API function for it; so Java wouldn't have > any chance. There is an API for it. Not all programs have GUIs so the HIG doesn't restrict the scope of the OS's APIs. Otherwise, one couldn't write assistive software or userland drivers for new hardware. How do you think ControllerMate does what it does? http://www.orderedbytes.com/controllermate/ In 10.4 and up, the recommended API is to use CGEventCreateMouseEvent and CGEventPost. Before that, there was CGPostMouseEvent back to 10.0, but there are situations where that can lock things up, so it is deprecated and not recommended for use. http://developer.apple.com/documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
Re: Control mouse position and clicking
Glich wrote: > hi, how can I, control mouse position and clicking from python? > > I want to interact with a flash application inside firefox. thanks. > > ps: I am not using windows. I've use the external program xte with some success if you don't send it too many events too quickly. I start it using subprocess and feed it commands. On Ubuntu sudo apt-get install xautomation It uses the XTest extension for X11 to send mouse events to the system. One could probably easily wrap the xlib API for it using ctypes so you wouldn't have to bother with an external program. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list
only test
this is a test -- http://mail.python.org/mailman/listinfo/python-list
Re: only test
On Thu, 29 Nov 2007 18:56:31 +, Rui Li wrote: > this is a test test on reply -- http://mail.python.org/mailman/listinfo/python-list
setters and getters in python 2.6 and 3.0
Hi list, I've been following a discussion on a new way of defining getters and setters on python-dev and just can't understand what the purpose is. Everybody agreed on the dev list that this is a good idea so I guess it must be right :) The whole thing started with this post of Guido: http://mail.python.org/pipermail/python-dev/2007-October/075057.html which then continued into November. Basically, the idea is that using the new way a setter can be added to property that was read-only before. But if I have this already, class C: @property def attr( self ): return self._attr what prevents me using the following for adding a setter for attr: class C: def attr( self ): return self._attr def set_attr( self, value ): self._attr = value attr = property( attr, set_attr ) In other words all I needed to do is delete @property, write the setter method and add attr = property( attr, set_attr ). What does the new way improve on this? -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine whether program was started by clicking icon or command line
On Nov 28, 10:51 pm, Benjamin Hell <[EMAIL PROTECTED]> wrote: > Hi! > > I wonder whether there might be a way to find out how a Python > program was started (in my case in Windows): By double clicking the > file or by calling it on the "DOS" command line prompt. > > Background: I would like to have the program run in an "interactive > mode" if double clicked, and silently in a "batch mode" when started > otherwise. I'm not sure whether this applies to your situation, but often programs started by clicking an icon are run by pythonw, but when started from the command line are run by python. If this is the case sys.stdin.fileno() will return -1 in the former case and 0 in the latter. -- http://mail.python.org/mailman/listinfo/python-list
Detecting mod_rewrite via CGI
Hi, I am using an Apache webserver with mod_rewrite and the cgi module. Is there a way to do the following that isn't completely evil? def mod_rewrite_enabled(): try: file = open(os.path.join(os.environ['DOCUMENT_ROOT'], '.htaccess')) except: return False for line in file: if line.startswith('RewriteEngine on'): file.close() return True file.close() return False Unfortunately, not using .htaccess isn't an option. -Samuel -- http://mail.python.org/mailman/listinfo/python-list
Re: setters and getters in python 2.6 and 3.0
Daniel Fetchinson schrieb: > Hi list, I've been following a discussion on a new way of defining > getters and setters on python-dev and just can't understand what the > purpose is. Everybody agreed on the dev list that this is a good idea > so I guess it must be right :) > > The whole thing started with this post of Guido: > > http://mail.python.org/pipermail/python-dev/2007-October/075057.html > > which then continued into November. Basically, the idea is that using > the new way a setter can be added to property that was read-only > before. But if I have this already, > > class C: > @property > def attr( self ): return self._attr > > what prevents me using the following for adding a setter for attr: > > class C: > def attr( self ): return self._attr > def set_attr( self, value ): self._attr = value > attr = property( attr, set_attr ) > > In other words all I needed to do is delete @property, write the > setter method and add attr = property( attr, set_attr ). What does the > new way improve on this? It prevents namespace-pollution in a clever way. By first defining the getter, the @propset-decorator will augment the already createt property and return it. Thus you don't end up with a set_attr function. Other, more complex recipes to do the same look like this and are much harder to grasp: @apply def my_property() def fget(self): return self._value def fset(self, value): self._value = value return property(**locals()) So the proposed propset-decorator certainly makes things clearer. Diez -- http://mail.python.org/mailman/listinfo/python-list
Oh no, my code is being published ... help!
There is a Linux forum that I frequent from time to time on which I mentioned a couple of scripts that I wrote. The editors of a small Linux magazine heard and found them interesting enough to ask me to write an article about them. I accepted gladly, of course. I wrote the article and submitted it and I was told to look for it on the January issue. Sounds good, right? The thing is I am starting to get a little nervous about it. You see, programming is not my full time job. I dabble in it from time to time, mostly to scratch my own itches, as they say. But, I know that my code is probably far from being of professional quality. So, I was wondering if some of you would be interested in taking a peak and offer some suggestions for improving the quality and safety of the code. Let me try to explain what they do. Lets say, for example that you have, as I do, a large directory tree that you want to compress containing data that you hardly ever use, but that you want to have easy access to from time to time. In my case, that directory tree contains the RAW image files that come from my DSLR camera. Each of those files is about 10 MB. The total size of that directory tree is about 45 GB, and it is constantly growing. (Note: I store my finished, "processed", images on a different directory tree. They are stored as JPEG files, so they are already compressed.) How would you go about using compression to retake some disk space on a situation like this one? Well, one way I came up with was to write my own tool to do this job. I created a program called 7sqz (7Squeeze) that can take care of this task with ease. It is a Python script that navigates through a directory tree compressing its contents only, not the actual directories. As it enters each directory on the tree it saves all the files on that directory on an archive on that same directory giving it the name of the directory itself. If it finds that the directory already has an archive file with the correct name it leaves it alone and goes to the next directory, unless it also finds an uncompressed file in it. When that happens it simply moves it into the existing archive file, updating it inside the archive if it was already there. I also created 7usqz which is the opposite counterpart of 7sqz. It will simply go through a specified directory tree looking for archive files named as the holding directory and will uncompress them, essentially leaving the directory as it was before being squeezed. Both 7sqz and 7usqz use p7zip for the actual compression, so you need to have p7zip already installed. You can obtain 7sqz from here: http://rmcorrespond.googlepages.com/7sqz And you can get 7usqz from here: http://rmcorrespond.googlepages.com/7usqz After downloading them, save them in a place like /usr/bin and make sure they are executable. To use 7sqz you could just give it a target directory as a parameter, like this: 7sqz /home/some_directory By default it will use the 7z format (which gives better compression than zip), but you can use the zip format if you prefer by using the - m option like this: 7sqz -m zip /home/some_directory By default it will use Normal as the level of compression, but you can use EXTRA or MAX if you prefer by using the -l option like this: 7sqz -l Extra /home/some_directory By default it will just skip any file if it found an error during compression and will log the error, but you can tell it to "Halt on Error" with the -e option like this: 7sqz -e /home/some_directory And of course, you can combine options as you please like this: 7sqz -m zip -l Max -e /home/some_directory As I said, 7usqz is the opposite counterpart of 7sqz. To use it you could just give it a target directory as a parameter, like this: 7usqz /home/some_directory By default it will just skip any file if it found an error during decompression and will log the error, but you can tell it to "Halt on Error" with the -e option like this: 7usqz -e /home/some_directory Please do a few, or better yet a lot of tests, before using it on a directory that you cannot afford to loose. I believe it has all the necessary safety precautions to protect your data, but I can't guaranty it. That is why I'm asking for your help. All I can say is that I have never lost any data with it and that it works great for me. What do you think? -- http://mail.python.org/mailman/listinfo/python-list
How to Split a String
Hi, I need to convert the string: '(a, b, "c", d, "e")' into the following list ['a', 'b', 'c', 'd', 'e']. Much like a csv reader does. I usually use the split function, but this mini-monster wouldn't properly get split up due to those random quotations postgresql returns to me. Please help me with this, Thanks, Sia -- http://mail.python.org/mailman/listinfo/python-list
A context manager for temporary memoization.
I posted this to my blog at http://michaelspeer.blogspot.com/2007/11/context-manager-for-temporary.html. I decided to forward it onto the list for comments. I thought someone might find it interesting. *** This is very much a fragile hack at the moment. It's an interesting idea I think. I was disappointed when I initially found that the with_statement syntax does not restore the value of the `as var` upon completion. This made doing something along the lines of with temporarily_memoized( func ) : for datum in data : func( datum ) unattainable. Well, just a lot hackier actually. Thus temporarily_memoized( ... ) was born : #!/usr/bin/python # a context manager for temporarily turning any function into # a memoized version of itself. from __future__ import with_statement import contextlib , sys , types def memoize ( func ) : """ In haskell mutability must be handled explicitly. Only fair that Python do the same to transparent functionality """ remembered = {} def memoized ( *args ) : """ memoized version of function """ if args in remembered : return remembered[ args ] else : new = func( *args ) remembered[ args ] = new return new return memoized @contextlib.contextmanager def temporarily_memoized ( func ) : """ memoize the given function for the duration of this block save anything in the local variables that gets in the way of using this so that it can be restored afterward , the memoized version is found in the locals. use on actual functions only. no members. """ # this is being called, there has to be a frame above it frame = sys._getframe().f_back.f_back if func.func_name in frame.f_locals : f = frame.f_locals[ func.func_name ] frame.f_locals[ func.func_name ] = memoize( func ) try : # this hack replaces whatever in the local scope # has the name of the variable. if you try to use # the 'as whatever' portion of the syntax , you # are doing it wrong yield None finally : frame.f_locals[ f.func_name ] = f else : frame.f_locals[ func.func_name ] = memoize( func ) try : yield None finally : del frame.f_locals[ func.func_name ] def fib(n): """ biggus fibbus """ if n == 0 or n == 1: return n else: return fib(n-1) + fib(n-2) if __name__ == '__main__' : print fib.__doc__ with temporarily_memoized( fib ) : print fib.__doc__ for i in xrange( 36 ) : print "n=%d => %d" % (i, fib(i)) print fib.__doc__ print fib.__doc__ outputs : biggus fibbus memoized version of function n=0 => 0 . n=35 => 9227465 memoized version of function biggus fibbus -- http://mail.python.org/mailman/listinfo/python-list
Job posting on the site is broken
To the webmaster of python.org, I have tried to have a job posted on the job board but! Alas, it doesn't work and I cannot get a response from the webmaster. Shall I post here ? Stephane -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Split a String
On 2007-11-29, Siah <[EMAIL PROTECTED]> wrote: > I need to convert the string: '(a, b, "c", d, "e")' into the following > list ['a', 'b', 'c', 'd', 'e']. Much like a csv reader does. http://docs.python.org/lib/module-csv.html -- Grant Edwards grante Yow! ... the HIGHWAY is at made out of LIME JELLO and visi.commy HONDA is a barbequeued OYSTER! Yum! -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Split a String
> I need to convert the string: '(a, b, "c", d, "e")' into the > following list ['a', 'b', 'c', 'd', 'e']. Much like a csv > reader does. I usually use the split function, but this > mini-monster wouldn't properly get split up due to those > random quotations postgresql returns to me. Uh...use the csv reader? :) No need to reinvent the parsing wheel. >>> import csv >>> from StringIO import StringIO >>> s = 'a,b,"c",d,"e"' >>> csv.reader(StringIO(s)).next() ['a', 'b', 'c', 'd', 'e'] If you really have the parens in your string too, you can peal them off first with "s[1:-1]" >>> s = '(a,b,"c",d,"e")' >>> csv.reader(StringIO(s[1:-1])).next() ['a', 'b', 'c', 'd', 'e'] or strip any/all parens: >>> s = '(a,b,"c",d,"e")' >>> csv.reader(StringIO(s.lstrip('(').rstrip(')'))).next() ['a', 'b', 'c', 'd', 'e'] -tkc -- http://mail.python.org/mailman/listinfo/python-list
Outbound HTML Authentication
Hi, I was trying to do a simple web scraping tool, but the network they use at work does some type of internal authentication before it lets the request out of the network. As a result I'm getting the '401 - Authentication Error' from the application. I know when I use a web browser or other application that it uses the information from my Windows AD to validate my user before it accesses a website. I'm constantly getting asked to enter in this info before I use Firefox, and I assume that IE picks it up automatically. However I'm not sure how to tell the request that I'm building in my python script to either use the info in my AD account or enter in my user/pass automatically. Anyone know how to do this? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Split a String
Siah ha scritto: > Hi, > > I need to convert the string: '(a, b, "c", d, "e")' into the following > list ['a', 'b', 'c', 'd', 'e']. Much like a csv reader does. I usually > use the split function, but this mini-monster wouldn't properly get > split up due to those random quotations postgresql returns to me. > > Please help me with this, > Thanks, > Sia One solution: >>> s = '(a, b, "c", d, "e")' >>> print [x.strip('" ') for x in s.strip('()').split(',')] ['a', 'b', 'c', 'd', 'e'] -- http://mail.python.org/mailman/listinfo/python-list
Re: Control mouse position and clicking
Glich wrote: > I am running ubuntu. :) I neither asserted differently nor am I competent in clairvoyance. Regards, Björn -- BOFH excuse #93: Feature not yet implemented -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Split a String
Siah wrote: > I need to convert the string: '(a, b, "c", d, "e")' into the > following list ['a', 'b', 'c', 'd', 'e']. Much like a csv reader > does. I usually use the split function, but this mini-monster > wouldn't properly get split up due to those random quotations > postgresql returns to me. I heavily suggest you to look at the docs -- those are very basic functions. http://docs.python.org/lib/string-methods.html One solution might be: >>> results = [] >>> for part in '(a, b, "c", d, "e")'.split(","): ... part = part.strip() ... part = part.strip("(),\"") ... part = part.strip() ... results.append(part) ... >>> print results ['a', 'b', 'c', 'd', 'e'] >>> Regards, Björn -- BOFH excuse #285: Telecommunications is upgrading. -- http://mail.python.org/mailman/listinfo/python-list
Re: Control mouse position and clicking
Robert Kern wrote: > There is an API for it. Not all programs have GUIs so the HIG > doesn't restrict the scope of the OS's APIs. Ah, okay. In (IIRC) wxPython docs, I read differently. Regards, Björn -- BOFH excuse #40: not enough memory, go get system upgrade -- http://mail.python.org/mailman/listinfo/python-list
Re: Outbound HTML Authentication
On Nov 29, 2007 2:22 PM, Mudcat <[EMAIL PROTECTED]> wrote: > Hi, > > I was trying to do a simple web scraping tool, but the network they > use at work does some type of internal authentication before it lets > the request out of the network. As a result I'm getting the '401 - > Authentication Error' from the application. > > I know when I use a web browser or other application that it uses the > information from my Windows AD to validate my user before it accesses > a website. I'm constantly getting asked to enter in this info before I > use Firefox, and I assume that IE picks it up automatically. > > However I'm not sure how to tell the request that I'm building in my > python script to either use the info in my AD account or enter in my > user/pass automatically. > You can configure a proxy for urllib2, but your proxy probably uses NTLM authentication which urllib2 doesn't support. Your best bet is to use a local proxy which understands NTLM. -- http://mail.python.org/mailman/listinfo/python-list
Re: Outbound HTML Authentication
twill is a simple language for browsing the Web. It's designed for automated testing of Web sites, but it can be used to interact with Web sites in a variety of ways. In particular, twill supports form submission, cookies, redirects, and HTTP authentication. Mudcat wrote: > Hi, > > I was trying to do a simple web scraping tool, but the network they > use at work does some type of internal authentication before it lets > the request out of the network. As a result I'm getting the '401 - > Authentication Error' from the application. > > I know when I use a web browser or other application that it uses the > information from my Windows AD to validate my user before it accesses > a website. I'm constantly getting asked to enter in this info before I > use Firefox, and I assume that IE picks it up automatically. > > However I'm not sure how to tell the request that I'm building in my > python script to either use the info in my AD account or enter in my > user/pass automatically. > > Anyone know how to do this? > > Thanks > -- Shane Geiger IT Director National Council on Economic Education [EMAIL PROTECTED] | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -- http://mail.python.org/mailman/listinfo/python-list
Re: Outbound HTML Authentication
Hello, You should probably read the HTTP RFC is you're going to write a screen scraper... but either way. 401 tells you that Auth is required there are several types of "server-based auth" (Different from form based auth)... They include - Basic - Digest - NTLM (or Negotiate) Basic is easy to implement... Digest is slightly more complex... NTLM requires that you have an understanding of how NTLM works in general. There are a couple things you can do... 1. Find a public implementation of NTLM in python (I don't believe one exists... but if it does, I'd love if someone could point it out) 2. Use the NTLM Authentication Proxy Server ( http://www.geocities.com/rozmanov/ntlm/ ) 3. Follow Ronald Tschalär's write-up on NTLM over HTTP and implement it yourself ( http://www.innovation.ch/personal/ronald/ntlm.html ) I actually did the recently for a project that I'm working on... and looked fairly deeply at Ronald's write-up... It is fairly decent... and I may actually implement it at some point in the future as a released Python module... for now though you'll have to do it yourself. -- Tyler Reguly http://www.computerdefense.org On 11/29/07, Mudcat <[EMAIL PROTECTED]> wrote: > > Hi, > > I was trying to do a simple web scraping tool, but the network they > use at work does some type of internal authentication before it lets > the request out of the network. As a result I'm getting the '401 - > Authentication Error' from the application. > > I know when I use a web browser or other application that it uses the > information from my Windows AD to validate my user before it accesses > a website. I'm constantly getting asked to enter in this info before I > use Firefox, and I assume that IE picks it up automatically. > > However I'm not sure how to tell the request that I'm building in my > python script to either use the info in my AD account or enter in my > user/pass automatically. > > Anyone know how to do this? > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Determine whether program was started by clicking icon or command line
Roger Miller wrote: >> I wonder whether there might be a way to find out how a Python >> program was started (in my case in Windows): By double clicking >> the file or by calling it on the "DOS" command line prompt. > > I'm not sure whether this applies to your situation, but often > programs started by clicking an icon are run by pythonw, but when > started from the command line are run by python. If this is the > case sys.stdin.fileno() will return -1 in the former case and 0 > in the latter. Nice idea, but this... import sys print sys.stdin.fileno() raw_input("Press any key to exit") ... always prints "0" in my case ("DOS", double click in Windows Explorer, Cygwin shell). Thanks anyways! Ben -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Split a String
The basic split/strip method wouldn't split '(a, b, "c,...", d)', which is why I chose not to use it. The csv solution seems to work well, that helped me much here (thank you), but I am looking to see if I can get it solved with some regular expression. This is how far I've come so far, but it needs much work: re.compile('"*,"*').split(x[1:-1]) Thanks for your help, Sia On Nov 29, 3:24 pm, Bjoern Schliessmann wrote: > Siah wrote: > > I need to convert the string: '(a, b, "c", d, "e")' into the > > following list ['a', 'b', 'c', 'd', 'e']. Much like a csv reader > > does. I usually use the split function, but this mini-monster > > wouldn't properly get split up due to those random quotations > > postgresql returns to me. > > I heavily suggest you to look at the docs -- those are very basic > functions. > > http://docs.python.org/lib/string-methods.html > > One solution might be: > > >>> results = [] > >>> for part in '(a, b, "c", d, "e")'.split(","): > > ... part = part.strip() > ... part = part.strip("(),\"") > ... part = part.strip() > ... results.append(part) > ...>>> print results > > ['a', 'b', 'c', 'd', 'e'] > > > > Regards, > > Björn > > -- > BOFH excuse #285: > > Telecommunications is upgrading. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Split a String
On 2007-11-29, Grant Edwards <[EMAIL PROTECTED]> wrote: >> One solution: >> >> >>> s = '(a, b, "c", d, "e")' >> >>> print [x.strip('" ') for x in s.strip('()').split(',')] >> ['a', 'b', 'c', 'd', 'e'] > > That fails when a quoted string contains commas: > s = '(a, b, "c", d, "e,f,g")' print [x.strip('" ') for x in s.strip('()').split(',')] > ['a', 'b', 'c', 'd', 'e', 'f', 'g'] > > I presume the correct result would be > > ['a', 'b', 'c', 'd', 'e,f,g'] You can get that result easily with the csv module: >>> repr(ss) '\'a,b,"c",d,"e,f,g"\'' >>> for row in csv.reader([ss],skipinitialspace=True): ... print row ... ['a', 'b', 'c', 'd', 'e,f,g'] -- Grant Edwards grante Yow! I'm not available at for comment.. visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Split a String
Thanks Mr. Edwards, I went ahead and started using the csv reader. Sia -- http://mail.python.org/mailman/listinfo/python-list
Using Windows Apache2triad with python. Need feedback form
I need to process post data from a web feedback form and create an email which will be sent to me. (Something like cgiemail but with python code) Does anyone have suggestions/samples? -- http://mail.python.org/mailman/listinfo/python-list
Accessing a URL file Remotely
I have been given a url of CSV file (http://hostname/dir/file.csv), which when I put the full URL in a web browser shows the contents of the file. I want to be able to use the CSV module to read that file, which I have successfully used with a local CSV file. Any examples anywhere would be appreciated. My basic research suggests URLLIB, but I can not find a suitable example. I do not understand what additional information, needs to be given to the remote site in order for it to expose the contents of the file as though I was reading it locally. Do I need to copy it to my local machine or can I read it directly from the remote site. As you can probably tell, I have never done anything like this, so any help will be gratefully received. Thanks Richard -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Split a String
On 2007-11-29, imho <[EMAIL PROTECTED]> wrote: > Siah ha scritto: >> Hi, >> >> I need to convert the string: '(a, b, "c", d, "e")' into the following >> list ['a', 'b', 'c', 'd', 'e']. Much like a csv reader does. I usually >> use the split function, but this mini-monster wouldn't properly get >> split up due to those random quotations postgresql returns to me. >> >> Please help me with this, >> Thanks, >> Sia > > One solution: > > >>> s = '(a, b, "c", d, "e")' > >>> print [x.strip('" ') for x in s.strip('()').split(',')] > ['a', 'b', 'c', 'd', 'e'] That fails when a quoted string contains commas: >>> s = '(a, b, "c", d, "e,f,g")' >>> print [x.strip('" ') for x in s.strip('()').split(',')] ['a', 'b', 'c', 'd', 'e', 'f', 'g'] I presume the correct result would be ['a', 'b', 'c', 'd', 'e,f,g'] -- Grant Edwards grante Yow! I wonder if I could at ever get started in the visi.comcredit world? -- http://mail.python.org/mailman/listinfo/python-list
Is os.lstat available on all platforms?
Hi there. In a code of mine I'd like to use os.lstat whenever possible. My only concern is if it's available on all platforms. It could be safe using always os.lstat instead of: try: os.lstat except AttributeError: os.stat ...? As far as I know where symlinks are not supported os.lstat should be an alias for os.stat but I'm not 100% sure. -- http://mail.python.org/mailman/listinfo/python-list
Re: setters and getters in python 2.6 and 3.0
> > Hi list, I've been following a discussion on a new way of defining > > getters and setters on python-dev and just can't understand what the > > purpose is. Everybody agreed on the dev list that this is a good idea > > so I guess it must be right :) > > > > The whole thing started with this post of Guido: > > > > http://mail.python.org/pipermail/python-dev/2007-October/075057.html > > > > which then continued into November. Basically, the idea is that using > > the new way a setter can be added to property that was read-only > > before. But if I have this already, > > > > class C: > > @property > > def attr( self ): return self._attr > > > > what prevents me using the following for adding a setter for attr: > > > > class C: > > def attr( self ): return self._attr > > def set_attr( self, value ): self._attr = value > > attr = property( attr, set_attr ) > > > > In other words all I needed to do is delete @property, write the > > setter method and add attr = property( attr, set_attr ). What does the > > new way improve on this? > > It prevents namespace-pollution in a clever way. By first defining the > getter, the @propset-decorator will augment the already createt property > and return it. > > Thus you don't end up with a > > set_attr > > function. > > > Other, more complex recipes to do the same look like this and are much > harder to grasp: > > > @apply > def my_property() > def fget(self): > return self._value > def fset(self, value): > self._value = value > return property(**locals()) > > So the proposed propset-decorator certainly makes things clearer. > > Diez Aha :) Makes sense indeed. Thanks, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Is os.lstat available on all platforms?
Giampaolo Rodola' wrote: > As far as I know where symlinks are not supported os.lstat should be > an alias for os.stat but I'm not 100% sure. You are right, it should be an alias. os.lstat is available on Windows, too. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Is os.lstat available on all platforms?
I'd just want to be sure that even on a strange python implementation I won't ever get an AttributeError exception because os.lstat is not defined. -- http://mail.python.org/mailman/listinfo/python-list
Re: Job posting on the site is broken
sjol <[EMAIL PROTECTED]> writes: > To the webmaster of python.org, > > I have tried to have a job posted on the job board but! Alas, it > doesn't work and I cannot get a response from the webmaster. > > Shall I post here ? No. But, since you say webmaster is not responding, asking here (as you have done) seems the correct next action to find someone responsible for the website. -- \ "Experience is that marvelous thing that enables you to | `\ recognize a mistake when you make it again." -- Franklin P. | _o__)Jones | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Split a String
Grant Edwards ha scritto: >> One solution: >> > s = '(a, b, "c", d, "e")' > print [x.strip('" ') for x in s.strip('()').split(',')] >> ['a', 'b', 'c', 'd', 'e'] > > That fails when a quoted string contains commas: > s = '(a, b, "c", d, "e,f,g")' print [x.strip('" ') for x in s.strip('()').split(',')] > ['a', 'b', 'c', 'd', 'e', 'f', 'g'] > > I presume the correct result would be > > ['a', 'b', 'c', 'd', 'e,f,g'] > Uhm, agree. I supposed quoted strings were presumed to be 'trivial'. Definitely csv module is the solution :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: os.path.islink documentation error?
:) You're right... My skimpy English cheated me. -- http://mail.python.org/mailman/listinfo/python-list
Using marshal to manually "import" a python module
I had a situation recently that required I manually load python bytecode from a .pyc file on disk. So, for the most part, I took code from imputil.py which loads the .pyc data via the marshal module and then exec's it into a newly created module object (created by imp.new_module()). The relevant pieces of code are in imputil.py_suffix_importer and imputil.Importer._process_result (where it exec's the code into the module's __dict__) The strange thing is, it worked fine locally on my two machines (32bit running python 2.3.5 and 64bit running python 2.4.1), but when run by a 64bit machine on the network, it would fail every time in the following manner: My marshal/exec-based loader would load the module from the pyc apparently without problems, but if I then pulled a specific function attr out of the resulting module object, and that function called another function defined within the same module, it would raise a "TypeError: 'NoneType' object is not callable" exception when attempting to call that second function. So the setup is: module blah: def A(): ... def B(): x = A() compiled to bytecode: blah.pyc then, in my program: m = my_marshal_loader("blah.pyc") f = getattr(m,"B") x = f() raises "TypeError: 'NoneType' object is not callable" inside that call to f(), on the line x = A(), as though A is a None and not the function object defined in the module. I can't figure out why this would work locally, but not when the module is loaded across a network. In fact, I have no idea what would ever cause it not to see A as a function. I'm stumped, and this is over my head as far as intimate knowledge of the direct loading of python bytecode via marshal is concerned...so I'm not clear on the best way to debug it. If anyone has an inkling of what might be going on, I'd love to hear it. Thanks in advance, -Dave -- Presenting: mediocre nebula. -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing a URL file Remotely
On Nov 29, 3:13 pm, mcl <[EMAIL PROTECTED]> wrote: > I have been given a url of CSV file (http://hostname/dir/file.csv), > which when I put the full URL in a web browser shows the contents of > the file. > > I want to be able to use the CSV module to read that file, which I > have successfully used with a local CSV file. > > Any examples anywhere would be appreciated. > > My basic research suggests URLLIB, but I can not find a suitable > example. > > I do not understand what additional information, needs to be given to > the remote site in order for it to expose the contents of the file as > though I was reading it locally. > > Do I need to copy it to my local machine or can I read it directly > from the remote site. > > As you can probably tell, I have never done anything like this, so any > help will be gratefully received. > > Thanks > > Richard -untested-- import urllib, csv fp_page = urllib.urlopen("http://URL_of_file";) reader = csv.reader(fp_page) for row in reader: print row Duane -- http://mail.python.org/mailman/listinfo/python-list
Embedding Python - Passing by Reference
I understand the parameters to Python functions are passed by reference: def foo(a): a = a + 1 Will change the value of a in the calling function. How do I implement the equivalent in C when extending Python? I know how to write a function that can be called from Python and I know how to use PyArg_ParseTuple to get the value of a. But how do I update the value of a in C? I tried (greatly simplified): PyObject *a; int value; PyArg_ParseTuple(args, "O", &a); value = PyLong_AsLong(a); value++; a = PyLong_FromLong(value); but this doesn't work. Any suggestions? Note that I am trying to wrap an existing C based API as closely as possible, so I can't return the value using return (this example is greatly simplified and I'm already using the return value for other things). Thanks! Andy -- http://mail.python.org/mailman/listinfo/python-list
Re: A context manager for temporary memoization.
On Nov 29, 3:20 pm, "Michael Speer" <[EMAIL PROTECTED]> wrote: > I posted this to my blog > athttp://michaelspeer.blogspot.com/2007/11/context-manager-for-temporar > > I decided to forward it onto the list for comments. I thought someone > might find it interesting. > > *** > > This is very much a fragile hack at the moment. It's an interesting > idea I think. I was disappointed when I initially found that the > with_statement syntax does not restore the value of the `as var` upon > completion. > > This made doing something along the lines of > >with temporarily_memoized( func ) : > for datum in data : >func( datum ) > > unattainable. > > Well, just a lot hackier actually. > > Thus temporarily_memoized( ... ) was born : > > #!/usr/bin/python > > # a context manager for temporarily turning any function into > # a memoized version of itself. > > from __future__ import with_statement > import contextlib , sys , types > > def memoize ( func ) : > """ In haskell mutability must be handled explicitly. > Only fair that Python do the same to transparent functionality > """ > remembered = {} > def memoized ( *args ) : > """ memoized version of function """ > if args in remembered : >return remembered[ args ] > else : >new = func( *args ) >remembered[ args ] = new >return new > return memoized > > @contextlib.contextmanager > def temporarily_memoized ( func ) : > """ memoize the given function for the duration of this block > save anything in the local variables that gets in the way of > using this so that it can be restored afterward , the memoized > version is found in the locals. use on actual functions only. > no members. """ > > # this is being called, there has to be a frame above it > frame = sys._getframe().f_back.f_back > > if func.func_name in frame.f_locals : > f = frame.f_locals[ func.func_name ] > frame.f_locals[ func.func_name ] = memoize( func ) > try : ># this hack replaces whatever in the local scope ># has the name of the variable. if you try to use ># the 'as whatever' portion of the syntax , you ># are doing it wrong >yield None > finally : >frame.f_locals[ f.func_name ] = f > else : > frame.f_locals[ func.func_name ] = memoize( func ) > try : >yield None > finally : >del frame.f_locals[ func.func_name ] > > def fib(n): > """ biggus fibbus """ > if n == 0 or n == 1: > return n > else: > return fib(n-1) + fib(n-2) > > if __name__ == '__main__' : > print fib.__doc__ > with temporarily_memoized( fib ) : > print fib.__doc__ > for i in xrange( 36 ) : >print "n=%d => %d" % (i, fib(i)) > print fib.__doc__ > print fib.__doc__ > > outputs : > > biggus fibbus > memoized version of function > n=0 => 0 > . > n=35 => 9227465 > memoized version of function > biggus fibbus Did you try to use temporarily_itemized inside a function? It might not work as you think. BTW, the name temporarily_memoized is superfluous. By definition, whatever a context manager does is temporary, so using "temporarily" in the name just adds a lot of letters and tells us nothing we didn't already know. Just call it memoized. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Dynamically adding a runtime generated method to a class.
I'm not sure how to even ask this question. I'm working on a financial reporting application. The current system is very limited in what it can display. You can see reports with columns of Period, Quarter, Year to date or you can see a yearly trend. I'd like for the users to be able to define the columns on the fly but I'm not sure how to do it in Python in the cleanest most efficient manner. The easy way would be to keep a list of class methods like this; #My first attempt class lineClass1: def __init__(self, desc, trend): self.desc = desc self.trend = trend def Ptd(self, per): return self.trend[per] def Ytd(self, per): return sum(self.trend[:per]) def getLine(self, cols, per): # return the descriptionin the first column vals = [self.desc] for col in cols: vals.append(col(self, per)) return vals # create the instance line1 = lineClass1('Some Description', [1,2,3,4,5,6,7,8,9,10,11,12]) # Now I can get the columns out in the order I want by passing in a list of methods cols = [lineClass1.Ptd, lineClass1.Ytd] print line1.getLine(cols, 5) This would work and not be too terribly inefficient but I was thinking it would be much better generate the getLine method at runtime and dynamically add it to the class so I wouldn't have to pass the columns around and loop through them every time; #Define the class with just the trend class lineClass2: def __init__(self, desc, trend): self.desc = desc self.trend = trend def Ptd(self, per): return self.trend[per] def Ytd(self, per): return sum(self.trend[:per]) # # Here, I want to dyamically add a class method that has the return line below defined at runtime # def getLine(self, per): return [self.desc, self.Ptd(per), self.Ytd(per)] # create a couple of instances line = lineClass('Some Description', [1,2,3,4,5,6,7,8,9,10,11,12]) # try it out. print line.getLine(5) Is there any way to dynamically generate the getLine function at runtime? Can the eval statement do that? -- http://mail.python.org/mailman/listinfo/python-list
Yet Another Tabular Data Question
Hi all, Fairly new Python guy here. I am having a lot of trouble trying to figure this out. I have some data on some regulations in Excel and I need to basically add up the total regulations for each country--a statistical analysis thing that I'll copy to another Excel file. Writing with pyExcelerator has been easier than reading with xlrd for me...So that's what I did first, but now I'd like to learn how to crunch some data. The input looks like this: Country Module Topic # of Docs Argentina Food and Consumer Products Cosmetics1 Argentina Food and Consumer Products Cosmetics8 Argentina Food and Consumer Products Food Additives 1 Argentina Food and Consumer Products Food Additives 1 Australia Food and Consumer Products Drinking Water 7 Australia Food and Consumer Products Food Additives 3 Australia Food and Consumer Products Food Additives 1 etc... So I need to add up all the docs for Argentina, Australia, etc...and add up the total amount for each Topic for each country so, Argentina has 9 Cosmetics laws and 2 Food Additives Laws, etc... So, here is the reduced code that can't add anything...Any thoughts would be really helpful. import xlrd import pyExcelerator from pyExcelerator import * #Open Excel files for reading and writing path_file = "c:\\1\\data.xls" book = xlrd.open_workbook(path_file) Counts = book.sheet_by_index(1) wb=pyExcelerator.Workbook() matrix = wb.add_sheet("matrix") #Get all Excel data n=1 data = [] while nhttp://mail.python.org/mailman/listinfo/python-list
Re: Embedding Python - Passing by Reference
On Thu, 29 Nov 2007 14:39:52 -0800 (PST), [EMAIL PROTECTED] wrote: >I understand the parameters to Python functions are passed by >reference: > >def foo(a): > a = a + 1 > >Will change the value of a in the calling function. How do I implement >the equivalent in C when extending Python? You misunderstand how parameters are passed in Python: >>> x = 10 >>> def foo(y): ... y = y + 1 ... >>> foo(x) >>> x 10 >>> So there's no behavior here to attempt to emulate when embedding or extending. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Science list
As I said in response to the original post, there are 200 specialized Python mailing lists accessible for free as newsgroups via news.gmane.org. I think a few are science oriented. -- http://mail.python.org/mailman/listinfo/python-list
Re: Variables and their domain
"Jose Ignacio Gisbert" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] | I have one doubt, in my applciation I have a method (Method1) which has | other method (Method2) inside of it. You have a function inside a function. In Python, methods are functions bound to classes. |Method1 |Lista=a,b,c,d. That makes a tuple, not a list. Do lista = [a,b,c,d] to make a list that you can modify inside an inner function using item or slice assignment or modify-in-place methods |Lb=listbox |Method2 | Lista=e,f,g.. -->error! lista[:] = [e,f,g] will replace the contents of lista Good luck. tjr -- http://mail.python.org/mailman/listinfo/python-list