accessor/mutator functions
When I look at how classes are set up in other languages (e.g. C++), I often observe the following patterns: 1) for each data member, the class will have an accessor member function (a Get function) 2) for each data member, the class will have a mutator member function (a Set function) 3) data members are never referenced directly; they are always referenced with the accessor and mutator functions My questions are: a) Are the three things above considered pythonic? b) What are the tradeoffs of using getattr() and setattr() rather than creating accessor and mutator functions for each data member? -- http://mail.python.org/mailman/listinfo/python-list
Re: Default value for Listbox (Tkinter)
Thanks Jorgen! I was reading the Tkinter tutorial (I was looking at this particular page: http://www.pythonware.com/library/tkinter/introduction/x5513-methods.htm) and saw this for select_set(): select_set(index), select_set(first, last) Add one or more items to the selection. I think this was why I overlooked it. The description for it says the listbox adds one or more items to a selection. I would think the description should say the listbox sets the index or element. Thanks again, Harlin -- http://mail.python.org/mailman/listinfo/python-list
Re: accessor/mutator functions
[EMAIL PROTECTED] wrote: When I look at how classes are set up in other languages (e.g. C++), I often observe the following patterns: 1) for each data member, the class will have an accessor member function (a Get function) 2) for each data member, the class will have a mutator member function (a Set function) 3) data members are never referenced directly; they are always referenced with the accessor and mutator functions My questions are: a) Are the three things above considered pythonic? No b) What are the tradeoffs of using getattr() and setattr() rather than creating accessor and mutator functions for each data member? Use property descriptors instead: http://www.python.org/2.2.1/descrintro.html#property http://users.rcn.com/python/download/Descriptor.htm#properties Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython tutorials
Raghul, The second link Harlin gave is to the wxPython wiki - it has a variety of pages with information about the toolkit including a number of tutorial pages. The "Getting Started" document linked on the main page is pretty thorough. Once you comfortable with some of the basic concepts, I'd suggest looking through the wxPython demo code. Find something interesting in the demo, then look at the associated "Demo Code" tab to see how it's implemented. In case you have any questions, the wxpython-users list is a great source of information for wxpython beginners as well as more advanced users. It's archived in a few different locations (some are easier to read or search than others): Via wxwidgets.org http://lists.wxwidgets.org/cgi-bin/ezmlm-cgi/11 Via ActiveState http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/wxPython-users Via Gmane http://dir.gmane.org/gmane.comp.python.wxpython -- http://mail.python.org/mailman/listinfo/python-list
Re: web status display for long running program
> I was inspired to enhance your code, and perform a critical bug-fix. > Your code would not have sent large files out to dialup users, because > it assumed all data was sent on the 'send' command. I added code to > check for the number of bytes sent, and loop until it's all gone. Another solution is to simply use the socket.sendall method, which will continue to send all data until all the bytes have been sent. Sw. -- http://mail.python.org/mailman/listinfo/python-list
Re: accessor/mutator functions
> My questions are: > a) Are the three things above considered pythonic? Python uses a function called 'property to achieve the same effect. This example is taken from the documentation: class C(object): def __init__(self): self.__x = 0 def getx(self): return self.__x def setx(self, x): if x < 0: x = 0 self.__x = x x = property(getx, setx) In the above example, "C().x" would invoke and return the result of .getx (the accessor), and "C().x = 10" would invoke .setx (the mutator). Are they considered Pythonic? Well, It depends on how they are used. If you are using properties to perform some kind of type checking... then the answer is probably No. I've found that they are quite useful for implementing lazy evaluation of attributes, which I would consider quite Pythonic. Sw. -- http://mail.python.org/mailman/listinfo/python-list
Re: duplicate file finder
On Thu, 24 Feb 2005 15:32:03 -0800, rumours say that Lowell Kirsh <[EMAIL PROTECTED]> might have written: >It looks pretty good, but I'll have to take a better look later. Out of >curiosity, why did you convert the first spaces to pipes rather than add >the code as an attachment? (As you probably noticed, the pipes ended up as dots in the final version, but I forgot to change the text.) I considered the code to be small enough to leave it in the message. And using some non-space character at the start of every line (usually dots) is common use lately in the group. Even if one doesn't use vi for editing, it's easiest with Idle to remove the dot at the start of every line. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Python Online Programming Contest
Hi Friends, Department of Information Technology, Madras Institute of Technology, Anna University, India is conducting a technical symposium, Samhita. As a part of samhita, an Online Programming Contest is scheduled on Sunday, 27 Feb 2005. This is the first Online Programming Contest in India to support Python . Other languages supported are C and C++. For Registration and Rules of the contest, http://www.samhita.info/opc For details about samhita http://www.samhita.info/ Regards, -Online Programming Contest team -- http://mail.python.org/mailman/listinfo/python-list
Python Online Programming Contest
Hi Friends, Department of Information Technology, Madras Institute of Technology, Anna University, India is conducting a technical symposium, Samhita. As a part of samhita, an Online Programming Contest is scheduled on Sunday, 27 Feb 2005. This is the first Online Programming Contest in India to support Python . Other languages supported are C and C++. For Registration and Rules of the contest, http://www.samhita.info/opc For details about samhita http://www.samhita.info/ Regards, -Online Programming Contest team -- http://mail.python.org/mailman/listinfo/python-list
auto-completion history
Hi Folks, I have auto-completion set up in my python interpreter so that if I hit the tab key it will complete a variable or a python command*. eg. if I type >>> imp and if I then hit the tab key, the interpreter will complete it to... >>> import Now, I also use Matlab at the command line a lot and it has a nice additional auto-completion feature, whereby, if you type a few letters and hit the up-arrow, it will go back to the last command you typed that began with those letters. If you keep hitting up-arrow it will cycle through all the commands you typed beginning with these letters. eg. if I type... >>> import datetime >>> import sys >>> today = datetime.date.today() >>> imp After typing the last imp I hit up-arrow once I would like the history to return to >>> import sys and if I hit twice, I would like to go to >>> import datetime Does a feature like this already exist in python??? Thanks The PorterBoy - "Lovely day for a Guinness" ps... * If you are unsure how to set up auto completion (UNIX only) ... 1. Include this line in your .tcshrc file (or equivalent in .bashrc): setenv PYTHONSTARTUP "$HOME/.pythonrc.py" 2. In the file ~/.pythonrc.py include the lines: import rlcompleter, readline readline.parse_and_bind('tab: complete') del rlcompleter, readline 3. For the effect to work, open a new terminal, and type python. If you do not fire up a new session, python has no way to become aware of your changes. -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython tutorials
Raghul wrote: > hi, > > I want to learn Wxpython to work in windows.Is there any tutorials > available?Pls specify the link that will be easy to learn for beginers > like me I'm just learning wxPython, but rather than do it directly I'm using wax. wax is another layer that sits on top of wxPython and greatly simplifies using it in practise. It's written by Hans Nowak and you can find it over at http://zephyrfalcon.org The documentation sin't brilliant (but improving), but the examples are very good. I'm finding it quite easy - but I did learn Tkinter first, so I'm familiar with concepts like parent frames, event oriented programming, call backs, packing widgets, etc. YMMV :-) Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: wanted: C++ parser written in Python
On Fri, 25 Feb 2005 15:10:06 +0800, "mep" <[EMAIL PROTECTED]> wrote: >Try ANTLR with python code generation: >http://www.antlr.org/ > >And C++ grammers: >http://www.antlr.org/grammar/cpp > >You can generate a c++ parser in python with the above. Thank you, but it is too big. Anyway: I'm looking for some (simple) "rules" to parse (regex) and try to implement myself, if nothing is available. It don't have to be perfect. Maybe I look for some code in for example Dev-Cpp from Bloodshed (there is also a c++ class browser). -- Franz Steinhaeusler -- http://mail.python.org/mailman/listinfo/python-list
how to use property
My question is how should I use "property" which wraps up (B__get_channel() and __set_channel()in the following program. (BI tried the program that written below, and it worked. Then I tried: (Bchannel = property(__get_channel,__set_channel) as in comment 1, 2, (Band 3, (B (Bbut it generates the error: (BTraceback (most recent call last): (B File "C:/WINDOWS/desktop/test.py", line 41, in -toplevel- (Bmain() (B File "C:/WINDOWS/desktpo/test.py", line 37, in main (Btv.change_channel(choice) (B File "C:/WINDOWS/desktop/test.py", line 27, in change_channel (Bself.channel(choice) (BTypeError: 'int' object is not callable (B (BI am now studying class, so want to use property. (BThis program simulates changing channel number 1 through 10 on TV. (BHow should I use property here? (B (B--- (B##simulating a TV (B (B##defining class (Bclass TV(object): (Bdef __init__(self, channel = 1): (Bself.__channel = channel (Bself.__volume = volume (Bprint "the default channel is", self.__channel (B (Bdef __get_channel(self): (Breturn self.__channel (B (Bdef __set_channel(self, choice): (Bif choice == "+": (Bself.__channel += 1 (Belif choice == "-": (Bself.__channel -= 1 (Bif self.__channel == 0: (Bself.__channel = 10 (Belif self.__channel == 11: (Bself.__channel = 1 (B (B#comment1: channel = property(__get_channel, __set_channel) (B (Bdef change_channel(self, choice): (Bself.__set_channel(choice) (Bprint self.__get_channel() (B (B#comment2: self.channel(choice) (B#comment3: print "channel: ", self.channel (B (B (B##main part (Bdef main(): (Btv = TV() (Bchoice = " " (Bwhile choice: (Bchoice = raw_input("choice (+ / -): ") (Btv.change_channel(choice) (B (B (B##starting program (Bmain() (B (B-- (Bhttp://mail.python.org/mailman/listinfo/python-list
automatic nesting and indentation in emacs
CONTEXT: I am using Emacs to edit Python code and sometimes also Matlab code. When I hit in a loop of some sort, Emacs usually gets the nesting indentation right, which is particularly important in Python. To ensure this I have used python-mode.el and matlab.el modes in emacs. QUESTION: If I suddenly decide I want an outer loop, do I have to manually readjust the indentation of all the inner loops? Or can emacs do it automatically? I know the Matlab in-built editor has a tool called "smart-indent" which will automatically align highlighted text to have the correct indentation. Does Emacs have something similar? Thanks The Porterboy - "Lovely day for a Guinness" -- http://mail.python.org/mailman/listinfo/python-list
Re: wanted: C++ parser written in Python
> "Franz" == Franz Steinhaeusler <[EMAIL PROTECTED]> writes: Franz> Thank you, but it is too big. Franz> Anyway: Franz> I'm looking for some (simple) "rules" to parse (regex) and Franz> try to implement myself, if nothing is available. Check out http://pyparsing.sourceforge.net/ Before you start implementing one yourself. Regexp solution would probably be a bit flakier. And do share your results when you get some; I'm in need of a c++ parser myself. -- Ville Vainio http://tinyurl.com/2prnb -- http://mail.python.org/mailman/listinfo/python-list
Re: Shift Confusion
Hi Kamilche, Aside from the 7bit confusion you should take a look at the 'struct' module. I bet it will simplify your life considerably. #two chars >>> import struct >>> struct.pack('cc','A','B') 'AB' #unsigned short + two chars >>> struct.pack('Hcc',65535,'a','b') '\xff\xffab' Cheers Lars -- http://mail.python.org/mailman/listinfo/python-list
Re: automatic nesting and indentation in emacs
[EMAIL PROTECTED] (porterboy) writes: > CONTEXT: > I am using Emacs to edit Python code and sometimes also Matlab code. > When I hit in a loop of some sort, Emacs usually gets the > nesting indentation right, which is particularly important in Python. > To ensure this I have used python-mode.el and matlab.el modes in > emacs. > > QUESTION: > If I suddenly decide I want an outer loop, do I have to manually > readjust the indentation of all the inner loops? Or can emacs do it > automatically? I know the Matlab in-built editor has a tool called > "smart-indent" which will automatically align highlighted text to have > the correct indentation. Does Emacs have something similar? Mark the lines to be readjusted, then hit 'C-c >' or 'C-c <'. Or hit 'C-h m' to get an overview for Python mode. Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: wanted: C++ parser written in Python
On 25 Feb 2005 12:38:53 +0200, Ville Vainio <[EMAIL PROTECTED]> wrote: Hello Ville, >> "Franz" == Franz Steinhaeusler <[EMAIL PROTECTED]> writes: > >Franz> Thank you, but it is too big. > >Franz> Anyway: > >Franz> I'm looking for some (simple) "rules" to parse (regex) and >Franz> try to implement myself, if nothing is available. > >Check out > >http://pyparsing.sourceforge.net/ Thank you for this information! Also a little to complicated, I'm looking for a quick solution. > >Before you start implementing one yourself. Regexp solution would >probably be a bit flakier. And do share your results when you get >some; I'm in need of a c++ parser myself. I don't want to scan a whole project, only the currently open file. class definition method/function ignore comment lines show #includes would be enough at first. I will inform again :) -- Franz Steinhaeusler -- http://mail.python.org/mailman/listinfo/python-list
Re: web status display for long running program
This is fun, so I will give my solution too (of course, the effort here is to give the shortest solution, not the more robust solution ;). This is the server program, which just counts forever: from threading import Thread from CGIHTTPServer import test import os class Counter(Thread): def run(self): n = 0 self.loop = True while self.loop: n += 1 os.environ["COUNTER"] = str(n) def stop(self): self.loop = False if __name__ == "__main__": counter = Counter() counter.start() try: test() finally: # for instance, if CTRL-C is called counter.stop() And this is the CGI viewer: #!/usr/bin/python import os print "Content-type: text/plain\n" print "Counter: %s" % os.environ["COUNTER"] Pretty bare-bone ;) Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
xhtml-print parser
my question is i have parsed the xhtml data stream using c i need to diplay the content present in the command prompt as the data present in the webpage as links how it can be done? -- http://mail.python.org/mailman/listinfo/python-list
Re: Trees
Would this be for a GUI toolkit or maybe using a standard class scheme? -- http://mail.python.org/mailman/listinfo/python-list
Re: wanted: C++ parser written in Python
> "Franz" == Franz Steinhaeusler <[EMAIL PROTECTED]> writes: Franz> On 25 Feb 2005 12:38:53 +0200, Ville Vainio <[EMAIL PROTECTED]> wrote: Franz> Hello Ville, >>> "Franz" == Franz Steinhaeusler >>> <[EMAIL PROTECTED]> writes: >> Franz> Thank you, but it is too big. >> Franz> Anyway: >> Franz> I'm looking for some (simple) "rules" to parse (regex) and Franz> try to implement myself, if nothing is available. >> >> Check out >> >> http://pyparsing.sourceforge.net/ Franz> Thank you for this information! Franz> Also a little to complicated, I'm looking for a quick Franz> solution. >> >> Before you start implementing one yourself. Regexp solution >> would probably be a bit flakier. And do share your results when >> you get some; I'm in need of a c++ parser myself. Franz> I don't want to scan a whole project, only the currently Franz> open file. Franz> class definition method/function ignore comment lines show Franz> #includes would be enough at first. Franz> I will inform again :) Franz> -- Franz Steinhaeusler In the "instant gratification" department, there is Emacs with the Emacs Code Browser interface. ECB contains a C++ parser done in Lisp. If you need to extract things, there is a PyMacs interface that works quite well. See http://www.emacswiki.org for details. Given the "power, performance, ease of use; pick any two" cliché, we're clearly ditching the middle one with this approach. :) Best, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Interesting decorator use.
> "Tom" == Tom Willis <[EMAIL PROTECTED]> writes: Tom> Pretty slick that python can have AOP-like features sort of Tom> out of the box. One wonders if there will not be py>import AOP in the pythonic future. These decorators could lead to byzantine trees of @. Now, if the decorators start writing code on the fly, shall python have achieved Lisp macros? Best, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: xhtml-print parser
[EMAIL PROTECTED] wrote: my question is i have parsed the xhtml data stream using c That's not a question. And this is a language for discussing Python, not C. i need to diplay the content present in the command prompt as the data present in the webpage as links how it can be done? http://www.catb.org/~esr/faqs/smart-questions.html -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
ANN: Leo 4.3-a3 Outlining IDE
Leo 4.3 alpha 3 is now available at http://sourceforge.net/projects/leo/ Leo 4.3 is the culmination of more than five months of work. This alpha 3 release corrects various bugs in Leo's core and in plugins. This is the first release that include an installer for MacOSX. The defining features of Leo 4.3: - 1. Leo now stores options in @settings trees, that is, outlines whose headline is '@settings'. When opening a .leo file, Leo looks for @settings trees not only in the outline being opened but also in various leoSettings.leo files. Users can create arbitrarily complex user options with @settings trees. Leo settings outlines are, in fact, infinitely more flexible and powerful than any scheme based on flat text. Readers of Python's configParser shootout take note. 2. The Preferences command temporarily replaces the outline pane with an outline showing all the @settings trees in effect. The Preferences command also replaces the body pane with a "settings pane". This settings pane allows you to change the settings selected in the outline pane using standard gui widgets. 3. Leo's read/write code in leoAtFile.py has been rewritten to support user-defined tangling and untangling. This is a major cleanup of Leo's core. 4. Leo now boasts an excellent Plugins Manager plugin. This plugin enables and disables plugins automatically and tells you everything you need to know about each plugin. This plugin also lets you download plugins from Leo's cvs site. 5. You can install third-party extensions in Leo's extensions directory. Leo will attempt to import such extensions from the extensions directory when normal imports fail. The distribution contains Python Mega Widgets in the extensions directory. What people are saying about Leo "[Leo] should either replace or greatly augment the development tools that I use." -- Zak Greant "Leo is a marriage of outlining and literate programming. Pure genius. The main reason I am impressed with this tool is that it doesn't affect your choice of tools. You can use whatever IDE for whatever language and switch back and forth between Leo and it." -- Austin King "Leo is the best IDE that I have had the pleasure to use. I have been using it now for about 2--3 months. It has totally changed not only the way that I program, but also the way that I store and organize all of the information that I need for the job that I do." -- Ian Mulvany "I only have one week of Leo experience but I already know it will be my default IDE/project manager...people complain about the lack of a project manager for the free/standard Python IDE's like Idle. Leo clearly solves that problem and in a way that commercial tools can't touch." -- Marshall Parsons "[Leo has] become my main development platform, and I do this for a living. -- Nicola Larosa "I have been using Leo for about 3 weeks and I hardly use my other programming editor anymore...I find it easy and enjoyable to use. I plan to adopt it as my presentation tool for code reviews." -- Jim Vickroy "I'm absolutely astounded by the power of such a simple idea! It works great and I can immediately see the benefits of using Leo in place of the standard flat file editor." -- Tom Lee, <[EMAIL PROTECTED]> I think you're really showing what open source can do and your current trajectory puts you on track to kick Emacs into the dustbin of computing history. -- Dan Winkler More quotes at: http://webpages.charter.net/edreamleo/testimonials.html What makes Leo special? --- - Leo's outlines add a new dimension to programming. - Leo shows you your code and data the way _you_ want to see them. - Leo extends, completes and simplifies literate programming. - Leo's script buttons bring scripts to data. What is Leo? - A programmer's editor, an outlining editor and a flexible browser. - A literate programming tool, compatible with noweb and CWEB. - A data organizer and project manager. Leo provides multiple views of projects within a single outline. - Fully scriptable using Python. Leo saves its files in XML format. - Portable. leo.py is 100% pure Python. - Open Software, distributed under the Python License. Leo requires Python 2.2.1 or above and tcl/tk 8.4 or above. Leo works on Linux, Windows and MacOs X. Links: -- Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://sourceforge.net/cvs/?group_id=3458 Quotes: http://webpages.charter.net/edreamleo/testimonials.html Wiki: http://leo.hd1.org/ Edward K. Ream Edward K. Ream email: [EMAIL PROTECTED] Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -- http://mail.python.org/mailman/l
Re: Leo 4.3-a3 Outlining IDE
I really only posted this once to comp.lang.python. The duplicate appears to be the work of the Department of Redundancy Department. Edward Edward K. Ream email: [EMAIL PROTECTED] Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -- http://mail.python.org/mailman/listinfo/python-list
Re: automatic nesting and indentation in emacs
> Thomas Heller <[EMAIL PROTECTED]> writes: > [EMAIL PROTECTED] (porterboy) writes: >> CONTEXT: I am using Emacs to edit Python code and sometimes >> also Matlab code. When I hit in a loop of some sort, >> Emacs usually gets the nesting indentation right, which is >> particularly important in Python. To ensure this I have used >> python-mode.el and matlab.el modes in emacs. >> >> QUESTION: If I suddenly decide I want an outer loop, do I have >> to manually readjust the indentation of all the inner loops? Or >> can emacs do it automatically? I know the Matlab in-built >> editor has a tool called "smart-indent" which will >> automatically align highlighted text to have the correct >> indentation. Does Emacs have something similar? > Mark the lines to be readjusted, then hit 'C-c >' or 'C-c <'. > Or hit 'C-h m' to get an overview for Python mode. > Thomas I've liked the XEmacs python mode, as it is doesn't trigger the nasty readline dependency. Possibly fixed. At any rate, with a region selected, "C-c >" and "C-c <" do the obvious. Two other killer features of the One True Editor are rectangles, e.g. "C-x r o" with a highlighted region, align-regexp, and registers. Three! Three killer features of TOTE are rectangles, align-regexp, registers, and PyMacs. Oh! I'll just give up on the feeble Spanish Inquisition reference and send you to http://www.emacswiki.org , where these and other righteous goodies will, indeed, sanctify you within the bosom of the only editor that has its own house of worship. Best, Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: Vectors in Visual Python
FLChamp wrote: > If anything was addressed to my problem then it has completely passed > me by as most points were clearly made by a computer scientist and I am > not one of those in the slightest. My experience of using any type of > programming language is limited to the little we are taught in my > non-computing subject and hence I have no idea what the below is all > about!! In future example code may be more useful to help newbies like > me :) I think it has been addressed, by Art: """ My understanding: is that VPython "vectors" are in effect flat 3 element Numeric arrays, and Numeric ararys can be constructed with Float64 specified as the datatype. """ It was embedded in some disgressing comments (he himself says so, btw.) so you might have missed it. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: Trees
Alex Le Dain wrote: > Is there a generic "tree" module that can enable me to sort and use > trees (and nodes). Basically having methods such as .AddNode(), > .GetAllChildren(), .FindNode() etc. > > Is this handled natively with any of the core modules? > > cheers, Alex. > > -- > Poseidon Scientific Instruments Pty Ltd > 1/95 Queen Victoria St > FREMANTLE WA, AUSTRALIA > > Ph: +61 8 9430 6639 Fx: +61 8 9335 4650 > Website: www.psi.com.au > > PSI, an ISO-9001 Company > > CONFIDENTIALITY: The contents of this email (and any attachments) are > confidential and may contain proprietary and/or copyright material of > Poseidon Scientific Instruments Pty Ltd (PSI) or third parties. You may > only reproduce or distribute the material if you are expressly > authorised to do so. If you are not the intended recipient, any use, > disclosure or copying of this email (and any attachments) is > unauthorised. If you have received this email in error, please > immediately delete it and any copies of it from your system and notify > PSI by return email to sender or by telephone on +61 (08) 9430 6639. > > DISCLAIMER: You may only rely on electronically transmitted documents when: > (a) those documents are confirmed by original documents signed by an > authorised employee of PSI; and/or > (b) the document has been confirmed and checked against a hard copy > of that document provided by PSI. > > VIRUSES: PSI does not represent or warrant that files attached to this > e-mail are free from computer viruses or other defects. Any attached > files are provided, and may only be used, on the basis that the user > assumes all responsibility for any loss or damage resulting directly or > indirectly from such use. PSI's liability is limited in any event to > either the re-supply of the attached files or the cost of having the > attached files re-supplied. Long sig !! :-) Try elemtree by the F-bot Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: auto-completion history
porterboy wrote: > Hi Folks, > > I have auto-completion set up in my python interpreter so that if I > hit the tab key it will complete a variable or a python command*. eg. > if I type > >>> imp > and if I then hit the tab key, the interpreter will complete it to... > >>> import > > Now, I also use Matlab at the command line a lot and it has a nice > additional auto-completion feature, whereby, if you type a few > letters and hit the up-arrow, it will go back to the last command > you typed > that began with those letters. If you keep hitting > up-arrow it will cycle through all the commands you typed beginning > with these letters. eg. if I type... > > Does a feature like this already exist in python??? It's not in python, it's in readline library. To read the documentation do 'man readline' readline.parse_and_bind('"\e[A": history-search-backward') works for me. To find out what your up arrow key sends remove \e[A and hit on your keyboard Control-v and then up arrow. Serge. -- http://mail.python.org/mailman/listinfo/python-list
Re: Trees
Alex Le Dain wrote: > Is there a generic "tree" module that can enable me to sort and use > trees (and nodes). Basically having methods such as .AddNode(), > .GetAllChildren(), .FindNode() etc. No. Usually, one uses the built-in python datastructures for this. E.g. ('root', [('child1', None), ('child2', None)]) Or writing a Node-class is also so straightforward that few care about them being part of the core: class Node(object): def __init__(self, payload, childs=None): self.payload = payload self.childs = childs def depth_first(self): if self.childs: for child in self.childs: for node in child.depth_first(): yield node yield self.payload tree = Node('root', [Node('child1'), Node('child2')]) for n in tree.depth_first(): print n -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython tutorials
Raghul said the following on 2/25/2005 12:24 AM: hi, I want to learn Wxpython to work in windows.Is there any tutorials available?Pls specify the link that will be easy to learn for beginers like me Raghul - If you have the patience, you can look at the demo source code. A good thing about the latest wxPython Demo version is that you can change the demo code in the *running* demo and execute the changed code to to see the results right away. I love that feature! So, my suggestion to you is to start reading tutorials. A nice tutorial to get your feet wet is http://www-106.ibm.com/developerworks/library/l-wxpy/ Once you feel comfortable with drawing a basic frame with a menu bar and able to handle events, you can build complex apps using a demo as your guide. Also, there is a weapon in your arsenal in the form of the wxWidgets Help Manual that is installed with wxPython. It is geared towards the wxWidget C++ library but the information can be used to build wxPython apps rather easily. The Help also annotates differences between the C++ class and wxPython (and wxPerl) usage where approporiate. Have fun! -Kartic -- http://mail.python.org/mailman/listinfo/python-list
Re: Trees
[Alex Le Dain] > Is there a generic "tree" module that can enable me to sort and use > trees (and nodes). Basically having methods such as .AddNode(), > .GetAllChildren(), .FindNode() etc. > Is this handled natively with any of the core modules? Using only standard Python, look at the suite of `xml...' modules. > cheers, Alex. P.S. - Your signature and company disclaimer use more than 30 lines. That's really a lot. I hope you can bring them down to reason! :-) -- François Pinard http://pinard.progiciels-bpi.ca -- http://mail.python.org/mailman/listinfo/python-list
Re: how to use property
try this: self.channel = choice -- http://mail.python.org/mailman/listinfo/python-list
strange SyntaxError
Hi, I wrote this sample piece of code: def main(): lambda x: 'ABC%s' % str(x) for k in range(2): exec('print %s' % k) main() With the lambda line, I get this: SyntaxError: unqualified exec is not allowed in function 'main' it contains a nested function with free variables Without the lambda, it's ok... What's this ? thanks -- A t t i l a :: [EMAIL PROTECTED] :: S z a b o -- http://mail.python.org/mailman/listinfo/python-list
split a directory string into a list
QUESTION: How do I split a directory string into a list in Python, eg. '/foo/bar/beer/sex/cigarettes/drugs/alcohol/' becomes ['foo','bar','beer','sex','cigarettes','drugs','alcohol'] I was looking at the os.path.split command, but it only seems to separate the filename from the path (or am I just using it wrong?). I don't want to do it manually if I can help it, as there will have to be exceptions for the cases where there is (not) a trailing (leading) slash, or escape sequences involving /. Is there a built in command for this? -- http://mail.python.org/mailman/listinfo/python-list
Re: xhtml-print parser
Michael Hoffman wrote: [EMAIL PROTECTED] wrote: my question is i have parsed the xhtml data stream using c That's not a question. And this is a language for discussing Python, not C. Whoa, there! Ease off that trigger-finger, pardner ... i need to diplay the content present in the command prompt as the data present in the webpage as links how it can be done? Looks like a question to me ... http://www.catb.org/~esr/faqs/smart-questions.html Consider that the OP might want to pass the C parser output to a Python web-content generator, which would make a deal of sense. regards Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: split a directory string into a list
[EMAIL PROTECTED] wrote: QUESTION: How do I split a directory string into a list in Python, eg. '/foo/bar/beer/sex/cigarettes/drugs/alcohol/' becomes ['foo','bar','beer','sex','cigarettes','drugs','alcohol'] >>> '/foo/bar/beer/sex/cigarettes/drugs/alcohol/'.strip('/').split('/') ['foo', 'bar', 'beer', 'sex', 'cigarettes', 'drugs', 'alcohol'] Kent I was looking at the os.path.split command, but it only seems to separate the filename from the path (or am I just using it wrong?). I don't want to do it manually if I can help it, as there will have to be exceptions for the cases where there is (not) a trailing (leading) slash, or escape sequences involving /. Is there a built in command for this? -- http://mail.python.org/mailman/listinfo/python-list
Re: how to use property
[EMAIL PROTECTED] said the following on 2/25/2005 5:25 AM: (B> My question is how should I use "property" which wraps up (B> __get_channel() and __set_channel()in the following program. (B> I tried the program that written below, and it worked. Then I tried: (B> channel = property(__get_channel,__set_channel) as in comment 1, 2, (B> and 3, (B> (B> but it generates the error: (B> Traceback (most recent call last): (B> File "C:/WINDOWS/desktop/test.py", line 41, in -toplevel- (B> main() (B> File "C:/WINDOWS/desktpo/test.py", line 37, in main (B> tv.change_channel(choice) (B> File "C:/WINDOWS/desktop/test.py", line 27, in change_channel (B> self.channel(choice) (B> TypeError: 'int' object is not callable (B> (B> I am now studying class, so want to use property. (B> This program simulates changing channel number 1 through 10 on TV. (B> How should I use property here? (B> (B> def change_channel(self, choice): (B> self.__set_channel(choice) (B> print self.__get_channel() (B> (B> #comment2: self.channel(choice) (B (B (BYou see comment#2... You say self.channel(choice). self.channel is an (Bint object that you are trying to call - channel(choice) - and that is (Bwhat your exception states when it says 'int object is not callable'. (B (BYou probably meant self.channel = choice (B (BAlso, there is a problem in your posted version. You have not defined (Bvolume before usage. So I added it to __init__(..,.., volume=120) to (Bmake it work. (B (BCheers, (B-Kartic (B-- (Bhttp://mail.python.org/mailman/listinfo/python-list
genetic algorithms
Could anyone recommend me a genetic algorithm package? So far I have found a few, such as GAS, pyGP, Genetic, and of course scipy.ga My problem is that most of the development of these packages seems to be stalled, or that in scipy.ga's case, the module seems huge and somewhat overly complicated. Could someone recommend me a module, which is still being developed, somewhat more concurrent than the stuff I'm finding? Any recommendations, since most of these modules seem to be more projects developed in sake of grasping GA's rather than actually using these ;-) Cheers, Jelle. -- http://mail.python.org/mailman/listinfo/python-list
Re: automatic nesting and indentation in emacs
In emacs matlab-mode, highlight a region then use indent-region: C-M-\ runs the command indent-region which is an interactive compiled Lisp function in `indent'. (indent-region START END COLUMN) Indent each nonblank line in the region. With prefix no argument, indent each line using `indent-according-to-mode', or use `indent-region-function' to do the whole region if that's non-nil. If there is a fill prefix, make each line start with the fill prefix. With argument COLUMN, indent each line to that column. When you call this from a program, START and END specify the region to indent, and COLUMN specifies the indentation column. If COLUMN is nil, then indent each line according to the mode. porterboy wrote: CONTEXT: I am using Emacs to edit Python code and sometimes also Matlab code. When I hit in a loop of some sort, Emacs usually gets the nesting indentation right, which is particularly important in Python. To ensure this I have used python-mode.el and matlab.el modes in emacs. QUESTION: If I suddenly decide I want an outer loop, do I have to manually readjust the indentation of all the inner loops? Or can emacs do it automatically? I know the Matlab in-built editor has a tool called "smart-indent" which will automatically align highlighted text to have the correct indentation. Does Emacs have something similar? Thanks The Porterboy - "Lovely day for a Guinness" -- http://mail.python.org/mailman/listinfo/python-list
RE: split a directory string into a list
I would start with something like this: somestring = '/foo/bar/beer/sex/cigarettes/drugs/alcohol/' somelist = somestring.split('/') print somelist This is close to what you seem to want. Good luck. *gina* -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Sent: Friday, February 25, 2005 8:36 AM To: python-list@python.org Subject: split a directory string into a list QUESTION: How do I split a directory string into a list in Python, eg. '/foo/bar/beer/sex/cigarettes/drugs/alcohol/' becomes ['foo','bar','beer','sex','cigarettes','drugs','alcohol'] I was looking at the os.path.split command, but it only seems to separate the filename from the path (or am I just using it wrong?). I don't want to do it manually if I can help it, as there will have to be exceptions for the cases where there is (not) a trailing (leading) slash, or escape sequences involving /. Is there a built in command for this? -- http://mail.python.org/mailman/listinfo/python-list
Re: xhtml-print parser
Steve Holden wrote: Consider that the OP might want to pass the C parser output to a Python web-content generator, which would make a deal of sense. You're welcome to guess what the OP wants to do, but I'm not going to. If he or she asks a coherent question it will probably be answered. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: split a directory string into a list
On 25 Feb 2005, at 14:09, Harper, Gina wrote: I would start with something like this: somestring = '/foo/bar/beer/sex/cigarettes/drugs/alcohol/' somelist = somestring.split('/') print somelist However - this will not work on Windows. It'd work on all the OS I usually use though ;) Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: web status display for long running program
Not exactly on point, but this is what I use in many of my programs to show progress on long running console apps. Larry Bates class progressbarClass: def __init__(self, finalcount, progresschar=None): import sys self.finalcount=finalcount self.blockcount=0 # # See if caller passed me a character to use on the # progress bar (like "*"). If not use the block # character that makes it look like a real progress # bar. # if not progresschar: self.block=chr(178) else:self.block=progresschar # # Get pointer to sys.stdout so I can use the write/flush # methods to display the progress bar. # self.f=sys.stdout # # If the final count is zero, don't start the progress gauge # if not self.finalcount : return self.f.write('\n-- % Progress ---1\n') self.f.write('1234567890\n') self.f.write('0000000000\n') return def progress(self, count): # # Make sure I don't try to go off the end (e.g. >100%) # count=min(count, self.finalcount) # # If finalcount is zero, I'm done # if self.finalcount: percentcomplete=int(round(100*count/self.finalcount)) if percentcomplete < 1: percentcomplete=1 else: percentcomplete=100 #print "percentcomplete=",percentcomplete blockcount=int(percentcomplete/2) #print "blockcount=",blockcount if blockcount > self.blockcount: for i in range(self.blockcount,blockcount): self.f.write(self.block) self.f.flush() if percentcomplete == 100: self.f.write("\n") self.blockcount=blockcount return if __name__ == "__main__": from time import sleep pb=progressbarClass(8,"*") count=0 while count<9: count+=1 pb.progress(count) sleep(0.2) pb=progressbarClass(100) pb.progress(20) sleep(0.2) pb.progress(47) sleep(0.2) pb.progress(90) sleep(0.2) pb.progress(100) print "testing 1:" pb=progressbarClass(1) pb.progress(1) Brian Roberts wrote: > I have a command line Python program that sometimes takes a bit > (several minutes) to run. I want to provide an optional method for an > impatient user (me!) to check the status of the program. The type and > amount of status information doesn't fit nicely into a --verbose or > logger -- either too little or too much information at different > points. > > I think an optional web page would be convenient interface. The > Python program would listen on some port, and if queried (by me > browsing to localhost:12345 for example) would return a pretty status > display. Hitting reload would update the status etc. > > My problem is that I'm not sure how to do this: > - I don't want to embed a full web server into the application or > require any special PC setup. > - I think I know how to listen on a socket, but not sure how to send > stuff to to a web browser -- just start with ? Or like a CGI > script with the header stuff like text/html? (I don't care if I have > to write the HTML by hand or can use a toolkit -- not important). > - Do I need a separate thread to listen and send the HTML? The > application is currently single threaded. I'm confortable with > threads, but would prefer to avoid them if possible. > > Or is there a better/different way of doing this? Any general advice > or pointers to some code that already does this would be very much > appreciated. > > Python 2.3, under both Linux & Windows if that makes a difference. > > Thanks, > Brian. -- http://mail.python.org/mailman/listinfo/python-list
ANN: T602Parser 0.1
Text602 was a very popular word processor for IBM PC MS DOS compatibles, used in Czechoslovakia. T602Parser provides a simple class modelled after HTMLParser that can be used to parse Text602 documents (MS DOS version, not Win602) and to extract/convert data contained in them. Version: 0.1 (initial release) Author: Radovan GarabÃk License: GPL URL: http://kassiopeia.juls.savba.sk/~garabik/software/602/ -- --- | Radovan GarabÃk http://melkor.dnp.fmph.uniba.sk/~garabik/ | | __..--^^^--..__garabik @ kassiopeia.juls.savba.sk | --- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! -- http://mail.python.org/mailman/listinfo/python-list
Is there way to determine which class a method is bound to?
I'm doing some evil things in Python and I would find it useful to determine which class a method is bound to when I'm given a method pointer. For example: class Foo(object): def somemeth(self): return 42 class Bar(Foo): def othermethod(self): return 42 Is there some way I can have something like : findClass(Bar.somemeth) that would return the 'Foo' class, and findClass(Bar.othermethod) would return the 'Bar' class? vic -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there way to determine which class a method is bound to?
[vic] > I'm doing some evil things in Python and I would find it useful to > determine which class a method is bound to when I'm given a method > pointer. Here you go: >>> class Foo: ... def bar(self): ... pass ... >>> Foo.bar.im_class >>> Foo().bar.im_class >>> -- Richie Hindle [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: strange SyntaxError
Attila Szabo wrote: Hi, def main(): lambda x: 'ABC%s' % str(x) for k in range(2): exec('print %s' % k) OK, to no real effect, in main you define an unnamed function that you can never reference. Pretty silly, but I'll bite. Next you run run a loop with exec looking like you think it is a function. In the loop, your "exec" statement does not control (specify) its access to global and local variables. This could be a problem if your function were different. The function above does not do any up-referencing, but: def main(): def inner(): return k + 1 for k in range(4): exec 'k = 3 * k' print k, inner() What should this do? If you think you know, how about replacing the exec line with: exec raw_input('Tricky: ') You can fix this by controlling what variables the exec can write: exec 'k = 3 * k' in globals(), locals() This is why locals() does not do write-back. The rule below (which was high on the list when searching for exec), tells the exact rules, the above stuff is just why. http://www.python.org/doc/2.4/ref/dynamic-features.html --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there way to determine which class a method is bound to?
No - that doesn't work, im_class gives me the current class - in the case of inheritance, I'd like to get the super class which provides 'bar'. I suppose I could walk the __bases__ to find the method using the search routine outlined in: http://www.python.org/2.2/descrintro.html but I was hoping for an automatic way of resolving this. vic On Fri, 25 Feb 2005 14:54:34 +, Richie Hindle <[EMAIL PROTECTED]> wrote: > > [vic] > > I'm doing some evil things in Python and I would find it useful to > > determine which class a method is bound to when I'm given a method > > pointer. > > Here you go: > > >>> class Foo: > ... def bar(self): > ... pass > ... > >>> Foo.bar.im_class > > >>> Foo().bar.im_class > > >>> > > -- > Richie Hindle > [EMAIL PROTECTED] > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Nevow examples
Does anyone know of a site(s) that shows examples of what you can do with Nevow? I'm not necessarily referring to code, but what it can do over the web. (Something I can show my boss if needed.) In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] says... > > There was a request for nevow examples. Nevow is a fantastic > web-development framework for Python. > > I used nevow to create http://www.scipy.org/livedocs/ > > This site uses nevow and self introspection to produce (live) > documentation for scipy based on the internal docstrings. It would be > nice to add the capability for users to update the documentation through > the web-site. But, that functionality is not complete. > > The code itself is available in the util directory of scipy which can be > checked out of CVS (or browsed). Go to http://www.scipy.org for mor > details. > > -Travis Oliphant > > -- http://mail.python.org/mailman/listinfo/python-list
problem installing wxPython 2.5.3, wxWidgets installed ok
I'm trying to install wxPython 2.5.3.1 using Python 2.3.2 on a Fedora 2 machine. I have python in a non-standard place, but I'm using --prefix with the configure script to point to where I have everything. The make install in $WXDIR seemed to go fine. I have the libxw* libraries in my lib/ directory libwx_base-2.5.so@libwx_gtk_adv-2.5.so.3.0.0* libwx_base-2.5.so.3@ libwx_gtk_core-2.5.so@ libwx_base-2.5.so.3.0.0* libwx_gtk_core-2.5.so.3@ libwx_base_net-2.5.so@libwx_gtk_core-2.5.so.3.0.0* libwx_base_net-2.5.so.3@ libwx_gtk_gl-2.4.so@ libwx_base_net-2.5.so.3.0.0* libwx_gtk_gl-2.4.so.0@ libwx_base_xml-2.5.so@libwx_gtk_gl-2.4.so.0.1.1* libwx_base_xml-2.5.so.3@ libwx_gtk_html-2.5.so@ libwx_base_xml-2.5.so.3.0.0* libwx_gtk_html-2.5.so.3@ libwx_gtk-2.4.so@ libwx_gtk_html-2.5.so.3.0.0* libwx_gtk-2.4.so.0@ libwx_gtk_xrc-2.5.so@ libwx_gtk-2.4.so.0.1.1* libwx_gtk_xrc-2.5.so.3@ libwx_gtk_adv-2.5.so@ libwx_gtk_xrc-2.5.so.3.0.0* libwx_gtk_adv-2.5.so.3@ I also have a wx/ directory under my lib. directory. The problem is when I try to do a 'python setup.py install' in the ./wxPython directory. I get a message about not finding a config file for wx-config and then several errors during gcc compiles. > python setup.py build Found wx-config: /project/c4i/Users_Share/williams/Linux/bin/wx-config Using flags: --toolkit=gtk2 --unicode=no --version=2.5 Warning: No config found to match: /project/c4i/Users_Share/williams/Linux/bin/wx-config --toolkit=gtk2 --unicode=no --version=2.5 --cxxflags in /project/c4i/Users_Share/williams/Linux/lib/wx/config If you require this configuration, please install the desired library build. If this is part of an automated configuration test and no other errors occur, you may safely ignore it. You may use wx-config --list to see all configs available in the default prefix. ... Preparing OGL... Preparing STC... Preparing GIZMOS... running build running build_py copying wx/__version__.py -> build-gtk2/lib.linux-i686-2.3/wx running build_ext building '_core_' extension creating build-gtk2/temp.linux-i686-2.3 creating build-gtk2/temp.linux-i686-2.3/src creating build-gtk2/temp.linux-i686-2.3/src/gtk gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DSWIG_GLOBAL -DHAVE_CONFIG_H -DWXP_USE_THREAD=1 -UNDEBUG -DXTHREADS -D_REENTRANT -DXUSE_MTSAFE_API -Iinclude -Isrc -I/usr/include/gtk-2.0 -I/usr/lib/gtk-2.0/include -I/usr/X11R6/include -I/usr/include/atk-1.0 -I/usr/include/pango-1.0 -I/usr/include/freetype2 -I/usr/include/freetype2/config -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -I/project/c4i/Users_Share/williams/Linux/include/python2.3 -c src/libpy.c -o build-gtk2/temp.linux-i686-2.3/src/libpy.o -O3 gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -fPIC -DSWIG_GLOBAL -DHAVE_CONFIG_H -DWXP_USE_THREAD=1 -UNDEBUG -DXTHREADS -D_REENTRANT -DXUSE_MTSAFE_API -Iinclude -Isrc -I/usr/include/gtk-2.0 -I/usr/lib/gtk-2.0/include -I/usr/X11R6/include -I/usr/include/atk-1.0 -I/usr/include/pango-1.0 -I/usr/include/freetype2 -I/usr/include/freetype2/config -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -I/project/c4i/Users_Share/williams/Linux/include/python2.3 -c src/gtk/_core_wrap.cpp -o build-gtk2/temp.linux-i686-2.3/src/gtk/_core_wrap.o -O3 cc1plus: warning: command line option "-Wstrict-prototypes" is valid for Ada/C/ObjC but not for C++ In file included from src/gtk/_core_wrap.cpp:400: include/wx/wxPython/wxPython_int.h:19:19: wx/wx.h: No such file or directory include/wx/wxPython/wxPython_int.h:21:25: wx/busyinfo.h: No such file or directory include/wx/wxPython/wxPython_int.h:22:22: wx/caret.h: No such file or directory include/wx/wxPython/wxPython_int.h:23:25: wx/choicebk.h: No such file or directory include/wx/wxPython/wxPython_int.h:24:24: wx/clipbrd.h: No such file or directory include/wx/wxPython/wxPython_int.h:25:25: wx/colordlg.h: No such file or directory include/wx/wxPython/wxPython_int.h:26:23: wx/config.h: No such file or directory include/wx/wxPython/wxPython_int.h:27:23: wx/cshelp.h: No such file or directory include/wx/wxPython/wxPython_int.h:28:25: wx/dcmirror.h: No such file or directory include/wx/wxPython/wxPython_int.h:29:21: wx/dcps.h: No such file or directory include/wx/wxPython/wxPython_int.h:30:24: wx/dirctrl.h: No such file or directory include/wx/wxPython/wxPython_int.h:31:23: wx/dirdlg.h: No such file or directory include/wx/wxPython/wxPython_int.h:32:20: wx/dnd.h: No such file or directory include/wx/wxPython/wxPython_int.h:33:24: wx/docview.h: No such file or directory include/wx/wxPython/wxPython_int.h:34:24: wx/encconv.h: No such file or directory include/wx/wxPython/wxPython_int.h:35:25: wx/fdrepdlg.h: No such file or direct ... Why isn't there a -I../include switch on the compile line, and how do I reconfigure it so it does? Thanks for any help. -- http://mail.python.org/mailma
Re: split a directory string into a list
Michael Maibaum wrote: > On 25 Feb 2005, at 14:09, Harper, Gina wrote: > >> I would start with something like this: >> somestring = '/foo/bar/beer/sex/cigarettes/drugs/alcohol/' >> somelist = somestring.split('/') >> print somelist > > However - this will not work on Windows. It'd work on all the OS I > usually use though ;) > This should work reasonably reliably on Windows and Unix: >>> somestring = '/foo/bar/beer/sex/cigarettes/drugs/alcohol/' >>> os.path.normpath(somestring).split(os.path.sep) ['', 'foo', 'bar', 'beer', 'sex', 'cigarettes', 'drugs', 'alcohol'] However a better solution is probably to call os.path.split repeatedly until it won't split anything more: >>> somestring = r'C:\foo\bar\beer' >>> def splitpath(p): res = [] while 1: p, file = os.path.split(p) if not file: break res.append(file) res.append(p) res.reverse() return res >>> splitpath(somestring) ['C:\\', 'foo', 'bar', 'beer'] >>> splitpath('foo/bar') ['', 'foo', 'bar'] The first component is an empty string for relative paths, a drive letter or \ for absolute Windows paths, \\ for UNC paths, / for unix absolute paths. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there way to determine which class a method is bound to?
Victor Ng wrote: > I'm doing some evil things in Python and I would find it useful to > determine which class a method is bound to when I'm given a method > pointer. > > For example: > > class Foo(object): > def somemeth(self): > return 42 > > class Bar(Foo): > def othermethod(self): > return 42 > > > Is there some way I can have something like : > >findClass(Bar.somemeth) > > that would return the 'Foo' class, and > >findClass(Bar.othermethod) > > would return the 'Bar' class? > > vic >>> import inspect >>> class Foo(object): ... def foo(self): pass ... >>> class Bar(Foo): ... def bar(self): pass ... >>> def get_imp_class(method): ... return [t for t in inspect.classify_class_attrs(method.im_class) if t[-1] is method.im_func][0][2] ... >>> [get_imp_class(m) for m in [Bar().foo, Bar().bar, Bar.foo, Bar.bar]] [, , , ] but with this approach you will get into trouble as soon as you are using the same function to define multiple methods. There may be something in the inspect module more apt to solve the problem -- getmro() perhaps? Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there way to determine which class a method is bound to?
Awesome! I didn't see the getmro function in inspect - that'll do the trick for me. I should be able to just look up the methodname in each of the class's __dict__ attributes. vic On Fri, 25 Feb 2005 16:29:25 +0100, Peter Otten <[EMAIL PROTECTED]> wrote: > Victor Ng wrote: > > > I'm doing some evil things in Python and I would find it useful to > > determine which class a method is bound to when I'm given a method > > pointer. > > > > For example: > > > > class Foo(object): > > def somemeth(self): > > return 42 > > > > class Bar(Foo): > > def othermethod(self): > > return 42 > > > > > > Is there some way I can have something like : > > > >findClass(Bar.somemeth) > > > > that would return the 'Foo' class, and > > > >findClass(Bar.othermethod) > > > > would return the 'Bar' class? > > > > vic > > >>> import inspect > >>> class Foo(object): > ... def foo(self): pass > ... > >>> class Bar(Foo): > ... def bar(self): pass > ... > >>> def get_imp_class(method): > ... return [t for t in inspect.classify_class_attrs(method.im_class) if > t[-1] is method.im_func][0][2] > ... > >>> [get_imp_class(m) for m in [Bar().foo, Bar().bar, Bar.foo, Bar.bar]] > [, , , > ] > > but with this approach you will get into trouble as soon as you are using > the same function to define multiple methods. There may be something in the > inspect module more apt to solve the problem -- getmro() perhaps? > > Peter > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there way to determine which class a method is bound to?
Peter Otten wrote: import inspect class Foo(object): > ... def foo(self): pass > ... class Bar(Foo): > ... def bar(self): pass > ... def get_imp_class(method): > ... return [t for t in inspect.classify_class_attrs(method.im_class) > if t[-1] is method.im_func][0][2] > ... [get_imp_class(m) for m in [Bar().foo, Bar().bar, Bar.foo, Bar.bar]] > [, , , > ] > > but with this approach you will get into trouble as soon as you are using > the same function to define multiple methods. There may be something in I think it might be better to demonstrate the problem than just to describe it: >>> def another(self): pass ... >>> Foo.alpha = another >>> Bar.beta = another >>> get_imp_class(Bar.alpha) >>> get_imp_class(Bar.beta) A name check won't help either: >>> Foo.alpha.__name__ 'another' Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: accessor/mutator functions
If the class had two attributes--x and y--would the code look like something lik this: class C(object): def __init__(self): self.__x = 0 self.__y = 0 def getx(self): return self.__x def setx(self, x): if x < 0: x = 0 self.__x = x def gety(self): return self.__y def sety(self, y): if y < 0: y = 0 self.__y = y x = property(getx, setx) y = property(gety, sety) ? Because if so, does the term 'lazy evaluation' refer to the fact that instead of: C().getx() C().gety() C().setx(10) C().sety(10) one would substitute: C().x C().y C().x = 10 C().y = 10 ? -- http://mail.python.org/mailman/listinfo/python-list
Splitting strings - by iterators?
I have a large string containing lines of text separated by '\n'. I'm currently using text.splitlines(True) to break the text into lines, and I'm iterating over the resulting list. This is very slow (when using 40 lines!). Other than dumping the string to a file, and reading it back using the file iterator, is there a way to quickly iterate over the lines? I tried using newpos=text.find('\n', pos), and returning the chopped text text[pos:newpos+1], but this is much slower than splitlines. Any ideas? Thanks Jeremy -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there way to determine which class a method is bound to?
Victor Ng wrote: I'm doing some evil things in Python and I would find it useful to determine which class a method is bound to when I'm given a method pointer. For example: class Foo(object): def somemeth(self): return 42 class Bar(Foo): def othermethod(self): return 42 Is there some way I can have something like : findClass(Bar.somemeth) that would return the 'Foo' class, and findClass(Bar.othermethod) would return the 'Bar' class? vic I think you can use the mro function >>> class Foo(object): ... def somemeth(self): ... pass ... >>> class Bar(Foo): ... def othermeth(self): ... pass ... >>> def findClass(meth): ... for x in meth.im_class.mro(): ... if meth.im_func in x.__dict__.values(): return x ... >>> findClass(Bar.somemeth) >>> findClass(Bar.othermeth) >>> -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there way to determine which class a method is bound to?
In article <[EMAIL PROTECTED]>, Victor Ng <[EMAIL PROTECTED]> wrote: >I'm doing some evil things in Python and I would find it useful to >determine which class a method is bound to when I'm given a method >pointer. I don't know where (or if) it's documented, but im_class seems to give you what you want. -- class Foo(object): def x(self): return 42 f = Foo() print f.x.im_class -- king:play$ ./x.py I have no idea why it's not __imclass__ or some such, but poking around with dir() is a great way to explore little nooks and crannies like this. I just printed dir(Foo().x) and tried stuff that looked interesting until I found what I (you) wanted. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there way to determine which class a method is bound to?
In article <[EMAIL PROTECTED]>, Victor Ng <[EMAIL PROTECTED]> wrote: >No - that doesn't work, im_class gives me the current class - in the >case of inheritance, I'd like to get the super class which provides >'bar'. Oh my. You said you were doing something evil, but didn't say *how* evil. What are you trying to do that you need to know this? -- http://mail.python.org/mailman/listinfo/python-list
Re: accessor/mutator functions
> Because if so, does the term 'lazy evaluation' refer to the fact that > instead of: No, it is a common technical term. It means that a value is computed the time it is requested for the first time. Like this: class Foo(object): def __init__(self): self.__bar = None def getBar(self): if self.__bar is None: self.__bar = some_lengthy_computation() return self.__bar That you can make bar a property of Foo is unrelated to this. Another reason to use properties is if the value is always or at least frequently a freshly computed one. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: Splitting strings - by iterators?
Jeremy Sanders wrote: > I have a large string containing lines of text separated by '\n'. I'm > currently using text.splitlines(True) to break the text into lines, and > I'm iterating over the resulting list. > > This is very slow (when using 40 lines!). Other than dumping the > string to a file, and reading it back using the file iterator, is there a > way to quickly iterate over the lines? > > I tried using newpos=text.find('\n', pos), and returning the chopped text > text[pos:newpos+1], but this is much slower than splitlines. > > Any ideas? Maybe [c]StringIO can be of help. I don't know if it's iterator is lazy. But at least it has one, so you can try and see if it improves performance :) -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: update images inside a mysql database
On 25/02/2005 Dennis Lee Bieber wrote: > On Thu, 24 Feb 2005 23:10:48 +0100, Jonas Meurer <[EMAIL PROTECTED]> > declaimed the following in comp.lang.python: > > > > version used placeholders as well. anyway, i changed my code to resemble > > "resemble" is the key... It is NOT the correct sample. > > > 261 db_connect.cursor.execute("""UPDATE Images SET Image=%s WHERE > > 262 ImgID = %s""" % (image, imgid)) > 262 ImgID = %s""" , (image, imgid)) > > The .execute method ITSELF performs the argument conversion into > the place holders, including applying what ever quoting is required. > YOUR version is using the Python formatting operator, which does NOT > handle database quoting. oh, your correct. sorry for the noise. now it works quite good. bye jonas -- http://mail.python.org/mailman/listinfo/python-list
Re: Splitting strings - by iterators?
On Fri, 25 Feb 2005 17:14:24 +0100, Diez B. Roggisch wrote: > Maybe [c]StringIO can be of help. I don't know if it's iterator is lazy. But > at least it has one, so you can try and see if it improves performance :) Excellent! I somehow missed that module. StringIO speeds up the iteration by a factor of 20! Thanks Jeremy -- http://mail.python.org/mailman/listinfo/python-list
Re: Splitting strings - by iterators?
Jeremy, How did you get the string in memory in the first place? If you read it from a file, perhaps you should change to reading it from the file a line at the time and use file.readline as your iterator. fp=file(inputfile, 'r') for line in fp: ...do your processing... fp.close() I don't think I would never read 400,000 lines as a single string and then split it. Just a suggestion. Larry Bates Jeremy Sanders wrote: > I have a large string containing lines of text separated by '\n'. I'm > currently using text.splitlines(True) to break the text into lines, and > I'm iterating over the resulting list. > > This is very slow (when using 40 lines!). Other than dumping the > string to a file, and reading it back using the file iterator, is there a > way to quickly iterate over the lines? > > I tried using newpos=text.find('\n', pos), and returning the chopped text > text[pos:newpos+1], but this is much slower than splitlines. > > Any ideas? > > Thanks > > Jeremy > -- http://mail.python.org/mailman/listinfo/python-list
Fonts
I'm cpmpletely lost on fonts. I'm using Tkinter I do medarial = '-*-Arial-Bold-*-*--24-*-*-*-ISO8859-1" or Courier or Fixed in various sizes. Works great on my RH 7.2 But a small embedded system Im working on, nothing seems to work, almost everything falls back to a fixed 12 The X*4 fontpaths are the same and all the fonts, 75, 100, misc Speedo, PEX, etc are there. There is something wrong with where the fonts are. Help? -- http://mail.python.org/mailman/listinfo/python-list
Re: xhtml-print parser
Michael Hoffman wrote: Steve Holden wrote: Consider that the OP might want to pass the C parser output to a Python web-content generator, which would make a deal of sense. You're welcome to guess what the OP wants to do, but I'm not going to. If he or she asks a coherent question it will probably be answered. I have no problem with that. Indeed I am often surprised that questions that I regard as too incoherent to be understood are frequently not only understood but also answered with patience and fortitude. Given that you couldn't spare the time to try to intuit the purpose of the question, I was surprised you took the time to complain about its incoherence. It's usually (IMHO) much more productive to ignore c.l.py questions I don't have time for, and it's certainly more polite. If more of us had ignored Iliardis Lazarus, or whatever his name was, he'd have gone away a lot quicker :-) regards Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: Splitting strings - by iterators?
On Fri, 25 Feb 2005 10:57:59 -0600, Larry Bates wrote: > How did you get the string in memory in the first place? They're actually from a generated python script, acting as a saved file format, something like: interpret(""" lots of lines """) another_command() Obviously this isn't the most efficient format, but it's nice to encapsulate the data and the script into one file. Jeremy -- http://mail.python.org/mailman/listinfo/python-list
Re: accessor/mutator functions
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > When I look at how classes are set up in other languages (e.g. C++), I > often observe the following patterns: > 1) for each data member, the class will have an accessor member > function (a Get function) > 2) for each data member, the class will have a mutator member function > (a Set function) > 3) data members are never referenced directly; they are always > referenced with the accessor and mutator functions > > My questions are: > a) Are the three things above considered pythonic? As others have said, 'no', as in 'unnecessary because we have a better way to accomplish the same purpose without doubling the attribute namespace'. The purpose of the pattern is to hide the specific implementation of a class (which attributes are static and which dynamic) and to allow that implementation to change without changing programs that use the class. Consider a complex class with interdependent .real, .imag, .rad, and .theta attributes and the possible behind-the-scene implementations for what is kept static and how they are kept synchronized. The need for get/set to accomplish this in C++ arises from the fact that attribute names are resolved at compile time, so that x.a syntax can only be used for simple static attributes and access. Python, on the other hand, has means to 'magically' map what looks like direct attribute access into a function call. First there was __get/setattr__ (which is awkward for multiple dynamic attributes) and now properties with get/set/del for individual dynamic attributes. > b) What are the tradeoffs of using getattr() and setattr() rather than > creating accessor and mutator functions for each data member? > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Unit testing - one test class/method, or test class/class
I do something more or less like your option b. I don't think there is any orthodox structure to follow. You should use a style that fit your taste. What I really want to bring up is your might want to look at refactoring your module in the first place. 348 test cases for one module sounds like a large number. That reflects you have a fairly complex module to be tested to start with. Often the biggest benefit of doing automated unit testing is it forces the developers to modularize and decouple their code in order to make it testable. This action alone improve that code quality a lot. If breaking up the module make sense in your case, the test structure will follows. Hi, I just found py.test[1] and converted a large unit test module to py.test format (which is actually almost-no-format-at-all, but I won't get there now). Having 348 test cases in the module and huge test classes, I started to think about splitting classes. Basically you have at least three obvious choises, if you are going for consistency in your test modules: Choise a: Create a single test class for the whole module to be tested, whether it contains multiple classes or not. ...I dont think this method deserves closer inspection. It's probably rather poor method to begin with. With py.test where no subclassing is required (like in Python unittest, where you have to subclass unittest.TestCase) you'd probably be better off with just writing a test method for each class and each class method in the module. Choise b: Create a test class for each class in the module, plus one class for any non-class methods defined in the module. + Feels clean, because each test class is mapped to one class in the module + It is rather easy to find all tests for given class + Relatively easy to create class skeleton automatically from test module and the other way round - Test classes get huge easily - Missing test methods are not very easy to find[2] - A test method may depend on other tests in the same class Choise c: Create a test class for each non-class method and class method in the tested module. + Test classes are small, easy to find all tests for given method + Helps in test isolation - having separate test class for single method makes tested class less dependent of any other methods/classes + Relatively easy to create test module from existing class (but then you are not doing TDD!) but not vice versa - Large number of classes results in more overhead; more typing, probably requires subclassing because of common test class setup methods etc. What do you think, any important points I'm missing? Footnotes: [1] In reality, this is a secret plot to advertise py.test, see http://codespeak.net/py/current/doc/test.html [2] However, this problem disappears if you start with writing your tests first: with TDD, you don't have untested methods, because you start by writing the tests first, and end up with a module that passes the tests -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! One day, when he was naughty, Mr Bunnsy looked over the hedge into Farmer Fred's field and it was full of fresh green lettuces. Mr Bunnsy, however, was not full of lettuces. This did not seem fair. --Mr Bunnsy has an adventure -- http://mail.python.org/mailman/listinfo/python-list
Re: accessor/mutator functions
[EMAIL PROTECTED] wrote: If the class had two attributes--x and y--would the code look like something lik this: class C(object): def __init__(self): self.__x = 0 self.__y = 0 def getx(self): return self.__x def setx(self, x): if x < 0: x = 0 self.__x = x def gety(self): return self.__y def sety(self, y): if y < 0: y = 0 self.__y = y x = property(getx, setx) y = property(gety, sety) It could do - that works. One feature of this solution is that it leaves the accessor/mutator functions in the namespace. That may be a good or a bad thing. If bad, you could simply delete them after the property call (which is probably better written as close as possible to the functions) i.e., class C(object): def __init__(self): self.__x = 0 self.__y = 0 def getx(self): return self.__x def setx(self, x): if x < 0: x = 0 self.__x = x x = property(getx, setx) del getx, setx def gety(self): return self.__y def sety(self, y): if y < 0: y = 0 self.__y = y y = property(gety, sety) del gety, sety There are also recipes in the cookbook for defining property "suites" more elegantly Note, that it is also easy to "roll your own" descriptor, which may be worthwhile if you have a lot of similar properties, for example (not tested beyond what you see): from weakref import WeakKeyDictionary class Property(object): def __init__(self, adapter): """adapter is a single argument function that will be applied to the value before setting it""" self.objdict = WeakKeyDictionary() self.adapter = adapter def __get__(self, obj, cls): if isinstance(obj, cls): return self.objdict[obj] else: return self def __set__(self, obj, value): self.objdict[obj] = self.adapter(value) class C(object): x = Property(lambda val: max(val, 0)) y = Property(lambda val: val%2) z = Property(abs) >>> c= C() >>> c.x = -3 >>> c.x 0 >>> c.y = -3 >>> c.y 1 >>> c.z = -3 >>> c.z 3 >>> Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: Unit testing - one test class/method, or test class/class
I tend to write one test class per class, but that's just the way I got started. My feeling is that the methods in a test class should tell a story if you read the names in the order they were written, so I'd split the tests for a class into several classes if they had different stories to tell. John Roth "Edvard Majakari" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] Hi, I just found py.test[1] and converted a large unit test module to py.test format (which is actually almost-no-format-at-all, but I won't get there now). Having 348 test cases in the module and huge test classes, I started to think about splitting classes. Basically you have at least three obvious choises, if you are going for consistency in your test modules: Choise a: Create a single test class for the whole module to be tested, whether it contains multiple classes or not. ...I dont think this method deserves closer inspection. It's probably rather poor method to begin with. With py.test where no subclassing is required (like in Python unittest, where you have to subclass unittest.TestCase) you'd probably be better off with just writing a test method for each class and each class method in the module. Choise b: Create a test class for each class in the module, plus one class for any non-class methods defined in the module. + Feels clean, because each test class is mapped to one class in the module + It is rather easy to find all tests for given class + Relatively easy to create class skeleton automatically from test module and the other way round - Test classes get huge easily - Missing test methods are not very easy to find[2] - A test method may depend on other tests in the same class Choise c: Create a test class for each non-class method and class method in the tested module. + Test classes are small, easy to find all tests for given method + Helps in test isolation - having separate test class for single method makes tested class less dependent of any other methods/classes + Relatively easy to create test module from existing class (but then you are not doing TDD!) but not vice versa - Large number of classes results in more overhead; more typing, probably requires subclassing because of common test class setup methods etc. What do you think, any important points I'm missing? Footnotes: [1] In reality, this is a secret plot to advertise py.test, see http://codespeak.net/py/current/doc/test.html [2] However, this problem disappears if you start with writing your tests first: with TDD, you don't have untested methods, because you start by writing the tests first, and end up with a module that passes the tests -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY availableSoli Deo Gloria! One day, when he was naughty, Mr Bunnsy looked over the hedge into Farmer Fred's field and it was full of fresh green lettuces. Mr Bunnsy, however, was not full of lettuces. This did not seem fair. --Mr Bunnsy has an adventure -- http://mail.python.org/mailman/listinfo/python-list
Re: split a directory string into a list
Hi Duncan, This should work reasonably reliably on Windows and Unix: somestring = '/foo/bar/beer/sex/cigarettes/drugs/alcohol/' os.path.normpath(somestring).split(os.path.sep) ['', 'foo', 'bar', 'beer', 'sex', 'cigarettes', 'drugs', 'alcohol'] However a better solution is probably to call os.path.split repeatedly until it won't split anything more: somestring = r'C:\foo\bar\beer' def splitpath(p): res = [] while 1: p, file = os.path.split(p) if not file: break res.append(file) res.append(p) res.reverse() return res splitpath(somestring) ['C:\\', 'foo', 'bar', 'beer'] splitpath('foo/bar') ['', 'foo', 'bar'] The first component is an empty string for relative paths, a drive letter or \ for absolute Windows paths, \\ for UNC paths, / for unix absolute paths. I don't understand why the second approach is better than the first one. In my opinion it is the contrary: On the first approach, you only scan the string twice: when you do "os.path.normpath(somestring)" and finally when splitting the string. On the other hand, the second approach goes through the string several times, when doing the os.path.split. Finally when doing the res.reverse(). Or am I wrong? I also saw you said: "This should work ***reasonably*** reliably on Windows and Unix". Are there any cases when it does not work? Regards, Josef -- http://mail.python.org/mailman/listinfo/python-list
Re: Tuple index
On 21 Feb 2005 15:01:05 -0800, "John Machin" <[EMAIL PROTECTED]> wrote: > >Steve M wrote: >> John Machin wrote: >> >> > >> > Steve M wrote: >> >> I'm actually doing this as part of an exercise from a book. What >the >> > program >> >> is supposed to do is be a word guessing game. The program >automaticly >> >> randomly selects a word from a tuple. >> > >> > Care to tell us which book is using a tuple for this, but hasn't >got to >> > lists yet? >> > >> > Cheers, >> > John >> >> Python Programming for the absoulte beginner by Michael Dawson > >In a review I found on the web: >http://www.skattabrain.com/css-books-plain/1592000738.html >"Dawson will take you by the hand and lead you down the garden path." > >Malapropism? Intentional humour? The book teaches you enough about programming and python to get you programming. It was the only python book in my local library so I read it while trying to learn the basics of python. It got me to the point where I could comfortably write Fortran-style python (I am not claiming that anyone else will leave the book that way, only that was as far as I had progressed in understanding python). I think that this book suggests using pickle/unpickle to send data over the internet. This is an amazingly bad idea, which is obvious once you understand how overloading works (I'm pretty sure overloading isn't covered in that book). In short, I think that this book is a good introduction to programming, and it will explain the basics of python, but it doesn't really begin to explain how to program in python. Scott Robinson -- http://mail.python.org/mailman/listinfo/python-list
Re: Threading and consuming output from processes
In article <[EMAIL PROTECTED]>, Jack Orenstein <[EMAIL PROTECTED]> wrote: > I am developing a Python program that submits a command to each node > of a cluster and consumes the stdout and stderr from each. I want all > the processes to run in parallel, so I start a thread for each > node. There could be a lot of output from a node, so I have a thread > reading each stream, for a total of three threads per node. (I could > probably reduce to two threads per node by having the process thread > handle stdout or stderr.) > > I've developed some code and have run into problems using the > threading module, and have questions at various levels of detail. > > 1) How should I solve this problem? I'm an experienced Java programmer > but new to Python, so my solution looks very Java-like (hence the use of > the threading module). Any advice on the right way to approach the > problem in Python would be useful. > > 2) How many active Python threads is it reasonable to have at one > time? Our clusters have up to 50 nodes -- is 100-150 threads known to > work? (I'm using Python 2.2.2 on RedHat 9.) > > 3) I've run into a number of problems with the threading module. My > program seems to work about 90% of the time. The remaining 10%, it > looks like notify or notifyAll don't wake up waiting threads; or I > find some other problem that makes me wonder about the stability of > the threading module. I can post details on the problems I'm seeing, > but I thought it would be good to get general feedback > first. (Googling doesn't turn up any signs of trouble.) One of my colleagues here wrote a sort of similar application in Python, used threads, and had plenty of troubles with it. I don't recall the details. Some of the problems could be specific to Python. For example, there are some extra signal handling issues - but this is not to say that there are no signal handling issues with a multithreaded C application. For my money, you just don't get robust applications when you solve problems like multiple I/O sources by throwing threads at them. As I see another followup has already mentioned, the classic "pre threads" solution to multiple I/O sources is the select(2) function, which allows a single thread to serially process multiple file descriptors as data becomes available on them. When using select(), you should read from the file descriptor, using os.read(fd, size), socketobject.recv(size) etc., to avoid reading into local buffers as would happen with a file object. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: strange SyntaxError
"Attila Szabo" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hi, > > I wrote this sample piece of code: > > def main(): >lambda x: 'ABC%s' % str(x) >for k in range(2): exec('print %s' % k) > > main() > > With the lambda line, I get this: > SyntaxError: unqualified exec is not allowed in function 'main' > it contains a nested function with free variables The lambda expression is the nested function, the free variable is 'str'. Since this general situation *could* be a problem, as Scott explained, the compiler quits, since it cannot do the analysis needed to determine whether the specific situation *is* a problem. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: [Tutor] threads
> >Can anyone guide me on how to spawn > >simultaneously( or > > pseudo simultaneously) running microthreads using > > stackless. > > > > Here is what i tried.. > > > > def gencars(num,origin,dest,speed): > > global adjls > > global cars > > global juncls > > for i in range(num): > > > > cars.append(car(orig,dest,speed) > > task=tasklet(cars[i].run()) > > task.setup('Bind using Setup') > > > > Now this is what i copied from somewhere...i dont > > claim to understand fully what is happening.Here > > car.run() is a process which takes a long time to > > execute. > > > > What happens on execution isOne car is > >initialised > > and then the program waits for its run method to > > complete before proceeding. > > > >How is it different from : > > for i in cars: i.run() > > I also feel that there is no clear documentation > > on > > stackless. > > > > Show me the light. > > __ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail -- http://mail.python.org/mailman/listinfo/python-list
Minor, but annoying legend problem in matplotlib
I have a problem that I run into a lot with the 'legend' command's default behavior. I've found a work-around but I wonder if there's a better way. For a simple example, take the following: x= [1,2,3,4,5,6,7,8] a= [5,3,2,4,6,5,8,7] b= [4,1,3,5,2,8,3,6] c= [8,4,9,6,7,3,9,4] DataSets= [a,b,c] Symb= ['k-o','k--s','k-.^'] for index,d in enumerate(DataSets): plot(x,DataSets[index],Symb[index]) legend(["a","b","c"]) ___ This behaves just as I would want it to. Normally, though I want 'open' markers, which (AFAIK) require me to set the color to 'w' (white), and so the (white-on-white) lines won't show up in this case (the markers still have black outlines). I tried using two colors in one marker definition, 'k-wo', but that didn't work. The obvious solution is to plot the lines and symbols in two different commands: ___ Symb= ['wo','ws','w^'] LineType= ['k-','k--','k-.'] for index,d in enumerate(DataSets): plot(x,DataSets[index],LineType[index]) plot(x,DataSets[index],Symb[index]) legend(["a","b","c"]) ___ This produces the correct plot, but the legend here alternates between symbol and marker in its what uses for designating each dataset (a uses 'marker a', b uses 'line b', c uses 'marker c'). Is there some rationale for this being the default behavior? The workaround I've found has been to use two separate loops for the symbol and line plotting: ___ Symb= ['wo','ws','w^'] LineType= ['k-','k--','k-.'] #Loop 1 for index,d in enumerate(DataSets): plot(x,DataSets[index],LineType[index]) # Loop 2 for index,d in enumerate(DataSets): plot(x,DataSets[index],Symb[index]) legend(["a","b","c"]) ___ This works and will give me a legend that uses only marker symbols in it, as desired. It's not an ideal solution though as I often have some moderate amount of processing within the loop that I'd rather not have to repeat or write out to some temporary variable just in order to have it available for the second loop. I've gotten around this before for somewhat similar cases using suggestions from this group of explicitly defining the values the legend will use: L1= plot(x,y,... but I can't figure how to do this here because of the looping over the data sets. On a related note, is there any way to increase the size of the markers within the legend? TIA, J.S. -- Actual e-mail: 'dot' @comcast.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Trouble with mysql-python 1.2.0 on Solaris 8 sparc
What happens when you try to connect? Be sure to check /etc/hosts.allow and .deny on the server, if your server is compiled with TCP wrapper support. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there way to determine which class a method is bound to?
Another way is to make a simple metaclass, setting an attribute (like defining_class, or something) on each function object in the class dictionary. -- http://mail.python.org/mailman/listinfo/python-list
Re: wanted: C++ parser written in Python
You can look at the techniques and regular expressions in the testgen.c.unit test module that is part of a generic test framework called TestGen. TestGen uses a parser to automatically stub / copy functions for testing purposes. The parser is capable of identifying the function/method name as well as the parameters and return type. The only caveat with using regular expressions is the function/method's closing } must be in column zero. If you figure out a different way to get around the restriction or other improvements to the parser let me know. I'm about to release a newer version, but the area that you would be looking at is not changing so I would go ahead and download the latest that is there. TestGen can be found at sourceforge.net/projects/testgen Regards, Dan Gass -- http://mail.python.org/mailman/listinfo/python-list
Converting HTML to ASCII
Hans, Thanks for the tip. I took a look at Beatiful Soup, and it looked like it was a framework to parse HTML. I'm not really interetsed in going through it tag by tag - just to get it converted to ASCII. How can I do this with B. Soup? --Thanks PS William - thanks for the reference to lynx, but I need a Python solution - forking and execing for each file I need to convert is too slow for my application Hans wrote: Try Beautiful Soup! > 1) Be able to handle badly formed, or illegal, HTML, > as best as possible. From the description: "It won't choke if you give it ill-formed markup: it'll just give you access to a correspondingly ill-formed data structure." > Can anyone direct me to something which could help me > for this? http://www.crummy.com/software/BeautifulSoup/ Hans Christian __ Do you Yahoo!? Yahoo! Mail - Easier than ever with enhanced search. Learn more. http://info.mail.yahoo.com/mail_250 -- http://mail.python.org/mailman/listinfo/python-list
Re: Unit testing - one test class/method, or test class/class
aurora <[EMAIL PROTECTED]> writes: > What I really want to bring up is your might want to look at refactoring > your module in the first place. 348 test cases for one module sounds like a > large number. That reflects you have a fairly complex module to be tested > to start with. Often the biggest benefit of doing automated unit testing is > it forces the developers to modularize and decouple their code in order to > make it testable. This action alone improve that code quality a lot. If > breaking up the module make sense in your case, the test structure will > follows. Here I have to emphasize a little: of those 348 test cases, only ~30 or so are real, hand-coded methods. Some of the tests are generated on the fly by py.test. It is not as fancy as it sounds, though. All it does is test_some_feature(self): for foo, bar, expected in known_values: yield self.foo_bar_equals, foo, bar, expected def foo_bar_equals(self, foo, bar, expected): assert some_feature(foo, bar) == expected There are two methods. However, if known_values contains 100 tuples, py.test generates 100 "test methods" on the fly. Of course you could just do test_some_feature(self): for foo, bar, expected in known_values: assert some_feature(foo, bar) == expected but then you wouldn't see so easily which values are tested when you use verbose mode, that is. That's one of the (many) nice things in py.test I like :) However, being practical in testing is probably more worth than being completely orthodox, on that I agree. That's why I seldom stick to strict rules in doing tests, though being systematic helps alot, especially regarding orthogonality. It doesn't help to test same features over and over again. Eg. if I wrote a test for a dot in 2D space, I'd write tests for dot on origo, on positive x-axis with y < 0 and y > 0, ditto for x and y reversed, then same tests for negative x and y, and last for positive and negative x and y with other being exactly zero. There's no point testing other values; all other combinations fall to some of the categories mentioned. -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; -- http://mail.python.org/mailman/listinfo/python-list
Re: Unit testing - one test class/method, or test class/class
"John Roth" <[EMAIL PROTECTED]> writes: > I tend to write one test class per class, but that's > just the way I got started. My feeling is that the > methods in a test class should tell a story if you > read the names in the order they were written, > so I'd split the tests for a class into several > classes if they had different stories to tell. Well, that's one of the things I forgot to mention. Often I use TestSomeClassA: # test for normal, legal inputs TestSomeClassB: # test for extreme/border cases, still legal inputs TestSomeClassC: # test cases with illegal input, eg. negative integer when only positive # inputs make sense etc. Just like you said, they tell a bit different story each, so it probably makes sense to separate those. > > John Roth > > "Edvard Majakari" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] >> >> Hi, >> >> I just found py.test[1] and converted a large unit test module to py.test >> format (which is actually almost-no-format-at-all, but I won't get there >> now). Having 348 test cases in the module and huge test classes, I started >> to think about splitting classes. Basically you have at least three >> obvious >> choises, if you are going for consistency in your test modules: >> >> Choise a: >> >> Create a single test class for the whole module to be tested, whether it >> contains multiple classes or not. >> >> ...I dont think this method deserves closer inspection. It's probably >> rather >> poor method to begin with. With py.test where no subclassing is required >> (like in Python unittest, where you have to subclass unittest.TestCase) >> you'd probably be better off with just writing a test method for each >> class >> and each class method in the module. >> >> Choise b: >> >> Create a test class for each class in the module, plus one class for any >> non-class methods defined in the module. >> >> + Feels clean, because each test class is mapped to one class in the >> module >> + It is rather easy to find all tests for given class >> + Relatively easy to create class skeleton automatically from test module >> and the other way round >> >> - Test classes get huge easily >> - Missing test methods are not very easy to find[2] >> - A test method may depend on other tests in the same class >> >> Choise c: >> >> Create a test class for each non-class method and class method in the >> tested >> module. >> >> + Test classes are small, easy to find all tests for given method >> + Helps in test isolation - having separate test class for single method >> makes tested class less dependent of any other methods/classes >> + Relatively easy to create test module from existing class (but then you >> are not doing TDD!) but not vice versa >> >> - Large number of classes results in more overhead; more typing, probably >> requires subclassing because of common test class setup methods etc. >> >> What do you think, any important points I'm missing? >> >> Footnotes: >> [1] In reality, this is a secret plot to advertise py.test, see >> http://codespeak.net/py/current/doc/test.html >> >> [2] However, this problem disappears if you start with writing your tests >>first: with TDD, you don't have untested methods, because you start by >>writing the tests first, and end up with a module that passes the tests >> >> >> -- >> # Edvard Majakari Software Engineer >> # PGP PUBLIC KEY availableSoli Deo Gloria! >> One day, when he was naughty, Mr Bunnsy looked over the hedge into Farmer >> Fred's field and it was full of fresh green lettuces. Mr Bunnsy, however, >> was >> not full of lettuces. This did not seem fair. --Mr Bunnsy has an >> adventure -- # Edvard Majakari Software Engineer # PGP PUBLIC KEY available Soli Deo Gloria! $_ = '456476617264204d616a616b6172692c20612043687269737469616e20'; print join('',map{chr hex}(split/(\w{2})/)),uc substr(crypt(60281449,'es'),2,4),"\n"; -- http://mail.python.org/mailman/listinfo/python-list
Re: wxpython tutorials
Raghul wrote: > hi, > > I want to learn Wxpython to work in windows.Is there any tutorials > available?Pls specify the link that will be easy to learn for beginers > like me An approach that I find useful is to use an IDE to build the base application structure, then examine the generated code. This has an advantage over trying to build something from scratch as a newbie - the code will run straightaway. wxPython has Boa Constructor and wxGlade available. http://sourceforge.net/project/showfiles.php?group_id=1909&release_id=150280 http://wxglade.sourceforge.net/ Some depends on how much you want to learn wxPython vs. just use it. If you learn more easily building from scratch then the other replies are pointing you in the right direction. Bill -- http://mail.python.org/mailman/listinfo/python-list
Handle user abort
Hallo! I use Python mostly for CGI (using Apache). And now I habe a problem: How can I handle the situation if a user clicks on ?abort? in the browser? It seems that a CGI-script is NOT stopped at this point. Is there any signal send to the CGI-process if the user clicks on ?abort?? Thank you. Best regards Markus -- http://mail.python.org/mailman/listinfo/python-list
Handle user abort inside of a CGI-script
Hallo! I use Python mostly for CGI (Apache). And now I habe a problem: How can I handle the situation if a user clicks on "abort" in the browser? It seems that a CGI-script is NOT stopped at this point. Is there any signal send to the CGI-process if the user clicks on "abort"? Thank you. Best regards Markus -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting HTML to ASCII
gf gf wrote: [wants to extract ASCII from badly-formed HTML and thinks BeautifulSoup is too complex] You haven't specified what you mean by "extracting" ASCII, but I'll assume that you want to start by eliminating html tags and comments, which is easy enough with a couple of regular expressions: >>> import re >>> comments = re.compile('', re.DOTALL) >>> tags = re.compile('<.*?>', re.DOTALL) ... >>> def striptags(text): ... text = re.sub(comments,'', text) ... text = re.sub(tags,'', text) ... return text ... >>> def collapsenewlines(text): ... return "\n".join(line for line in text.splitlines() if line) ... >>> import urllib2 >>> f = urllib2.urlopen('http://www.python.org/') >>> source = f.read() >>> text = collapsenewlines(striptags(source)) >>> This will of course fail if there is a "<" without a ">", probably in other cases too. But it is indifferent to whether the html is well-formed. This leaves you with the additional task of substituting the html escaped characters e.g., " ", not all of which will have ASCII representations. HTH Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: Flushing print()
In article <[EMAIL PROTECTED]>, Daniel Yoo <[EMAIL PROTECTED]> wrote: >gf gf <[EMAIL PROTECTED]> wrote: . . . >: If not, how can I flush it manually? sys.stdout.flush() didn't >: seem to work. > >H, that's odd. sys.stdout.flush() should do it. How are you >testing that stdout isn't flushing as you expect? > > >Best of wishes to you! gf, remember to write sys.stdout.flush() rather than sys.stdout.flush That's a mistake that catches many. -- http://mail.python.org/mailman/listinfo/python-list
Re: Splitting strings - by iterators?
Hi, Using finditer in re module might help. I'm not sure it is lazy nor performant. Here's an example : === BEGIN SNAP import re reLn = re.compile(r"""[^\n]*(\n|$)""") sStr = \ """ This is a test string. It is supposed to be big. Oh well. """ for oMatch in reLn.finditer(sStr): print oMatch.group() === END SNAP Regards, Francis Girard Le vendredi 25 Février 2005 16:55, Jeremy Sanders a écrit : > I have a large string containing lines of text separated by '\n'. I'm > currently using text.splitlines(True) to break the text into lines, and > I'm iterating over the resulting list. > > This is very slow (when using 40 lines!). Other than dumping the > string to a file, and reading it back using the file iterator, is there a > way to quickly iterate over the lines? > > I tried using newpos=text.find('\n', pos), and returning the chopped text > text[pos:newpos+1], but this is much slower than splitlines. > > Any ideas? > > Thanks > > Jeremy -- http://mail.python.org/mailman/listinfo/python-list
Re: [perl-python] generic equivalence partition
David Eppstein <[EMAIL PROTECTED]> writes: > In article <[EMAIL PROTECTED]>, > "Xah Lee" <[EMAIL PROTECTED]> wrote: > >> parti(aList, equalFunc) >> >> given a list aList of n elements, we want to return a list that is a >> range of numbers from 1 to n, partition by the predicate function of >> equivalence equalFunc. (a predicate function is a function that >> takes two arguments, and returns either True or False.) > > In Python it is much more natural to use ranges from 0 to n-1. > In the worst case, this is going to have to take quadratic time > (consider an equalFunc that always returns false) so we might as well do > something really simple rather than trying to be clever. As you say, with the spec as it stands, you can't do better than quadratic time (although it's O(n*m) where m is the number of partitions, rather than O(n^2)). You can do a lot better if you can use a "key" function, rather than an "equivalence" function, much as list.sort has a "key" argument, and itertools.groupby (which is pretty close in function to this partitioning problem) uses a key argument. In fact, I'd have difficulty thinking of an example where I'd want a partition function as specified, in Python. In Perl, it makes a lot of sense, as Perl's array indexing operations lend themselves to slinging round lists of indices like this. But in Python, I'd be far more likely to use list.sort followed by itertools.groupby - sort is stable (so doesn't alter the relative order within equivalence classes), and groupby then picks out the equivalence classes: >>> elements = [['x', 'x', 'x', '1'], ... ['x', 'x', 'x', '2'], ... ['x', 'x', 'x', '2'], ... ['x', 'x', 'x', '2'], ... ['x', 'x', 'x', '3'], ... ['x', 'x', 'x', '4'], ... ['x', 'x', 'x', '5'], ... ['x', 'x', 'x', '5']] >>> # No need to sort here, as the elements are already sorted! >>> from pprint import pprint >>> pprint([(k, list(v)) for k, v in groupby(elements, itemgetter(3))]) [('1', [['x', 'x', 'x', '1']]), ('2', [['x', 'x', 'x', '2'], ['x', 'x', 'x', '2'], ['x', 'x', 'x', '2']]), ('3', [['x', 'x', 'x', '3']]), ('4', [['x', 'x', 'x', '4']]), ('5', [['x', 'x', 'x', '5'], ['x', 'x', 'x', '5']])] If you avoid the sort, the whole thing is highly memory efficient, as well, because by using iterators, we don't ever take a copy of the original list. Having cleverly redefined the question so that it fits the answer I wanted to give, I'll shut up now :-) Paul. -- To attain knowledge, add things every day; to attain wisdom, remove things every day. -- Lao-Tse -- http://mail.python.org/mailman/listinfo/python-list
File descriptor open in one thread, closed in another?!
Hello gang, My coworker and I are writing a Python class for the other developers within our team. This class is supposed to encapsulate several things, including daemonizing, setting up logging, and spawning a thread to host an XML-RPC server. I'm having a real problem with logging.Logger and threading.Thread. In the main thread, we set up two loggers, each with file handlers. We then spawn the xml-rpc server thread, and allow the parent thread to continue. At some point, the stream of the file handlers appears to be closed from the xml-rpc server's thread, but still open from the POV of the parent thread?! How is this possible? Here's the POV from the child thread: > /Users/marco/work/cam/services/common/lib/camService.py(226)__run_xr_server() -> self.loggers['main'].info("ABOUT TO WAIT FOR START") (Pdb) self._camBaseService__serviceLog._camLog__handlers['file']['main']['handler'].stream (Pdb) n Traceback (most recent call last): File "/export/crawlspace/cam/python/builds/current/python-2.4-cam/lib/python2.4/logging/handlers.py", line 62, in emit if self.shouldRollover(record): File "/export/crawlspace/cam/python/builds/current/python-2.4-cam/lib/python2.4/logging/handlers.py", line 132, in shouldRollover self.stream.seek(0, 2) #due to non-posix-compliant Windows feature ValueError: I/O operation on closed file And here's the POV from the parent thread: (Pdb) camd._camBaseService__serviceLog._camLog__handlers['file']['main']['handler'].stream Obviously, these are two different pdb runs, but I've stepped through the parent very carefully, and stream.close() is NEVER called, either by the child nor the parent. BUT, while it continues to appear open to the parent, it clearly IS changed in the child. How is this even possible?! They're the same file handle! Here are some code snippets. Unfortunately, we have a considerable amount of inheritance going on. >From the parent: if __name__ == "__main__": camd = camBaseService("camd", parsedOptions.configFile, configDef) if not camd.start(): print "Start failed, exiting..." sys.exit(1) camd.loggers['main'].info("Main loop waiting for XML-RPC Server to quit.") Any call to that info() method will continue to work forever. camBaseService does some initialziation in that camd object: # Flags for communicating to the XRServer thread self.xrStart = False self.xrInitialized = False self.__initialize_logging() self.loggers['xr-server'] = self.__serviceLog.add_logger('xr-server') self.loggers['main'] = self.__serviceLog.add_logger('main') self.xrSvcThread = threading.Thread(target=self.__run_xr_server) camd.start (see __main__, above) spawns the thread, so it runs this code in the parent thread: self.xrSvcThread.start() i = 0 while i < 10 and not self.xrInitialized: if not self.xrInitialized: i = i + 1 time.sleep(1) if self.xrInitialized: self.xrStart = True return True In the child thread: # some misc configuration goo self.xrInitialized = True self.loggers['main'].info("ABOUT TO WAIT FOR START") I've isolated the switch from open to closed (from the POV of the child ONLY) to that exchange of flags xrInitiated (child says, "I'm ready to go!") to the parent thread's setting xrStart (ok! go!). Can anyone PLEASE help me understand what's going on here? -- ___ Marco E. Nicosia | http://www.escape.org/~marco/ | [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Best IDe
Jubri Siji napisał(a): Please i am new to python , whats the best IDE to start with Vim, Emacs or jEdit. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ -- http://mail.python.org/mailman/listinfo/python-list
Re: exclude binary files from os.walk
On Wed, 26 Jan 2005 18:25:09 -0500, "Dan Perl" <[EMAIL PROTECTED]> wrote: > >"rbt" <[EMAIL PROTECTED]> wrote in message >news:[EMAIL PROTECTED] >> Is there an easy way to exclude binary files (I'm working on Windows XP) >> from the file list returned by os.walk()? >> >> Also, when reading files and you're unsure as to whether or not they are >> ascii or binary, I've always thought it safer to 'rb' on the read, is this >> correct... and if so, what's the reasoning behind this? Again all of this >> pertains to files on Windows XP and Python 2.4 > >Please clarify: is your question about identifying binary (non-ascii) files >or about using os.walk? > > I have a feeling it's about walking directories and identifying which files to should be "cooked" (to normalize line endings when opened and read). Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting HTML to ASCII
Michael Spencer <[EMAIL PROTECTED]> writes: > gf gf wrote: >> [wants to extract ASCII from badly-formed HTML and thinks BeautifulSoup is >> too complex] > > You haven't specified what you mean by "extracting" ASCII, but I'll > assume that you want to start by eliminating html tags and comments, > which is easy enough with a couple of regular expressions: > > >>> import re > >>> comments = re.compile('', re.DOTALL) > >>> tags = re.compile('<.*?>', re.DOTALL) > ... > >>> def striptags(text): > ... text = re.sub(comments,'', text) > ... text = re.sub(tags,'', text) > ... return text > ... > >>> def collapsenewlines(text): > ... return "\n".join(line for line in text.splitlines() if line) > ... > >>> import urllib2 > >>> f = urllib2.urlopen('http://www.python.org/') > >>> source = f.read() > >>> text = collapsenewlines(striptags(source)) > >>> > > This will of course fail if there is a "<" without a ">", probably in > other cases too. But it is indifferent to whether the html is > well-formed. It also fails on tags with a ">" in a string in the tag. That's well-formed but ill-used HTML. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
fdups: calling for beta testers
Hi all, I am looking for beta-testers for fdups. fdups is a program to detect duplicate files on locally mounted filesystems. Files are considered equal if their content is identical, regardless of their filename. Also, fdups ignores symbolic links and is able to detect and ignore hardlinks, where available. In contrast to similar programs, fdups does not rely on md5 sums or other hash functions to detect potentially identical files. Instead, it does a direct blockwise comparison and stops reading as soon as possible, thus reducing the file reads to a maximum. fdups has been developed on Linux but should run on all platforms that support Python. fdups' homepage is at http://www.homepages.lu/pu/fdups.html, where you'll also find a link to download the tar. I am primarily interested in getting feedback if it produces correct results. But as I haven't been programming in Python for a year or so, I'd also be interested in comments on code if you happen to look at it in detail. Your help is much appreciated. -pu -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting HTML to ASCII
On Fri, 25 Feb 2005 10:51:47 -0800 (PST), gf gf <[EMAIL PROTECTED]> wrote: > Hans, > > Thanks for the tip. I took a look at Beatiful Soup, > and it looked like it was a framework to parse HTML. This is my understanding, too. > I'm not really interetsed in going through it tag by > tag - just to get it converted to ASCII. How can I do > this with B. Soup? You should probably do what some other poster suggested -- download lynx or some other text-only browser and make your code execute it in -dump mode to get the text-formatted html. You'll get that working in an hour or so, and then you can see if you need something more complicated. /Jorgen -- // Jorgen GrahnR'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list
Re: unicode encoding usablilty problem
> This will help in your code, but there is big pile of modules in stdlib > that are not unicode-friendly. From my daily practice come shlex > (tokenizer works only with encoded strings) and logging (you cann't > specify encoding for FileHandler). You can, of course, pass in a stream opened using codecs.open to StreamHandler. Not quite as friendly, I'll grant you. Regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
Re: Dealing with config files what's the options
On Tue, 22 Feb 2005 20:38:28 -0500, Tom Willis <[EMAIL PROTECTED]> wrote: > How are the expert pythoneers dealing with config files? ... > Any ideas? How about writing them in Python? I have no URL handy, but it would surprise me if there wasn't a lot written about different techniques for doing this. /Jorgen -- // Jorgen GrahnR'lyeh wgah'nagl fhtagn! -- http://mail.python.org/mailman/listinfo/python-list