Re: KeyError
On Wednesday 15 December 2004 13:33, [EMAIL PROTECTED] wrote: > Hello. > Maybe someone will help me with this KeyError: > > > Traceback (most recent call last): > File "C:\Python\tabla.py", line 929, in -toplevel- > tablesDirectory = tablesDirectoryPrefix + os.environ['REMOTE_ADDR'] > File "C:\Python23\lib\os.py", line 417, in __getitem__ > return self.data[key.upper()] > KeyError: 'REMOTE_ADDR' > .. What trouble do you have? AFAICT, The key REMOVE_ADDR wasn't in the dictionary, meaning that the environment variable doesn't exist. Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: Import trouble
On Wednesday 15 December 2004 13:44, Craig Ringer wrote: > On Wed, 2004-12-15 at 21:45, Frans Englich wrote: > > 2) I use Python modules which are not usually installed(libxml2/libxslt) > > and want to fail gracefully in case the modules aren't available; print > > an informative message. Since these imports are done in several related > > programs, I don't want to duplicate the code, but instead centralize it. > > The problem is that when I put the module imports/exception code in a > > function, it is as if it wasn't imported, even though there was no > > exceptions. I suspect this is because the import is only done into the > > current namespace: the function scope(instead of file scope as I want). > > Is there any solution to my problem? Or should I solve it in another way? > > def import_xml: >try: >import libxml >except ImportError,err: ># handle the error >return libxml > > libxml = import_xml() Ah thanks. When will one stop to take the limits of Python's introspection for granted? Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: Python IDE
On Wednesday 15 December 2004 13:59, Chris wrote: > > Try WingIDE if you have some money (about 35 E/$ for the personal > > version) to spend, it's worth every (euro)cent. But please try SPE > > first, maybe that's enough for you. > > SPE? After googling for "python spe", my guess is "SPE - Stani's Python Editor": http://spe.pycs.net/ Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Import trouble
Hello all, I have a couple of questions related to module importing. 1) When I start my Python program with `python foo.py` instead of simply adding a interpreter comment on the first line and do `./foo.py`, some "local" imports fails, I guess because current working directory is different. Is CWD the only difference between running `python foo.py` and `./foo.py`? What is the recommended way? (I guess security is one aspect that can be argued) 2) I use Python modules which are not usually installed(libxml2/libxslt) and want to fail gracefully in case the modules aren't available; print an informative message. Since these imports are done in several related programs, I don't want to duplicate the code, but instead centralize it. The problem is that when I put the module imports/exception code in a function, it is as if it wasn't imported, even though there was no exceptions. I suspect this is because the import is only done into the current namespace: the function scope(instead of file scope as I want). Is there any solution to my problem? Or should I solve it in another way? 3) And the last -- but funniest -- import problem: sometimes imports of modules in "xml." fails, sometimes it works. For example, this code: from xml.dom.minidom import getDOMImplementation impl = getDOMImpmentation() #NameError: name 'getDOMImpmentation' is not defined fails as shown, and other times it works. When running pydoc as local web server, it also sometimes fails, although I haven't been able to reproduce for a error message. I have recent versions of PyXML and 4suite installed. What is wrong? Any idea what that could be wrong with my setup, which could cause this? Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: getopt: Make argument mandatory
On Wednesday 15 December 2004 20:12, Marc 'BlackJack' Rintsch wrote: > In <[EMAIL PROTECTED]>, Frans Englich > > wrote: > > Hello, > > > > In my use of getopt.getopt, I would like to make a certain parameter > > mandatory. > > Isn't a *mandatory option* a contradiction? Why don't you turn it into an > argument? You already called it argument in the subject of your post. I probably used an inconsisten wording; option equals argument. My point is to make an option/parameter/argument/call-it-what-you-like mandatory. When that particular option/argument then also has a value(instead of a simple toggle), that means a user specified value must always be specified. Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: libxml2/xpath
On Thursday 16 December 2004 14:46, [EMAIL PROTECTED] wrote: > > # confDocument is a libxml2 document, from parseFile() etc > > xp = confDocument.xpathNewContext() > > xp.xpathRegisterNs("xhtml", "http://www.w3.org/1999/xhtml";) > > dirElement = xp.xpathEval( "/xhtml:html" ) > > Stupid question, but can the namespace somehow be changed to null to > make queries simpler? (I am no libxml2, XML, or Python expert) There's a danger to that; the namespace is there for a reason. For example, if you put all elements in the document into one namespace, that could mean that you get elements which not is XHTML, but something else, totally different. In case you want to ignore namespaces, you must be 100% sure what the files to be processed contains, and that all namespaces that are thrown together can be treated equally. Regarding removing the namespace; you could probably process the DOM tree and remove all namespaces, before doing any XPath lookups. Perhaps libxml2 has utility functions for things like this(something like recursively set namespace for an element). Standard namespace-aware DOM probably has it.. Feel free to post your findings afterwards, although I wouldn't do it in the first place :) Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: getopt: Make argument mandatory
On Wednesday 15 December 2004 14:07, Diez B. Roggisch wrote: > > In my use of getopt.getopt, I would like to make a certain parameter > > mandatory. I know how to specify such that a parameter must have a value > > if it's specified, but I also want to make the parameter itself > > mandatory(combined with a mandatory value, the result is that the user > > must specify a value). > > Use optparse - in the examples section you'll find what you need. I'm slow here, do you mean in of the callback examples in 6.21.4? http://docs.python.org/lib/module-optparse.html Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: Time Difference
On Friday 17 December 2004 15:40, Fredrik Lundh wrote: > "GMane Python" <[EMAIL PROTECTED]> wrote: > > I was wondering if there is an existing function that would let me > > determine the difference in time. To explain: > > > > Upon starting a program: > > > > startup = time.time() > > > > After some very long processing: > > now = time.time() > > > > print, now - startup > > > > So, to print in a formatted way (D-H-M-S) the difference in time of > > startup and now. > > now - startup gives you the difference in seconds; turning that into (days, > hours, minutes, seconds) isn't that hard (hint: lookup the divmod function > in the manual). I've been struggling with that too. Here's some more documentation: http://pleac.sourceforge.net/pleac_python/datesandtimes.html I have a followup question on this, slightly off-topic: What is the best/simplest method to transfer a time to W3C XML Schema's type duration[1]? Is there any helper function for that? Cheers, Frans 1. http://www.w3.org/TR/xmlschema-2/#duration -- http://mail.python.org/mailman/listinfo/python-list
Re: A completely silly question
On Friday 17 December 2004 16:40, Amir Dekel wrote: > This must be the silliest question ever: > > What about user input in Python? (like stdin) > Where can I find it? I can't find any references to it in the > documentation. See sys.stdin Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
getopt: Make argument mandatory
Hello, In my use of getopt.getopt, I would like to make a certain parameter mandatory. I know how to specify such that a parameter must have a value if it's specified, but I also want to make the parameter itself mandatory(combined with a mandatory value, the result is that the user must specify a value). Here's code illustrating my point(see the TODO): # Parse command line flags # configurationFile = "" try: opts, args = getopt.getopt( argv, "hVc:", ["help", "version", "configuration-file="]) for opt,arg in opts: if opt in ("-c", "--configuration-file"): configurationFile = arg if opt in ("-h", "--help"): usage() if opt in ("-V", "--version"): print "Version:", common.version["Runner"] sys.exit() # TODO Can't getopt make an argument mandatory? if configurationFile == "": print "You must pass an URL/path to a configuration file, see --help." sys.exit(common.exitCodes["parameter"]) except getopt.GetoptError: usage() # Is it possible? Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: libxml2/xpath
On Thursday 16 December 2004 12:29, Maxim Khesin wrote: > I do not believe it is... You can see the doc by clicking on the link. > Does it have to be? No, but your XPath statements must match the namespace, no matter what it is. The document do have a namespace -- as XHTML should: http://www.w3.org/1999/xhtml";> The problem with this: mydoc.xpathEval('/html') is that it tries to match a top element whose local name is "html" and whose namespace is null, but in the source document, the local name is "html" but the namespace is not null, it's "http://www.w3.org/1999/xhtml"; --> they don't match. The solution is to have a matching namespace, such that the whole qualified name matches. AFAIK, it is done like this in libxml2: # confDocument is a libxml2 document, from parseFile() etc xp = confDocument.xpathNewContext() xp.xpathRegisterNs("xhtml", "http://www.w3.org/1999/xhtml";) dirElement = xp.xpathEval( "/xhtml:html" ) Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Documenting data members
Hello, I have a custom module which among others contains a dictionary, acting as a "constant". I want to document it, but no matter what I do, it doesn't show up in `pydoc`. For example, the following doesn't work: """ A dictionary of the namespaces. """ xmlns = { ... } or xmlns = { """ A dictionary of the namespaces. """ ... } Bottom line: how do I document data members? I also have another documentation question: In a module which I install, the file starts with a comment containing a license header, to then be followed by a Python documentation string("""this module ..."""). The problem is that in pydoc, I get the uninteresting license header as documentation, instead of the doc string. I want to have the license header at the top. Is this somehow fixable? That the doc string, instead of the license header, shows up in pydoc despite the latter being first in the file? Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
PyChecker messages
Hello, I take PyChecker partly as an recommender of good coding practice, but I cannot make sense of some of the messages. For example: runner.py:878: Function (main) has too many lines (201) What does this mean? Cannot functions be large? Or is it simply an advice that functions should be small and simple? runner.py:200: Function (detectMimeType) has too many returns (11) The function is simply a long "else-if" clause, branching out to different return statements. What's wrong? It's simply a "probably ugly code" advice? A common message is these: runner.py:41: Parameter (frame) not used But I'm wondering if there's cases where this cannot be avoided. For example, this signal handler: #--- def signalSilencer( signal, frame ): """ Dummy signal handler for avoiding ugly tracebacks when the user presses CTRL+C. """ print "Received signal", str(signal) + ", exiting." sys.exit(1) #--- _must_ take two arguments; is there any way that I can make 'frame' go away? Also, another newbie question: How does one make a string stretch over several lines in the source code? Is this the proper way? print "asda asda asda asda asda asda " \ "asda asda asda asda asda asda " \ "asda asda asda asda asda asda" Thanks in advance, Frans PS. Any idea how to convert any common time type to W3C XML Schema datatype duration? -- http://mail.python.org/mailman/listinfo/python-list
Refactoring; arbitrary expression in lists
As continuation to a previous thread, "PyChecker messages", I have a question regarding code refactoring which the following snippet leads to: > > runner.py:200: Function (detectMimeType) has too many returns (11) > > > > The function is simply a long "else-if" clause, branching out to > > different return statements. What's wrong? It's simply a "probably ugly > > code" advice? > > That is also advice. Generally you use a dict of functions, or some other > structure to lookup what you want to do. More specifically, my function looks like this: #-- def detectMimeType( filename ): extension = filename[-3:] basename = os.path.basename(filename) if extension == "php": return "application/x-php" elif extension == "cpp" or extension.endswith("cc"): return "text/x-c++-src" # etcetera elif extension == "xsl": return "text/xsl" elif basename.find( "Makefile" ) != -1: return "text/x-makefile" else: raise NoMimeError #-- (don't bother if the MIME detection looks like stone age, it's temporary until PyXDG gets support for the XDG mime type spec..) I'm now wondering if it's possible to write this in a more compact way, such that the if-clause isn't necessary? Of course, the current code works, but perhaps it could be prettier. I'm thinking along the lines of nested lists, but what is the obstacle for me is that both the test and return statement are simple expressions; not functions or a particular data type. Any ideas? Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: Refactoring; arbitrary expression in lists
On Wednesday 12 January 2005 18:56, [EMAIL PROTECTED] wrote: > I can not break the original code in 2.4, if I try this: [...] > > So although the dictionary solution is much nicer nothing seems wrong > with your code as it is - or am I missing something? Nope, the current code works. I'm just looking at Python's cool ways of solving problems. (the matter about 11 returns was a coding-style report from PyChecker). Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Assigning to self
Hello, I am having trouble with throwing class instances around. Perhaps I'm approaching my goals with the wrong solution, but here's nevertheless a stripped down example which demonstrates my scenario: #-- class foo: tests = {} def __init__( self, id ): try: me = self.__class__.tests[ id ] except KeyError: print "Did not exist, initializing myself.." self.attr = "exists" self.__class__.tests[ id ] = self else: print "Already exists! Re-using existing instance" self = me print "Me", self.attr + "!" # line 18 def yo(self): return self.attr # line 21 def main(): a = foo( "test" ) print "ATTR:", a.yo() b = foo( "test" ) print "ATTR:", b.yo() if __name__ == "__main__": main() #-- This is the output: Did not exist, initializing myself.. Me exists! ATTR: exists Already exists! Re-using existing instance Me exists! ATTR: Traceback (most recent call last): File "cpClass.py", line 32, in ? main() File "cpClass.py", line 29, in main print "ATTR:", b.yo() File "cpClass.py", line 21, in yo return self.attr # line 21 AttributeError: foo instance has no attribute 'attr' #-- What the code attempts to do is implementing a, to the API user, transparent memory-saver by ensuring that no more than one instance of the class foo exists for a particular id. E.g, the user can simply "create" an instance and if one not already exists, it is created. First of all; am I approaching the goal with the right solution? The way I do fails, obviously. The line 'self = me'(scary..) doesn't really work for the attribute attr; the attribute exists on line 21, but it fails when yo() tries to access it. What have failed? Is it a namespace scope issue? Do 'self = me' do what I think it should? Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: Assigning to self
On Monday 17 January 2005 18:45, Frans Englich wrote: > The line 'self = me'(scary..) doesn't really > work for the attribute attr; the attribute exists on line 21, but it fails > when yo() tries to access it. Typo; line 21 is yo(). I ment line 18, the print statement in __init__. Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: Assigning to self
On Monday 17 January 2005 19:02, Peter Otten wrote: > Frans Englich wrote: > > What the code attempts to do is implementing a, to the API user, > > transparent memory-saver by ensuring that no more than one instance of > > the class foo exists for a particular id. E.g, the user can simply > > "create" an instance and if one not already exists, it is created. > > By the time __init__() is called, a new Foo instance has already been > > created. Therefore you need to implement Foo.__new__(). E. g.: > >>> class Foo(object): > > ... cache = {} > ... def __new__(cls, id): > ... try: > ... return cls.cache[id] > ... except KeyError: > ... pass > ... cls.cache[id] = result = object.__new__(cls, id) > ... return result > ... def __init__(self, id): > ... self.id = id > ... def __repr__(self): > ... return "Foo(id=%r)" % self.id > ... I'm not sure, but I think this code misses one thing: that __init__ is called each time __new__ returns it, as per the docs Peter posted. Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: Assigning to self
On Monday 17 January 2005 20:55, Frans Englich wrote: > On Monday 17 January 2005 19:02, Peter Otten wrote: > > Frans Englich wrote: > > > What the code attempts to do is implementing a, to the API user, > > > transparent memory-saver by ensuring that no more than one instance of > > > the class foo exists for a particular id. E.g, the user can simply > > > "create" an instance and if one not already exists, it is created. > > > > By the time __init__() is called, a new Foo instance has already been > > > > created. Therefore you need to implement Foo.__new__(). E. g.: > > >>> class Foo(object): > > > > ... cache = {} > > ... def __new__(cls, id): > > ... try: > > ... return cls.cache[id] > > ... except KeyError: > > ... pass > > ... cls.cache[id] = result = object.__new__(cls, id) > > ... return result > > ... def __init__(self, id): > > ... self.id = id > > ... def __repr__(self): > > ... return "Foo(id=%r)" % self.id > > ... > > I'm not sure, but I think this code misses one thing: that __init__ is > called each time __new__ returns it, as per the docs Peter posted. Ahem, John I ment :) The second typo today.. Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: Assigning to self
On Monday 17 January 2005 20:03, John Roth wrote: > "Frans Englich" <[EMAIL PROTECTED]> wrote in message > In other words, you're trying to create a singleton. In general, > singletons are frowned on these days for a number of reasons, > not least because of the difficulty of testing them. Then I have some vague, general questions which perhaps someone can reason from: what is then the preferred methods for solving problems which requires Singletons? Is it only frowned upon in Python code? Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: Assigning to self
On Monday 17 January 2005 21:24, Peter Otten wrote: > Frans Englich wrote: > > On Monday 17 January 2005 20:03, John Roth wrote: > >> "Frans Englich" <[EMAIL PROTECTED]> wrote in message > > > > > > > >> In other words, you're trying to create a singleton. In general, > >> singletons are frowned on these days for a number of reasons, > >> not least because of the difficulty of testing them. > > > > Then I have some vague, general questions which perhaps someone can > > reason from: what is then the preferred methods for solving problems > > which requires Singletons? Is it only frowned upon in Python code? > > Sorry, no answer here, but do you really want a singleton? > > Singleton: "Ensure a class only has one instance, and provide a global > point of access to it" > > whereas > > Flyweight: "Use sharing to support large numbers of fine-grained objects > efficiently" > > as per "Design Patterns" by Gamma et al. Hehe :) Singleton sounds like what I want, but OTOH I do not know what Flyweight is, except for sounding interesting. Darn, I really must save for that Design Patterns by GOF. Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
What is print? A function?
Nah, I don't think it's a function, but rather a builtin "statement". But it's possible to invoke it as an function; print( "test" ) works fine. So I wonder, what _is_ exactly the print statement? The untraditional way of invoking it(without paranteses) makes me wonder. The reason I thinks about this is I need to implement a debug print for my program; very simple, a function/print statement that conditionally prints its message whether a bool is true. Not overly complex. I tried this by overshadowing the print keyword, but that obviously didn't work.. Is defining a two-liner function the right way to go, or is there better ways to approach it? Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: What is print? A function?
On Sunday 23 January 2005 18:04, Michael Hoffman wrote: > Frans Englich wrote: [...] > if command_line_debug_option: > debug = _debug_true > else > debug = _debug_false I find this a nice solution. The most practical would be if it was possible to do this with print, of course. But print won't budge. Is it possible to create own statements, such that it would be possible to do: printDebug "test" ? Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Distutils: blurring the file==module borders
Hello all, Due to the size of my source, I want to split it up into multiple files(basically one class in each file), but then I have difficulties with the directory layout when the modules are installed with distutils. This is my file layout: in ./ I have a setup.py which has 'packages="foo"' in ./foo/ I have an __init__.py and a handful of files named ClassA.py, ClassB.py, ClassC.py and so forth. The problem is that when installed, in order to reach, say, classB, I need to do: import foo.ClassA var = foo.ClassA.ClassA() while I want to do var = foo.ClassA() In other words, the result I want can be achieved by putting all code in __init__.py. The problem is that I would find it horrible to have all code in one file. Python have this one-to-one relationship between modules and files; can what I want somehow be achieved? Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: Distutils: blurring the file==module borders
On Tuesday 25 January 2005 02:17, Bill Mill wrote: > read this thread, it should help you: > > http://mail.python.org/pipermail/tutor/2005-January/035124.html Thanks, it did. Not optimally, but in the way I suspected it would be solved. In short, the solution, when translated to my case, is to in __init__.py do `from ClassA import ClassA`, and hence get the /class/ ClassA in the module's namespace. Note, I did not do `from foo.ClassA import ClassA` because that failed. To me, it is kinda hackish; it doesn't show up in the pydocs, and no idea if it shadows the actual module(assuming they have identical names, which they have) but it appears it can't be solved in a better way. Another approach would to do copy&paste with the build system at install time, but I will not sink that low.. Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: python without OO
On Wednesday 26 January 2005 18:55, Terry Reedy wrote: > Your Four Steps to Python Object Oriented Programming - vars, lists, dicts, > and finally classes is great. It makes this thread worthwhile. I saved it > and perhaps will use it sometime (with credit to you) to explain same to > others. I think so too. M.E. Farmer's reflections on management was also a shining piece of gold in this thread. Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Inherting from object. Or not.
(Picking up a side track of the "python without OO" thread.) On Wednesday 26 January 2005 11:01, Neil Benn wrote: > I say this because you do need to be aware of the > 'mythical python wand' which will turn you from a bad programmer into a > good programmer simply by typing 'class Klass(object):'. What is the difference between inherting form object, and not doing it? E.g, what's the difference between the two following classes? class foo: pass class bar(object): pass Sometimes people inherit from it, and sometimes not. I don't see a pattern in their choices. Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: Inherting from object. Or not.
On Wednesday 26 January 2005 21:24, M.E.Farmer wrote: > Hello Frans, > What you are seeing is a step on the path to unification of types and > classes. I changed all base classes in my project to inherit object. There appears to be no reason to not do it, AFAICT. Thanks, Frans -- http://mail.python.org/mailman/listinfo/python-list
Python's idiom for function overloads
Hello, Since Python doesn't have static typing, how is the same result as traditional function overloads results in acheived? With function overloads the "selection of code path depending on data type" is transparent and automatic since the typing system figure out what goes to what. But in Python, when one wants to be able to pass different data types into a single "entry point" for functionality, how is that best done? To in a function do an if statement with the type() function? Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: variable declaration
On Tuesday 01 February 2005 05:08, Cameron Laird wrote: > We learned long ago to treat you, Alex, as an exception. > While it's rather unpythonic to have implicit rules, let's > forgive Robert for failing to mention the one that regards > you as an outlier for inferential purposes. Excellent timing! I thought I would miss the next episode of "Xah Lee -- will you flee?" but I think I will manage to zap back in time. You see, my friends think I am different from them when I ignore the soap operas on TV, to go for the daily read of python-list. They couldn't be more wrong. Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's idiom for function overloads
On Tuesday 01 February 2005 05:02, Steven Bethard wrote: > Frans Englich wrote: > > But in Python, when one wants to be able to pass different data types > > into a single "entry point" for functionality, how is that best done? To > > in a function do an if statement with the type() function? > > It often depends a lot on the specific use case... Do you have a > particular example in mind? I did have a specific scenario, but it blurred into a general wondering about typing. I think my problem was, and still is, that I don't think in Python terms but try to force other idioms. Thinking in static typic terms when Python goes in the opposite direction clearly shows friction is created. The replies were interesting, Frans -- http://mail.python.org/mailman/listinfo/python-list
What's wrong with `is not None`?
That's what PyChecker tells me, at least. A line of: if testReport is not None: results in: runner.py:587: Using is not None, may not always work In what circumstances can `is not None` fail? How and why does it fail? What is the equivalent expression which is more secure; `!= None`? Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Hack with os.walk()
Hello, Have a look at this recursive function: def walkDirectory( directory, element ): element = element.newChild( None, "directory", None ) # automatically appends to parent element.setProp( "name", os.path.basename(directory)) for root, dirs, files in os.walk( directory ): for fileName in files: element.addChild( parseFile( os.path.join( root, fileName )) for dirName in filter( acceptDirectory, dirs): walkDirectory( os.path.join( root, dirName ), element ) return ### Note, this is inside for loop What it does, is it recurses through all directories, and, with libxml2's bindings, builds an XML document which maps directly to the file hierarchy. For every file is parseFile() called, which returns a "file element" which is appended; the resulting structure looks the way one expect -- like a GUI tree view. The current code works, but I find it hackish, and it probably is inefficient, considering that os.walk() is not called once(as it usually is), but for every directory level. My problem, AFAICT, with using os.walk() the usual way, is that in order to construct the /hierarchial/ XML document, I need to be aware of the directory depth, and a recursive function handles that nicely; os.walk() simply concentrates on figuring out paths to all files in a directory, AFAICT. I guess I could solve it with using os.walk() in a traditional way, by somehow pushing libxml2 nodes on a stack, after keeping track of the directory levels etc(string parsing..). Or, one could write ones own recursive directory parser.. My question is: what is the least ugly? What is the /proper/ solution for my problem? How would you write it in the cleanest way? Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: Kill GIL
On Monday 14 February 2005 00:53, Aahz wrote: > In article <[EMAIL PROTECTED]>, Mike Meyer <[EMAIL PROTECTED]> wrote: > >[EMAIL PROTECTED] (Aahz) writes: > >> In article <[EMAIL PROTECTED]>, Mike Meyer <[EMAIL PROTECTED]> wrote: > >>>Here here. I find that threading typically introduces worse problems > >>>than it purports to solve. > >> > >> Threads are also good for handling blocking I/O. > > > >Actually, this is one of the cases I was talking about. I find > >it saner to convert to non-blocking I/O and use select() for > >synchronization. That solves the problem, without introducing any of > >the headaches related to shared access and locking that come with > >threads. > > It may be saner, but Windows doesn't support select() for file I/O, and > Python's threading mechanisms make this very easy. If one's careful > with application design, there should be no locking problems. (Have you > actually written any threaded applications in Python?) Hehe.. the first thing a google search on "python non-blocking io threading" returns "Threading is Evil". Personally I need a solution which touches this discussion. I need to run multiple processes, which I communicate with via stdin/out, simultaneously, and my plan was to do this with threads. Any favorite document pointers, common traps, or something else which could be good to know? Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Distutils: relative paths
Hello, I have trouble installing a data directory which is not a child of my package directory in the source directory. My source directory looks like this: ./setup.py schemas/*.xsd foo/*.py And when it's installed, it should look like: site-packages/foo/*.py site-packages/foo/schemas/*.xsd In other words, schemas, from being a sibling of foo, became a child of foo. Now, how is this expressed in the setup.py? I tried this: setup( name="Foo", packages=["foo"], package_data={ "foo": ["../schemas/*.xsd"] }, package_dir={ "foo": "foo"}, [...] but it resulted in schemas being a package, not child of foo(!). I've read the relevant page in the reference manual, http://www.python.org/doc/current/dist/node11.html but I can't find the trick. Any ideas? Cheers, Frans -- http://mail.python.org/mailman/listinfo/python-list
Accessing files installed with distutils
This is silly. How do I access data files I've installed with distutils? In a portable, generic way, I want to find out what is the following path on most systems: /usr/local/lib/python2.4/lib/site-packages/foo/bar.txt How do I figure out the rest, if I know foo/bar.txt? sys.prefix doesn't get me far. I've googled, and looked in the python reference. I must be blind if the distutils section[1] covers this. Cheers, Frans 1. http://www.python.org/doc/current/dist/dist.html -- http://mail.python.org/mailman/listinfo/python-list
Default function arguments, KURL::cleanPath() -- a bindings bug?
Hello, I've stumbled over a behavior related to default function arguments which appears to be a bug, from what I can tell. See this snippet: >>> from kdecore import KURL >>> u = KURL( "http://www.example.org/test/../"; ) >>> u.cleanPath() Traceback (most recent call last): File "", line 1, in ? TypeError: insufficient number of arguments to KURL.cleanPath() >>> >>> u.cleanPath(True) >>> Apparently, cleanPath /requires/ a boolean argument, but the C++ function definition says: void cleanPath(bool cleanDirSeparator = true); What have I missed? Thanks in advance, Frans -- http://mail.python.org/mailman/listinfo/python-list
Re: Default function arguments, KURL::cleanPath() -- a bindings bug?
Ups, that was meant to go to the pykde list. Sorry, Frans -- http://mail.python.org/mailman/listinfo/python-list