December PSF Board meeting minutes available
Minutes of a Regular Meeting of the Board of Directors of the Python Software Foundation, December 10, 2007: http://www.python.org/psf/records/board/minutes/2007-12-10/ -- David Goodger http://python.net/~goodger -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Bookmarks Database and Internet Robot 4.1
Hello! Bookmarks Database and Internet Robot WHAT IS IT A set of classes, libraries, programs and plugins I use to manipulate my bookmarks.html. I like Mozilla, but I need more features. I want to extend Mozilla's Check for updates feature (Navigator4 called it Update bookmarks). WHAT'S NEW in version 4.1.0 (2008-01-14) Parser for HTML based on BeautifulSoup. Changed User-agent header: I saw a number of sites that forbid Mozilla compatible browsers. Added a number of fake headers to pretend this is a real web-browser - there are still stupid sites that are trying to protect themselves from robots by analyzing headers. Handle redirects while looking for the icon. Handle float timeouts in HTML redirects. Minimal required version of Python is 2.5 now. WHAT'S NEW in version 4.0.0 (2007-10-20) Extended support for Mozilla: charset and icon in bookmarks. Use the charset to add Accept-Charset header. Retrieve favicon.ico (or whatever link points to) and store it. The project celebrates 10th anniversary! WHAT'S NEW in version 3.4.1 (2005-01-29) Updated to Python 2.4. Switched from CVS to Subversion. WHERE TO GET Master site:http://phd.pp.ru/Software/Python/#bookmarks_db A mirror: http://phd.webhost.ru/Software/Python/#bookmarks_db AUTHOR Oleg Broytmann [EMAIL PROTECTED] COPYRIGHT Copyright (C) 1997-2008 PhiloSoft Design LICENSE GPL Oleg. -- Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED] Programmers don't die, they just GOSUB without RETURN. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: virtualpython / workingenv / virtualenv ... shouldn't this be part of python
My question is, shoudn't it be enough to set PYTHONPATH and everything automagically to work then? Is there some work done on this for python 3.0 or 2.6 perhaps? I'm working on a PEP for a per user site dir for 2.6 and 3.0 great .. can't hardly wait. -- damjan -- http://mail.python.org/mailman/listinfo/python-list
Re: hide object property from dir() function?
jerryji wrote: Sorry for this newbie question, I was puzzled why the existing property of an object is not shown in the dir() function output. The under-development version of Python (2.6) allows for a __dir__ magic method by which the class implementer can return whatever he wishes from a dir (). This is to help, for example, modules like my WMI one which makes heavy use of __getattr__ magic to proxy across Windows COM attributes. This, in turn, helps editors and IDEs which can provide popup lists of attributes etc. All that said, I don't believe it takes any automatic account of properties. TJG noddy code example class X (object): def __init__ (self, a): self.a = a print dir (X (1)) def __dir__ (self): return ['x', 'y', 'z'] X.__dir__ = __dir__ print dir (X (2)) /code -- http://mail.python.org/mailman/listinfo/python-list
Re: import from question
iu2 [EMAIL PROTECTED] wrote: file a3.py: from a1 import the_number import a2 ... Why doesn't it work in the first version of a3.py? Think of 'import a2' as being the same as: a2 = __import__('a2') and 'from a1 import the_number' as roughly the same as: the_number = __import__('a1').the_number In other words think of them as assignments and it should all make sense. -- http://mail.python.org/mailman/listinfo/python-list
print to a derived file
Hi, I'm trying to write data to both a file and the console, so I did: class File_and_console(file): def write(self, s): file.write(self, s) print s, f = File_and_console('1.txt', 'w') f.write('hello') hello print f, 'world' the 'write' method works, but 'print ' doesn't, it writes only to the file. It doesn't actually call File_and_console.write Why? How can I fix it? Thanks iu2 -- http://mail.python.org/mailman/listinfo/python-list
Re: env parameter to popen won't accept Unicode on Windows - minor Unicode bug
John Nagle wrote: Benjamin wrote: On Jan 14, 6:26 pm, Bjoern Schliessmann usenet- [EMAIL PROTECTED] wrote: John Nagle wrote: It turns out that the strings in the env parameter have to be ASCII, not Unicode, even though Windows fully supports Unicode in CreateProcess. That's of course nonsense, they don't need to be ascii, they need to be byte-strings in whatever encoding you like. Are you sure it supports Unicode, not UTF8 or UTF16? Probably using something like uthestring.encode(utf16) will help. Otherwise: bugs.python.org John's understanding of the differences between unicode and it's encodings is a bit blurry, to say the least. Whatever translation is necessary should be done in popen, which has cases for Windows and POSIX. popen is supposed to be cross-platform to the extent possible. I think it's just something that didn't get fixed when Unicode support went in. Sure thing, python will just magically convert unicode to the encoding the program YOU invoke will expect. Right after we introduced the solve_my_problem() built-in-function. Any other wishes? If I write this simple program -- test.py --- import os import sys ENCODDINGS = ['utf-8', 'latin1'] os.env[MY_VARIABLE].encode(ENCODINGS[int(sys.argv[1])]) -- test.py --- how's python supposed to know that suprocess.call(python test.py 0, env=dict(MY_VARIABLE=u'foo')) needs to be UTF-8? Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamical scoping
On 15 Jan., 02:13, Paul Rubin http://[EMAIL PROTECTED] wrote: George Sakkis [EMAIL PROTECTED] writes: What's the best way to simulate dynamically scoped variables ala Lisp ? Ugh check the docs for the python 2.5 with statement, which gives you sort of a programmable unwind-protect (more powerful than try/except). You'd have an environment dictionary and use the with statement to maintain a stack of shallow-binding cells like in an old-time lisp system, automatically unwinding when the with suite finishes. The whole concept sounds hopelessly crufty--I think nobody even does it that way in Lisp any more, you're better off passing an environment around explicitly. If there were a lot of variables, this could be a good application for functional maps, which I've been wanting to implemetn for python. -- http://mail.python.org/mailman/listinfo/python-list
[help request] how to set sys.stderr to object of cStringIO type
I am in a perculiar situation. I want to use PyRun_SimpleString for creating Python functions in embedded Python in C++. But there could be cases when Python function code compilation could fail PyRun_SimpleString will return -1 as return status. At this time, it prints the error message to sys.stderr. So, we do not have any control or cannot use that message to show to user to correct the errors in the function code. I could assign an object of cStringIO type to sys.stderr at Python command prompt as below: import sys import cStringIO obj=cStringIO.StringIO() sys.stderr=obj And then using the obj.getvalue(), I could print exceptions printed to sys.stderr. But, I am not able to figure out, how can I do this same thing in Python/C API in my program using Py* functions? How do we set the sys.stderr to cStringIO object from Python embedded in C++ or C? Should I be using PyFile_FromFile for convert the cStringIO object? Please help. -- http://mail.python.org/mailman/listinfo/python-list
Re: Append zip files together, just get the binary data (in memory)
On Jan 15, 9:58 am, Diez B. Roggisch [EMAIL PROTECTED] wrote: Module StringIO is your friend. and cStringIO is your ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Data mapper - need to map an dictionary of values to a model
Luke: What design patterns would you use here? What about generator (scanner) with parameters? :-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
Hrvoje Niksic a écrit : Ben Finney [EMAIL PROTECTED] writes: Hrvoje Niksic [EMAIL PROTECTED] writes: Wildemar Wildenburger [EMAIL PROTECTED] writes: __init__() /initializes/ an instance (automatically after creation). It is called, /after/ the instance has been constructed I don't understand the purpose of this correction. After all, __init__ *is* the closest equivalent to what other languages would call a constructor. No. That would be '__new__', which actually constructs the instance, That's not what other OO languages (C++, Java) actually call a constructor, There are actually quite a few other OOPLs than C++ and Java, and at least one of them (namely Smalltalk, which predates both C++ and Java) uses distinct phases for allocation and initialisation. IOW, it's not because C++ and/or Java use a given terminology that this terminology should be blindly applied to each and every other OOPL. FWIW, there are quite a lot of other differences between C++/Java and Python when it comes to object model, and what OO is is definitively *not* defined by C++ and/or Java. So while it's true that __init__ is the closest equivalent to what C++ and Java (and possibly a couple other languages) call a constructor, it doesn't imply that you should refer to it as the constructor. As Neil Cerutti points out, there's in fact nothing like a 'constructor method' in Python : there are a __new__ method, an __init__ method, and constructor expressions which may invoke them !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too slow?
Paul Boddie: what is everyone with any degree of concern about Python's performance doing to improve the situation? They are probably developing systems like Cython and ShedSkin, and hoping to see Psyco improved again to manage itertools better (and maybe 64 bit CPUs too). Sure, C (or actually C++) seems to win the shootout [1], Beside C++ being the faster (not C anymore), there are other ways to win the Shootout, like using less RAM, writing shorter code, etc. If you change the way you measure you can see that FreePascal, Ruby and D too win the Shootout :-) (the first as the one using less memory, the second one as the one with shorter programs, and the third one as faster with shorter programs). but there are plenty of language implementations between g++ and CPython to suggest that the old choice of extension modules written in C vs. other code written in Python doesn't provide a complete map of the opportunities. I think in few years it may become feasible to use Pyd to write extensions in D for CPython :-) Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamical scoping
On 14 Jan., 21:17, George Sakkis [EMAIL PROTECTED] wrote: What's the best way to simulate dynamically scoped variables ala Lisp ? The use case is an open-ended set of objects that need to access the same piece of information (e.g. a dict, a ConfigParser object, a logger etc.). I know that the proper OO and functional way is to pass the information explicitly but that's less maintenable in the long run. Also this is in a web environment so the information can't be really global (though within-thread global should be fine). Is there some standard pattern for this scenario ? George What do you mean by really global and why is module local or builtin a problem in the presence of the GIL? Passing objects as parameters into functions doesn't ensure any more thread safety. Where do you think does Lisp ( which one? ) stores dynamically scoped variables? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too slow?
Jaimy Azle a écrit : [EMAIL PROTECTED] wrote: fact 1: CPython compiles source code to byte-code. fact 2: CPython executes this byte-code. fact 3: Sun's JDK compiles source code to byte-code. fact 4: Sun's JDK executes this byte-code. Fact 4 is misleading because it is only one option available to Sun's JDK. Sun's JDK is also capable of transforming the byte-code to native code and letting the processor execute that instead of the original byte code, and that is where the most significant speed increase comes from. Most importantly, it does so automatically, by default, with no programmer intervention or configuration, and with 100% compatibility, so it doesn't compare well to Python accelerators like psyco. Then fact 1 is misleading too since Python handles the compilation automatically without programmer's intervention while Java requires someone to explicitely invoke the byte-code compiler. Sadly it is true also, I read somewhere this silly point was used also to make distinction between java and python, then claiming python is just like another interpreter, while java has it's own (what they call as) 'compiler'. :) perhaps in the future another sillly point could be added also, Java has Jython, while Python doesn't have some thing like PyJava or... perhaps Py-va (Python based Java Language). Lol. At least some common sens in this stupid thread. Thanks Jaimy, you made my day !-) Salam, Peace. PS : and BTW : my apologies to the community - I should have made my point only once and then shut up. Sorry. -- http://mail.python.org/mailman/listinfo/python-list
common problem - elegant solution sought
Hi, I'm looking for an elegant solution of the following tiny but common problem. I have a list of tuples (Unique_ID,Date) both of which are strings. I want to delete the tuple (element) with a given Unique_ID, but I don't known the corresponding Date. My straight forward solution is a bit lengthy, e.g. L=[(a,070501),(b,080115),(c,071231)] pos=-1 found=-1 for (Key,Date) in L : pos+= 1 if Key == b : found= pos break if found = 0 : del L[found] print L Most probably there are much more elegant solutions. Unfortunately, the index-list-method doesn't take an additional function argument for the comparisons. Many thanks for your hints, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQL-python-1.2.2 install with no mysql
washakie napisał(a): I need to install the MySQL-python-1.2.2 connector in order to access a db on another machine. In the install it asks for the location of the mysql_config file, and if I leave it as the default I get: [EMAIL PROTECTED] MySQL-python-1.2.2]# python setup.py build sh: mysql_config: command not found Traceback (most recent call last): File setup.py, line 16, in ? metadata, options = get_config() File /opt/MySQL-python-1.2.2/setup_posix.py, line 43, in get_config libs = mysql_config(libs_r) File /opt/MySQL-python-1.2.2/setup_posix.py, line 24, in mysql_config raise EnvironmentError, %s not found % mysql_config.path EnvironmentError: mysql_config not found [EMAIL PROTECTED] MySQL-python-1.2.2]# How can I install MySQL-python-1.2.2 without installing MySQL??? In short: without installing client libraries you cann't. -- Jarek Zgoda Skype: jzgoda | GTalk: [EMAIL PROTECTED] | voice: +48228430101 We read Knuth so you don't have to. (Tim Peters) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too slow?
A lecturer gave me the perfect answer to the question of speed. You have two choices when it comes to programming. Fast code, or fast coders. -- http://mail.python.org/mailman/listinfo/python-list
Re: common problem - elegant solution sought
I have a list of tuples (Unique_ID,Date) both of which are strings. I want to delete the tuple (element) with a given Unique_ID, but I don't known the corresponding Date. My straight forward solution is a bit lengthy, e.g. L=[(a,070501),(b,080115),(c,071231)] Do they have to be tuples? Seems to me if you are using a Unique_ID that a dictionary would be perfect. Indeed when you are looking to delete an entry you can simply look for the Unique_ID in the dictionary and it will be a very fast look up. if key in my_dictionary: However, if you must use a list of tuples, your current method is very inefficient. Why not use the del within the if Key == b:? I cannot provide extremely elegant solutions with your current system, but I can tell you with a large enough list your way is going to take a very long time since you will iterate over the whole list sequentially to find an entry... -- http://mail.python.org/mailman/listinfo/python-list
Re: common problem - elegant solution sought
Helmut Jarausch wrote: I'm looking for an elegant solution of the following tiny but common problem. I have a list of tuples (Unique_ID,Date) both of which are strings. I want to delete the tuple (element) with a given Unique_ID, but I don't known the corresponding Date. My straight forward solution is a bit lengthy, e.g. L=[(a,070501),(b,080115),(c,071231)] pos=-1 found=-1 for (Key,Date) in L : pos+= 1 if Key == b : found= pos break if found = 0 : del L[found] print L Most probably there are much more elegant solutions. Unfortunately, the index-list-method doesn't take an additional function argument for the comparisons. Probably the most common solution to this in Python is to produce a second list which has all the items in the first except for the one(s) you wish to delete: code L=[(a,070501),(b,080115),(c,071231)] L2 = [(uniqid, date) for (uniqid, date) in L if not uniqid == 'b'] /code It might look a little wasteful, but since Python lists are supremely fast and since the tuples themselves aren't copied, only their references, the result is probably what you need. Obviously you've given us a toy example, which is fine for demonstrating the problem. Suggestions might vary if, for example, your data set were much bigger or if the tuples were more complex. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: print to a derived file
This might have something to do with the class being derived from file. I've written it so that it doesn't derive from file, and it works. class File_and_console(): def __init__(self, *args): self.fileobj = open(*args) def write(self, s): self.fileobj.write(s) print s, f = File_and_console('testout.tmp','w') f.write('hello') print f,'hello', On 1/15/08, iu2 [EMAIL PROTECTED] wrote: Hi, I'm trying to write data to both a file and the console, so I did: class File_and_console(file): def write(self, s): file.write(self, s) print s, f = File_and_console('1.txt', 'w') f.write('hello') hello print f, 'world' the 'write' method works, but 'print ' doesn't, it writes only to the file. It doesn't actually call File_and_console.write Why? How can I fix it? Thanks iu2 -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
MySQL-python-1.2.2 install with no mysql
Hello, I need to install the MySQL-python-1.2.2 connector in order to access a db on another machine. In the install it asks for the location of the mysql_config file, and if I leave it as the default I get: [EMAIL PROTECTED] MySQL-python-1.2.2]# python setup.py build sh: mysql_config: command not found Traceback (most recent call last): File setup.py, line 16, in ? metadata, options = get_config() File /opt/MySQL-python-1.2.2/setup_posix.py, line 43, in get_config libs = mysql_config(libs_r) File /opt/MySQL-python-1.2.2/setup_posix.py, line 24, in mysql_config raise EnvironmentError, %s not found % mysql_config.path EnvironmentError: mysql_config not found [EMAIL PROTECTED] MySQL-python-1.2.2]# How can I install MySQL-python-1.2.2 without installing MySQL??? thanks!! -- View this message in context: http://www.nabble.com/MySQL-python-1.2.2-install-with-no-mysql-tp14836669p14836669.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: __init__ explanation please
Bruno Desthuilliers [EMAIL PROTECTED] writes: So while it's true that __init__ is the closest equivalent to what C++ and Java (and possibly a couple other languages) call a constructor, it doesn't imply that you should refer to it as the constructor. As Neil Cerutti points out, there's in fact nothing like a 'constructor method' in Python : there are a __new__ method, an __init__ method, and constructor expressions which may invoke them !-) I agree with this. The poster I was responding to called __init__ akin to a constructor, which (to me) implied connection to other languages, not aspiration to define __init__ as THE constructor. -- http://mail.python.org/mailman/listinfo/python-list
Re: print to a derived file
On Jan 15, 12:44 pm, Ben Fisher [EMAIL PROTECTED] wrote: This might have something to do with the class being derived from file. I've written it so that it doesn't derive from file, and it works. class File_and_console(): def __init__(self, *args): self.fileobj = open(*args) def write(self, s): self.fileobj.write(s) print s, f = File_and_console('testout.tmp','w') f.write('hello') print f,'hello', Thanks, but that's what I tried first. Then I though it would be nice if I could just inherit from 'file' and implement this with less code. -- http://mail.python.org/mailman/listinfo/python-list
Re: common problem - elegant solution sought
Helmut Jarausch a écrit : Hi, I'm looking for an elegant solution of the following tiny but common problem. I have a list of tuples (Unique_ID,Date) both of which are strings. I want to delete the tuple (element) with a given Unique_ID, but I don't known the corresponding Date. If you don't care about ordering, you could use a dict: L=[(a,070501),(b,080115),(c,071231)] d = dict(L) del d['b'] L = d.items() But I guess you care about ordering !-) Anyway, you can still use a dict to find out the date part: L=[(a,070501),(b,080115),(c,071231)] d = dict(L) t = ('b', d['b']) L.remove(t) Or you could build an 'index' list to find out the appropriate index: L=[(a,070501),(b,080115),(c,071231)] index = [key for key, val in L] pos = index.index('b') del L[pos] My straight forward solution is a bit lengthy, e.g. L=[(a,070501),(b,080115),(c,071231)] pos=-1 found=-1 for (Key,Date) in L : pos+= 1 if Key == b : found= pos break if found = 0 : del L[found] print L You could have used the enumerate(seq) function here. And since you're breaking out once the element deleted, you could as well delete it from within the loop: for pos, (key, date) in enumerate(L): if key == 'b': del L[pos] break Benchmarking left as an exercice to the reader !-) Also note that the best solution may depend on your real use case and dataset. -- http://mail.python.org/mailman/listinfo/python-list
Re: common problem - elegant solution sought
Thanks to you all for your help. The solution to regenerate the list skipping the one to be deleted is fine for me since my lists are of moderate size and the operation is infrequent. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Re: how to set sys.stderr to object of cStringIO type
On Jan 15, 5:45 pm, grbgooglefan [EMAIL PROTECTED] wrote: I am in a perculiar situation. I want to use PyRun_SimpleString for creating Python functions in embedded Python in C++. But there could be cases when Python function code compilation could fail PyRun_SimpleString will return -1 as return status. At this time, it prints the error message to sys.stderr. So, we do not have any control or cannot use that message to show to user to correct the errors in the function code. I could assign an object of cStringIO type to sys.stderr at Python command prompt as below: import sys import cStringIO obj=cStringIO.StringIO() sys.stderr=obj And then using the obj.getvalue(), I could print exceptions printed to sys.stderr. But, I am not able to figure out, how can I do this same thing in Python/C API in my program using Py* functions? How do we set the sys.stderr to cStringIO object from Python embedded in C++ or C? Should I be using PyFile_FromFile for convert the cStringIO object? Please help. I have got a solution for this. Would like to know if this is the correct way or will it cause any problems if program runs for long time? /***/ /--1st stage is assign object of cStringIO to sys.stderr at initialization /-- once that is done, we can call getvalue() on that object on every error. /-/ PyObject *_pPyobStringIO; PyObject *_pPyGetValFunc; _pPyobStringIO=NULL; _pPyGetValFunc=NULL; PyObject *obFuncStringIO = NULL; int ret1 = 0; // Import cStringIO module PyObject * modStringIO = PyImport_ImportModule(cStringIO); if(PyErr_Occurred() || modStringIO == NULL){ printf(pyParserEvaluator::Init::PyImport cStringIO failed:); PyErr_Print(); goto PY_INIT_ERR; } // get StringIO constructor obFuncStringIO = PyObject_GetAttrString(modStringIO, StringIO); if(PyErr_Occurred() || obFuncStringIO == NULL){ printf(pyParserEvaluator::Init: cant find cStringIO.StringIO:); PyErr_Print(); goto PY_INIT_ERR; } // Construct cStringIO object _pPyobStringIO = PyObject_CallObject(obFuncStringIO, NULL); if(PyErr_Occurred() || _pPyobStringIO==NULL){ printf(pyParserEvaluator::Init: cStringIO.StringIO() failed:); PyErr_Print(); goto PY_INIT_ERR; } // get the getvalue function ptr _pPyGetValFunc = PyObject_GetAttrString(_pPyobStringIO, getvalue); if(PyErr_Occurred() || _pPyGetValFunc==NULL){ printf(pyParserEvaluator::Init: cant find getvalue function:); PyErr_Print(); goto PY_INIT_ERR; } // try assigning this object to sys.stderr ret1 = PySys_SetObject(stderr, _pPyobStringIO); if(ret1 != 0){ printf(failed to assign _pPyobStringIO to stderr\n); } else printf(assigned _pPyobStringIO to stderr\n); PY_INIT_ERR: printf(pyParseEvaluator::pyParseEvaluator failed\n); / **/ int ret = PyRun_SimpleString(strFunction); if(ret != 0){ // call getvalue() method in StringIO instance PyObject *obResult=NULL; obResult = PyObject_CallObject(_pPyGetValFunc, NULL); if(PyErr_Occurred() || obResult==NULL){ printf(getvalue() failed\n); return -1; } elseprintf(PyObject_CallObject on getvalue is ok\n); // did getvalue return a string? if(!PyString_Check(obResult)){ printf(getvalue() did not return error string\n); return -1; } else printf(getvalue returned string object\n); // retrieve error message string from this object char *sresult = NULL; if(NULL != (sresult = PyString_AsString(obResult))){ printf(result string was [%s]\n,sresult); } } /**/ -- http://mail.python.org/mailman/listinfo/python-list
Re: common problem - elegant solution sought
Helmut Jarausch wrote: Hi, I'm looking for an elegant solution of the following tiny but common problem. I have a list of tuples (Unique_ID,Date) both of which are strings. I want to delete the tuple (element) with a given Unique_ID, but I don't known the corresponding Date. My straight forward solution is a bit lengthy, e.g. L=[(a,070501),(b,080115),(c,071231)] pos=-1 found=-1 for (Key,Date) in L : pos+= 1 if Key == b : found= pos break if found = 0 : del L[found] print L Most probably there are much more elegant solutions. Unfortunately, the index-list-method doesn't take an additional function argument for the comparisons. Many thanks for your hints, Several solutions: - use a different datastructure, as others suggested - use a database. SQLite for example. - replace the list in-place like this: L[:] = [(k, d) for k, d in L if k != b] Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQL-python-1.2.2 install with no mysql
washakie napisał(a): Okay, I've installed mysql then using yum... it installed the same version running on another machine with identical python where all works well... but now I get this error during build... thoughts?!?? mysql_config is there, and the site.cfg file is pointing correctly to it... : You need to install -dev package too. -- Jarek Zgoda Skype: jzgoda | GTalk: [EMAIL PROTECTED] | voice: +48228430101 We read Knuth so you don't have to. (Tim Peters) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too slow?
On 15 Jan, 08:33, Jaimy Azle [EMAIL PROTECTED] wrote: perhaps in the future another sillly point could be added also, Java has Jython, while Python doesn't have some thing like PyJava or... perhaps Py-va (Python based Java Language). You could compile Java to CPython bytecode or, in the case of a little experiment I did some time ago, translate Java bytecode to CPython bytecode: the CPython virtual machine operates at a higher level and can support the Java instructions fairly easily, whereas a fair amount of work is required to support CPython instructions on the Java virtual machine. I found that the biggest obstacle was probably treating Java packages like Python packages - something which admittedly isn't completely necessary, but which would make the thing more usable at the prompt. Ultimately, I had little need for Java- based software and thus wasn't motivated into continuing the work, although Python 2.5 and beyond do provide some conveniences which might make some aspects of the implementation more bearable. Given that other languages (eg. Logix [2], various Lisp dialects) have been implemented for CPython, I think your point could be better formulated. Paul [1] http://www.boddie.org.uk/python/javaclass.html [2] http://www.livelogix.net/logix/ -- http://mail.python.org/mailman/listinfo/python-list
Re: common problem - elegant solution sought
On Tue, 15 Jan 2008 11:33:36 +0100, Helmut Jarausch wrote: Hi, I'm looking for an elegant solution of the following tiny but common problem. I have a list of tuples (Unique_ID,Date) both of which are strings. I want to delete the tuple (element) with a given Unique_ID, but I don't known the corresponding Date. My straight forward solution is a bit lengthy, e.g. L=[(a,070501),(b,080115),(c,071231)] pos=-1 found=-1 for (Key,Date) in L : pos+= 1 if Key == b : found= pos break if found = 0 : del L[found] print L Most probably there are much more elegant solutions. Unfortunately, the index-list-method doesn't take an additional function argument for the comparisons. Your code mixes two distinct steps into one, and therefore becomes a little messy. I suggest you change your problem to the two step problem (1) find an item with the given key; and (2) delete it. Here's a solution to the first part: def find_by_key(L, key, where=0): Search the 'where'th position of elements of L. for i, x in enumerate(L): if x[where] == key: return i return -1 # or raise an exception And the second: pos = find_by_key(L, 'b') if pos != -1: del L[pos] This too could be made into a function, if necessarily. How else could we solve this problem? class Tester(object): def __init__(self, key, where=0): self.key = key self.where = where def __eq__(self, other): return other[self.where] == self.key L = [(a, 070501), (b, 080115), (c, 071231)] L.index(Tester(c)) But beware, this technique might not generalize to arbitrary elements in the list L. It should work if the elements are tuples, but may not work if they are a custom class. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQL-python-1.2.2 install with no mysql
Okay, I've installed mysql then using yum... it installed the same version running on another machine with identical python where all works well... but now I get this error during build... thoughts?!?? mysql_config is there, and the site.cfg file is pointing correctly to it... : [root@ MySQL-python-1.2.2]# python setup.py build running build running build_py copying MySQLdb/release.py - build/lib.linux-i686-2.4/MySQLdb running build_ext building '_mysql' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -D_GNU_SOURCE -fPIC -fPIC -Dversion_info=(1,2,2,'final',0) -D__version__=1.2.2 -I/usr/include/mysql -I/usr/include/python2.4 -c _mysql.c -o build/temp.linux-i686-2.4/_mysql.o -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -fno-strict-aliasing -fwrapv _mysql.c:35:23: error: my_config.h: No such file or directory _mysql.c:40:19: error: mysql.h: No such file or directory _mysql.c:41:26: error: mysqld_error.h: No such file or directory _mysql.c:42:20: error: errmsg.h: No such file or directory _mysql.c:78: error: expected specifier-qualifier-list before ‘MYSQL’ _mysql.c:92: error: expected specifier-qualifier-list before ‘MYSQL_RES’ _mysql.c: In function ‘_mysql_Exception’: _mysql.c:122: warning: implicit declaration of function ‘mysql_errno’ _mysql.c:122: error: ‘_mysql_ConnectionObject’ has no member named ‘connection’ _mysql.c:125: error: ‘CR_MAX_ERROR’ undeclared (first use in this function) _mysql.c:125: error: (Each undeclared identifier is reported only once _mysql.c:125: error: for each function it appears in.) _mysql.c:133: error: ‘CR_COMMANDS_OUT_OF_SYNC’ undeclared (first use in this function) _mysql.c:134: error: ‘ER_DB_CREATE_EXISTS’ undeclared (first use in this function) _mysql.c:135: error: ‘ER_SYNTAX_ERROR’ undeclared (first use in this function) _mysql.c:136: error: ‘ER_PARSE_ERROR’ undeclared (first use in this function) _mysql.c:137: error: ‘ER_NO_SUCH_TABLE’ undeclared (first use in this function) _mysql.c:138: error: ‘ER_WRONG_DB_NAME’ undeclared (first use in this function) _mysql.c:139: error: ‘ER_WRONG_TABLE_NAME’ undeclared (first use in this function) _mysql.c:140: error: ‘ER_FIELD_SPECIFIED_TWICE’ undeclared (first use in this function) _mysql.c:141: error: ‘ER_INVALID_GROUP_FUNC_USE’ undeclared (first use in this function) _mysql.c:142: error: ‘ER_UNSUPPORTED_EXTENSION’ undeclared (first use in this function) _mysql.c:143: error: ‘ER_TABLE_MUST_HAVE_COLUMNS’ undeclared (first use in this function) _mysql.c:172: error: ‘ER_DUP_ENTRY’ undeclared (first use in this function) _mysql.c:215: warning: implicit declaration of function ‘mysql_error’ _mysql.c:215: error: ‘_mysql_ConnectionObject’ has no member named ‘connection’ _mysql.c:215: warning: passing argument 1 of ‘PyString_FromString’ makes pointer from integer without a cast _mysql.c: In function ‘_mysql_server_init’: _mysql.c:310: warning: label ‘finish’ defined but not used _mysql.c:236: warning: unused variable ‘item’ _mysql.c:235: warning: unused variable ‘groupc’ _mysql.c:235: warning: unused variable ‘i’ _mysql.c:235: warning: unused variable ‘cmd_argc’ _mysql.c:234: warning: unused variable ‘s’ _mysql.c: In function ‘_mysql_ResultObject_Initialize’: _mysql.c:365: error: ‘MYSQL_RES’ undeclared (first use in this function) _mysql.c:365: error: ‘result’ undeclared (first use in this function) _mysql.c:370: error: ‘MYSQL_FIELD’ undeclared (first use in this function) _mysql.c:370: error: ‘fields’ undeclared (first use in this function) _mysql.c:379: error: ‘_mysql_ResultObject’ has no member named ‘use’ _mysql.c:382: warning: implicit declaration of function ‘mysql_use_result’ _mysql.c:382: error: ‘_mysql_ConnectionObject’ has no member named ‘connection’ _mysql.c:384: warning: implicit declaration of function ‘mysql_store_result’ _mysql.c:384: error: ‘_mysql_ConnectionObject’ has no member named ‘connection’ _mysql.c:385: error: ‘_mysql_ResultObject’ has no member named ‘result’ _mysql.c:388: error: ‘_mysql_ResultObject’ has no member named ‘converter’ _mysql.c:391: warning: implicit declaration of function ‘mysql_num_fields’ _mysql.c:392: error: ‘_mysql_ResultObject’ has no member named ‘nfields’ _mysql.c:393: error: ‘_mysql_ResultObject’ has no member named ‘converter’ _mysql.c:394: warning: implicit declaration of function ‘mysql_fetch_fields’ _mysql.c:438: error: ‘_mysql_ResultObject’ has no member named ‘converter’ _mysql.c: In function ‘_mysql_ResultObject_traverse’: _mysql.c:450: error: ‘_mysql_ResultObject’ has no member named ‘converter’ _mysql.c:451: error: ‘_mysql_ResultObject’ has no member named ‘converter’ _mysql.c: In function ‘_mysql_ResultObject_clear’: _mysql.c:462: error:
Re: Python too slow?
[EMAIL PROTECTED] writes: A lecturer gave me the perfect answer to the question of speed. You have two choices when it comes to programming. Fast code, or fast coders. Yes, although it's more a continuum than that suggests. The tricky bit is deciding in each situation where you should be on the continuum. -- http://mail.python.org/mailman/listinfo/python-list
RE: env parameter to popen won't accept Unicode on Windows -minor Unicode bug
Diez B. Roggisch wrote: Sure thing, python will just magically convert unicode to the encoding the program YOU invoke will expect. Right after we introduced the solve_my_problem() built-in-function. Any other wishes? There's no reason to be rude. Anyway, at least on Windows it makes perfect sense for people to expect Unicode to be handled automatically. popen() knows that it is running on Windows, and it knows what encoding Windows needs for its environment (it's either UCS2 or UTF-16 for most Windows APIs). At least when it receives a unicode string, it has enough information to apply the conversion automatically, and doing so saves the caller from having to figure out what exact encoding is to be used. - Brian -- http://mail.python.org/mailman/listinfo/python-list
Re: common problem - elegant solution sought
On Jan 15, 2008 5:33 AM, Helmut Jarausch [EMAIL PROTECTED] wrote: Hi, I'm looking for an elegant solution of the following tiny but common problem. I have a list of tuples (Unique_ID,Date) both of which are strings. I want to delete the tuple (element) with a given Unique_ID, but I don't known the corresponding Date. My straight forward solution is a bit lengthy, e.g. L=[(a,070501),(b,080115),(c,071231)] If the data is truly sorted by Unique_ID, then binary search may be feasible (though not actually recommended for such small list). import bisect i = bisect.bisect_left(L, ('b', '00')) if i[0] == 'b': del L[i] -- Neil Cerutti [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Append zip files together, just get the binary data (in memory)
On Jan 15, 2008 4:28 AM, John Machin [EMAIL PROTECTED] wrote: On Jan 15, 9:58 am, Diez B. Roggisch [EMAIL PROTECTED] wrote: Module StringIO is your friend. and cStringIO is your ? ... friend +1? -- Neil Cerutti [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: env parameter to popen won't accept Unicode on Windows -minor Unicode bug
Brian Smith wrote: Diez B. Roggisch wrote: Sure thing, python will just magically convert unicode to the encoding the program YOU invoke will expect. Right after we introduced the solve_my_problem() built-in-function. Any other wishes? There's no reason to be rude. If you'd know John, you'd know there is. Anyway, at least on Windows it makes perfect sense for people to expect Unicode to be handled automatically. popen() knows that it is running on Windows, and it knows what encoding Windows needs for its environment (it's either UCS2 or UTF-16 for most Windows APIs). At least when it receives a unicode string, it has enough information to apply the conversion automatically, and doing so saves the caller from having to figure out what exact encoding is to be used. For once, the distinction between windows and other platforms is debatable. I admit that subprocess contains already quite a few platform specific aspects, but it's purpose is to abstract these away as much as possible. However, I'm not sure that just because there are wide-char windows apis available automatically means that using UCS2/UTF-16 would succeed. A look into the python sources (PC/_subprocess.c) reveals that someone already thought about this, but it seems that just setting a CREATE_UNICODE_ENVIRONMENT in the CreateProcess-function should have been easy enough to do it if there weren't any troubles to expect. Additionally, passing unicode to env would also imply that os.environ should yield unicode as well. Not sure how much code _that_ breaks. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too slow?
On Jan 15, 1:28 pm, Paul Rudin [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] writes: A lecturer gave me the perfect answer to the question of speed. You have two choices when it comes to programming. Fast code, or fast coders. Yes, although it's more a continuum than that suggests. The tricky bit is deciding in each situation where you should be on the continuum. Ah, it all comes from hindsight! You always realise in the last week of the deadline you were on the wrong end of the continuum! Problem solved, panic created! :) -- http://mail.python.org/mailman/listinfo/python-list
Re: short path evaluation, why is f() called here: dict(a=1).get('a', f())
On Jan 15, 12:15 am, Paul Rubin http://[EMAIL PROTECTED] wrote: Steven D'Aprano [EMAIL PROTECTED] writes: map = {'a': Aclass, 'b': Bclass, 'c': Cclass} class_ = map.get(astring, default=Zclass) The result I want is the class, not the result of calling the class (which would be an instance). If I wanted the other semantics, I'd be using defaultdict instead. I used default as a keyward arg name indicating the presence of a callable. I probably should have called it defaultfunc or something. x = d.get('a', f) # -- default value is f x = d.get('a', defaultfunc=f) # -- default value is result of f() . Nice idea, but if I want args I need to write it like that: x=d.get('a', defaultfunc=f, funcargs=(1,2,3)) instead of d['a', f(1,2,3)] -- http://mail.python.org/mailman/listinfo/python-list
Re: Basic inheritance question
Lie a écrit : On Jan 7, 2:46 am, Bruno Desthuilliers [EMAIL PROTECTED] wrote: Lie a écrit : On Jan 5, 5:40 pm, [EMAIL PROTECTED] wrote: Jeroen Ruigrok van der Werven wrote: Shouldn't this be: self.startLoc = start self.stopLoc = stop Thanks! Of course it should. Old Java habits die slowly. No, seriously it isn't Java habits only, most other languages wouldn't need explicit calling of class name. Where is the explicit calling of class name exactly ? Perhaps I was a bit tired when writing that (I wouldn't understand what I wrote if I were you)... what I meant is most other languages doesn't usually enforce us to explicitly state the containing class name, which in python is generally called self. 'self' (or whatever you name it) is not the containing class name, it's the first argument of the function - which usually happens to be the current instance when the function is used as a method. Most other languages 1) automatically assign the containing class' object s/containing class' object/current instance/ in a keyword (Java: this, VB: Me) behind the screen, That's not very far from what a Python method object does - automatically assign the current instance to something. The difference is that Python uses functions to implement methods (instead of having two distinct contructs), so the only reliable way to inject the reference to the current instance is to pass it as an argument to the function (instead of making it pop from pure air). There are some benefits to this solution. One of them is the ability to dynamically assign functions as methods. So if you do have some function taking an object as first argument, you can easily turn it into a method. and 2) automatically searches variable name in both the local variable table and the containing class variable table (so to refer to a class variable named var from a method inside the class, we only need to write var, not self.var as in python). This - as you know - cannot work well with Python's scoping rules and dynamicity. Anyway, implicit object reference is definitively a BadThing(tm) wrt/ readbility, specially with multiparadigm languages (like Python or C++). Why do you think s many C++ shops impose the m_something naming scheme ? Anyway, I actually know 3 languages (4 if C# works the same) that has this implicit 'this' (or whatever the name) 'feature', and at least 5 that don't. So I'm not sure that the most other languages qualifier really applies to point 2 !-) In VB, Me is extremely rarely used, I used to systematically use it - like I've always systematically used 'this' in C++ and Java. in Python, self is all over the place. Well, there is positive and negative to both sides, convenience in VB, and flexibility in Python. As far as I'm concerned, there's *no* positive point in implicit object reference, and there has never been (and before some paranoid nutcase around accuse me of overzealous biggotry : I already held this very same opinion years before I discovered Python). Compare the following codes: VB.NET: Public Class A Dim var Public Function aFunction() return var Add three levels of inheritence and a couple globals and you'll find out that readability count !-) In any non-trivial piece of C++ code, and unless the author either used the explicit 'this' reference or the 'm_xxx' naming convention, you'll have hard time figuring out where a given name comes from when browsing a function's code. -- http://mail.python.org/mailman/listinfo/python-list
Re: short path evaluation, why is f() called here: dict(a=1).get('a', f())
On Jan 14, 8:07 pm, aspineux [EMAIL PROTECTED] wrote: On Jan 14, 7:49 pm, Chris Mellon [EMAIL PROTECTED] wrote: On Jan 14, 2008 12:39 PM, aspineux [EMAIL PROTECTED] wrote: This append in both case dict(a=1).get('a', f()) dict(a=1).setdefault('a', f()) This should be nice if f() was called only if required. Think about the change to Python semantics that would be required for this to be true, and then use collections.defaultdict instead. Yes, I missed 'get' and 'setdefault' are functions :-) Then why not some new semantic d.get('a', f()) -- d['a', f()] d.setdefault('a', f()) -- d['a'=f()] Is is a good idea enough to change the python semantic ? Or simply is it a good idea ? Thanks for all your answers. Anyway these notations are very compact, don't require the definition of a specific function, and work with old style/or already existing dictionary, dictionary you didn't created yourself. While the use of defaultdict require the definition of such a function and to control the creation of the dictionary. For me the best alternative that match the requirement above is the one provided by Paul Rubin. Regards. -- http://mail.python.org/mailman/listinfo/python-list
Re: Restart crashing modules in windows
On Jan 14, 9:02 pm, Astan Chee [EMAIL PROTECTED] wrote: Hi, I have a python module that keeps on crashing with various windows errors (not BSOD but the less lethal windows XP popup ones). Now these are intentional and rather sporadic so I cant really solve it by attempting to fix the crash; rather what Im trying to do is make another module outside it that restarts this module every time it crashes. Is this possible? How do I do this? Or does one windows crash in one python module crash python entirely and I have to resort in an external program to restart python everytime it crashes? Thanks again for all the help. Astan If you're not going to catch the error that is causing the crash, then I think your only option is to restart your application with an external program. However, maybe someone else will have a better idea. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: i am new guy for this discussion group
HI! I'm also chinese. welcome to you! bill.wu [EMAIL PROTECTED] ??:[EMAIL PROTECTED] i am new guy to learn python,also for this discussion group, i am chinese. nice to meet you, everyone. -- http://mail.python.org/mailman/listinfo/python-list
ElementTree and namespaces in the header only
Here's my code (simplified): NS_URL = 'http://www.snapexpense.com/atom_ns#' ElementTree._namespace_map[NS_URL] = 'se' def SEN(tag): return {%s}%s % (NS_URL, tag) root = Element('feed', xmlns='http://www.w3.org/2005/Atom') root.set('xmlns:se', NS_URL) entry = SubElement(root, 'entry') SubElement(root, 'title').text = 'Title' SubElement(entry, SEN('category')).text = 'Category' And here's the generated XML string: feed xmlns=http://www.w3.org/2005/Atom; xmlns:se=http:// www.snapexpense.com/atom_ns# entry se:category xmlns:se=http://www.snapexpense.com/ atom_ns#Category/se:category /entry titleTitle/title /feed But surely the xmlns:se attribute on the se:category tag is excessive since the namespace (by the URI) is already defined in the feed tag. How do I set non-default namespace tags in elements without the automatic xmlns:se attribute repeated each time? -- http://mail.python.org/mailman/listinfo/python-list
Re: common problem - elegant solution sought
Neil Cerutti wrote: On Jan 15, 2008 5:33 AM, Helmut Jarausch [EMAIL PROTECTED] wrote: Hi, I'm looking for an elegant solution of the following tiny but common problem. I have a list of tuples (Unique_ID,Date) both of which are strings. I want to delete the tuple (element) with a given Unique_ID, but I don't known the corresponding Date. My straight forward solution is a bit lengthy, e.g. L=[(a,070501),(b,080115),(c,071231)] If the data is truly sorted by Unique_ID, then binary search may be feasible (though not actually recommended for such small list). import bisect i = bisect.bisect_left(L, ('b', '00')) if i[0] == 'b': del L[i] Thanks, unfortunately, they are sorted on 'Date' Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Re: A question about event handlers with wxPython
def HandleSomething(self, event): generating_control = event.GetEventObject() print generating_control HTH, Thank you.That is what I was looking for, but as often seems the case, one thing exposes another. Is there any way to listen for events without specifically binding to a handler (it seems one cannot bind an event to two handlers?)? One could do so with globals, but I'm trying to avoid that. For example, press any button to stop def HandleSomething(self, event): . while generating_control: == something: run else stop -- http://mail.python.org/mailman/listinfo/python-list
Benchmark [was Re: common problem - elegant solution sought]
Again, many thanks to all who provide their solution. I have timed these (though on my old P3(0.9GHz)) - see below Helmut. Helmut Jarausch wrote: Hi, I'm looking for an elegant solution of the following tiny but common problem. I have a list of tuples (Unique_ID,Date) both of which are strings. I want to delete the tuple (element) with a given Unique_ID, but I don't known the corresponding Date. #!/usr/bin/python import random import timeit Lorg=[] def genList(L) : for f in range(ord('A'),ord('z')+1) : for s in range(ord('A'),ord('z')+1) : L.append((chr(f)+chr(s),str(random.randrange(0,100 genList(Lorg) Times= 1000 T0= timeit.Timer('L=list(Lorg)','from __main__ import Lorg').timeit(Times) print T0 SetUp1=r'''from __main__ import Lorg def del_by_key(L,key) : d= dict(L) del d[key] L[:]= d.items() ''' SetUp2=r'''from __main__ import Lorg def del_by_key(L,key) : d= dict(L) t= (key,d[key]) L.remove(t) ''' SetUp3=r'''from __main__ import Lorg def del_by_key(L,key) : index= [k for k,val in L] pos = index.index(key) del L[pos] ''' SetUp4=r'''from __main__ import Lorg def del_by_key(L,key) : for pos, (k,d) in enumerate(L): if k == key : del L[pos] break ''' SetUp5=r'''from __main__ import Lorg def del_by_key(L,key) : L[:]= [(k,d) for (k,d) in L if k !=key] ''' SetUp6=r'''from __main__ import Lorg class Tester(object) : def __init__(self,key) : self.key= key def __eq__(self,other) : return other[0] == self.key def del_by_key(L,key) : del L[L.index(Tester(key))] ''' print '*** ready ***' T= timeit.Timer(L=list(Lorg);del_by_key(L,'Zz'),SetUp1).timeit(Times) print Method 1 :,T-T0 T= timeit.Timer(L=list(Lorg);del_by_key(L,'Zz'),SetUp2).timeit(Times) print Method 2 :,T-T0 T= timeit.Timer(L=list(Lorg);del_by_key(L,'Zz'),SetUp3).timeit(Times) print Method 3 :,T-T0 T= timeit.Timer(L=list(Lorg);del_by_key(L,'Zz'),SetUp4).timeit(Times) print Method 4 :,T-T0 T= timeit.Timer(L=list(Lorg);del_by_key(L,'Zz'),SetUp5).timeit(Times) print Method 5 :,T-T0 T= timeit.Timer(L=list(Lorg);del_by_key(L,'Zz'),SetUp6).timeit(Times) print Method 6 :,T-T0 # Results on an old P3 (0.9 GHz) # *** ready *** # Method 1 : 10.9850928783 # Method 2 : 5.96455168724 # Method 3 : 3.97821164131 # Method 4 : 1.66151881218 # Method 5 : 8.90886187553 # Method 6 : 6.2503888607 The clear winner is def del_by_key(L,key) : for pos, (k,d) in enumerate(L): if k == key : del L[pos] break -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Why this apparent assymetry in set operations?
I've noticed that I can update() a set with a list but I can't extend a set with a list using the |= assignment operator. s = set() s.update([1,2,3]) s set([1, 2, 3]) s |= [4,5,6] Traceback (most recent call last): File stdin, line 1, in module TypeError: unsupported operand type(s) for |=: 'set' and 'list' s |= set([4,5,6]) s set([1, 2, 3, 4, 5, 6]) Why is that? Doesn't the |= operator essentially map to an update() call? Skip -- http://mail.python.org/mailman/listinfo/python-list
Interesting Thread Gotcha
I thought I would share this nasty little gotcha with the group. Consider the following code fragment: start print 'starting kbd thread' keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) print 'starting main loop' error = Mainloop(s,port_q,active_q_list) end It produces, as output, the following: starting kbd thread we get here - a It does not print 'starting main loop', the Mainloop routine is never executed, and no exceptions are raised. Here is the offending routine that seems to capture the control: start def kbd_driver(out_q,in_q): thread to look for keyboard input and to put it on the queue out_q also looks for replies on in_q and prints them kbdname = '/dev/stdin' kbd = open(kbdname,'r+',1) # Reading, line buffered unblock(kbd) # Call the magic to unblock keyboard print 'we get here - a' while True: try: d = kbd.readline() # see if any kbd input except: IOError try: msg=in_q.get(block=False) except Queue.Empty: time.sleep(0.1) continue print msg time.sleep(0.1) continue d = d.rstrip()# get rid of line feed out_q.put([d + '\r',in_q]) # add a carriage return and return q and send to port end The unblock is a routine that unblocks a port using fcntl - it is not the problem. In case you don't believe me, here it is: def unblock(f): Given file 'f', sets its unblock flag to true. fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) I will post the solution tomorrow when I read my mail, if no one has spotted it by then. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: A question about event handlers with wxPython
On Jan 15, 9:04 am, Erik Lind [EMAIL PROTECTED] wrote: def HandleSomething(self, event): generating_control = event.GetEventObject() print generating_control HTH, Thank you.That is what I was looking for, but as often seems the case, one thing exposes another. Is there any way to listen for events without specifically binding to a handler (it seems one cannot bind an event to two handlers?)? One could do so with globals, but I'm trying to avoid that. For example, press any button to stop def HandleSomething(self, event): . while generating_control: == something: run else stop There are a number of ways to handle this. You could just bind the parent to the handler. Something like this: self.Bind(wx.EVT_BUTTON, self.onStop) This will bind all button presses to the onStop handler. You could also do something like this: self.Bind(wx.EVT_BUTTON, self.onBtnStop) def onBtnStop(self, event): #do something event.Skip() By calling the Skip() method, it will propagate the event and look for another handler, which in this case would be the onStop handler. On Windows, you will most likely need to make a wx.Panel be the parent of the rest of the widgets to have this effect. My complete test code is below. code import wx class Closer(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, wx.ID_ANY, title='Test Frame') panel = wx.Panel(self, -1) sizer = wx.BoxSizer(wx.VERTICAL) btn1 = wx.Button(panel, wx.ID_ANY, 'Button 1') btn2 = wx.Button(panel, wx.ID_ANY, 'Button 2') btn3 = wx.Button(panel, wx.ID_ANY, 'Button 3') sizer.Add(btn1) sizer.Add(btn2) sizer.Add(btn3) self.Bind(wx.EVT_BUTTON, self.onDone) self.Bind(wx.EVT_BUTTON, self.onStop, btn1) panel.SetSizer(sizer) def onStop(self, event): print 'Stop!' event.Skip() def onDone(self, event): print 'Done!' if __name__ == '__main__': app = wx.PySimpleApp() Closer().Show() app.MainLoop() /code FYI: There is an excellent wxPython group that you can join over on the wxPython.org website. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Why this apparent assymetry in set operations?
Neil Cerutti wrote: On Jan 15, 2008 10:10 AM, [EMAIL PROTECTED] wrote: I've noticed that I can update() a set with a list but I can't extend a set with a list using the |= assignment operator. s = set() s.update([1,2,3]) s set([1, 2, 3]) s |= [4,5,6] Traceback (most recent call last): File stdin, line 1, in module TypeError: unsupported operand type(s) for |=: 'set' and 'list' s |= set([4,5,6]) s set([1, 2, 3, 4, 5, 6]) Why is that? Doesn't the |= operator essentially map to an update() call? No, according to 3.7 Set Types, s | t maps to s.union(t). If the RHS is a set then it works OK: *** Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32. *** import sets s1= sets.Set([2, 4, 5]) Set([2, 4, 5]) s1= sets.Set([2, 4, 5]) s2= sets.Set([4, 5, 6]) s1|s2 Set([2, 4, 5, 6]) s1|=s2 s1 Set([2, 4, 5, 6]) It could be modifies to handle any iterable on the RHS. Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why this apparent assymetry in set operations?
On Jan 15, 2008 10:10 AM, [EMAIL PROTECTED] wrote: I've noticed that I can update() a set with a list but I can't extend a set with a list using the |= assignment operator. s = set() s.update([1,2,3]) s set([1, 2, 3]) s |= [4,5,6] Traceback (most recent call last): File stdin, line 1, in module TypeError: unsupported operand type(s) for |=: 'set' and 'list' s |= set([4,5,6]) s set([1, 2, 3, 4, 5, 6]) Why is that? Doesn't the |= operator essentially map to an update() call? No, according to 3.7 Set Types, s | t maps to s.union(t). -- Neil Cerutti [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Interesting Thread Gotcha
On Jan 15, 10:07 am, Hendrik van Rooyen [EMAIL PROTECTED] wrote: I thought I would share this nasty little gotcha with the group. Consider the following code fragment: start print 'starting kbd thread' keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) print 'starting main loop' error = Mainloop(s,port_q,active_q_list) end It produces, as output, the following: starting kbd thread we get here - a It does not print 'starting main loop', the Mainloop routine is never executed, and no exceptions are raised. Here is the offending routine that seems to capture the control: start def kbd_driver(out_q,in_q): thread to look for keyboard input and to put it on the queue out_q also looks for replies on in_q and prints them kbdname = '/dev/stdin' kbd = open(kbdname,'r+',1) # Reading, line buffered unblock(kbd) # Call the magic to unblock keyboard print 'we get here - a' while True: try: d = kbd.readline() # see if any kbd input except: IOError try: msg=in_q.get(block=False) except Queue.Empty: time.sleep(0.1) continue print msg time.sleep(0.1) continue d = d.rstrip()# get rid of line feed out_q.put([d + '\r',in_q]) # add a carriage return and return q and send to port end The unblock is a routine that unblocks a port using fcntl - it is not the problem. In case you don't believe me, here it is: def unblock(f): Given file 'f', sets its unblock flag to true. fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) I will post the solution tomorrow when I read my mail, if no one has spotted it by then. - Hendrik keyboard_thread = thread.start_new_thread(kbd_driver (port_q,kbd_q)) Needs to be keyboard_thread = thread.start_new_thread(kbd_driver, (port_q,kbd_q)) Commas are important! -Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: jpype with JFreeChart, anyone interested to help?
On Jan 14, 8:25 pm, oyster [EMAIL PROTECTED] wrote: Thanx However I knew Chaco and matplotlib, and I use matplotlib during my school days. And as I have pointed out, they are for plot, but not chart. If you don't know the difference between plot and chart, you can have a look at athttp://www.jfree.org/jfreechart,http://www.rmchart.com Yes, it is true we can use plot lib to draw chart, but that is tedious. What are the chart types that are missing? Or do you find that the handling of categorical data is generally lacking? Charting and plotting are quite related, and I think you might get better traction trying to add the exact chart and axis types that you need to an existing package rather than starting yet another plotting package for Python. :) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Why this apparent assymetry in set operations?
Colin J. Williams wrote: Neil Cerutti wrote: On Jan 15, 2008 10:10 AM, [EMAIL PROTECTED] wrote: I've noticed that I can update() a set with a list but I can't extend a set with a list using the |= assignment operator. s = set() s.update([1,2,3]) s set([1, 2, 3]) s |= [4,5,6] Traceback (most recent call last): File stdin, line 1, in module TypeError: unsupported operand type(s) for |=: 'set' and 'list' s |= set([4,5,6]) s set([1, 2, 3, 4, 5, 6]) Why is that? Doesn't the |= operator essentially map to an update() call? No, according to 3.7 Set Types, s | t maps to s.union(t). If the RHS is a set then it works OK: *** Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32. *** import sets s1= sets.Set([2, 4, 5]) Set([2, 4, 5]) s1= sets.Set([2, 4, 5]) s2= sets.Set([4, 5, 6]) s1|s2 Set([2, 4, 5, 6]) s1|=s2 s1 Set([2, 4, 5, 6]) It could be modified to handle any iterable on the RHS. Colin W. I'm sorry, there appears to be a bug: # tSet.py import sets s1= sets.Set([1, 2, 3]) s1.union_update([3, 4,5]) print(s1) s2= sets.Set([6, 7, 8]) s1 |+ s2 # This fails: exceptions.TypeError: bad operand type for unary +: 'Set' print s1 Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why this apparent assymetry in set operations?
If the RHS is a set then it works OK: Yup, I understand that. Would be kind of bad if it didn't. ;-) It could be modifies to handle any iterable on the RHS. That's my question. Why does it work in one place but not everywhere? Skip -- http://mail.python.org/mailman/listinfo/python-list
Retrieving info from DBUS at application startup
Hello, Detecting Hotpluggable hardware using DBUS works great, but usually peripherals are already connected when launching the application. How can I (preferably using DBUS) detect which USB printers for example are connected to the system at application launch without engaging in some insane probing activity? Thanks, Frank Aune -- http://mail.python.org/mailman/listinfo/python-list
Re: Why this apparent assymetry in set operations?
Why is that? Doesn't the |= operator essentially map to an update() call? No, according to 3.7 Set Types, s | t maps to s.union(t). I was asking about the |= assignment operator which according to the docs *does* map to the update method. Skip -- http://mail.python.org/mailman/listinfo/python-list
Re: Why this apparent assymetry in set operations?
Both of you are correct. x = set([1,2,3]) y = set([4,5]) x |= y x set([1, 2, 3, 4, 5]) On Jan 15, 2008 11:07 AM, Skip Montanaro [EMAIL PROTECTED] wrote: Why is that? Doesn't the |= operator essentially map to an update() call? No, according to 3.7 Set Types, s | t maps to s.union(t). I was asking about the |= assignment operator which according to the docs *does* map to the update method. Skip -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Leo 4.4.6 beta 2 released
Leo 4.4.6 beta 2 is available at: http://sourceforge.net/project/showfiles.php?group_id=3458package_id=29106 Leo 4.4.6 fixes several recently reported bugs, all minor. Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4.6: - Fixes all known bugs. - Added @auto importers for javascript and xml files. - Added find-next-clone and toggle-sparse-move commands. 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://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html Edward K. Ream email: [EMAIL PROTECTED] Leo: http://webpages.charter.net/edreamleo/front.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Python too slow?
[EMAIL PROTECTED]: A lecturer gave me the perfect answer to the question of speed. You have two choices when it comes to programming. Fast code, or fast coders. I don't believe that anymore, ShedSkin compiles slowly and it has limitations still, but it shows that it's possible to create a language with simple short syntax and high running speed at the same time. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Benchmark [was Re: common problem - elegant solution sought]
Helmut Jarausch: The clear winner is def del_by_key(L,key) : for pos, (k,d) in enumerate(L): if k == key : del L[pos] break If you use Psyco this is faster: def del_by_key(L,key): pos = 0 for pair in L: if pair[0] == key : del L[pos] break pos += 1 Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: A question about event handlers with wxPython
On Jan 15, 9:04 am, Erik Lind [EMAIL PROTECTED] wrote: def HandleSomething(self, event): generating_control = event.GetEventObject() print generating_control HTH, Thank you.That is what I was looking for, but as often seems the case, one thing exposes another. Is there any way to listen for events without specifically binding to a handler (it seems one cannot bind an event to two handlers?)? One could do so with globals, but I'm trying to avoid that. For example, press any button to stop def HandleSomething(self, event): . while generating_control: == something: run else stop I forgot to provide a link to a fairly straight-forward explanation of event propagation on the wxPython wiki: http://wiki.wxpython.org/EventPropagation Hope that helps! Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Why this apparent assymetry in set operations?
On Jan 15, 2008 11:07 AM, Skip Montanaro [EMAIL PROTECTED] wrote: Why is that? Doesn't the |= operator essentially map to an update() call? No, according to 3.7 Set Types, s | t maps to s.union(t). I was asking about the |= assignment operator which according to the docs *does* map to the update method. Oops! You're right. That's surprising. This inconsistency is due to the c implementation. Internally, |= maps to the c function set_ior, while .update(...) maps to set_update. Both eventually call set_update_internal, which works fine when the operand is not a set. But set_ior specifically punts non-sets before calling set_update_internal. So this is a bug in set_update or in set_ior. They can't both be right. -- Neil Cerutti [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Why this apparent assymetry in set operations?
On Jan 15, 11:51 am, Neil Cerutti [EMAIL PROTECTED] wrote: So this is a bug in set_update or in set_ior. They can't both be right. It's not a bug. Note, the non-operator versions of union(), intersection(), difference(), and symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like set('abc') 'cbs' in favor of the more readable set('abc').intersection('cbs'). -- http://mail.python.org/mailman/listinfo/python-list
Re: ElementTree and namespaces in the header only
Peter Bengtsson wrote: root = Element('feed', xmlns='http://www.w3.org/2005/Atom') root.set('xmlns:se', NS_URL) entry = SubElement(root, 'entry') SubElement(root, 'title').text = 'Title' SubElement(entry, SEN('category')).text = 'Category' But surely the xmlns:se attribute on the se:category tag is excessive since the namespace (by the URI) is already defined in the feed tag. How do I set non-default namespace tags in elements without the automatic xmlns:se attribute repeated each time? ET 1.2's standard serializer doesn't take explicitly set namespaces into account. If you want full control over namespace generation, you have to do it yourself: http://effbot.org/zone/element-namespaces.htm#explicitly-setting-namespace-attributes ET 1.3 provides a default_namespace option for this specific case (but you still have to use universal names for everything that should go into the default namespace). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: super, decorators and gettattribute
On Jan 13, 5:51 am, Richard Szopa [EMAIL PROTECTED] wrote: On Jan 13, 8:59 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Sat, 12 Jan 2008 14:23:52 -0800, Richard Szopa wrote: However, I am very surprised to learn that super_object.__getattr__(name)(*args, **kwargs) getattr(super_object, name)(*args, **kwargs) are not equivalent. This is quite odd, at least when with len() and .__len__, str() and .__str__. Do you maybe know what's the rationale behind not following that convention by getattr? I think you are confusing `__getattr__` and `__getattribute__` here! `getattr()` maps to `__getattr__()`, it's `__getattribute__` that's different. Well, in my code calling super_object.__getattr__(name)(*args, **kwargs) and getattr(super_object, name)(*args, **kwargs) gives *different* effects (namely, the latter works, while the former doesn't). That kinda suggests that they don't map to each other :-). And that makes me feel confused. Don't think of them as mappings. Think of them as a way for a class to hook into getattr's protocol, conveniently named similar to getattr (__getattr__ and __getattribute__). getattr() may call several methods, no methods at all, change the arguments, etc. Although len() may seem simple, many others are not so simple. -- Adam Olsen, aka Rhamphoryncus -- http://mail.python.org/mailman/listinfo/python-list
Re: Python's great, in a word
Op Mon, 07 Jan 2008 05:09:15 -0800, schreef MartinRinehart: Would you Python old-timers try to agree on a word or two that completes: The best thing about Python is ___. Please, no laundry lists, just a word or two. I'm thinking fluid or grace but I'm not sure I've done enough to choose. The best thing about Python is how it tries to find the perfect balance between elegance, practicality clarity. -- JanC -- http://mail.python.org/mailman/listinfo/python-list
Open existing Word document, modify and save.
New to Python and new to Win32. Help please. O.k., so this might seem like one of those can you do my homework kind of postings, except that is not homework, it is officework. I have been reading the Core Python book and I am really excited about starting my next project with Python, instead of tcl/tk/Fortran/C. While I can see how to use it for scientific computing and have gone with the NumPy and SciPy tutorials, I am having a hard time with Win32. Attempted to read some of the documentation for Win32 and while the basic stuff talks about creating a document, I did not see how to open an existing document and modify certain parts of it...and then it seems that it got very complicated (for me) really quick. Sure, it seems powerful, but all I need is a small part of it, I think. Here is the thing. Here at the office, we have computer programs to generate spec data and the Applications people have MS-Word documents in a very specific format where they would like to put such spec data. Initially, I was using merge fields and VB macros, until they stopped working when newer (non-backwards-compatible) versions came along; then, I switched to generating *.xml out of the original *.doc file, breaking it appart, modifying it and gluing back together...this is very laborious task and I have to go through the whole exercise, should the application people modify the original *.doc So, basically, I am looking for a way to work directly with the original *.doc, assuming I know everything about it...which I do; in fact, I have it and can also modify it, should I need to bookmark it or otherwise modify as needed. How to go about it? What's the python code to open an existing document, modify it and save it back? how does the Word document needs to be bookmarked/formatted so that it can be modified? For example, after the computer program has been run and the new, say, machine rating calculated, I need to deposit such value in a very specific spot in the Word document. I presume somebody out there already does this and is willing to provide some code?. Thank you very much in advance. gsal -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamical scoping
Kay Schluehr [EMAIL PROTECTED] writes: On 15 Jan., 02:13, Paul Rubin http://[EMAIL PROTECTED] wrote: George Sakkis [EMAIL PROTECTED] writes: What's the best way to simulate dynamically scoped variables ala Lisp ? Ugh check the docs for the python 2.5 with statement, which gives you sort of a programmable unwind-protect (more powerful than try/except). You'd have an environment dictionary and use the with statement to maintain a stack of shallow-binding cells like in an old-time lisp system, automatically unwinding when the with suite finishes. The whole concept sounds hopelessly crufty--I think nobody even does it that way in Lisp any more, you're better off passing an environment around explicitly. If there were a lot of variables, this could be a good application for functional maps, which I've been wanting to implemetn for python. Kay, did you have something to add? You quoted the above two posts and then your message stopped. -- http://mail.python.org/mailman/listinfo/python-list
Re: Benchmark [was Re: common problem - elegant solution sought]
Helmut Jarausch [EMAIL PROTECTED] writes: def del_by_key(L,key) : for pos, (k,d) in enumerate(L): if k == key : del L[pos] break This looks very dangerous, mutating L while iterating over it. -- http://mail.python.org/mailman/listinfo/python-list
Re: short path evaluation, why is f() called here: dict(a=1).get('a', f())
aspineux [EMAIL PROTECTED] writes: Nice idea, but if I want args I need to write it like that: x=d.get('a', defaultfunc=f, funcargs=(1,2,3)) Yeah, that looks good. The default arg to f should be the key being looked up. -- http://mail.python.org/mailman/listinfo/python-list
Re: Why this apparent assymetry in set operations?
Chris M [EMAIL PROTECTED] writes: precludes error-prone constructions like set('abc') 'cbs' in favor of the more readable set('abc').intersection('cbs'). set('abc') set('cbs') -- http://mail.python.org/mailman/listinfo/python-list
Re: Why this apparent assymetry in set operations?
On Jan 15, 2008 12:06 PM, Chris M [EMAIL PROTECTED] wrote: On Jan 15, 11:51 am, Neil Cerutti [EMAIL PROTECTED] wrote: So this is a bug in set_update or in set_ior. They can't both be right. It's not a bug. Note, the non-operator versions of union(), intersection(), difference(), and symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like set('abc') 'cbs' in favor of the more readable set('abc').intersection('cbs'). Thanks. That neatly answers Skip's question, assuming he buys the putative error pronicity. The docs say the design is based on lessons learned from the sets module, so that also explains why it's different from the module version, as well. -- Neil Cerutti [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Iterate through slots
How can I iterate through the slots of a class, including those it inherits from parent classes? class C(object): __slots__ = ['a'] class D(C): __slots__ = ['b'] d = D() d.__slots__ ['b'] d.a = 1 # this works, so slots inherit properly d.b = 2 d.c = 3 # this doesnt work, like we expect Traceback (most recent call last): File stdin, line 1, in ? AttributeError: 'D' object has no attribute 'c' The reason I want to do this is that I want to have the following, and let all the children inherit the parent's __init__: class Parent(object): __slots__ = ['whatever'] def __init__(self, context=None, **kw): if context is None: context=getContext() for slot in SLOTITERATORHERE: # Resolve the slot's value, even for those things not specifically set in kw class Child1(Parent): __slots__ = ['for_me_only'] -- http://mail.python.org/mailman/listinfo/python-list
Re: Open existing Word document, modify and save.
On Jan 15, 12:01 pm, gsal [EMAIL PROTECTED] wrote: New to Python and new to Win32. Help please. O.k., so this might seem like one of those can you do my homework kind of postings, except that is not homework, it is officework. I have been reading the Core Python book and I am really excited about starting my next project with Python, instead of tcl/tk/Fortran/C. While I can see how to use it for scientific computing and have gone with the NumPy and SciPy tutorials, I am having a hard time with Win32. Attempted to read some of the documentation for Win32 and while the basic stuff talks about creating a document, I did not see how to open an existing document and modify certain parts of it...and then it seems that it got very complicated (for me) really quick. Sure, it seems powerful, but all I need is a small part of it, I think. Here is the thing. Here at the office, we have computer programs to generate spec data and the Applications people have MS-Word documents in a very specific format where they would like to put such spec data. Initially, I was using merge fields and VB macros, until they stopped working when newer (non-backwards-compatible) versions came along; then, I switched to generating *.xml out of the original *.doc file, breaking it appart, modifying it and gluing back together...this is very laborious task and I have to go through the whole exercise, should the application people modify the original *.doc So, basically, I am looking for a way to work directly with the original *.doc, assuming I know everything about it...which I do; in fact, I have it and can also modify it, should I need to bookmark it or otherwise modify as needed. How to go about it? What's the python code to open an existing document, modify it and save it back? how does the Word document needs to be bookmarked/formatted so that it can be modified? For example, after the computer program has been run and the new, say, machine rating calculated, I need to deposit such value in a very specific spot in the Word document. I presume somebody out there already does this and is willing to provide some code?. Thank you very much in advance. gsal As I understand it, the only way to work with MS Word in Python is through COM in much the same manner as VB does. So if you know the COM model that MS Word uses, you shouldn't have too much trouble. I would recommend getting Hammond's and Robinson's book Python Programming on Win32 though, as it explains using Python this way. They have a sample chapter here: http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html It should be noted that Hammond is the author of the PyWin32 modules. ActiveState's website has a special version of Python that includes a COM browser and you can install it without harming your current installation. At least, I've had no problems. Other than that, you'll probably be spending a lot of time on MSDN. Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: SyntaxError: 'import *' not allowed with 'from .'
George Sakkis wrote: Unless I missed it, PEP 328 doesn't mention anything about this. What's the reason for not allowing from .relative.module import *' ? Generally, there's a move away from all import * versions these days. For example, Python 3.0 removes the ability to use import * within a function: http://www.python.org/dev/peps/pep-3100/ I suspect the import * version is not enabled for relative imports because most of python-dev is against import * forms anywhere. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Python in IIS + WSGI
Looks like Sourceforge had a problem with the file upload, causing it to be empty - I just fixed it. http://pyisapie.sourceforge.net/ On Jan 11, 4:37 pm, Phillip Sitbon [EMAIL PROTECTED] wrote: Recently (finally) updated the PyISAPIe project. Version 1.0.4 includes WSGI support (tested with current Django SVN and Trac 0.10) and a Django-native handler, as well as other examples of using it as a standalone web app. Also added some installation/usage docs on the project page. Comments/feedback welcome! -- http://mail.python.org/mailman/listinfo/python-list
Re: Benchmark [was Re: common problem - elegant solution sought]
Paul Rubin wrote: Helmut Jarausch [EMAIL PROTECTED] writes: def del_by_key(L,key) : for pos, (k,d) in enumerate(L): if k == key : del L[pos] break This looks very dangerous, mutating L while iterating over it. No, as Bruno Desthuilliers has pointed out, because one breaks out of the loop immediately. Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Re: super, decorators and gettattribute
Michele Simionato wrote: I really need to publish this one day or another, since these questions about super keeps coming out: http://www.phyast.pitt.edu/~micheles/python/super.html Unfortunately the links [2], [3] and [4] are not given, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Re: Data mapper - need to map an dictionary of values to a model
On Jan 15, 1:53 am, [EMAIL PROTECTED] wrote: Luke: What design patterns would you use here? What about generator (scanner) with parameters? :-) Bye, bearophile I'm not familiar with this pattern. I will search around, but if you have any links or you would like to elaborate, that would be wonderful. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Benchmark [was Re: common problem - elegant solution sought]
On Jan 15, 6:18 pm, Paul Rubin http://[EMAIL PROTECTED] wrote: Helmut Jarausch [EMAIL PROTECTED] writes: def del_by_key(L,key) : for pos, (k,d) in enumerate(L): if k == key : del L[pos] break This looks very dangerous, mutating L while iterating over it. This would indeed be dangerous *without* the break statement !-) -- http://mail.python.org/mailman/listinfo/python-list
RE: env parameter to popen won't accept Unicode on Windows -minor Unicode bug
Brian Smith wrote: popen() knows that it is running on Windows, and it knows what encoding Windows needs for its environment (it's either UCS2 or UTF-16 for most Windows APIs). At least when it receives a unicode string, it has enough information to apply the conversion automatically, and doing so saves the caller from having to figure out what exact encoding is to be used. So you propose Python should employ a hidden automatism that automagically guesses the right encoding? Why not leave it explicitly/consistently and let the user decide? What will happen if a future Windows changes its encoding? Will we need another magic routine to tell it apart? Regards, Björn -- BOFH excuse #353: Second-system effect. -- http://mail.python.org/mailman/listinfo/python-list
Re: Data mapper - need to map an dictionary of values to a model
Luke: I'm not familiar with this pattern. I will search around, but if you have any links or you would like to elaborate, that would be wonderful. :) It's not a pattern, it's a little thing: def line_filter(filein, params): for line in filein: if good(line, params): yield extract(line, params) That equals to this too: def line_filter(filein, params): return (extract(line, params) for line in filein if good(line, params)) But probably that's not enough to solve your problem, so other people can give you a better answer. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: Perl Template Toolkit: Now in spicy new Python flavor
Congrats. This will no doubt prove valuable to any Python programmer. -- http://mail.python.org/mailman/listinfo/python-list
UTF-8 in basic CGI mode
Hi, I have a basic Python CGI web form that shows data from a SQLite3 database. It runs under the built-in CGIWebserver which looks like this: [code] import SimpleHTTPServer import SocketServer SocketServer.TCPServer((, 80),SimpleHTTPServer.SimpleHTTPRequestHandler).serve_forever() [/code] The script runs Ok with ANSI characters, but when I try to process non- ASCII data I get an UnicodeDecodeError exception ('ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)). I have added the the 'u' prefix to all my literal strings, and I _have_ wrapped all my output statements into myString.encode('utf8', replace), but, apparently the UnicodeDecodeError exception occurs because of a string that I get back to the script through cgi.FieldStorage( ). I.e. I have the lines: form = cgi.FieldStorage( ) word= form['word'] which retrieve the 'word' value from a GET request. I am using this 'word' variable like this: print u'''input type=text name=blabla value=%s''' % (word) and apparently this causes exceptions with non-ASCII strings. I've also tried this: print u'''input type=text name=blabla value=%s''' % (word.encode('utf8')) but I still get the same UnicodeDecodeError.. What is the general good practice for working with UTF8? The standard Python CGI documentation has nothing on character sets. It looks insane to have to explicitly wrap every string with .encode('utf8'), but even this does not work. Could the problem be related to the encoding of the string returned by the cgi.fieldstorage()? My page is using UTF-8 encoding. What would be encoding for the data that comes from the browser after the form is submitted? Why does Python always try to use 'ascii'? I have checked all my strings and they are prefixed with 'u'. I have also tried replacing print statements with sys.stdout.write (DATA.encode('utf8')) but this did not help. Any clues? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQL-python-1.2.2 install with no mysql
Thank you... after: %yum install mysql* I was able to build and install mysql-python -- View this message in context: http://www.nabble.com/MySQL-python-1.2.2-install-with-no-mysql-tp14836669p14845579.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Perl Template Toolkit: Now in spicy new Python flavor
[EMAIL PROTECTED] wrote: I'd like to inform the Python community that the powerful and popular Template Toolkit system, previously available only in its original Perl implementation, is now also available in a beta Python implementation: http://tt2.org/python/index.html I created this port both as a fun programming project, and for use in environments where Perl is not available, for reasons technical, cultural, or otherwise. The extensive Perl test suites have also been ported, and most templates require no or very little modification. I must say...wow. That would have saved me some time and hassle about a year ago, but of course, I wouldn't have fell in love with pure XML templates either. :) As someone who has used Template Toolkit quite a bit, I must say that is is quite cool. Congrats on a job well done! j -- http://mail.python.org/mailman/listinfo/python-list
Re: env parameter to popen won't accept Unicode on Windows - minor Unicode bug
Diez B. Roggisch wrote: John Nagle wrote: Benjamin wrote: On Jan 14, 6:26 pm, Bjoern Schliessmann usenet- [EMAIL PROTECTED] wrote: John Nagle wrote: It turns out that the strings in the env parameter have to be ASCII, not Unicode, even though Windows fully supports Unicode in CreateProcess. That's of course nonsense, they don't need to be ascii, they need to be byte-strings in whatever encoding you like. Are you sure it supports Unicode, not UTF8 or UTF16? Probably using something like uthestring.encode(utf16) will help. Otherwise: bugs.python.org John's understanding of the differences between unicode and it's encodings is a bit blurry, to say the least. Who's this guy? Whatever translation is necessary should be done in popen, which has cases for Windows and POSIX. popen is supposed to be cross-platform to the extent possible. I think it's just something that didn't get fixed when Unicode support went in. I've been looking at the source code. There's _PyPopenCreateProcess in posixmodule.c.That one doesn't support passing an environment at all; see the call to Windows CreateProcess. Is that the one that Popen uses? Where is win32process in the source? It ought to be in Modules, but it's not. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: A question about event handlers with wxPython
That all looks cool. I will experiment more. I'm a bit slow on this as only two weeks old so far. Thanks for the patience -- http://mail.python.org/mailman/listinfo/python-list
searching an XML doc
Hello, I've been reading about ElementTreee and ElementPath so I could use them to find the right elements in the DOM. Unfortunately neither of these seem to offer XPath like capabilities where I can find elements based on tag, attribute values etc. Are there any libraries which can give me XPath like functionality? Thanks in advance -- http://mail.python.org/mailman/listinfo/python-list
Re: A question about event handlers with wxPython
On Jan 15, 2:20 pm, Erik Lind [EMAIL PROTECTED] wrote: That all looks cool. I will experiment more. I'm a bit slow on this as only two weeks old so far. Thanks for the patience No problem. I'm pretty slow with some toolkits too...such as SQLAlchemy. Ugh. Mike -- http://mail.python.org/mailman/listinfo/python-list
UTF-8 in basic CGI mode
Hi, I have a basic Python CGI web form that shows data from a SQLite3 database. It runs under the built-in CGIWebserver which looks something like this: [code] from BaseHTTPServer import HTTPServer from CGIHTTPServer import CGIHTTPRequestHandler HTTPServer(8000, CGIHTTPRequestHandler).serve_forever( ) [/code] The script runs Ok with ANSI characters, but when I try to process non- ASCII data I get an UnicodeDecodeError exception ('ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)). I have added the the 'u' prefix to all my literal strings, and I _have_ wrapped all my output statements into myString.encode('utf8', replace), but, apparently the UnicodeDecodeError exception occurs because of a string that I get back to the script through cgi.FieldStorage( ). I.e. I have the lines: form = cgi.FieldStorage( ) word= form['word'] which retrieve the 'word' value from a GET request. I am using this 'word' variable like this: print u'''input type=text name=blabla value=%s''' % (word) and apparently this causes exceptions with non-ASCII strings. I've also tried this: print u'''input type=text name=blabla value=%s''' % (word.encode('utf8')) but I still get the same UnicodeDecodeError.. What is the general good practice for working with UTF8? The standard Python CGI documentation has nothing on character sets. It looks insane to have to explicitly wrap every string with .encode('utf8'), but even this does not work. Could the problem be related to the encoding of the string returned by the cgi.fieldstorage()? My page is using UTF-8 encoding. What would be encoding for the data that comes from the browser after the form is submitted? Why does Python always try to use 'ascii'? I have checked all my strings and they are prefixed with 'u'. I have also tried replacing print statements with sys.stdout.write (DATA.encode('utf8')) but this did not help. Any clues? -- http://mail.python.org/mailman/listinfo/python-list
Compile with GLib-1.2 instead of 2.4
Hi, I am having to compile a standalone python because the webserver I use doesn't allow access to /usr/lib/python. I tried compiling on my lappy and uploading it, but the webserver does not have GLib-2.4. What arguments would I have to include in order for it to compile with GLib-1.2 instead of/and GLib2.4? Thanks, Brandon -- http://mail.python.org/mailman/listinfo/python-list
Re: super, decorators and gettattribute
On Jan 15, 8:06 pm, Helmut Jarausch [EMAIL PROTECTED] wrote: Unfortunately the links [2], [3] and [4] are not given, Luckily, there's Google :) [2] Article about MRO: http://www.python.org/download/releases/2.3/mro/ [3] Descriptor HowTo: http://users.rcn.com/python/download/Descriptor.htm [4] Articles about metaclasses (second one relevant to super): * http://www.ibm.com/developerworks/linux/library/l-pymeta.html, * http://www-128.ibm.com/developerworks/linux/library/l-pymeta2/?S_TACT=105AGX03S_CMP=ART, * http://www.ibm.com/developerworks/linux/library/l-pymeta3.html?S_TACT=105AGX03S_CMP=ART Of course, it would be very nice if the article was updated to include the links. HTH, -- Richard -- http://mail.python.org/mailman/listinfo/python-list
Re: ElementTree and namespaces in the header only
Hallöchen! Fredrik Lundh writes: Peter Bengtsson wrote: root = Element('feed', xmlns='http://www.w3.org/2005/Atom') root.set('xmlns:se', NS_URL) entry = SubElement(root, 'entry') SubElement(root, 'title').text = 'Title' SubElement(entry, SEN('category')).text = 'Category' But surely the xmlns:se attribute on the se:category tag is excessive since the namespace (by the URI) is already defined in the feed tag. How do I set non-default namespace tags in elements without the automatic xmlns:se attribute repeated each time? ET 1.2's standard serializer doesn't take explicitly set namespaces into account. If you want full control over namespace generation, you have to do it yourself: http://effbot.org/zone/element-namespaces.htm#explicitly-setting-namespace-attributes ET 1.3 provides a default_namespace option for this specific case (but you still have to use universal names for everything that should go into the default namespace). I've worked with Saxon for a couple of years, and it tries to generate the minimal (well, sort of) XML file possible: It uses the prefixes given in the source XSLT file rather than generating something, and detects implicitly set namespaces, thus avoiding spitting them out again. Wouldn't this be an option for ET, too? Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: [EMAIL PROTECTED] (See http://ime.webhop.org for further contact info.) -- http://mail.python.org/mailman/listinfo/python-list
Running Multiple Versions
Hi, We are windows shop with some unix servers as well. We run 2.4.1 and want to begin migrating to 2.5.1. I am looking for information dealing with having more than one version of python on a server at one time. I believe this is called side-by-side and all that is needed to select a version on a windows box is to set the path to the desired version of python prior to launching the script. Does this sound correct? Is there doc online that describes this? For windows, has anyone come up with a way to have the script launch the correct version at load time - similar to the she-bang method used in unix? Thanks Noel -- http://mail.python.org/mailman/listinfo/python-list
Re: Compile with GLib-1.2 instead of 2.4
Sorry, I know what arg to use with ./configure. With --with-libc=STRING, do I put the version I want, or the path to my GLib 1.2 files? On Tue, 2008-01-15 at 14:53 -0600, Brandon Perry wrote: Hi, I am having to compile a standalone python because the webserver I use doesn't allow access to /usr/lib/python. I tried compiling on my lappy and uploading it, but the webserver does not have GLib-2.4. What arguments would I have to include in order for it to compile with GLib-1.2 instead of/and GLib2.4? Thanks, Brandon -- http://mail.python.org/mailman/listinfo/python-list
Re: env parameter to popen won't accept Unicode on Windows -minor Unicode bug
Diez B. Roggisch wrote: Brian Smith wrote: Diez B. Roggisch wrote: Sure thing, python will just magically convert unicode to the encoding the program YOU invoke will expect. Right after we introduced the solve_my_problem() built-in-function. Any other wishes? There's no reason to be rude. If you'd know John, you'd know there is. ? Anyway, at least on Windows it makes perfect sense for people to expect Unicode to be handled automatically. popen() knows that it is running on Windows, and it knows what encoding Windows needs for its environment (it's either UCS2 or UTF-16 for most Windows APIs). At least when it receives a unicode string, it has enough information to apply the conversion automatically, and doing so saves the caller from having to figure out what exact encoding is to be used. For once, the distinction between windows and other platforms is debatable. I admit that subprocess contains already quite a few platform specific aspects, but it's purpose is to abstract these away as much as possible. However, I'm not sure that just because there are wide-char windows apis available automatically means that using UCS2/UTF-16 would succeed. A look into the python sources (PC/_subprocess.c) reveals that someone already thought about this, but it seems that just setting a CREATE_UNICODE_ENVIRONMENT in the CreateProcess-function should have been easy enough to do it if there weren't any troubles to expect. The problem is that only the NT-derived Microsoft systems talk Unicode. The DOS/Win16/Win9x family did not. But they did have CreateProcess. So the current code will handle Win9x, but not Unicode. When do we drop support for Win9x? It probably has to happen in Python 3K, since that's Unicode-everywhere. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: Why this apparent assymetry in set operations?
On Tue, 15 Jan 2008 11:25:25 -0500, Colin J. Williams wrote: I'm sorry, there appears to be a bug: # tSet.py import sets s1= sets.Set([1, 2, 3]) s1.union_update([3, 4,5]) print(s1) s2= sets.Set([6, 7, 8]) s1 |+ s2 # This fails: exceptions.TypeError: bad operand type for unary +: 'Set' And so it should fail. Did you mean |= instead of |+ ? -- Steven -- http://mail.python.org/mailman/listinfo/python-list