From andy at andygross.org Mon Dec 6 12:56:34 2004 From: andy at andygross.org (Andy Gross) Date: Mon, 6 Dec 2004 12:56:34 -0500 Subject: xmlrpclib or twisted? In-Reply-To: References: Message-ID: <2ABCDEEA-47B0-11D9-B0E6-000A95CED3AC@andygross.org> If you're not concerned about interoperability with other languages and are already using Twisted, I'd go with PB. Especially if you are using complicated datatypes that have to be serialized and sent over the wire - PB has a nice Cacheable type that doesn't serialize the whole object. XMLRPC on the other hand is a little simpler and will work with third-party stuff. /arg On Dec 6, 2004, at 5:11 AM, flupke wrote: > Hi, > > previously i made an application that used sockets to > do some network based processing. > My next app is again going to be a client/server app > and i wanted to see if i can't find an easier way to > make the networking going. > I bumped into xmlrpclib and also twisted (pb). > I'm not sure which on of these would suit my needs better. > I am planning to build a web GUI for the client so if i > use twisted, i would already have the components in there > to do so, so this could be a plus for twisted. > The client will connect to the server to receive data. > The data is the result of one of several queries and these raw > results would then be displayed in the client via a webgui or > wxPython. (leaning towards webgui) > > Any other ideas? > > Thanks > Benedict > -- > http://mail.python.org/mailman/listinfo/python-list From rschroev_nospam_ml at fastmail.fm Mon Dec 13 04:36:19 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 13 Dec 2004 09:36:19 GMT Subject: Skinnable/Stylable windows in wxPython? In-Reply-To: References: <1102870917.313182.98790@z14g2000cwz.googlegroups.com> Message-ID: Daniel Bickett wrote: > Solution found! > > Not only would this make it more multi-platform (I have no access to > a GTK machine so I don't know if this works. Could someone please > check?) Looks like it works (I had to change frame.Show() to frame.Show(1) though, but that could be because it's an old version). One odd thing though: the Windows version doesn't react to clicking or dragging the mouse, which seems to be the expected behavior. The GTK version can be moved by dragging the mouse; even just clicking the mouse moves the window somewhat down and to the left. -- "Codito ergo sum" Roel Schroeven From skip at pobox.com Fri Dec 24 23:18:52 2004 From: skip at pobox.com (Skip Montanaro) Date: Fri, 24 Dec 2004 22:18:52 -0600 Subject: Lambda going out of fashion In-Reply-To: <86oegj8fey.fsf@guru.mired.org> References: <41CB473E.6030600@freemail.gr> <86oegj8fey.fsf@guru.mired.org> Message-ID: <16844.59948.467728.585916@montanaro.dyndns.org> Mike> Perl 6.0 is going to include even more drastic changes. It will Mike> also include a Perl 5.x interpreter, and will have to be switched Mike> to 6.0 mode by a magic cookie of some kind in the source. Possibly Mike> Python 3.0 could do something similar. -1 Things are complex enough as it is. Maintaining two interpreters that have to somehow comingle would be worse. Maintain Python 2.x as a separate release for a period of time after Python 3.0 is released (a couple years, anyway, maybe longer), but don't mix the two. Skip From danb_83 at yahoo.com Sun Dec 26 09:37:28 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 26 Dec 2004 06:37:28 -0800 Subject: A Revised Rational Proposal References: <86llbl7kvv.fsf@guru.mired.org> <1104071161.355661.10550@f14g2000cwb.googlegroups.com> Message-ID: <1104071847.995822.53400@f14g2000cwb.googlegroups.com> Dan Bishop wrote: > Mike Meyer wrote: > > This version includes the input from various and sundry people. > Thanks > > to everyone who contributed. > > > > > > > PEP: XXX > > Title: A rational number module for Python > ... > > Implementation > > ============== > > > > There is currently a rational module distributed with Python, and a > > second rational module in the Python cvs source tree that is not > > distributed. While one of these could be chosen and made to conform > > to the specification, I am hoping that several people will volunteer > > implementatins so that a ''best of breed'' implementation may be > > chosen. > > I'll be the first to volunteer an implementation. The new Google Groups software appears to have problems with indentation. I'm posting my code again, with indents replaced with instructions on how much to indent. from __future__ import division import decimal import math def _gcf(a, b): {indent 1}"Returns the greatest common factor of a and b." {indent 1}a = abs(a) {indent 1}b = abs(b) {indent 1}while b: {indent 2}a, b = b, a % b {indent 1}return a class Rational(object): {indent 1}"Exact representation of rational numbers." {indent 1}def __init__(self, numerator, denominator=1): {indent 2}"Contructs the Rational object for numerator/denominator." {indent 2}if not isinstance(numerator, (int, long)): {indent 3}raise TypeError('numerator must have integer type') {indent 2}if not isinstance(denominator, (int, long)): {indent 3}raise TypeError('denominator must have integer type') {indent 2}if not denominator: {indent 3}raise ZeroDivisionError('rational construction') {indent 2}factor = _gcf(numerator, denominator) {indent 2}self.__n = numerator // factor {indent 2}self.__d = denominator // factor {indent 2}if self.__d < 0: {indent 3}self.__n = -self.__n {indent 3}self.__d = -self.__d {indent 1}def __repr__(self): {indent 2}if self.__d == 1: {indent 3}return "Rational(%d)" % self.__n {indent 2}else: {indent 3}return "Rational(%d, %d)" % (self.__n, self.__d) {indent 1}def __str__(self): {indent 2}if self.__d == 1: {indent 3}return str(self.__n) {indent 2}else: {indent 3}return "%d/%d" % (self.__n, self.__d) {indent 1}def __hash__(self): {indent 2}try: {indent 3}return hash(float(self)) {indent 2}except OverflowError: {indent 3}return hash(long(self)) {indent 1}def __float__(self): {indent 2}return self.__n / self.__d {indent 1}def __int__(self): {indent 2}if self.__n < 0: {indent 3}return -int(-self.__n // self.__d) {indent 2}else: {indent 3}return int(self.__n // self.__d) {indent 1}def __long__(self): {indent 2}return long(int(self)) {indent 1}def __nonzero__(self): {indent 2}return bool(self.__n) {indent 1}def __pos__(self): {indent 2}return self {indent 1}def __neg__(self): {indent 2}return Rational(-self.__n, self.__d) {indent 1}def __abs__(self): {indent 2}if self.__n < 0: {indent 3}return -self {indent 2}else: {indent 3}return self {indent 1}def __add__(self, other): {indent 2}if isinstance(other, Rational): {indent 3}return Rational(self.__n * other.__d + self.__d * other.__n, self.__d * other.__d) {indent 2}elif isinstance(other, (int, long)): {indent 3}return Rational(self.__n + self.__d * other, self.__d) {indent 2}elif isinstance(other, (float, complex)): {indent 3}return float(self) + other {indent 2}elif isinstance(other, decimal.Decimal): {indent 3}return self.decimal() + other {indent 2}else: {indent 3}return NotImplemented {indent 1}__radd__ = __add__ {indent 1}def __sub__(self, other): {indent 2}if isinstance(other, Rational): {indent 3}return Rational(self.__n * other.__d - self.__d * other.__n, self.__d * other.__d) {indent 2}elif isinstance(other, (int, long)): {indent 3}return Rational(self.__n - self.__d * other, self.__d) {indent 2}elif isinstance(other, (float, complex)): {indent 3}return float(self) - other {indent 2}elif isinstance(other, decimal.Decimal): {indent 3}return self.decimal() - other {indent 2}else: {indent 3}return NotImplemented {indent 1}def __rsub__(self, other): {indent 2}if isinstance(other, (int, long)): {indent 3}return Rational(other * self.__d - self.__n, self.__d) {indent 2}elif isinstance(other, (float, complex)): {indent 3}return other - float(self) {indent 2}elif isinstance(other, decimal.Decimal): {indent 3}return other - self.decimal() {indent 2}else: {indent 3}return NotImplemented {indent 1}def __mul__(self, other): {indent 2}if isinstance(other, Rational): {indent 3}return Rational(self.__n * other.__n, self.__d * other.__d) {indent 2}elif isinstance(other, (int, long)): {indent 3}return Rational(self.__n * other, self.__d) {indent 2}elif isinstance(other, (float, complex)): {indent 3}return float(self) * other {indent 2}elif isinstance(other, decimal.Decimal): {indent 3}return self.decimal() * other {indent 2}else: {indent 3}return NotImplemented {indent 1}__rmul__ = __mul__ {indent 1}def __truediv__(self, other): {indent 2}if isinstance(other, Rational): {indent 3}return Rational(self.__n * other.__d, self.__d * other.__n) {indent 2}elif isinstance(other, (int, long)): {indent 3}return Rational(self.__n, self.__d * other){indent 2} {indent 2}elif isinstance(other, (float, complex)): {indent 3}return float(self) / other {indent 2}elif isinstance(other, decimal.Decimal): {indent 3}return self.decimal() / other {indent 2}else: {indent 3}return NotImplemented {indent 1}__div__ = __truediv__ {indent 1}def __rtruediv__(self, other): {indent 2}if isinstance(other, (int, long)): {indent 3}return Rational(other * self.__d, self.__n) {indent 2}elif isinstance(other, (float, complex)): {indent 3}return other / float(self) {indent 2}elif isinstance(other, decimal.Decimal): {indent 3}return other / self.decimal() {indent 2}else: {indent 3}return NotImplemented {indent 1}__rdiv__ = __rtruediv__ {indent 1}def __floordiv__(self, other): {indent 2}truediv = self / other {indent 2}if isinstance(truediv, Rational): {indent 3}return truediv.__n // truediv.__d {indent 2}else: {indent 3}return truediv // 1 {indent 1}def __rfloordiv__(self, other): {indent 2}return (other / self) // 1 {indent 1}def __mod__(self, other): {indent 2}return self - self // other * other {indent 1}def __rmod__(self, other): {indent 2}return other - other // self * self {indent 1}def __divmod__(self, other): {indent 2}return self // other, self % other {indent 1}def __cmp__(self, other): {indent 2}if other == 0: {indent 3}return cmp(self.__n, 0) {indent 2}else: {indent 3}return cmp(self - other, 0) {indent 1}def __pow__(self, other): {indent 2}if isinstance(other, (int, long)): {indent 3}if other < 0: {indent 4}return Rational(self.__d ** -other, self.__n ** -other) {indent 3}else: {indent 4}return Rational(self.__n ** other, self.__d ** other) {indent 2}else: {indent 3}return float(self) ** other {indent 1}def __rpow__(self, other): {indent 2}return other ** float(self) {indent 1}def decimal(self): {indent 2}"Decimal approximation of self in the current context" {indent 2}return decimal.Decimal(self.__n) / decimal.Decimal(self.__d) {indent 1}@staticmethod {indent 1}def fromExactFloat(x): {indent 2}"Returns the exact rational equivalent of x." {indent 2}mantissa, exponent = math.frexp(x) {indent 2}mantissa = int(mantissa * 2 ** 53) {indent 2}exponent -= 53 {indent 2}if exponent < 0: {indent 3}return Rational(mantissa, 2 ** (-exponent)) {indent 2}else: {indent 3}return Rational(mantissa * 2 ** exponent) {indent 1}@staticmethod {indent 1}def fromExactDecimal(x): {indent 2}"Returns the exact rational equivalent of x." {indent 2}sign, mantissa, exponent = x.as_tuple() {indent 2}sign = (1, -1)[sign] {indent 2}mantissa = sign * reduce(lambda a, b: 10 * a + b, mantissa) {indent 2}if exponent < 0: {indent 3}return Rational(mantissa, 10 ** (-exponent)) {indent 2}else: {indent 3}return Rational(mantissa * 10 ** exponent) {indent 1}@staticmethod {indent 1}def approxSmallestDenominator(x, tolerance): {indent 2}"Returns a rational m/n such that abs(x - m/n) < tolerance,\n" \ {indent 2}"minimizing n." {indent 2}tolerance = abs(tolerance) {indent 2}n = 1 {indent 2}while True: {indent 3}m = int(round(x * n)) {indent 3}result = Rational(m, n) {indent 3}if abs(result - x) < tolerance: {indent 4}return result {indent 3}n += 1 {indent 1}@staticmethod {indent 1}def approxSmallestError(x, maxDenominator): {indent 2}"Returns a rational m/n minimizing abs(x - m/n),\n" \ {indent 2}"with the constraint 1 <= n <= maxDenominator." {indent 2}result = None {indent 2}minError = x {indent 2}for n in xrange(1, maxDenominator + 1): {indent 3}m = int(round(x * n)) {indent 3}r = Rational(m, n) {indent 3}error = abs(r - x) {indent 3}if error == 0: {indent 4}return r {indent 3}elif error < minError: {indent 4}result = r {indent 4}minError = error {indent 2}return result From insert at spam.here Tue Dec 14 01:02:04 2004 From: insert at spam.here (Doug Holton) Date: Tue, 14 Dec 2004 00:02:04 -0600 Subject: how can I import a module without using pythonpath? In-Reply-To: References: Message-ID: Phd wrote: > Hi, > > I'm using python 2.2, I want to import a module by referring to its > relative location. The reason for this is that there is another module > with the same name that's already in pythonpath( not my decision, but I > got to work around it, bummer). So is there any easy way to do it? import sys, os sys.path.insert(0,os.path.abspath("relative path")) import module sys.path.remove(os.path.abspath("relative path")) From alessandro.crugnola at gmail.com Thu Dec 16 20:40:31 2004 From: alessandro.crugnola at gmail.com (Alessandro Crugnola) Date: Fri, 17 Dec 2004 01:40:31 GMT Subject: regular expression for javadoc style comment Message-ID: Hi all, i need to use a regular expression to match javadoc style comments in a file, something like /** * Constructs a new Call instance. * * @param object the object the Function shall be executed on * @param func the Function that shall be executed * @throws IllegalArgumentException if neigther the object or the function is not available. */ i'm finiding many difficulties to write a valid regular expression ale From bjg at network-theory.co.uk Thu Dec 9 09:25:55 2004 From: bjg at network-theory.co.uk (Brian Gough) Date: 09 Dec 2004 14:25:55 +0000 Subject: Python Docs. Hardcopy 2.4 Library Reference, interested? References: Message-ID: <87oeh3v98s.fsf@network-theory.co.uk> "Brad Clements" writes: > Is anyone interested in purchasing a hardcopy version of the Python 2.4 > Library reference? I have one in the pipeline but I'm waiting for sales of the Python Tutorial and Python Language Reference to justify bringing it out. The amount of text in the library manual is huge (it requires two volumes), which makes it more costly. -- best regards, Brian Gough Network Theory Ltd, Publishing the Python Manuals --- http://www.network-theory.co.uk/python/ From llistes at jrom.net Thu Dec 2 13:52:24 2004 From: llistes at jrom.net (Jordi Romero (qiz/jrom)) Date: Thu, 02 Dec 2004 19:52:24 +0100 Subject: debian python2.4 In-Reply-To: <7c60b605041202103646120f3d@mail.gmail.com> References: <20041203152746.GB24721@mrna.tn.nic.in> <7c60b605041202103646120f3d@mail.gmail.com> Message-ID: <41AF6468.30105@jrom.net> Just remove /usr/bin/python and make a new soft link to the /usr/bin/python2.4 (ln -s /usr/bin/python2.4 /usr/bin/python) Jonas Galvez wrote: >km wrote: > > > Only >downside is that /usr/bin/python still points to 2.3.4. Haven't >figured out how to change that, but I am also afraid it would break >mod_python so I decided to keep it unchanged for now. > > >-- >http://jonasgalvez.com >http://codeazur.com.br > > From deetsNOSPAM at web.de Thu Dec 2 09:47:12 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 02 Dec 2004 15:47:12 +0100 Subject: installing wxPython on Linux and Windows References: <318je3F389ffiU1@individual.net> Message-ID: > The package for wxPython2.5.3 currently is available > for Debian Sid/unstable but not for Sarge/testing .... Nevertheless, the point remains valid: _If_ you have proper dependency-management, installation of packages is easy. Of course tracking dependencies takes effort, and so unless a general scheme is adopted, no software project will burden itself with the task of doing this. So you have to wait for your distribution to do that for them - which may result in not-so-latest verisons. Or even none at all.... -- Regards, Diez B. Roggisch From steven.bethard at gmail.com Wed Dec 8 22:44:02 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 09 Dec 2004 03:44:02 GMT Subject: exec'ing functions (WAS: updating locals() and globals()) In-Reply-To: <10rf9tktfv9vr36@corp.supernews.com> References: <10rf4nrt72ktt1e@corp.supernews.com> <10rf9tktfv9vr36@corp.supernews.com> Message-ID: <5SPtd.210910$HA.146444@attbi_s01> Jeff Shannon wrote: > Steven Bethard wrote: > >> Jeff Shannon wrote: >> >>> Note also that functions which use exec cannot use the static >>> namespace optimization, and thus tend to be *much* slower than normal >>> functions >> >> In what circumstances will this be true? I couldn't verify it: [snip] > > I was referring to functions which have an internal exec statement, not > functions which are created entirely within an exec -- i.e., something > like this: Thanks for the clarification. Here's the results for some functions with internal exec statements: > cat fib.py def fib1(n): a, b = 0, 1 while True: a, b = b, a + b yield a exec """\ def fib2(n): a, b = 0, 1 while True: a, b = b, a + b yield a """ def fib3(n): a, b = 0, 1 while True: exec "a, b = b, a + b" yield a def fib4(n): exec "a, b = 0, 1" while True: exec "a, b = b, a + b" yield a > > python -m timeit -s "import fib" "fib.fib1(100)" 1000000 loops, best of 3: 0.71 usec per loop > python -m timeit -s "import fib" "fib.fib2(100)" 1000000 loops, best of 3: 0.678 usec per loop > python -m timeit -s "import fib" "fib.fib3(100)" 1000000 loops, best of 3: 0.826 usec per loop > python -m timeit -s "import fib" "fib.fib4(100)" 1000000 loops, best of 3: 0.821 usec per loop I'm not sure I'd say they're *much* slower, but you're right; they're definitely slower. Steve From wnebfynj at mnovryyb.pbz Thu Dec 23 05:55:46 2004 From: wnebfynj at mnovryyb.pbz (JZ) Date: Thu, 23 Dec 2004 11:55:46 +0100 Subject: PHP vs. Python References: <1103753016.780533.137480@f14g2000cwb.googlegroups.com> <7xzn0526ae.fsf@ruckus.brouhaha.com> Message-ID: <166lr9pr70piw.1ktyma1e6cfpo.dlg@40tude.net> Dnia Wed, 22 Dec 2004 20:57:07 -0500, Robert Kern napisa?(a): > I think he means, "scale to larger programs," not "scale to more > processors." Yes. I will try to be more specific. There is several reasons why Python scales better than PHP. (1) Python uses namespaces, PHP - not. The bigger programm the bigger probability of conflict among names in PHP. (2) Not only PHP lacks namespaces. It has one big inconsistent mess with its function naming! Inconsistent prefixes, order of parameters. Mess. It is difficult to memorize it. Python programming need less interupting for reading manual. (3) Python uses modules, PHP - not. Python can download single or some classes from many big modules (eg. from module1 import class1, var1, fun1). PHP is primitive in its copy-paste *all* included files! So Python uses less memory than PHP and do not need to parse so many lines. (4) Python automatic compile every imported modules into bytecode, PHP has to parse all those mess. Without accelerators PHP is much slower for bigger applications. This is the reason why PEAR is so slow. This is the reason why ezPublish is so slow. The bigger code (more included files), the slower PHP works. (5) Python compile its modules automatic and do not need to parse them for every browser request like PHP do. (6) Pythonic application server (eg. Webware) do not need to load and parse any files from filesystem at all! It loads them once, compile it and store compiled scripts in memory. PHP has to load files from filesystem, parse them and execute. From my own experience: when I moved from PHP to Webware and I compared its performance with (similar scale) php appplications, my webware was almost 6 times faster! (7) Python has much better free IDE editors with graphic debugger inside. PythonWin, Boa, SPE, Eric3 etc. It is much easier debug in Python than i PHP for larger programmes. (8) And last but not least. Python is truly object oriented, general purpose language. PHP is not general purpose language. PHP4 has very poor OO. (PHP5 has better, but has also some useless new features like private variables. They have sense for static compiled languages like C++ or Java , not for dynamic ones.) Python also uses sofisticated exception handling, uses namespaces, has module import, has better unicode support, has more consistent api etc. One more example from my experience. I always have problem with converting string among iso-8859-2, cp1250, mac-ce and utf-8. PHP utf8 functions are poor, implements useless (for me) iso-8859-1 only. iconv library for PHP is even worse, when it cannot convert some characters it deletes the following characters! PHP has no such like: unicode(txt, 'cp1250').encode('cp1250', 'xmlcharrefreplace'). When some characters exists only in cp1250 but not in iso-8859-2 that function convert them into xml entity &#number; Cute! -- JZ ICQ:6712522 http://zabiello.com From deetsNOSPAM at web.de Mon Dec 20 11:29:07 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 20 Dec 2004 17:29:07 +0100 Subject: extending python with a C-written dll References: <41c6e784$0$16084$a1866201@visi.com> <41c6f353$0$16095$a1866201@visi.com> Message-ID: > The fact is that the python interpreter I use is not a standard one > It is a python interpreter delivered within a software named Blender. > I don't know whether it is possible or not to add ctypes to it ..(I > don't even have a python shell to perform the setup) > > I'm sure it is possible to use dll-built with it .. > So please .. can you tell me where I can find Py_BuildValue and > Py_InitModule4 to link with ? I doubt that adding new modules as dlls is easier than incorporating pure-python ones or a mixture of both - as ctypes most probably is. After all, its pythons module loading mechanism that kicks in for all cases. If ctypes suits your needs outside of blender, I'd go for trying to incorporate it into the blender interpreter. -- Regards, Diez B. Roggisch From caleb1 at telkomsa.net Thu Dec 9 23:05:06 2004 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Thu, 09 Dec 2004 23:05:06 -0500 Subject: Calling a C program from a Python Script References: <41b89738$0$11034$a1866201@visi.com> <41b8a6f9$0$9757$a1866201@visi.com> Message-ID: Hi Brad Not that I'm an expert but note: 1. If you already know C, fair enough. You should know what you are getting into then. I sure as heck don't know it very well at all and I'm not gonna make that time investment now. MAYBE if I really really needed the extra speed (but this seems to arise more infrequently than one would imagine) for something where I couldn't interface with some existing binary library. 2. The PythonForDelphi crowd makes the creation of native binary extensions with Delphi pathetically easy (which is about equivalent to the degree of complexity I can handle). As I said in a previous post, C is not the only game in town for binary extensions. Of course, I happen to already know ObjectPascal (Delphi) quite well, so for me it is a good fit - maybe not so much for you if pascal would be new for you. If both pascal AND C are new for you, I suspect you will find Delphi a fair bit easier (& faster) to learn. btw, Works with Kylix also. I don't know about FPC. 3. As someone said previously, some of the 'builtin' python functionality is compiled C anyway. This point alone often makes it very difficult to qualify statements like 'python is slow'. You could even start with the Cpython source for something like file access and see how you go with optimization, if *that* performance was not enough for you. 4. Nobody mentioned Pyrex yet, I think it kinda allows you to write C within your python scripts, and then handles that all intellligently, compiles the necessary bits, and so on - try a google search for the facts rather than my broken memory of features. 5. If all you are is curious about interfacing a C extension with Python - that's cool too. I would be interested in hearing what to look out for in the learning stage of developing C-extensions, for when I am overcome by curiosity and feel the need to try it out. Keep well Caleb > I just want to know the basics of using C and Python together when the > need arises, that's all, I don't want to write a book about what exactly > it is that I'm involved in. > > I'm going to take It's Me's advice and have a look at SWIG. > > Thank you, > > Brad From postmaster at earthlink.net Wed Dec 15 20:15:02 2004 From: postmaster at earthlink.net (Daniel T.) Date: Thu, 16 Dec 2004 01:15:02 -0000 Subject: lies about OOP References: <1102995205.949964.76020@c13g2000cwb.googlegroups.com> <1103047408.886313.50230@c13g2000cwb.googlegroups.com> Message-ID: "H. S. Lahman" wrote: > > Les Hatton "Does OO sync with the way we think?", IEEE Software, 15(3), > > p.46-54 > > "This paper argues from real data that OO based systems written in C++ > > appear to increase the cost of fixing defects significantly when > > compared with systems written in either C or Pascal. It goes on to > > suggest that at least some aspects of OO, for example inheritance, do > > not fit well with the way we make mistakes." > > Try and find and experienced OO developer who would advocate that large, > complex generalizations are a good practice. You can write lousy > programs in any paradigm. The likelihood increases when you use the > most technically deficient of all the OOPLs. (If those developers had > used Smalltalk, I'll bet their defect rates would have been > substantially lower even if they weren't very good OO developers.) Careful, the paper never claims that C++ produced more defects than C or Pascal. It only claims that the defects found in the C++ program were more costly to fix. That is a very big difference. However, I agree completely with the rest of your comments. From peter at engcorp.com Wed Dec 22 15:27:38 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 22 Dec 2004 15:27:38 -0500 Subject: Newbie namespace question In-Reply-To: References: <1103726535.898895.207410@c13g2000cwb.googlegroups.com> <1103729308.940154.187760@f14g2000cwb.googlegroups.com> Message-ID: deelan wrote: > i believe that to avoid circular refs errors remember you can > lazy-import, for example here i'm importing the email package: > >>>> m = __import__('email') >>>> m > > > > check help(__import__) for futher details. I'm not sure what you think that does, but I don't think it does it. The code you show above is no more "lazy" than a simple "import email as m" would have been, I believe. All statements are executed as they are encountered during import, so any that are no inside a function or class definition, or protected by a conditional control structure in some way, will be executed right away, rather than lazily. I may have misinterpreted what you were trying to say... -Peter From fumanchu at amor.org Thu Dec 23 21:25:51 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 23 Dec 2004 18:25:51 -0800 Subject: Lambda going out of fashion Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3024F67@exchange.hqamor.amorhq.net> Stephen Thorne wrote: > Lambdas contain only a single expression. Even the py3k > wiki page ignores this critical difference. A single expression > means no statements of any kind can be included. Assignment, > if/elif/else, while, for, try/except, etc are not catered > for in lambdas. That's been the only serious use case I've had for lambdas: a way to have an Expression object, in effect. If we had a more rigorous syntax specifically for first-class expressions, lambda could go away forever in my book. Robert Brewer MIS Amor Ministries fumanchu at amor.org From ebolonev at mail.ru Wed Dec 8 05:42:09 2004 From: ebolonev at mail.ru (Egor Bolonev) Date: Wed, 08 Dec 2004 20:42:09 +1000 Subject: os.path.islink() References: Message-ID: On Wed, 08 Dec 2004 20:29:27 +1000, Egor Bolonev wrote: > gui folder link is a .lnk file i want to detect "'s" ============================================ C:\Documents and Settings\????\My Documents>dir ??? ? ?????????? C ?? ????? ?????. ???????? ????? ????: 386D-F630 ?????????? ????? C:\Documents and Settings\????\My Documents 08.12.2004 20:39 . 08.12.2004 20:39 .. 08.12.2004 20:39 Antiloop 06.12.2004 20:47 My eBooks 02.12.2004 22:50 My Music 06.12.2004 23:34 My Pictures 06.12.2004 23:56 My Videos 08.12.2004 20:23 Scripts 04.12.2004 16:23 upload 16.11.2004 21:14 Virtual CD v6 16.11.2004 21:15 Virtual CDs 08.12.2004 20:36 [temp] 04.12.2004 20:11 ?????? 06.12.2004 22:51 ????? ????? 0 ?????? 0 ???? 14 ????? 8?970?833?920 ???? ???????? ============================================ From alred at guam.net Sun Dec 5 20:37:47 2004 From: alred at guam.net (Alfred Canoy) Date: Mon, 6 Dec 2004 11:37:47 +1000 Subject: Programming help Message-ID: <006801c4db34$31a7f650$670880ca@Alfred> Hello, I'm stuck in the end of my source code. I'm trying to print all the numbers. How can I print all the list of numbers that I selected? Source code: # compute the Mean, Median & Mode of a list of numbers: sum = 0.0 print 'This program will take several numbers then average them' count = input(' How many numbers would you like to sum: ') current_count = 0 freq = {} freq [current_count] = number while current_count < count: current_count = current_count + 1 number = input ('Enter a number: ') print "Number", current_count,":",number sum = sum + number print " [x,...,x] ?" Output: This program will take several numbers then average them number 1: 2 number 2: 3 number 3: 4 number 4: 2 How can I print: [2,3,4,2]? Greatly appreciates! Al _ _ _ _ Alfred Canoy Agana, Guam Pacific time alred at guam.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From tzot at sil-tec.gr Fri Dec 31 07:16:29 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 31 Dec 2004 14:16:29 +0200 Subject: lies about OOP References: <1102995205.949964.76020@c13g2000cwb.googlegroups.com> <29Evd.32591$Jk5.26287@lakeread01> <41c026e6$0$78279$e4fe514c@news.xs4all.nl> <_j2wd.97962$lN.16566@amsnews05.chello.com> Message-ID: On Wed, 15 Dec 2004 17:37:08 -0500, rumours say that Peter Hansen might have written: >Martijn Faassen wrote: >> Peter Hansen wrote: >>> Well, in any case, thanks for setting the record straight, Martjin. >> >> That of course also happens to me once every while. I can take care of >> myself though -- Dijkstra however needs an advocate for the correct >> spelling of his name in this earthly realm. > >Then there's us Danes, with "sen" instead of "son" (as many people >think it ought to be). And I can't even claim the wrong form >sounds noticably different, making any defense seem petty. So this means that if Guido was Dane too we would program in Pythen. The Zon of Pythen. The Sen Of Dr Strangelove. Nice. Happy new year in advance every one, don't start drinking before you drive home :) -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From __peter__ at web.de Wed Dec 8 02:27:36 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 08 Dec 2004 08:27:36 +0100 Subject: converting textobject to name of other object. References: <41b62eac$0$56348$edfadb0f@dread16.news.tele.dk> Message-ID: Lars Tengnagel wrote: > I'm trying to use the matrix variable to collect a matrix in the file > MatrixInfo which contains a lot of different matrices. Yhe commented line > is the problem. > HOW ??????? > import re > import MatrixInfo > > class Diff: > def __init__(self,filobj,matrix='pam250',begin=0,end='none'): > self.fil = filobj > self.begin = begin > self.end = end > if matrix in MatrixInfo.available_matrices: > ######self.matrix =MatrixInfo.matrix > self.matrix= MatrixInfo.pam250 > else print "matrix don't exist %s" %matrix Assuming available_matrices_dict is a dictionary with the matrices' name as keys: if matrix in MatrixInfo.available_matrices_dict: self.matrix = MatrixInfo.available_matrices_dict[matrix] else: print "matrix don't exist %s" %matrix or a bit more pythonic, since a Diff instance with an unknown matrix probably doesn't make much sense: # you have to handle the exception outside of # Diff.__init__() self.matrix = MatrixInfo.available_matrices_dict[matrix] > self.seqnr=0 > self.basenr=0 > self.dict = {} Now how will the available_matrices_dict dictionary come to be? At the end of MatrixInfo do available_matrices_dict = dict([(name, globals()[name]) for name in available_matrices]) Or you drop the available_matrices list (I suppose) altogether and use a dict literal instead available_matrices_dict = {"pam250": pam250, ...} Peter From kent3737 at yahoo.com Thu Dec 16 15:05:11 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Thu, 16 Dec 2004 15:05:11 -0500 Subject: ".>>>" is a good idea! (OT, was: Re: do you master list comprehensions?) In-Reply-To: <41C1D0CE.9080603@kdart.com> References: <1102971085.659444.22790@z14g2000cwz.googlegroups.com> <41C1D0CE.9080603@kdart.com> Message-ID: <41c1e8c0$1_1@newspeer2.tds.net> Keith Dart wrote: > What I do is set Python's sys.ps1 variable to something else. I have a > module called "interactive" that I import implicitly by shell alias: > > py='python -i -c '\''import interactive'\' > > Which, among other things, sets the prompt to "Python> " You can do the same thing using a PYTHONSTARTUP file - see http://docs.python.org/tut/node4.html#SECTION004240000000000000000 You can change the prompts with import sys sys.ps1 = ' >>> ' sys.ps2 = ' ... ' Kent From fredrik at pythonware.com Tue Dec 21 02:30:58 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 21 Dec 2004 08:30:58 +0100 Subject: newbie question References: <3e8ca5c804122020157b89fb9b@mail.gmail.com> Message-ID: Stephen Thorne wrote:' > Is this a Sig? What is this referring to? You've said it in reply to > more than one post in the last week. Got a url I can read about the > Fredrik Lundh Python Syntax Manglation Consulting Service? it's the new Boo marketing motto: "have you harrassed a Pythoneer today?" From apardon at forel.vub.ac.be Tue Dec 21 05:45:44 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 21 Dec 2004 10:45:44 GMT Subject: Why are tuples immutable? References: <20041217193502.1029.1533501037.divmod.quotient.12346@ohm> Message-ID: Op 2004-12-18, Nick Coghlan schreef : > Jp Calderone wrote: >> On Fri, 17 Dec 2004 11:21:25 -0800, Jeff Shannon wrote: >> >> The correct characterization is that Python makes user-defined >> mutable classes hashable (arguably correctly so) as the default >> behavior. > > However, that is only achieved by using identity based equality by default. If > you inherit from something which *doesn't* use identity based equality (say, > list or dict), then the hashability isn't there. So while you're quite correct, > it doesn't affect the OP's original complaint (not being allowed to use a list > as a dictionary key). > > The Python docs are pretty precise about what the rules are: > > "__hash__(self) > Called for the key object for dictionary operations, and by the built-in > function hash(). Should return a 32-bit integer usable as a hash value for > dictionary operations. The only required property is that objects which compare > equal have the same hash value; it is advised to somehow mix together (e.g., > using exclusive or) the hash values for the components of the object that also > play a part in comparison of objects. If a class does not define a __cmp__() > method it should not define a __hash__() operation either; if it defines > __cmp__() or __eq__() but not __hash__(), its instances will not be usable as > dictionary keys. If a class defines mutable objects and implements a __cmp__() > or __eq__() method, it should not implement __hash__(), since the dictionary > implementation requires that a key's hash value is immutable (if the object's > hash value changes, it will be in the wrong hash bucket)." > > (from: http://www.python.org/dev/doc/devel/ref/customization.html) > > > The key points are: > 1. Objects which compare equal must have the same hash value > 2. An object's hash value must never change during it's lifetime > > Lists could achieve the former, but not the latter. Tuples can achieve both, by > virtue of being immutable, with immutable contents. Ditto for sets & frozensets. Yes they can. If you don't mutate a list it will never change during it's lifetime. -- Antoon Pardon From adonisv at DELETETHISTEXTearthlink.net Fri Dec 17 01:07:15 2004 From: adonisv at DELETETHISTEXTearthlink.net (Adonis) Date: Fri, 17 Dec 2004 06:07:15 GMT Subject: Question about Py C API implementation. Message-ID: I wrote a small script to flatten a list of lists without the need of recursion, it works fine for the most part, but was wanting to reimplement it in C just for kicks, and would give me and excuse to learn the Python C API, but the C implementation does not function properly, I *think* it might be how I am trying to copy a sub list that is found to a list object for seperate processing (line 22, flatten.c), but also could be where I am trying to pop the topmost from the list (line 35, flatten.c), but it has me stooped, I lack in C skills so not many things may be apparent to me immediately, any help is greatly appreciated. Adonis http://home.earthlink.net/~adonisv/flatten.py http://home.earthlink.net/~adonisv/flatten.c From matthew.s at orcon.net.nz Thu Dec 30 15:05:10 2004 From: matthew.s at orcon.net.nz (matiu) Date: 30 Dec 2004 12:05:10 -0800 Subject: Event-Driven Woes: making wxPython and Twisted work together In-Reply-To: References: Message-ID: <1104437110.505150.112840@c13g2000cwb.googlegroups.com> Hi Daniel, I went down that road for a long time. I made a recipe to help people out: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286201 Don't be intimidated by the size, that's a whole demo app complete with gui. It works quite well. It uses two threads, wx runs in the main thread and twisted runs in the second thread. You'll probably just want to glean solutions from it and write your own framework. It does still have some hicups! I gave up trying to perfectionalise it and switched to pygtk, glade and libglade. pygtk runs fine on both linux and windows, and you get a gui designer. The only downside is that it has less widgets. It has the advantage of themes though, this means on windows you can make it look like windows, linux, mac or whatever. Also your app will load faster than a wx app. Unfortunately it does take up more disk space though. Anyway to make wx and twisted work together, put twisted in a secondary thread. I tried making them co-exist in a single thread as some other recipes suggest, but basically modal dialogs don't seem to work properly. This recipe might be an easier solution for you. Haven't tried it though: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/203471 God Bless From itsme at yahoo.com Tue Dec 7 18:00:53 2004 From: itsme at yahoo.com (It's me) Date: Tue, 07 Dec 2004 23:00:53 GMT Subject: sys.stdin.read question References: <41b62008$0$9746$a1866201@visi.com> <41b628c9$0$11072$a1866201@visi.com> Message-ID: Yes, if I run the script from the command prompt, it works. I was running it inside the Python IDE. Thanks, -- It's me "Grant Edwards" wrote in message news:41b628c9$0$11072$a1866201 at visi.com... > On 2004-12-07, It's me wrote: > > >> Dunno. Works fine for me under 2.3.4, and according to the > >> docs, should work under 2.4. > >> > >> What do you get when you do this: > >> > >> import sys > > > > Done that. > > > >> type(sys.stdin) > > > > I get: > > > > > > > >> dir(sys.stdin) > > > > I get: > > > > ['_RPCProxy__attributes', '_RPCProxy__getattributes', > > '_RPCProxy__getmethods', '_RPCProxy__methods', '__doc__', '__getattr__', > > '__init__', '__module__', 'encoding', 'oid', 'sockio'] > > > ???????? > > As somebody else already suggested, you must be running your > program inside some sort of IDE that replaces sys.stdin with > some other object that doesn't have a read() method. Try > running the program from a shell prompt. > > > -- > Grant Edwards grante Yow! Someone in DAYTON, > at Ohio is selling USED > visi.com CARPETS to a SERBO-CROATIAN From newsgroups at jhrothjr.com Tue Dec 21 10:06:12 2004 From: newsgroups at jhrothjr.com (John Roth) Date: Tue, 21 Dec 2004 09:06:12 -0600 Subject: Tabnanny really useful? References: <10se8avsvbqad9@news.supernews.com> Message-ID: <10sgevcc0nllkbd@news.supernews.com> "Steve Holden" wrote in message news:qIVxd.57751$Jk5.26179 at lakeread01... > Do you think tabnanny is a useful piece of code now? I used it a lot when > I first started using Python, and still run it over code from unknown > sources (no pun intended) from time to time. I think it's a lot less useful today than it was a few years ago, but it's still useful if you're stuck with an editor that doesn't give you a robust set of options, or if you've got to check a lot of modules in a library. I think most python-aware editors have included the needed functionality, or at least some reasonable approximation. I know what I would like to see in an editor: First, it autodetects whether the module uses tabs consistently, spaces consistently or a mixture. If it uses tabs consistently, it then uses the current default. If it uses spaces consistently, it should also autodetect the indentation setting in use in the module and offer to change it if it's different from the current default indentation setting. If it's inconsistent, it should make an attempt to deduce the model the creating software used; if it can it should change it to the default setting without complaining. Otherwise it should complain. John Roth > > regards > Steve > -- > Steve Holden http://www.holdenweb.com/ > Python Web Programming http://pydish.holdenweb.com/ > Holden Web LLC +1 703 861 4237 +1 800 494 3119 From jeff at ccvcorp.com Fri Dec 17 14:21:25 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 17 Dec 2004 11:21:25 -0800 Subject: Why are tuples immutable? In-Reply-To: References: <20041215152606.1029.1225319887.divmod.quotient.10976@ohm> <10s48r5hbse5o57@corp.supernews.com> Message-ID: <10s6c6fbhnfpk37@corp.supernews.com> Antoon Pardon wrote: >Op 2004-12-17, Jeff Shannon schreef : > > >>To take another approach -- given some function that allows lists to >>(pretend to be) hashable: >> >>.>>> key = [1,2] >>.>>> d[key] = 'foo' >>.>>> d[[1,2]] >>???? >>.>>> key.append(3) >>.>>> d[key] >>??? >>.>>> >> >>As I understand it, it is impossible for there to be a hash function for >>which both of these cases can return the same object. >> >> > >How about: > > hash = id > > If hash equals id, then the first of those cases fails. I'm creating a new list with the same value but different. If hash *doesn't* equal id, then the second case fails. It's an either-or proposition; you *cannot* have both with mutable objects. And the proper definition of a hash requires that you have both. Now, even if hash were made to equal id... suppose I then pass that dict to a function, and I want to get the value that I've stored under [1,2]. In order to do that, I'd *also* have to pass in the *exact* list that I used as the key, because *only* that *exact* instance will hash correctly. Not only that, but if I've got a handful of such values that I want to retrieve, I'll have to pass in *all* of the lists that I used to key the dict. Any time I want to use the dict elsewhere, I need to pass not only the dict itself, but a list of keys to the dict. And then I need to know the order of the keys in that list. Ugh. I suppose I could just use keys() to get a complete list of keys from the dict itself. But still, I'd have to iterate over keys() to try to find the proper list that matches the value that I need, and then use the key to reference the dict. That leaves me with code like this: def process_dict(d): for key in d.keys(): if key == [1,2]: value1 = d[key] if key == [1,3]: value2 = d[key] if key == [2,2]: # and so on.... Double ugh. >You also make the fault that because people ask for the possibility of >keys being mutable objects, that they want to mutate those object while >being a key. > > If mutable objects can be used as dict keys, then dicts *must* be able to sensibly handle the keys being mutated underneath of them, because it *will* happen. Your assumption that it's okay to make keys mutable, just tell programmers not to do it, is along the same lines as assuming that memory leaks in C aren't a problem because you've told programmers to free() all of the memory that they malloc()'d. >>In order to maintain the logical consistency that if an object is used >>as a dict key, that same object should reasonably be expected to >>retrieve the same value, identity-based hashes are necessary. As a >>result, the first option must be disallowed. >> >> > >Then why don't we disallow lists of mutable objects to be sorted or >to be made into a heap. In fact each time we have a structure that >relies on some invariant among its members we should disallow mutable >members because with mutable members the invariant can be violated >without ever rebinding one of the elements. > > If we have an object that, *by definition*, has some invariant that can be violated by having mutable members, then sure. But lists aren't sorted or heaped by definition. Note also that, if a list becomes unsorted or unheaped, it's fairly easy to resort or re-heapify the list. It may take some time, but nothing is lost. If a dictionary key mutates, then data *is* lost. >>In either case, if it's ever possible for equality to change while >>identity doesn't, then somewhere along the lines one of the core >>requirements, the contract if you will, of a dictionary *must* be >>broken. And while it may be possible to get away with breaking that >>contract some of the time (by postulating, for example, that if one >>mutates a dict key then things will break), this will result in more >>bugs and more confusion over time. There is no way for Python to be >>able to behave consistently in the face of mutable dict keys, therefore >>("In the face of ambiguity, refuse the temptation to guess.") Python >>declines the temptation of making it trivial to use mutable objects as >>dict keys. >> >> > >As it turns out, python makes no difference in difficulty for making >either mutable or immutable objects usable as dictionary keys. The >only difference is that python only made its standard immutable >types hashable and not its standard mutable objects. > > No -- the mathematical definition of 'hashable' fails for mutable types, and Python doesn't try to pretend that it can hash mutable types. Python also provides features so that user-defined immutable types can be hashed properly, and those features can be abused to pretend to hash user-defined mutable types, but that's not the same as saying that Python is happy with mutable dictionary keys. (One can abuse __add__() to do all sorts of things other addition, too, but it would still be a stretch to say that Python supports using + to do multiplication, it just doesn't provide it on standard numeric types.) Jeff Shannon Technician/Programmer Credit International From ebolonev at mail.ru Fri Dec 24 06:05:43 2004 From: ebolonev at mail.ru (Egor Bolonev) Date: Fri, 24 Dec 2004 21:05:43 +1000 Subject: [PIL] is there a downloadable docs for PIL References: <41cbdac7$0$15843$8fcfb975@news.wanadoo.fr> Message-ID: On Fri, 24 Dec 2004 10:00:39 +0100, Michel Claveau - abstraction meta-galactique non triviale en fuite perpetuelle. wrote: > Is that ? http://www.pythonware.com/products/pil/pil-handbook.pdf yes. thanks From fredrik at pythonware.com Mon Dec 13 12:38:26 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Dec 2004 18:38:26 +0100 Subject: make uninstall? References: Message-ID: Christopher J. Bottaro wrote: >I installed Python-2.3.4 from source... > configure && make && make install > > Now I want to remove it, but make uninstall doesn't work. How do I > uninstall it? $ python >>> import sys >>> sys.executable '/usr/somewhere/bin/python' >>> sys.prefix '/usr/somewhere' >>> sys.version[:3] '2.3' >>> ^D $ rm /usr/somewhere/bin/python $ rm -rf /usr/somewhere/lib/python2.3 $ rm -rf /usr/somewhere/include/python2.3 From segphault at sbcglobal.net Mon Dec 27 17:59:07 2004 From: segphault at sbcglobal.net (Ryan Paul) Date: Mon, 27 Dec 2004 22:59:07 GMT Subject: Optional Static Typing References: <1103795375.843649.286620@c13g2000cwb.googlegroups.com> Message-ID: On Thu, 23 Dec 2004 01:49:35 -0800, bearophileHUGS wrote: > Adding Optional Static Typing to Python looks like a quite complex > thing, but useful too: > http://www.artima.com/weblogs/viewpost.jsp?thread=85551 I wrote a blog post this morning in which I briefly argue using DbC and predicate based argument constraints instead of static typing. Take a look if you are interested. It also contains a link to a wiki page where I have been producing a more refined specification complete with good examples: http://www.cixar.com/segphault/pytype.html I would appreciate some feedback, I want to know what other python programmers think about DbC and arg constraints. -- SegPhault From jeff at ccvcorp.com Wed Dec 15 21:10:40 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 15 Dec 2004 18:10:40 -0800 Subject: Module question In-Reply-To: <86sm67hzt3.fsf@guru.mired.org> References: <1103143345.721887.80940@c13g2000cwb.googlegroups.com> <86sm67hzt3.fsf@guru.mired.org> Message-ID: <10s1rdn8dnkjj51@corp.supernews.com> Mike Meyer wrote: >Grumman writes: > > > >>Bill Turczyn wrote: >> >> >>>Does python have a module similiar to the perl Spreadsheet::WriteExcel >>> >>> >>In a pinch, you can output an HTML table, give the file an .xls >>extension, and Excel will read it just fine. >> >> > >Welll, someone pointed out a third party package to do the job. I want >to point out the csv module included in the standard >distribution. That should work as well as an HTML table, with less >clutter in the file. > > The difference being that when Excel opens up a *.CSV, it goes through the import wizard. When you write an HTML table and save the file as *.XLS, Excel will open it without the need for the import wizard (it appears to act just as if the file were a true native-format Excel file) . Of course, this may also mean that you'll need to take extra care to make sure that the cell formatting gets done correctly, since you won't have the option of setting the formatting explicitly during import. (I frequently deal with numbers that have significant leading zeros, and Excel just loves to strip those off unless you set formatting to 'text'...) Jeff Shannon Technician/Programmer Credit International From grante at visi.com Mon Dec 20 11:22:16 2004 From: grante at visi.com (Grant Edwards) Date: 20 Dec 2004 16:22:16 GMT Subject: extending python with a C-written dll References: <41c6e784$0$16084$a1866201@visi.com> <41c6f353$0$16095$a1866201@visi.com> Message-ID: <41c6fc38$0$16108$a1866201@visi.com> On 2004-12-20, Jean-Baptiste PERIN wrote: > OK .. ctypes looks great .. and I plan to use it for futur > purposes > > The fact is that the python interpreter I use is not a > standard one It is a python interpreter delivered within a > software named Blender. I don't know whether it is possible or > not to add ctypes to it ..(I don't even have a python shell to > perform the setup) > > I'm sure it is possible to use dll-built with it .. So please > .. can you tell me where I can find Py_BuildValue and > Py_InitModule4 to link with ? Sorry, I don't know anything about doing C lanugage extensions under Windows. -- Grant Edwards grante Yow! Boy, am I glad it's at only 1971... visi.com From just at xs4all.nl Sun Dec 26 10:25:40 2004 From: just at xs4all.nl (Just) Date: Sun, 26 Dec 2004 16:25:40 +0100 Subject: Improving Python (was: Lambda going out of fashion) References: Message-ID: In article , "Fredrik Lundh" wrote: > func(*arg) instead of apply() is a step back Strongly disagree. I find func(*args) much more readable than apply(func, args). > -- it hides the fact that functions are objects, What does this have to do with anything? > and it confuses the heck out of both C/C++ programmers and > Python programmers that understand the "def func(*arg)" form, because it > looks like something it isn't (there's a false symmetry between the call-form > and the def-form). What's false about the symmetry? Call: you supply a sequence of args Def: you receive a sequence of args Lovely. > and I still do enough 1.5.2-programming to use "x = x + y"; when I find > myself in a situation where my code would benefit a lot from being able to > write "x += y" instead, I go back and fix the design. > > string methods are nice, but nothing groundbreaking, and their niceness is > almost entirely offset by the horrid "".join(seq) construct that keeps > popping > up when people take the "the string module is deprecated" yada yada too > seriously. and what do the python-devers do? they add a "sum" built-in, > but no "join"? hello? That's what you get for unsubscribing ;-) Just From rkern at ucsd.edu Wed Dec 22 20:57:07 2004 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 22 Dec 2004 20:57:07 -0500 Subject: PHP vs. Python In-Reply-To: <7xzn0526ae.fsf@ruckus.brouhaha.com> References: <1103753016.780533.137480@f14g2000cwb.googlegroups.com> <7xzn0526ae.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > JZ writes: > >>But pure speed is not the all. Python can scale better, > > > If a system is fast enough on a single processor, it doesn't need to scale. I think he means, "scale to larger programs," not "scale to more processors." -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From mwm at mired.org Thu Dec 9 19:20:10 2004 From: mwm at mired.org (Mike Meyer) Date: Thu, 09 Dec 2004 18:20:10 -0600 Subject: Distutils vs. Extension header files Message-ID: I've got a package that includes an extension that has a number of header files in the directory with the extension. They are specified as "depends = [...]" in the Extension class. However, Distutils doesn't seem to do anything with them. If I do an sdist, the include files aren't added to the tarball. If I do a bdist_rpm, the source files get copied into the build directory and the build starts, but the header files aren't copied with the source file, so the build fails with a missing header file. I find it hard to believe that this is a bug in distutils, so I'd appreciate it if someone could tell me what I'm doing wrong. Thanks, http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at holdenweb.com Mon Dec 13 07:35:07 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 13 Dec 2004 07:35:07 -0500 Subject: PIL for Windows for Python 2.4 In-Reply-To: <1102926162.831462.9520@z14g2000cwz.googlegroups.com> References: <1102587036.703951.63690@z14g2000cwz.googlegroups.com> <1102604285.448599.33660@f14g2000cwb.googlegroups.com> <%Hrud.10528$Jk5.3022@lakeread01> <1102926162.831462.9520@z14g2000cwz.googlegroups.com> Message-ID: Fuzzyman wrote: > Steve Holden wrote: > >>Fuzzyman wrote: >> >> >>>If you're determined enough there are instructions here : >>>http://www.vrplumber.com/programming/mstoolkit/ >>> >>>These will get you the Visual Studio 7 tools (free releases of) and >>>tell you how to configure distutils to use it. >>> >>>Hefty downloads though, do not attempt this without broadband ! >>> >>>Regards, >>> >>>Fuzzy >>>http://www.voidspace.org.uk/atlantibots/pythonutils.html >>> >> >>Wow! I already installed the oolkit Compiler, and now it seems I need > > to > >>install 646MB of SDK. Make that "you have to be *really, really* >>determined". >> >>Think I might wait a bit longer. >> >>regards >> Steve >>-- >>http://www.holdenweb.com >>http://pydish.holdenweb.com >>Holden Web LLC +1 800 494 3119 > > > Hello Steve, > > I've just completed following the instructions at > http://www.vrplumber.com/programming/mstoolkit/ > > It's really not too bad. The download is 400meg - which unpacks to > about a 650meg isntall... but is you're hard drive that full ? > > Once done it works fine........ > No, it's not that my hard drive is full (I have 22 GB spare on the current 60BG drive, and can add another 60 GB if I need (though that would be another 1lb to have to lug around :-). It's the unreliability of the download process. I have now tried the installation four times, and each time it's stalled during the download of a component. Maybe it's just the times I've been trying, but it's driving me nuts. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From alexs at advfn.com Fri Dec 17 05:12:19 2004 From: alexs at advfn.com (Alex Stapleton) Date: Fri, 17 Dec 2004 10:12:19 +0000 Subject: Cool object trick In-Reply-To: References: <97B6410BE753D411894E00D0B77E6F7F0340BF53@neam2mx1.corp.emc.com> <%Oxwd.251809$HA.98890@attbi_s01> Message-ID: <41C2B103.9040304@advfn.com> Steven Bethard wrote: > Alex Stapleton wrote: > >> you are setting the variable name in your code (b.varA), not >> generating the variable name in a string (var = "varA") (dictionary >> key) at run-time and fetching it from the __dict__ like i was >> attempting to describe. > > > Ahh. Well if you just want to get an attribute, I don't see why you > wouldn't do it the normal way: > > >>> b = Bunch(varA="Hello!") > >>> getattr(b, "varA") > 'Hello!' > > That's what getattr's for. ;) No need to go poking around in __dict__. > > Steve Hmm true, (i had forgotten about getattr :/) in that case im indifferent to Bunch() not that i really see why it's useful except for making code look a bit nicer occasionaly. From mwm at mired.org Thu Dec 16 19:59:53 2004 From: mwm at mired.org (Mike Meyer) Date: Thu, 16 Dec 2004 18:59:53 -0600 Subject: Python IDE References: <1103141895.620517.49860@z14g2000cwz.googlegroups.com> <1103218159.737726.241440@z14g2000cwz.googlegroups.com> Message-ID: <86ekhp3fjq.fsf@guru.mired.org> A: What's the most obnoxious thing on Usenet? Q: topposting. "Dan Perl" writes: > "fuzzylollipop" wrote in message > news:1103218159.737726.241440 at z14g2000cwz.googlegroups.com... >> no it was a sideways remark at all the software socialists that thing >> EVERYTHING should be free, never said anything about Eclipse, just the >> people that insist ALL software should be free. > Interesting. I've never met anyone like that. If they are in high tech, > they must be hardware people, otherwise how would they make a living? And > I'm not sure "socialists" is the correct term in this case, it sounds to me > more like "communists". Or "liberals" for our friends in the US. I have. They make a living supporting free software. Take a look at www.zope.com and www.zope.org for an example (to be clear, I am *not* claiming that the folks at zope believe that all software should be free. Merely that they make a living off software they give away for free.) There have been other examples of such before. There was a group that made a living porting GCC to vender-specific hardware platforms, one condition being that the port wound up in the GCC suite. I believe they got bought by redhat. Phillip Greenspun once ran a company on this model as well. It did well until the venture capatalists took it over. You can read his views on software pricing at . http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From thaddon at equilar.com Wed Dec 15 12:37:10 2004 From: thaddon at equilar.com (Tom Haddon) Date: Wed, 15 Dec 2004 09:37:10 -0800 Subject: Dynamically passing variables to unittest Message-ID: <0E52D69E86D25840AAE3611CB657F9F82016D6@millenium.equilar.com> Hi Peter, Yeah, you're right, the term "ConnectString" is a little confusing. Perhaps I should change that. Here's a valid call to DB: conn=DB.DB('pg','test','localhost',5432,'test','test') In the context of this unittest, a valid syntax would be (except that this unittest would fail, as this is a "good" connection: self.assertRaises(DB.InvalidConnectString, DB.DB,'pg','test','localhost',5432,'test','test') Thanks, Tom -----Original Message----- From: Peter Hansen [mailto:peter at engcorp.com] Sent: Wednesday, December 15, 2004 7:37 AM To: python-list at python.org Subject: Re: Dynamically passing variables to unittest Tom Haddon wrote: > So, my question is, how do I dynamically > pass the variables from a list, for example to the unittest module so I > can maintain the list of test cases more easily: > > ------------------------- > import DB > import unittest > > class ConnectString(unittest.TestCase): > InvalidStrings=(['pg','test','localhost','5432','test','test'] > ,['pg','test','local',5432,'test','test']) > > def testInvalidStrings(self): > for i in InvalidStrings: > self.assertRaises(DB.InvalidConnectString, DB.DB,",".join(i)) > ------------------------ > > My problem is, this passes one string containing > "'pg','test','localhost','5432','test','test'" rather than each > one of those as variables. "As variables"? What does that mean? Can you give an example of precisely what a valid DB.DB call would look like in the real code, rather than showing an example of something that *doesn't* do what you want it to? I thought connect strings looked like "host=localhost;port=5432" and so on... equal signs and semicolons or something. -Peter From grante at visi.com Thu Dec 9 13:19:36 2004 From: grante at visi.com (Grant Edwards) Date: 09 Dec 2004 18:19:36 GMT Subject: Calling a C program from a Python Script References: Message-ID: <41b89738$0$11034$a1866201@visi.com> On 2004-12-09, Brad Tilley wrote: > Is it possible to write a file open, then read program in C and then > call the C program from a Python script like this: Huh? What do you mean "write a file open"? You want to read a C source file and execute the C source? If you have access to a C interpreter, I guess you could invoke the interpreter from python using popen, and feed the C source to it. Alternatively you could invoke a compiler and linker from C to generate an executable and then execute the resulting file. > for root, files, dirs in os.walk(path) > for f in files: > try: > EXECUTE_C_PROGRAM You're going to have to explain clearly what you mean by "EXECUTE_C_PROGRAM". If you want to, you can certainly run a binary executable that was generated from C source, (e.g. an ELF file under Linux or whatever a .exe file is under Windows). > If possible, how much faster would this be over a pure Python > solution? Solution to what? -- Grant Edwards grante Yow! And furthermore, at my bowling average is visi.com unimpeachable!!! From schapira at psualum.com Thu Dec 23 14:18:29 2004 From: schapira at psualum.com (Emilio) Date: 23 Dec 2004 11:18:29 -0800 Subject: Windows XP - cron or scheduler for Python? In-Reply-To: References: Message-ID: <1103829509.215965.133120@f14g2000cwb.googlegroups.com> I have gone through the pain of trying to use those commands and use other available cron clients for Windows to find they are expensive, or have bugs and are not stable. So I wrote a very simple yet powerful script that handles all the basic functionality of Cron. It has been stable and used in production for about a year. The source code is in Python and you can read it, it is a simple page. I have also created a version for Windows with an installer that doesn't even require Python installed in the target machine. You can find the project here: http://sourceforge.net/projects/pycron Emilio. From skip at pobox.com Tue Dec 14 10:08:49 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 14 Dec 2004 09:08:49 -0600 Subject: [dictionary] how to get key by item In-Reply-To: References: Message-ID: <16831.513.963712.895483@montanaro.dyndns.org> Ola> If some keys has the same value as the item this will cause Ola> problems because keys in your result dictionary can be Ola> overwritten. That's why I said, "assuming your dictionary defines a one-to-one mapping...". Skip From bulba at bulba.com Fri Dec 31 08:08:25 2004 From: bulba at bulba.com (Bulba!) Date: Fri, 31 Dec 2004 14:08:25 +0100 Subject: Speed ain't bad References: <0189t05r3226bkp5e1vtmp0gd6odcsf2qp@4ax.com> <33kuf0F42nu02U1@individual.net> Message-ID: On Fri, 31 Dec 2004 13:19:44 +0100, Reinhold Birkenfeld wrote: >> True; however, it's my understanding that compressing individual files >> also means that in the case of damage to the archive it is possible to >> recover the files after the damaged file. This cannot be guaranteed when >> the archive is compressed as a single stream. > >With gzip, you can forget the entire rest of the stream; with bzip2, >there is a good chance that nothing more than one block (100-900k) is lost. A "good chance" sometimes is unacceptable -- I have to have a guarantee that as long as the hardware isn't broken a user can recover that old file. We've even thought about storing uncompressed directory trees, but holding them would consume too much diskspace. Hence compression had to be used. (initially, that was just a shell script, but whitespaces and strange chars that users love to enter into filenames break just too many shell tools) -- It's a man's life in a Python Programming Association. From steve at holdenweb.com Tue Dec 28 07:49:26 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 28 Dec 2004 07:49:26 -0500 Subject: More elegant way to cwd? In-Reply-To: <33chp7F3u6lt5U1@individual.net> References: <1103916780.062642.226270@f14g2000cwb.googlegroups.com> <33chp7F3u6lt5U1@individual.net> Message-ID: Kamilche wrote: >> Other than using os.pardir instead of '..', and possibly adding >> an "os.path.abspath()" call to the last bit (or does realpath >> already do that? It's unclear from the docs), I can't see >> anything fundamental I'd do differently... except package these >> functions up as nice clean subroutines, possibly in a library >> package, that I could then use in code that would magically >> become "elegant" (IMHO) by avoiding the repetition of all >> that non-elegant stuff above... >> >> -Peter > > > Well... but to call it from the shared directory, I'd have to first > switch to the shared directory! Which would defeat the purpose. > > I wish there was a way to store this in a single file and call it from > any script, but I'm unwilling to keep all my scripts in one folder to > accomodate it. If only Python would let you import modules from > different directories. :-/ > > --Kamilche Maybe I'm misunderstanding your requirements, but it seems to me perfectly practical to keep that script in a standard place (say, lib/site-packages, which was intended for exactly that purpose) and import it from there. There's no reason why its location has to relate to the location of the scripts that import it and use that function from it. What am I missing? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From klapotec at chello.at Fri Dec 31 06:30:15 2004 From: klapotec at chello.at (Christopher Koppler) Date: Fri, 31 Dec 2004 11:30:15 GMT Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: On Fri, 31 Dec 2004 02:13:27 +0100, Bulba! wrote: > On 30 Dec 2004 08:58:36 -0800, "Sridhar R" > wrote: > [snip] > >>What makes such companies to choose Java over dynamic, productive >>languages like Python? Are there any viable, technical reasons for >>that? > > It's the $$$ of the big organization behind it and all the > inertia^H^H^H^H^H^H stability of it. > > Note all the fuss that was made when IBM has "spent $1 > billion on Linux", for instance (or so it was said). Managers > paid attention to that (at least that was my impression). > > AFAIK, Linux didn't really change in technical sense > just because IBM has embraced Linux, or at least not much. > But to companies and manager the major point is: > > Big Blue has embraced it. [add a few grains of salt to the following...] Manager culture is still very much mired in rituals that may in one form or another go back to hunter-gatherer days (or maybe even further); that 'the industry choice' is more often than not something backed by a *major* company is part of a ritual complex based on relations to the alpha male. Small companies ingratiate themselves with their perceived betters by using their products, even when technically far superior products would be available. When the 'market leader' produces a new toy, everyone who wants to be in his favor must use it _and_ also damn the toys available from any of those competing for leadership, viz. the ongoing state of cold war between Sun and MS and their respective worshipers. Toys that have not been sanctioned by the leader, or that are, even worse, de facto unknown to him, are met with ignorance, scorn, or even repression. [snip] > For Python a Big Thing would happen if some Major Vendor > embraced it as its Official Language(tm). Python language > itself could turn into a smoking crock the very next day, but > everybody who doesn't live under the rock would still be > writing in it. The moral is, of course, that either the Python community's alpha geeks need to get access to controlling interest in a *major* company (or to become successful enough with their own companies to register on the current *major* companies radar as potential competition) or as you say, Python needs to be embraced like Linux was. That's the way to win the hearts of software companies' managers. -- Christopher From sdfATexpertuneDOTcom Thu Dec 9 09:07:40 2004 From: sdfATexpertuneDOTcom (Scott F) Date: Thu, 09 Dec 2004 14:07:40 -0000 Subject: PIL for Windows for Python 2.4 References: <1102587036.703951.63690@z14g2000cwz.googlegroups.com> Message-ID: "Fuzzyman" wrote in news:1102587036.703951.63690 at z14g2000cwz.googlegroups.com: > So you've built PIL for windows, Python 2.4 ? > > Any chance of sharing it ? What compiler have you configured > distutils to use ? I'm very sorry I spoke too soon. After making the initial change, the setup.py took off on a run. But it soon quit, informing me that I needed the Visual Studio 7 tools. So, I have no PIL either. From tjreedy at udel.edu Thu Dec 30 15:01:51 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 30 Dec 2004 15:01:51 -0500 Subject: More baby squeaking - iterators in a class References: Message-ID: "Bulba!" wrote in message news:njf8t09i9injk8cr7r1858ng4gkq6fu5o6 at 4ax.com... > "Define a __iter__() method which returns an object with a next() > method. If the class defines next(), then __iter__() can just return > self:" > > The thing is, I tried to define __iter__() directly without explicit > defining next (after all, the conclusion from this passage should > be that it's possible). It is, see below. > class R: > def __init__(self, d): > self.d=d > self.i=len(d) > def __iter__(self): > if self.i == 0: > raise StopIteration > self.i -= 1 > return self.d[self.i] Change 'return' to 'yield'. Then r.__iter__() *will* return a (generator)iterator with a .next method, as required. But it will only yield one value before running off the end. Since __iter__ is meant to be called only once, you need to loop explicitly in the generator. For instance def __iter__(self): i,d = self.i, self.d while i i =- 1 yield d[i] Copying i makes the generator non-destuctive. (PS, use spaces, not tabs, in posted code.) Terry J. Reedy From stuart at bmsi.com Sat Dec 11 00:01:08 2004 From: stuart at bmsi.com (Stuart D. Gathman) Date: Sat, 11 Dec 2004 00:01:08 -0500 Subject: Help beautify ugly heuristic code References: Message-ID: On Fri, 10 Dec 2004 22:03:20 +0000, JanC wrote: > Stuart D. Gathman schreef: > >> I have a function that recognizes PTR records for dynamic IPs. There > Did you also think about ISPs that use such a PTR record for both dynamic > and fixed IPs? There seems to be a lot of misunderstanding about this. I am not blocking anyones mail because they have a dynamic looking PTR. I simply don't accept such a PTR as MTA authentication. You see, MTAs *SHOULD* provide a fully qualified domain as their HELO name which resolves to the IP of the MTA. Sadly, however, many internet facing MTAs don't do this, but I accept a meaningful PTR as a substitute. I also waive the requirement for MTA authentication if the MAIL FROM has an SPF record (http://spf.pobox.com). So, if your MTA complies with RFC HELO recommendations, you'll have no trouble sending me mail. You can even use a dynamic IP with a dynamic DNS service. I 'do* block PTR names of "." or "localhost". I would like to block all single word HELO names - but there are too many clueless mail admins out there. People seem to be unsure of what to send for HELO. -- Stuart D. Gathman Business Management Systems Inc. Phone: 703 591-0911 Fax: 703 591-6154 "Confutatis maledictis, flamis acribus addictis" - background song for a Microsoft sponsored "Where do you want to go from here?" commercial. From ncoghlan at iinet.net.au Thu Dec 23 08:32:50 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 23 Dec 2004 23:32:50 +1000 Subject: Lambda going out of fashion In-Reply-To: <1gp91wn.1v9e6hb1qiryc2N%aleaxit@yahoo.com> References: <1gp91wn.1v9e6hb1qiryc2N%aleaxit@yahoo.com> Message-ID: <41CAC902.2040906@iinet.net.au> Alex Martelli wrote: > Nick Coghlan wrote: > ... > >>Perhaps something like: >> >>accepts_func( (def (a, b, c) to f(a) + o(b) - o(c)) ) > > > Nice, except I think 'as' would be better than 'to'. 'as' should be a > full keyword in 3.0 anyway (rather than a surprisingly-NOT-keyword like > today), and "define something as somethingelse" seems marginally more > readable to me than "define something to somethingelse" anyway. I actually flipped back and forth between preferring 'as' and 'to' while writing the message. It was the mathematical phrasing of "f is a function from R to R" (replacing the capital R's with the symbol for the real numbers) that first made me think of 'to', since I was trying to emphasise the parallels with mathematical functions. (To my mind, theoretical mathematics is one of the areas with significant legitimate uses for lambda functions). The '->' suggestion had a similar source. The way I'd read the 'to' version out loud when explaining to someone what the code did: "DEFine an anonymous function from arguments a, b and c TO the value f of a plus o of b minus o of c" or the short version: "DEFine a function from a, b and c TO f a plus o b minus o c" As an even simpler example, (def (x) to x * x) would be "define a function from x to x squared". (def () to ) would be "define a function from no arguments to " 'as' already implies renaming semantics due to from-style imports. In Py3k, it's likely to pick up the naming duties in except clauses as well (i.e. "except ValueError, TypeError as ex:"). 'as' is also a candidate for optional static typing and adaptation (and hopefully someone will talk Guido out of his punctuation happy version of that!). I eventually decided that using 'as' for anonymous functions as well would just be plain confusing. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From tzot at sil-tec.gr Fri Dec 17 11:08:30 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 17 Dec 2004 18:08:30 +0200 Subject: Efficient grep using Python? References: <38Zvd.32503$g4.608727@news2.nokia.com> Message-ID: On Fri, 17 Dec 2004 14:22:34 +0000, rumours say that P at draigBrady.com might have written: sf: >sf wrote: >> The point is that when you have 100,000s of records, this grep becomes >> really slow? > >There are performance bugs with current versions of grep >and multibyte characters that are only getting addressed now. >To work around these do `export LANG=C` first. You also should use the -F flag that P?draig suggests, since you don't have regular expressions in the B file. >In my experience grep is not scalable since it's O(n^2). >See below (note A and B are randomized versions of >/usr/share/dict/words (and therefore worst case for the >sort method)). > >$ wc -l A B > 45427 A > 45427 B > >$ export LANG=C > >$ time grep -Fvf B A >real 0m0.437s > >$ time sort A B B | uniq -u >real 0m0.262s > >$ rpm -q grep coreutils >grep-2.5.1-16.1 >coreutils-4.5.3-19 sf, you better do your own benchmarks (there is quick, sample code in other posts of mine and P?draig's) on your machine, since on my test machine the numbers are reversed re to these of P?draig's (grep takes half the time). package versions (on SuSE 9.1 64-bit): $ rpm -q grep coreutils grep-2.5.1-427 coreutils-5.2.1-21 language: $ echo $LANG en_US.UTF-8 Caution: both solutions are interexchangeable as long as you don't have duplicate lines in the A file. If you do, use the grep version. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From richie at entrian.com Thu Dec 23 09:48:16 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 23 Dec 2004 14:48:16 +0000 Subject: subclassing list In-Reply-To: References: Message-ID: [Uwe] > How [do] you clear the contents of a list subclass > without creating a new object? Use the paranoia emoticon: "del x[:]". For example: >>> class L(list): ... pass ... >>> x = L() >>> x.append("Spam") >>> del x[:] >>> x [] >>> type(x) >>> with-thanks-to-Gordon-McMillan-ly y'rs, -- Richie Hindle richie at entrian.com From cmedcoff at hotmail.com Sat Dec 18 14:47:59 2004 From: cmedcoff at hotmail.com (Chuck) Date: Sat, 18 Dec 2004 14:47:59 -0500 Subject: ActiveState Python 2.4 Woes Message-ID: I am having a lot of problems with this distribution. Is anyone else? Among many, many problems in the debugger I also see the error below when I start PythonWin using the context menu when selecting a python file in the windows shell explorer. Anyone having this problem? I done a complete uninstall/re-install but to no avail. Portions Copyright 1994-2004 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\mfc\docview.py", line 91, in CreateNewFrame wnd.LoadFrame(self.GetResourceID(), -1, None, context) # triggers OnCreateClient... win32ui: LoadFrame failed win32ui: CreateNewFrame() virtual handler (>) raised an exception TypeError: PyCTemplate::CreateNewFrame must return a PyCFrameWnd object. From fredrik at pythonware.com Mon Dec 20 07:15:04 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Dec 2004 13:15:04 +0100 Subject: Is this a good use for lambda References: <41c654b9.529432724@news.oz.net><41c69127$0$306$edfadb0f@dread12.news.tele.dk> <41c6ab41$0$225$edfadb0f@dread12.news.tele.dk> Message-ID: > I just found it amusing that somenone like Frederik Lundh, who has > written xml stuff like ElementTree, uses something that reminds of an old HTML tag as a sig. it's a perfectly valid XML end tag. locating the start tag is left as an exercise... From ronaldoussoren at mac.com Thu Dec 30 03:44:21 2004 From: ronaldoussoren at mac.com (Ronald Oussoren) Date: Thu, 30 Dec 2004 09:44:21 +0100 Subject: ANN: pyobjc-1.2 Message-ID: <002DD9F3-5A3F-11D9-85EE-000D93AD379E@mac.com> PyObjC 1.2 is now available for download at http://pyobjc.sourceforge.net/ PyObjC is a bridge between Python and Objective-C. It allows full featured Cocoa applications to be written in pure Python. It is also easy to use other frameworks containing Objective-C class libraries from Python and to mix in Objective-C, C and C++ source. Python is a highly dynamic programming language with a shallow learning curve. It combines remarkable power with very clear syntax. The installer package includes a number of Xcode templates for easily creating new Cocoa-Python projects. PyObjC also supports full introspection of Objective-C classes and direct invocation of Objective-C APIs from the interactive interpreter. PyObjC requires Mac OS X 10.2 or later and Python 2.3 or later. PyObjC works both with the Apple provided Python installation in Mac OS X 10.3 (and later) and with MacPython 2.3. This release features several bugfixes, improved documentation as well as support for categories, easier customization and basic support for creating Interface Builder palettes. See the news file at http://pyobjc.sourceforge.net/NEWS-1.2.txt for more information. PyObjC is released with an open source license (MIT style). From kepes.krisztian at peto.hu Thu Dec 16 04:06:42 2004 From: kepes.krisztian at peto.hu (kepes.krisztian) Date: Thu, 16 Dec 2004 10:06:42 +0100 Subject: python re - a not needed Message-ID: <41C15022.1010808@peto.hu> Hi ! I want to get infos from a html, but I need all chars except <. All chars is: over chr(31), and over (128) - hungarian accents. The .* is very hungry, it is eat < chars too. If I can use not, I simply define an regexp. [not<]* It is get all in the href. I wrote this programme, but it is too complex - I think: import re l=[] for i in range(33,65): if i<>ord('<') and i<>ord('>'): l.append('\\'+chr(i)) s='|'.join(l) all='\w|\s|\%s-\%s|%s'%(chr(128),chr(255),s) sre='([%s]{1,1024})'%all #sre='([?!\\<]{1,1024})' s='xmvccv ??? sdfkdsfj eirfie' print sre print s cp=re.compile(sre) m=cp.search(s) print m.groups() Have the python an regexp exception, or not function ? How to I use it ? Thanx for help: kk From kdart at kdart.com Sun Dec 12 19:23:18 2004 From: kdart at kdart.com (Keith Dart) Date: Mon, 13 Dec 2004 00:23:18 GMT Subject: Persistent objects In-Reply-To: <7xis77q1t7.fsf_-_@ruckus.brouhaha.com> References: <7xis77q1t7.fsf_-_@ruckus.brouhaha.com> Message-ID: <41BCE0F6.3030207@kdart.com> Paul Rubin wrote: > I've had this recurring half-baked desire for long enough that I > thought I'd post about it, even though I don't have any concrete > proposals and the whole idea is fraught with hazards. > > Basically I wish there was a way to have persistent in-memory objects > in a Python app, maybe a multi-process one. So you could have a > persistent dictionary d, and if you say > d[x] = Frob(foo=9, bar=23) > that creates a Frob instance and stores it in d[x]. Then if you > exit the app and restart it later, there'd be a way to bring d back > into the process and have that Frob instance be there. Check out the Durus project. http://www.mems-exchange.org/software/durus/ -- \/ \/ (O O) -- --------------------oOOo~(_)~oOOo---------------------------------------- Keith Dart vcard: public key: ID: F3D288E4 URL: ============================================================================ From robin at SPAMREMOVEjessikat.fsnet.co.uk Thu Dec 2 03:53:16 2004 From: robin at SPAMREMOVEjessikat.fsnet.co.uk (Robin Becker) Date: Thu, 02 Dec 2004 08:53:16 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 2) In-Reply-To: References: Message-ID: <41AED7FC.50606@jessikat.fsnet.co.uk> Cameron Laird wrote: > QOTW: "... why does Microsoft try so hard to protect its sources?" ..... > > 2.4 is final, buildable under Windows in at least a couple > of ways, improved, ... > http://www.brunningonline.net/simon/blog/archives/001657.html > > asyncore, Twisted, the Python core...--do you understand how > they relate to TLS, serial-port usage, GUI-oriented event > processing, and so on? > http://groups.google.com/groups?th=752ebdb8b57fa3f3 > > Ian Bicking and others describe the meaning of "Python 3000". > http://groups.google.com/groups?frame=left&th=8f9b6a3959888f2b > > Reading without blocking is possible--with care. > http://groups.google.com/groups?frame=left&th=78654cfc06d2fbbe > > Josiah Carlson and Paul McGuire explain decorators. > http://groups.google.com/groups?th=5bfb80b43887bc1f > > Nick Coghlan knows sick ways to spell "file". > http://groups.google.com/groups?frame=right&th=e562a771d1c827c9 > > Python works in Frontier. > http://radio.weblogs.com/0100039/2004/11/30.html#a626 > > ....... For some reason I can't seem to make use of the google links. When I use the above eg http://groups.google.com/groups?frame=right&th=e562a771d1c827c9 I get a not found google page with url http://groups-beta.google.com/groups?frame=right&th=e562a771d1c827c9 really wanted to spell file in a sickly manner :) > > Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and > sponsor the "Python-URL!" project. > > -- Robin Becker From steven.bethard at gmail.com Mon Dec 13 03:58:15 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 13 Dec 2004 08:58:15 GMT Subject: character encoding conversion In-Reply-To: References: <41bc7719$0$2069$9b622d9e@news.freenet.de> Message-ID: Christian Ergh wrote: > flag = true > for char in data: > if 127 < ord(char) < 128: > flag = false > if flag: > try: > data = data.encode('latin-1') > except: > pass A little OT, but (assuming I got your indentation right[1]) this kind of loop is exactly what the else clause of a for-loop is for: for char in data: if 127 < ord(char) < 128: break else: try: data = data.encode('latin-1') except: pass Only saves you one line of code, but you don't have to keep track of a 'flag' variable. Generally, I find that when I want to set a 'flag' variable, I can usually do it with a for/else instead. Steve [1] Messed up indentation happens in a lot of clients if you have tabs in your code. If you can replace tabs with spaces before posting, this usually solves the problem. From steven.bethard at gmail.com Tue Dec 7 17:50:59 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 07 Dec 2004 22:50:59 GMT Subject: How do I do this? (eval() on the left hand side) In-Reply-To: References: Message-ID: It's me wrote: > For simplicity sake, let's say I need to do something like this (for > whatever reason): > > retrieve> > > If I had a situation like this, I'd probably store my 'variables' as keys in a dict, e.g.: >>> bindings = {} >>> for i in range(3): ... name = raw_input('Name: ') ... value = int(raw_input('Value for %r: ' % name)) ... bindings[name] = value ... <... after inputting 'eggs', '7', 'badger', '42', 'spam', '13' ...> >>> bindings {'eggs': 7, 'badger': 42, 'spam': 13} Once you have the 'variables' in a dict, you can just use the dict values in any expressions you need. >>> bindings['eggs'] * bindings['badger'] 294 > I am just trying to understand the language and see what it can do. Well, it can do a lot, but the folks on this list are helpful enough to mention when things you *can* do aren't necessarily things you *want* to do. ;) Enjoy your explorations! Steve From alanmk at hotmail.com Sun Dec 12 08:20:25 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Sun, 12 Dec 2004 13:20:25 +0000 Subject: Persistent objects In-Reply-To: <7xis77q1t7.fsf_-_@ruckus.brouhaha.com> References: <7xis77q1t7.fsf_-_@ruckus.brouhaha.com> Message-ID: Hi Paul, [Paul Rubin] > Basically I wish there was a way to have persistent in-memory objects > in a Python app, maybe a multi-process one. So you could have a > persistent dictionary d, and if you say > d[x] = Frob(foo=9, bar=23) > that creates a Frob instance and stores it in d[x]. Then if you > exit the app and restart it later, there'd be a way to bring d back > into the process and have that Frob instance be there. Have you looked at Ian Bicking's SQLObject? http://sqlobject.org/ To define a class class MyPersistentObj(SQLObject): foo = IntCol() bar = IntCol() To instantiate a new object my_new_object = MyPersistentObj(foo=9, bar=23) Once the new object has been created, it has already been persisted into a RDBMS table automatically. To reload it from the table/database, e.g. after a system restart, simply supply its id. my_existing_object = MyPersistentObj.get(id=42) Select a subset of your persistent objects using SQL-style queries my_foo_9_objects = MyPersistentObj.select(MyPersistentObj.q.foo == 9) for o in my_foo_nine_objects: process(o) SQLObject also takes care of caching, in that objects are optionally cached, associated with a specific connection to the database. (this means that it is possible to have different versions of the same object cached with different connections, but that's easy to solve with good application architecture). So in your case, if your (web?) app is persistent/long-running, then you can simply have SQLObject cache all your objects, assuming you've got enough memory. (Hmm, I wonder if SQLObject could be made to work with weak-references?). Lastly, caching can be disabled. I've found performance of SQLObject to be pretty good, but since you haven't specified particular requirements for performance, it's not possible to say if it meets your criteria. Although I feel comfortable in saying that SQLObject combined with an SQLite in-memory database should give pretty good performance, if you've got the memory to spare for the large databases you describe. Other nice features include 1. RDBMS independent: currently supported are PostGres, FireBird, MySQL, SQLite, Oracle, Sybase, DBM. SQLServer support is in the pipepline. SQLObject code should be completely portable between such backend stores. 2. Full support for ACID transactional updates to data. 3. A nice facility for building SQL queries using python syntax. 4. Automated creation of tables and databases. Table structure modification supported on most databases. 5. Full support for one-to-one, one-to-many and many-to-many relationships between objects. All in all, a great little package. I recommend that you take a close look. Regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From chahnaz.ourzikene at wanadoo.fr Thu Dec 30 17:33:00 2004 From: chahnaz.ourzikene at wanadoo.fr (chahnaz.ourzikene) Date: Thu, 30 Dec 2004 23:33:00 +0100 Subject: need some help with threading module... References: <41cf2610$0$791$8fcfb975@news.wanadoo.fr> <41cf373e$0$786$8fcfb975@news.wanadoo.fr> <1104102769.321923.4140@z14g2000cwz.googlegroups.com> <41d0515b$0$30648$8fcfb975@news.wanadoo.fr> <1104178961.065566.7660@z14g2000cwz.googlegroups.com> <41d3dc20$0$29646$8fcfb975@news.wanadoo.fr> <1104431262.457172.295520@c13g2000cwb.googlegroups.com> Message-ID: <41d48219$0$17813$8fcfb975@news.wanadoo.fr> "M.E.Farmer" a ?crit dans le message de news: 1104431262.457172.295520 at c13g2000cwb.googlegroups.com... > What did you expect? This is what it did on win 2000/python 2.2.3 > ######> controller waiting... 0 loops > ######> controller waiting... 1 loops > Subject : the counter is now 0 > ######> controller waiting... 2 loops > Subject : the counter is now 1 >.... >.... >.... Yeah, looking to the trace i can easily say you have executed it from IDLE, because IDLE is so slow that threads can have IRQs. Try to execute it directly from a shell under windows, and you will see that the Subject thread has much more CPU time thant the Controller thread. Because Subject does his job in a loop, and have no sleep call inside its code. Controller sleeps a while to let Subject run a little on the CPU. Now try to run it under Linux directly from the shell and you'll have much more time for Subject and very less for Controler. If you run it from IDLE it can be a little more parallel. Now there's a strange behaviour on my machine when i run my script within IDLE under Windows : IDLE idles and never stops runnig !! i ran the same script from a shell and it's all perfect... Very strange.. Yacine Chaouche -- France > It seems to be what you were trying to do. > > M.E.Farmer > From nick at craig-wood.com Thu Dec 23 01:48:52 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 23 Dec 2004 06:48:52 GMT Subject: regular expression: perl ==> python References: <1103692329.420064.257540@f14g2000cwb.googlegroups.com> Message-ID: Fredrik Lundh wrote: > that's not a very efficient way to match multiple patterns, though. a > much better way is to combine the patterns into a single one, and use > the "lastindex" attribute to figure out which one that matched. lastindex is useful, yes. > see > > http://effbot.org/zone/xml-scanner.htm > > for more on this topic. I take your point. However I don't find the below very readable - making 5 small regexps into 1 big one, plus a game of count the brackets doesn't strike me as a huge win... xml = re.compile(r""" <([/?!]?\w+) # 1. tags |&(\#?\w+); # 2. entities |([^<>&'\"=\s]+) # 3. text strings (no special characters) |(\s+) # 4. whitespace |(.) # 5. special characters """, re.VERBOSE) Its probably faster though, so I give in gracelessly ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From rynt at yahoo9.com Tue Dec 21 09:04:44 2004 From: rynt at yahoo9.com (Ruben Baumann) Date: Tue, 21 Dec 2004 06:04:44 -0800 Subject: BASIC vs Python References: <41C342A0.3040700@users.ch> <86sm64tzax.fsf@guru.mired.org> Message-ID: <4pKdnYV7s4vgsFXcRVn-3g@megapath.net> "Doug Holton" wrote in message news:zIidndX_g7PCNFrcRVn-tw at comcast.com... > Mike Meyer wrote: >> Logo (my pick) has been called "Lisp without the parenthesis". It has >> the advantage of using standard algebraic notation for formulas, >> instead of operator post or pre. >> >> > This is comp.lang.python, not comp.lang.logo. Please refrain from > discussing topics not related to CPython. Holton, you've turned into a boring ass. So you got your feelings hurt. Get over it! Call 1-800-'Boo'-hoo! RB From flamesrock at gmail.com Sun Dec 26 00:50:47 2004 From: flamesrock at gmail.com (Aaron) Date: Sun, 26 Dec 2004 05:50:47 GMT Subject: Configuration Files Message-ID: Hi, I'm interested in creating a large number of configuration files which I have no experience doing in python. The fields will be static for the most part. But design changes and I might want to add new fields in the future.. My question is - whats the best module for creating, reading, and editing these files(something like an INI)? I want it to be powerful, yet simple and minimalistic, not requiring a huge amount of overhead. I've heard of xml, and have seen it used in both html fashion, and likewise, without any tags at all- just spaces in between entries; why is this? CSV is another thing I've seen thrown around on online documentation. Whats the difference between the two, and which one should I use(if either)? -thanks in advance From flamesrock at gmail.com Thu Dec 23 19:49:13 2004 From: flamesrock at gmail.com (Aaron) Date: Fri, 24 Dec 2004 00:49:13 GMT Subject: Creating Image Maps Message-ID: I know this is a thing used primarily on websites..but since python can do anything ;) I'm trying to make a clickable image map for my wxPython program. Basically, I know how to organize the images into one large image in a panel, but how do I make the individual pieces clickable like webpage links(in wxPython)? The goal is to add an event handler that displays the image piece in a different panel, along with attributes. Which I could do if only I could make the pieces clickable Any ideas? Also, if you have any hard to find links on the general area I'm talking about, I'd like to learn as much as possible. -thanks From peter at engcorp.com Wed Dec 15 10:25:38 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 15 Dec 2004 10:25:38 -0500 Subject: while 1 vs while True In-Reply-To: <7xsm6983rx.fsf@ruckus.brouhaha.com> References: <1102903165.589419.323000@z14g2000cwz.googlegroups.com> <7xllc1p3q4.fsf@ruckus.brouhaha.com> <7xsm6983rx.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Nick Coghlan writes: > >>Until this code: >> >>.>>> import pdb >>.>>> pdb.True = 0 >>.>>> pdb.x = "Darn writeable module dictionaries" >>.>>> from pdb import True >>.>>> True >>0 >>.>>> from pdb import x >>.>>> x >>'Darn writeable module dictionaries' > > > If Python really does behave that way, that bug should be fixed immediately. (My ISP's news server seems to be dropping messages, so I didn't see Nick's original message above, nor perhaps the message he was replying to. I hope that doesn't matter to my reply...) Paul, what is wrong with the above behaviour, that you believe it to indicate a bug? As Nick showed in his following reply, there are certainly people who make use of this behaviour, and I don't believe it could be duplicated with any other existing feature of Python. Removing it would, for but one example, cripple my ability to do effective automated testing in my field of work. -Peter From __peter__ at web.de Wed Dec 1 07:40:17 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 01 Dec 2004 13:40:17 +0100 Subject: Regular Expression Problem... References: Message-ID: andrea.gavana at agip.it wrote: > identifying/extracting a substring from another string. What I have to do > is to extract all the strings that begins with a "$" character, but > excluding characters like "." (point) and "'" (single quote) and "\" "/" > (slashes). For example I have: > > 1) This Is An $EXAMPLE String > 2) This Is An $EXAMPLE.String > 3) 'This Is An $EXAMPLE' > 4) This Is An \$EXAMPLE\String; > > I would like to extract only the "keyword" $EXAMPLE and what I'm using at Is that what you want? >>> import re >>> r = re.compile("[$]\w+") >>> r.findall(""" ... 1) This Is An $EXAMPLE String ... 2) This Is An $EXAMPLE.String ... 3) 'This Is An $EXAMPLE' ... 4) This Is An \$EXAMPLE\String; ... """) ['$EXAMPLE', '$EXAMPLE', '$EXAMPLE', '$EXAMPLE'] Peter From ndbecker2 at verizon.net Fri Dec 24 07:17:31 2004 From: ndbecker2 at verizon.net (Neal D. Becker) Date: Fri, 24 Dec 2004 07:17:31 -0500 Subject: Optional Static Typing - Haskell? References: <1103795375.843649.286620@c13g2000cwb.googlegroups.com> Message-ID: I've just started learning about Haskell. I suggest looking at this for an example. A good intro: http://www.haskell.org/tutorial From maxm at mxm.dk Mon Dec 20 03:48:22 2004 From: maxm at mxm.dk (Max M) Date: Mon, 20 Dec 2004 09:48:22 +0100 Subject: Is this a good use for lambda In-Reply-To: References: <41c654b9.529432724@news.oz.net> Message-ID: <41c69127$0$306$edfadb0f@dread12.news.tele.dk> The entity Fredrik Lundh wrote: Isn't it about time you became xml avare, and changed that to: ? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From kdart at kdart.com Sun Dec 12 19:23:59 2004 From: kdart at kdart.com (Keith Dart) Date: Mon, 13 Dec 2004 00:23:59 GMT Subject: Persistent objects In-Reply-To: <7xis77q1t7.fsf_-_@ruckus.brouhaha.com> References: <7xis77q1t7.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I've had this recurring half-baked desire for long enough that I > thought I'd post about it, even though I don't have any concrete > proposals and the whole idea is fraught with hazards. > > Basically I wish there was a way to have persistent in-memory objects > in a Python app, maybe a multi-process one. So you could have a > persistent dictionary d, and if you say > d[x] = Frob(foo=9, bar=23) > that creates a Frob instance and stores it in d[x]. Then if you > exit the app and restart it later, there'd be a way to bring d back > into the process and have that Frob instance be there. Check out the Durus project. http://www.mems-exchange.org/software/durus/ -- \/ \/ (O O) -- --------------------oOOo~(_)~oOOo---------------------------------------- Keith Dart vcard: public key: ID: F3D288E4 URL: ============================================================================ From magick-announce-bounces at imagemagick.org Wed Dec 8 01:44:32 2004 From: magick-announce-bounces at imagemagick.org (magick-announce-bounces at imagemagick.org) Date: Tue, 07 Dec 2004 22:44:32 -0800 Subject: Your message to Magick-announce awaits moderator approval Message-ID: Your mail to 'Magick-announce' with the subject Re: Thanks! Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. If you would like to cancel this posting, please visit the following URL: http://studio.imagemagick.org/mailman/confirm/magick-announce/3401b50e2d693ddafa3556164df365960847bb72 From jctobin at gmail.com Wed Dec 29 20:27:42 2004 From: jctobin at gmail.com (Nanoscalesoft) Date: 29 Dec 2004 17:27:42 -0800 Subject: PyQT installation Message-ID: <1104370062.562575.88620@f14g2000cwb.googlegroups.com> hello all, I am planning to start coding a nanoscale design software in python with QT interface.I have to do this in windows or linux.Intially windows would be fine. I have struggled almost full day today trying to make from import qt * execute...........................I have the basic python core. I went through the sites like riverbankcomputing and trolltech and few online pages and books which talk about PyQT but never say about their installation step properly. I need to know step by step what shud i do.I have also installed the windows binary of PyQT from riverbank and have ordered a QTdesigner CD.But i can't wait.I need to do this fast.(Is there any other thing i have to do) Any clean and clear cut info in linux or windows( as I hope this as the groups standard to be) would help me start my nanoscale project or otherwise i have to rethink the GUI..Common QT is my favourite i need my project work to be done on my favourite thing. regards, Charles (doing an example program wud be a welcome sweeet) From matt.gerrans at hp.com Wed Dec 1 15:01:41 2004 From: matt.gerrans at hp.com (Matt Gerrans) Date: Wed, 01 Dec 2004 20:01:41 GMT Subject: Python 3000 and "Python Regrets" References: <3064b51d.0412011016.6efc20a6@posting.google.com> Message-ID: Anyway, what's to worry about? When the time comes just whip out a little script that converts Python 1.6 (or whatever you like) to Python3K; it will only take seven lines of P3K code. From jb_perin at yahoo.fr Mon Dec 20 11:54:06 2004 From: jb_perin at yahoo.fr (Jean-Baptiste PERIN) Date: Mon, 20 Dec 2004 17:54:06 +0100 Subject: extending python with a C-written dll In-Reply-To: <41c6fc38$0$16108$a1866201@visi.com> References: <41c6e784$0$16084$a1866201@visi.com> <41c6f353$0$16095$a1866201@visi.com> <41c6fc38$0$16108$a1866201@visi.com> Message-ID: thanks for your valuable help .. ctypes is not lost for ever ..I'm going to explore a little bit .. it may suit my need in the end .. I had read : http://www.python.org/dev/doc/devel/ext/intro.html and eveything looked so simple in it .. I'm sad to realize that it only works for linux plateform :( I've tried to build and install ctypes from sources I ran the following command: >> python setup.py build and I got the following message: >> error: Python was built with version 6 of Visual Studio, and extensions need to be built with the same version of the compiler, but it isn't installed. :( :( :( :( So sad .... From deetsNOSPAM at web.de Fri Dec 17 09:01:31 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 17 Dec 2004 15:01:31 +0100 Subject: decorator peculiarity Message-ID: Hi, I just wrote my first decorator example - and I already love them. However I've encountered one peculiarity that strikes me odd: When one writes a decorated function like this: @decorate def foo(): pass the function decorate usually looks like this: def decorate(func): def _d(*args, **kwargs): do_something() # call func func(*args, **kwargs) return _d So the function decorator has to return a function that is bound to the name foo in the originating context (module or class) and gets the function passed as argument. But if I want my decorator to be parametrized, it looks like this: @decorate(arg) def foo(): pass def decorate(arg): def f(func): def _d(*args, **kwargs): do_something(arg) # call func func(*args, **kwargs) return _d So what happens is that an decorater with arguments is called with these, returns a callable that then is called with foo, and the result is stored under foo. Now why this layer of indirection? I would have supposed that things look like this: def decorate(func, arg): def _d(*args, **kwargs): do_something(arg) # call func func(*args, **kwargs) return _d A sideeffect of this behaviour is that for a fully keyword-argumentized function I still have to write parentheses: @decorate() def foo(): pass def decorate(arg=None): def f(func): def _d(*args, **kwargs): do_something(arg) # call func func(*args, **kwargs) return _d I don't mind the extra parentheses too much - it just made me wonder what the rationale behind this is. -- Regards, Diez B. Roggisch From steven.bethard at gmail.com Sat Dec 11 14:27:21 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 11 Dec 2004 19:27:21 GMT Subject: newbie questions In-Reply-To: <%eHud.90239$ha.15906@news.chello.at> References: <41ba6511$1@nntp.zianet.com> <%eHud.90239$ha.15906@news.chello.at> Message-ID: houbahop wrote: > Passing a pointer by value appears to me as passing a var by reference. Well, at least in the PL literature, there's a subtle difference. If Python supported pass-by-reference, you could do something like: >>> def clear(byref lst): ... lst = [] ... >>> x = [pow(x, 11, 17) for x in range(10)] >>> clear(x) >>> x [] Passing a variable by reference means that the *variable* in the function is the same *variable* as outside the function. Notice that this is not the same thing as saying that the variable in the function is a pointer to the same object as the variable outside the function. Python doesn't support pass-by-reference in this standard use of the term. But Python is basically *only* passing pointers around; there is no way to do anything else. So if passing a pointer by value is sufficient for your purposes then you won't have any problems with Python, because this is what it always does. =) > Thanks I will try all of that, but what does really means mutating in > python? It's the first time I hear this word in programming :)) The term is used most commonly in the pair accessor/mutator, also known as getter/setter. In general, a mutator is just a method of an object that changes that object's state. In Python, assignment does not invoke a method of an object; it binds a name to an object. For this reason, code like: def clear(lst): lst = [] # binds the name lst to a new value, [] # ignoring previous value will not change the list because it is not calling methods of the list object to change it. It will instead rebind the local name "lst" to a new object, []. This does not change the previous object that was associated with "lst" and so if you have another variable bound to the previous value ("x" in my examples), it will still retain the old, unchanged object. So, while assignment does not invoke a method of an object, many other things in Python do, and all of these things will appropriately modify the state of the object. For example: def clear(lst): lst[:] = [] # implicitly calls the setter/mutator list.__setslice__ def clear(lst): while lst: # implicitly calls the getter/accessor len(lst) lst.pop() # explicit call to setter/mutator list.pop # don't use this; it's inefficient, I'm just using it as an example # of using a different setter/mutator def clear(lst): while lst: # implicitly calls the getter/accessor len(lst) last_item = lst[-1] # implicitly calls the getter/accessor # list.__getitem__ lst.remove(last_item) # explicitly calls setter/mutator # list.remove Note that all of these functions will successfully clear the list because they mutate the object itself, instead of simply rebinding a name that at one point had been associated with the object. HTH, STeve From kartic.krishnamurthy at gmail.com Sun Dec 26 15:30:54 2004 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 26 Dec 2004 12:30:54 -0800 Subject: IDLE question In-Reply-To: References: Message-ID: <1104093054.426438.43640@f14g2000cwb.googlegroups.com> Rolf, IDLE presents you with an interactive python prompt where you can enter your code : single statments, class definitions, functions and it will execute interactively. >From the IDLE editor, I doubt if you can do what you want. In fact IDLE will force you to save your code in a file before you can execute it. To achieve what you describe (select a portion and execute) in IDLE, I use exec() or alternatively the compiler module both of which can take statements in a string variable and execute it. This works for me; may be there is a better way. Thanks, --Kartic From fredrik at pythonware.com Sun Dec 19 18:02:22 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Dec 2004 00:02:22 +0100 Subject: atmosphere on c.l.py (WAS: How about "pure virtual methods"?) References: <1gp06r8.10q8off1j9v6nvN%aleaxit@yahoo.com><1103448439.953120.209950@c13g2000cwb.googlegroups.com><1gp1415.10zjxtu1cfp9cxN%aleaxit@yahoo.com><1gp1afn.udxyw81p5gajqN%aleaxit@yahoo.com><1gp1m3i.1e39lko1nsv2z8N%aleaxit@yahoo.com> Message-ID: Steven Bethard wrote: > I do understand the feeling though; Fredrik Lundh jumped at me only a few days ago when I said > that I personally found list comprehensions more readable than map. if you think that's what you said, you're clearly didn't read the post you replied to very carefully. I read both posts before I made that comment. > If you find a good solution to this problem, please let me know. well, since I'm not in the ego-stroking business, what if I promise never to reply to posts by you, robert, and alex? From fredrik at pythonware.com Wed Dec 22 17:30:23 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Dec 2004 23:30:23 +0100 Subject: Help to find a library... References: <1gp7uy1.v63l261u1age8N%whamoo@_lollo_rknet.it> <1gp7y81.an9du01wik2joN%whamoo@_lollo_rknet.it> Message-ID: "whamoo" wrote >> > I'm looking for a library like ncurses, but that can be used also on >> > windows in a very simple way... >> > >> > There is some library that do some like curses? >> >> here's one: >> >> http://www.effbot.org/zone/console-index.htm > > Thanks for this library, but i was looking for a cross-platform library, > i need it for linux, macosx, and also windows.... sorry, missed the "also". googling for "python curses windows" (without the quotes) brings up a couple of hits, including: http://flangy.com/dev/python/curses/ might or might not work with the latest python. on the other hand, you could restrict yourself to using only a subset of curses, and write some glue code to map the functions in that subset to console calls. creating custom abstraction layers in Python is embarassingly easy... From kmcbrearty at yahoo.com Thu Dec 2 17:29:52 2004 From: kmcbrearty at yahoo.com (Kevin) Date: Thu, 2 Dec 2004 14:29:52 -0800 (PST) Subject: PySQLite Table indexing inside a functions Message-ID: <20041202222952.31154.qmail@web14022.mail.yahoo.com> Hello Everyone, I'm using PySQLite and would like to index this insert statement with the 'tablename'. Can anyone offer a suggestion? Also, this is a shot in the dark. Has anyone done anything with nested fields. I would like each vertex to have 3 points. currently, I'm just making 3 fields. Regards, Kevin def PARSE2DB(data,tablename): i = j = k = 0 cadu = GETdb().cursor() FacetNum = len(data [1]) while i < FacetNum: cadu.execute(""" insert into table = 'tablename'( V1_x, V1_y, V1_z, V2_x, V2_y, V2_z, V3_x, V3_y, V3_z, N_x, N_y, N_z) values(%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f) """, (data [1][i][1][0][0], data [1][i][1][0][1],data [1][i][1][0][2], data [1][i][1][1][0], data [1][i][1][1][1],data [1][i][1][1][2], data [1][i][1][2][0], data [1][i][1][2][1],data [1][i][1][2][2], data [1][i][0][0], data [1][i][0][1], data [1][i][0][2]) ) i = i + 1 return __________________________________ Do you Yahoo!? All your favorites on one personal page ? Try My Yahoo! http://my.yahoo.com From bncarper at cs.com Fri Dec 10 07:22:15 2004 From: bncarper at cs.com (Bob) Date: 10 Dec 2004 04:22:15 -0800 Subject: problem with datetime Message-ID: <1102681335.498436.290690@c13g2000cwb.googlegroups.com> Relatively new to python. I can get the following to work from the command line: Python 2.3.4 (#2, Aug 18 2004, 21:49:15) [GCC 3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import datetime >>> d = datetime.datetime.today() >>> d datetime.datetime(2004, 12, 10, 6, 13, 28, 154472) >>> But when I try to run the following small program I get the following results: import datetime d = datetime.datetime.today() print d Traceback (most recent call last): File "datetime.py", line 1, in ? import datetime File "/home/bob/pyshow/datetime.py", line 3, in ? d = datetime.datetime.today() AttributeError: 'module' object has no attribute 'today' Do I need to change a path? Running python 2.3.4 on linux redhat 7.3. Bob From mefjr75 at hotmail.com Fri Dec 17 21:11:31 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 17 Dec 2004 18:11:31 -0800 Subject: PyCrust: What am I suppose to do? References: <94Iwd.56$5R.11@newssvr21.news.prodigy.com> Message-ID: <1103335891.725816.325810@f14g2000cwb.googlegroups.com> It's me wrote: > I am trying out PyCrust and at a lost what to do next. With the previous > IDE I tried, the IDE pops up the console and the editor. From the editor, I > can set up breakpoints and debug and so forth. Yes, I can even run the > script. > > With PyCrust, the nice looking 3-pane window pops up with lots of tabs...a > prompt...and then??? Where is the file I am trying to run? Even the File > options are all greyed out... > > Yea it is not an IDE. It is supposed to be a 'flaky' interactive interpreter, with code completion, and other things. Never really use it. M.E.Farmer From fperez528 at yahoo.com Thu Dec 9 21:37:04 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Thu, 09 Dec 2004 19:37:04 -0700 Subject: Rationale behind the deprecation of __getslice__? References: <1102631406.573192.195670@c13g2000cwb.googlegroups.com> Message-ID: Terry Reedy wrote: > >> If no __getslice__() is found, a slice object is created instead, and >> passed to __getitem__() instead. > > The overwhelmingl most common case of a simple slice is more efficiently > done by having a separate function since no slice object is created. > >>>> a=[1,2,3] >>>> def f(): return a[0:1] > ... >>>> import dis >>>> dis.dis(f) [...] Very good point. I always forget how useful dis is, thanks. f From deetsNOSPAM at web.de Sun Dec 19 10:48:27 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 19 Dec 2004 16:48:27 +0100 Subject: newbie question References: <1103466821.444875.189440@z14g2000cwz.googlegroups.com> Message-ID: > It works as if you had written: > > for _i in xrange(len(myList)): > x = myList(_i) No, as this implies that the variable has to support random access using indices. But all that's required is the iterable-interface beeing supported - by calling __iter__ and .next() on the resulting object. -- Regards, Diez B. Roggisch From whamoo at _lollo_rknet.it Tue Dec 14 03:49:39 2004 From: whamoo at _lollo_rknet.it (whamoo) Date: Tue, 14 Dec 2004 08:49:39 GMT Subject: PyQt on MAC OS X References: <7bjvd.1605$sY5.237@fe37.usenetserver.com> Message-ID: <1gos3aw.1f6mgph1u40caoN%whamoo@_lollo_rknet.it> Michael McGarry wrote: > > thanks that did the trick!!! > > One problem is my Window created in Qt appears underneath all others on > the screen and focus never goes completely onto this window. Kind of weird. > > Any ideas? You must use pythonw for graphics application =) So launch the script with pythonw instead of python ;-) -- Whamoo www.rknet.it Powerd by: MacOsX, Gnu/Linux Debian Sarge, Amiga Os 3.9, Milk. From eric_brunel at despammed.com Wed Dec 8 08:24:36 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Wed, 08 Dec 2004 14:24:36 +0100 Subject: spawn or fork In-Reply-To: References: Message-ID: <41b6feda$0$8128$8fcfb975@news.wanadoo.fr> C Gillespie wrote: > Dear All, > > I have a function > def printHello(): > fp = open('file','w') > fp.write('hello') > fp.close() > > I would like to call that function using spawn or fork. My questions are: > > 1. Which should I use > 2. How do I call that function if it is defined in the same file. spawn execute an external executable program *outside* your current script, *not* a Python function. So say you want to run wordpad.exe from your Python script, you could do: os.spawn(os.P_NOWAIT, "C:\\Program files\\Accesories\\wordpad.exe, [...]) So you *need* an external executable to be passed to spawn. fork works another way: it duplicates the context of your process in another one and continues both processes in parallel. So basically, it doesn't *execute* anything, but just creates a process. You may then call your function is the new process (a.k.a the "child" process): def printHello(): ... if os.fork() == 0: ## fork returns 0 in the process copy => this is where we call our function printHello() else: ## If fork doesn't return 0, we're in the original => other code ... However, fork is only available on Unices. What are you trying to do exactly? If you provide more explanations, we may provide a better help than the simplistic one above. HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From FBatista at uniFON.com.ar Wed Dec 29 08:15:22 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Wed, 29 Dec 2004 10:15:22 -0300 Subject: Other notes Message-ID: [bearophileHUGS at lycos.com] #- Here are some questions and suggestions of mine that I've #- collected in #- the last weeks on the language (please note that some (most?) of them #- are probably wrong/useless/silly, but I've seen that such #- notes help me #- understand a lot of things and to find my weak spots.) It's a *very* good idea to address each subject in a different thread. Personally, maybe there's a point that interest me and where I can participate, but i don't have time to go through the rest of the mails. . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Dec 31 08:23:54 2004 From: steve at holdenweb.com (Steve Holden) Date: Fri, 31 Dec 2004 08:23:54 -0500 Subject: Why tuples use parentheses ()'s instead of something else like <>'s? In-Reply-To: <10t99ucg8b17o6e@corp.supernews.com> References: <1104299822.394489.161500@z14g2000cwz.googlegroups.com> <41d2ce43$0$35731$a1866201@visi.com> <10t5p4nedr06h94@news.supernews.com> <1gpmcad.1czfj31knykrrN%aleaxit@yahoo.com> <1104438184.632979.125880@z14g2000cwz.googlegroups.com> <1gpmtk6.sqjocy12xap15N%aleaxit@yahoo.com> <10t99ucg8b17o6e@corp.supernews.com> Message-ID: Jeff Shannon wrote: > Alex Martelli wrote: > >> Carl Banks wrote: >> >>> Then again, millenia past didn't have Frank Gehry (i.e., the Perl of >>> modern architecture). >> >> >> Uhm -- I count the Guggenheim Museum in Bilbao among the _successes_ of >> modern architecture... > > > I'll give you the Bilbao Guggenheim, which (at least in the exterior > pictures I can find) is a very attractive building, but here in Seattle > we must deal with the giant eyesore that is Gehry's Experience Music > Project, which (at least to my eyes) looks like a monstrous pile of > architectural rubbish. I can appreciate Gehry's attempts to get away > from the tyranny of the straight line, and even with the EMP there's > certain details which turned out well, but the overall effect is that of > an overturned garbage pail. > My wife, who's a commercila property manager, holds that many of the worst architectural excesses were designed as monuments to the architect rather that to fulfil the operational needs of the occupier. Come to think, I can remember at least one shitty piece of software that was designed on the same principles, but thankfully it's now over seven years since I worked in *that* environment. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From donn at drizzle.com Fri Dec 24 20:14:35 2004 From: donn at drizzle.com (Donn Cave) Date: 24 Dec 2004 19:14:35 -0600 Subject: Optional Static Typing - Haskell? References: <1103795375.843649.286620@c13g2000cwb.googlegroups.com> <1gpaypu.hp5icf1tvg99cN%aleaxit@yahoo.com> <41cc504b$1_1@127.0.0.1> <1gpbe96.1ioa9lt1t622shN%aleaxit@yahoo.com> Message-ID: <41ccbefb$1_2@127.0.0.1> Quoth aleaxit at yahoo.com (Alex Martelli): | Donn Cave wrote: ... | > He didn't dwell much on it, but there was some mention of type | > inference, kind of as though that could be taken for granted. | > I guess this would necessarily be much more limited in scope | > than what Haskell et al. do. | | Assuming that by "he" you mean GvR, I think I saw that too, yes. And | yes, a language and particularly a typesystem never designed to | facilitate inferencing are hard-to-impossible to retrofit with it in as | thorough a way as one that's designed around the idea. (Conversely, | making a really modular system work with static typing and inferencing | is probably impossible; in practice, the type inferencer must examine | all code, or a rather copious summary of it... it can't really work | module by module in a nice, fully encapsulated way...). Well, I would assume that a modules in a static system would present a typed external interface, and inference would apply only within the module being compiled. for example, Objective CAML revised syntax - $ cat mod.ml module T = struct type op = [On | Off]; value print t a = match t with [ On -> print_string a | Off -> () ]; value decide t a b = match t with [ On -> a | Off -> b ]; end; $ ocamlc -i -pp camlp4r mod.ml module T : sig type op = [ On | Off ]; value print : op -> string -> unit; value decide : op -> 'a -> 'a -> 'a; end; This is fairly obvious, so I'm probably missing the point, but the compiler here infers types and produces an interface definition. The interface definition must be available to any other modules that rely on this one, so they are relieved of any need to examine code within this module. There might be tricky spots, but I imagine the Objective CAML folks would object to an assertion like "making a really modular system work with static typing and inferencing is probably impossible"! Donn Cave, donn at drizzle.com From gh at ghaering.de Thu Dec 2 08:23:34 2004 From: gh at ghaering.de (Gerhard Haering) Date: Thu, 2 Dec 2004 14:23:34 +0100 Subject: exec size In-Reply-To: <20041203164448.GA25118@mrna.tn.nic.in> References: <20041203164448.GA25118@mrna.tn.nic.in> Message-ID: <20041202132334.GA3962@mylene.ghaering.de> On Fri, Dec 03, 2004 at 10:14:48PM +0530, km wrote: > Hi all, > just curious to know why /usr/bin/python2.3 is 890K and > /usr/bin/python2.4 is 3.5M in linux ? Did you try already removing the debug symbols with strip(1)? -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From tjreedy at udel.edu Mon Dec 27 14:10:15 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 27 Dec 2004 14:10:15 -0500 Subject: where is ctypes.py? References: <1104055174.719604.287630@c13g2000cwb.googlegroups.com> Message-ID: "Peter Hansen" > I see others have pointed you to the module, but nobody has > yet told you how you could have found it yourself. > > "ctypes" and many other such modules are third-party packages > which do not come with Python itself. In almost all cases, > you should be able to use Google quite easily to find such > a module by typing "python ctypes" (or substitute the appropriate > name in place of ctypes) in a Google search. Quite often > the home page of the package (where you'll find instructions > on downloading) will be the first result Google provides. If one does not already know the name of what one is searching for, there is also the PythonPackageIndex PyPI at python.org. Terry J. Reedy From plucker-dev-admin at rubberchicken.org Wed Dec 22 12:41:11 2004 From: plucker-dev-admin at rubberchicken.org (plucker-dev-admin at rubberchicken.org) Date: Thu, 23 Dec 2004 04:41:11 +1100 Subject: Your message to plucker-dev awaits moderator approval Message-ID: <20041222174111.7363.91283.Mailman@ike.inomial.com> Your mail to 'plucker-dev' with the subject Delivery (plucker-bugs at rubberchicken.org) Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list Either the message will get posted to the list, or you will receive notification of the moderator's decision. From daniel.wheeler at nist.gov Tue Dec 21 11:39:13 2004 From: daniel.wheeler at nist.gov (Daniel Wheeler) Date: Tue, 21 Dec 2004 11:39:13 -0500 Subject: memory leak Message-ID: Can python leak memory even if the reference count for all the objects is not increasing? For example: for i in range(N): print ref_count_all_objects() do_something() and every iteration the ref count is constant but the memory usage is increasing. What are the likely problems? Thanks ------------------------------------- Daniel Wheeler Telephone: (301) 975-8358 From replytogroup at nospam.org Sat Dec 11 22:24:59 2004 From: replytogroup at nospam.org (Michael McGarry) Date: Sat, 11 Dec 2004 20:24:59 -0700 Subject: Hashes In-Reply-To: References: Message-ID: Peter Hansen wrote: > Michael McGarry wrote: > >> Are there hashes in Python? > > > Define hash. Or look at Python's 'dict' type, or the hash() > function and decide for yourself if that's what you meant. > > -Peter Yes, I guess the dict type is what I am looking for. Thank you, Michael From fredrik at pythonware.com Mon Dec 20 01:36:56 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Dec 2004 07:36:56 +0100 Subject: Easy "here documents" ?? References: <41c604bf$1@nntp0.pdx.net> Message-ID: Jim Hill wrote: >>And if you prefer not to type so much: >> >>def I(*args): return "".join(map(str, args)) >>def F(v, fmt): return ("%" + fmt) % v > > Not that I don't appreciate the suggestions from masters of the Python > universe, but the reason I'm switching to Python from Perl is for the > readability. What you fells are suggesting might as well be riddled > with dollar signs and semicolons... . the I and F functions? add newlines to them, and replace that ugly-but- generally-accepted "".join thing with a proper string.join call, split the second expression into two subexpressions if necessary, and they'll look a lot better. or did you mean the call to I? did you look at it in a syntax-coloring editor? From ian at kirbyfooty.com Mon Dec 20 08:17:06 2004 From: ian at kirbyfooty.com (ian at kirbyfooty.com) Date: 20 Dec 2004 05:17:06 -0800 Subject: Python To Send Emails Via Outlook Express In-Reply-To: <41C6C9F8.7040400@holdenweb.com> References: <1103519604.987664.117400@c13g2000cwb.googlegroups.com> <1103521500.427846.238790@c13g2000cwb.googlegroups.com> <41C67E3D.5040205@kdart.com> <1103528498.945675.43920@z14g2000cwz.googlegroups.com> <1103529746.281597.103710@c13g2000cwb.googlegroups.com> <41C6C9F8.7040400@holdenweb.com> Message-ID: <1103548626.745378.220020@c13g2000cwb.googlegroups.com> Hi Steve, > Why the insistence on using Outlook Express, is you don;t mind me asking? Good question. The problem is that I have a developed a freeware application called Kirby Alarm And Task Scheduler (see www.kirbyfooty.com). The program can pop up a note, run a program, play a sound, or send an email at whatever intervals the user wants.. When it comes to sending emails the user has the option of sending them via smtp, or via there email client (eg outlook express). I prefer the send method as this makes setting up the email parameters a lot easier for the user. As the program is used by over 16,000 people around the world I don't want to complicate things by asking them to enter the mail server properties. I have written Kirby Alarm in Clarion. It can currently send the email via outlook express by calling MapiSendMail. I wanted to do the same thing in Python so I can build up a suite of useful utilities and therefore try an keep the program size relatively small. Ian From news at pointedstick.de Thu Dec 9 18:09:31 2004 From: news at pointedstick.de (Michael Auerswald) Date: Fri, 10 Dec 2004 00:09:31 +0100 Subject: Python 2.4 Tix failing on Windows XP In-Reply-To: References: Message-ID: j vickroy wrote: > Could someone tell me what I am doing incorrectly? All I can tell you is that I have the exact same problem (which I did not have with 2.3). Not much of a help, I know... From jeff at ccvcorp.com Wed Dec 22 14:02:27 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 22 Dec 2004 11:02:27 -0800 Subject: Newbie namespace question In-Reply-To: <1103729308.940154.187760@f14g2000cwb.googlegroups.com> References: <1103726535.898895.207410@c13g2000cwb.googlegroups.com> <1103729308.940154.187760@f14g2000cwb.googlegroups.com> Message-ID: <10sjgt06bt189de@corp.supernews.com> bcarlso at gmail.com wrote: >Now, in jdbc.py I have > >#jdbc.py >class DataSource: >def __init__(self, servername): >self.servername = servername > >def create(name, connectionInfo, etc): >#Call the IBM supplied WebSphere config object >AdminConfig.create('DataSource') > >Run it and get a name error, which, makes sense. >If I try to use the standard import solution as deelan suggests I have >a circular reference on the imports and I get an error that it can't >import class DataSource (presumbably because it hasn't gotten far >enough through jdbc.py to realize that there's a DataSource class >defined. > > How about you try this? def create(name, connectionInfo, ...): from configure_server_foo import AdminConfig AdminConfig.create('DataSource') This way, jdbc.py won't try to import configure_server.foo until create() is called. By deferring that import, you should be able to avoid the circular import problem... Jeff Shannon Technician/Programmer Credit International From fumanchu at amor.org Thu Dec 2 16:53:03 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 2 Dec 2004 13:53:03 -0800 Subject: RotatingFileHandler Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3245310@exchange.hqamor.amorhq.net> Kamus of Kadizhar wrote: > I'm having a problem with logging. I have an older app that used the > RotatingFileHandler before it became part of the main distribution (I > guess in 2.3). > > It worked fine then. Now I get: > > [yan at hermes bin]# ./mplayer.py file://test.avi > //test.avi > Traceback (most recent call last): > File "./mplayer.py", line 40, in ? > logFile.emit(movieName) > File > "/usr/src/build/394694-i386/install/usr/lib/python2.3/logging/ > handlers.py", line 102, in emit > File > "/usr/src/build/394694-i386/install/usr/lib/python2.3/logging/ > __init__.py", line 567, in format > File > "/usr/src/build/394694-i386/install/usr/lib/python2.3/logging/ > __init__.py", line 362, in format > AttributeError: 'str' object has no attribute 'getMessage' > > The offending snippet of code is: > > logFile = > logging.handlers.RotatingFileHandler('/var/log/user/movies2.lo > g','a',2000,4) > logFile.emit(movieName) Making a quick run-through of the logging module, it looks like you need to have a Formatter object added to your Handler: filename = '/var/log/user/movies2.log' logFile = logging.handlers.RotatingFileHandler(filename,'a',2000,4) formatter = logging.Formatter() logFile.setFormatter(formatter) ...then you can call emit. Robert Brewer MIS Amor Ministries fumanchu at amor.org From albaalu at gmail.com Thu Dec 23 23:53:13 2004 From: albaalu at gmail.com (PD) Date: 23 Dec 2004 20:53:13 -0800 Subject: String backslash characters Message-ID: <1103863993.900799.142090@z14g2000cwz.googlegroups.com> Hello, I am new to python, but i am quite curious about the following. suppose you had print '\378' which should not work because \377 is the max. then it displays two characters (an 8 and a heart in my case...). What else does'nt quite make sense is that if this is an octal why is an 8 accepted? for instance is 378 really 11, 111, 1000 which is then the two characters: <00000001>,<1111000>. And why is this accepted? I apologize if this has been discussed or if it is obvious. I would appreciate it if someone could clear me up. Yours, PD From steven.bethard at gmail.com Wed Dec 29 15:52:08 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 29 Dec 2004 20:52:08 GMT Subject: Python 3000, zip, *args and iterators In-Reply-To: <1104350860.774598.311040@f14g2000cwb.googlegroups.com> References: <3yGzd.289258$HA.962@attbi_s01> <1104171069.929732.69810@z14g2000cwz.googlegroups.com> <1104350860.774598.311040@f14g2000cwb.googlegroups.com> Message-ID: Raymond Hettinger wrote: > [Steven Bethard] I'm just suggesting that in a function with a > >>*args in the def, the args variable be an iterator instead of >>a tuple. > > > So people would lose the useful abilities to check len(args) or extract > an argument with args[1]? No more than you lose these abilities with any other iterators: def f(x, y, *args): args = list(args) # or tuple(args) if len(args) == 3: print args[0], args[1], args[2] True, if you do want to check argument counts, this is an extra step of work. I personally find that most of my functions with *args parameters look like: def f(x, y, *args): do_something1(x) do_something2(y) for arg in args: do_something3(arg) where having *args be an iterable would not be a problem. >> So basically what I've done here is to >>"transpose" (to use your word) the iterators, apply my function, and >>then transpose the iterators back. > > If you follow the data movements, you'll find that iterators provide no > advantage here. To execute transpose(map(f, transpose(iterator)), the > whole iterator necessarily has to be read into memory so that the first > function application will have all of its arguments present -- using > the star operator only obscures that fact. I'm not sure I follow you here. Looking at my code: labels, feature_dicts = starzip(generator) for label, feature_window in izip(labels, window(feature_dicts)): write_instance(label, combine_dicts(feature_widow)) A few points: (1) starzip uses itertools.tee, so it is not going to read the entire contents of the generator in at once as long as the two parallel iterators do not run out of sync (2) window does not exhaust the iterator passed to it; instead, it uses the items of that iterator to generate a new iterator in sync with the original, so izip(labels, window(feature_dicts)) will keep the labels and feature_dicts iterators in sync. (3) the for loop just iterates over the izip iterator, so it should be consuming (label, feature_window) pairs in sync. I assume you disagree with one of these points or you wouldn't say that "iterators provide no advantage here". Could you explain what doesn't work here? Steve From exarkun at divmod.com Sun Dec 5 15:17:31 2004 From: exarkun at divmod.com (Jp Calderone) Date: Sun, 05 Dec 2004 20:17:31 GMT Subject: help using sockets, and OOP? In-Reply-To: Message-ID: <20041205201731.1203.199223323.divmod.quotient.2538@ohm> On Mon, 06 Dec 2004 06:02:40 +1000, Dfenestr8 wrote: >Hi. > > I realise, that there's probably something intrinsic to OOP that I don't > understand here. Or maybe it's something to do with sockets. I'm not sure. > > Basically, I'm trying to hack up an IRC bot, that joins two servers at > once. I use two object instancs of the same class, both of which make > connections using the socket module. > > Problem is, I can't seem to get both objects to connect to their > constituent servers at the same time. I'm not sure whether it's that both > objects can't instantiate at once, or whether only one can use the socket > module at any one time. > > Here's my code: > > http://plz.donthack.us/~hairyman/mybot.py > > Can anybody see what it is I'm missing? Your problem doesn't seem to have anything to do with "OOP" (whatever that is). Rather, you are trying to use two blocking sockets at once. socket.connect() and socket.recv() are both "blocking" operations by default - they can take an arbitrary amount of time to return. Additionally, Botling.receiveData, one of your own functions, is also blocking: it will actually loop forever, never returning (until an exception blows it up). So execution of your program never even _gets_ to the "bert2 = ..." line. It's stuck running bert1.receiveData(). Handling concurrency can be quite tricky, but fortunately there are some tools to help you out. For starters, check out http://www.twistedmatrix.com/ - in particular, you may be interested in http://www.twistedmatrix.com/documents/current/examples/ircLogBot.py Jp From fredrik at pythonware.com Mon Dec 13 11:30:26 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Dec 2004 17:30:26 +0100 Subject: Another RegEx Question... References: Message-ID: wrote: > I'm quite new to Python and I don't know if this is a FAQ (I can't > find it) or an obvious question. I'm using the RE module in python, and I > would like to be able to contruct something like the Window$ "Find Files Or > Folders" engine. As the Window$ users know, you can filter the file names > using the character "*", as: > > myfilen* (Will find a file named myfilenames) > *yf*nam* (Will find a file named myfilenames) in Unix lingo, that's known as a "glob" pattern. it's not really a regular expression. if you insist on using regular expressions, you can use the fnmatch.translate function to convert from pattern to expression: >>> import fnmatch >>> fnmatch.translate("myfilen*") 'myfilen.*$' >>> fnmatch.translate("*yf*nam*") '.*yf.*nam.*$' or you can use fnmatch.filter() to find matching names in a list: >>> fnmatch.filter(["hello.txt", "bye.txt", "spam.egg"], "*.txt") ['hello.txt', 'bye.txt'] but it's likely that what you really want is the "glob" module, which looks for files matching a given pattern: >>> import glob >>> glob.glob("*.txt") ['key.txt', 'some_document.txt'] more info here: http://docs.python.org/lib/module-glob.html http://docs.python.org/lib/module-fnmatch.html From steve at holdenweb.com Fri Dec 3 07:35:42 2004 From: steve at holdenweb.com (Steve Holden) Date: Fri, 03 Dec 2004 07:35:42 -0500 Subject: pythonwin broke In-Reply-To: <8uQrd.4000728$yk.610217@news.easynews.com> References: <8uQrd.4000728$yk.610217@news.easynews.com> Message-ID: Jive wrote: > I've un-installed Python 2.4, re-installed Python 2.3 and PythonWin for 2.3, > but it's still broke. > > When I start PythonWin, sometimes it looks like it is going to be okay. But > as soon as I open a .py file, the interactive window grabs the focus and > will not let go. I am stumped. > > Is there something PythonWin uses that I could try re-installing? WxPython > maybe? > > This isn't something I can ever remember happening. You might consider asking on the python-win32 list, which is more specifically directed at Mark Hammond's stuff. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From aleaxit at yahoo.com Sun Dec 26 04:06:15 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Dec 2004 10:06:15 +0100 Subject: Complementary language? References: Message-ID: <1gpebha.1wxzwoss5rkfnN%aleaxit@yahoo.com> Robert Kern wrote: > Common Lisp might be a good one to learn. It's even more > "multi-paradigm" than Python. You could very easily learn more > approaches to programming through Common Lisp than three other > languages. This book[2] looks promising. If you're looking for SERIOUS multiparadigmaticity, I think Oz may be best -- (the book's authors critique the vagueness of the "paradigm" concept, and prefer "model", but that's much the same thing). You start with pure declarative programming (aka "functional" in many circles), move on to concurrency in a purely declarative worldview (easiest way to see concurrency), then enrich both sequential and concurrent models as the book progresses, by message-passing, explicit state ("procedural"), object-oriented, _shared_ state, and finally relational. GUI, distributed, and constraint-based programming round out a grandiose conceptual tour. "SICP for the 21st Century"...? (SICP: google for it!). I currently think so, though, studying CTMCP (the Oz book) in my spare time, it will take me a while before I've finished it and can fairly offer such a lofty recommendation for it... still, I notice from the back-page blurbs that Peter Norvig has no reservations drawing a parallel with SICP (aka Abelson and Sussman), and Norvig's assessment must count for more than mine! Alex From devanpraburam at yahoo.com Sat Dec 25 13:56:24 2004 From: devanpraburam at yahoo.com (devanpraburam at yahoo.com) Date: Sat, 25 Dec 2004 10:56:24 -0800 (PST) Subject: Yahoo! Auto Response Message-ID: <20041225185627.0BDA51E4005@bag.python.org> Hai devan have receved the mail but have not checked he will reply you sooner -------------------- Original Message: X-YahooFilteredBulk: 61.1.208.116 Authentication-Results: mta296.mail.scd.yahoo.com from=python.org; domainkeys=neutral (no sig) X-Originating-IP: [61.1.208.116] Return-Path: Received: from 61.1.208.116 (EHLO yahoo.com) (61.1.208.116) by mta296.mail.scd.yahoo.com with SMTP; Sat, 25 Dec 2004 10:56:24 -0800 From: python-list at python.org To: devanpraburam at yahoo.com Subject: Date: Sun, 26 Dec 2004 00:25:34 +0530 MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="----=_NextPart_000_0016----=_NextPart_000_0016" X-Priority: 3 X-MSMail-Priority: Normal This is a multi-part message in MIME format. ------=_NextPart_000_0016----=_NextPart_000_0016 Content-Type: text/plain; charset="Windows-1252" Content-Transfer-Encoding: 7bit ++++ Attachment: No Virus found ++++ Norton AntiVirus - www.symantec.de ------=_NextPart_000_0016----=_NextPart_000_0016 Content-Type: application/octet _________________________________________________________ DO YOU YAHOO!? Get your free @yahoo.com address at http://mail.yahoo.com From steve at holdenweb.com Tue Dec 21 09:34:47 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 21 Dec 2004 09:34:47 -0500 Subject: Tabnanny really useful? In-Reply-To: References: <10se8avsvbqad9@news.supernews.com> Message-ID: <3zWxd.57759$Jk5.52616@lakeread01> Franz Steinhaeusler wrote: > On Tue, 21 Dec 2004 08:36:31 -0500, Steve Holden > wrote: > > >>Franz Steinhaeusler wrote: >> >>[...] >> >>>Oh sorry, I meant >>>def a(): >>>->print >>>..->print >>> >>>C:\Python23\Lib>tabnanny.py -v c:\franz.py >>>'c:\\franz.py': *** Line 3: trouble in tab city! *** >>>offending line: ' \tprint\n' >>>indent not equal e.g. at tab size 1 >>> >>>C:\Python23\Lib>python -c "print repr(open('c:/franz.py').read())" >>>'def a():\n\tprint\n \tprint\n' >>> >>>C:\Python23\Lib>c:/franz.py >>> >>>C:\Python23\Lib> >> >>Well, you've probably answered your own question, then. Do you think >>tabnanny is a useful piece of code now? > > > Not really soo useful, because most syntax and also indentation errors > are actually detected by invoking python, i.e. the command compile. > But as combination for this: yes why not. > I looked for Stanis spe editor, which uses a combination of these two. > > The background is: > > I'm a member of the wxPython project Drpython (Python text editor > and much more), and wanted also check the usefulness of a kind of syntax > check, which should run, before saving a Python file. > PythonCard Codeeditor also uses tabnanny, as far as i can remember. > > >>[...] > > > regards I've used drpython, and liked it. I think it would be a good way for people to start to use the language, as it avoids the "just the command line" syndrome without being as complex as IDLE or PythonWin. In short, just about right for a beginner. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From http Thu Dec 9 09:51:10 2004 From: http (Paul Rubin) Date: 09 Dec 2004 06:51:10 -0800 Subject: results of division References: Message-ID: <7xacsnjzj5.fsf@ruckus.brouhaha.com> Brad Tilley writes: > What is the proper way to limit the results of division to only a few > spaces after the decimal? I don't need rocket-science like > precision. Here's an example: > > 1.775 is as exact as I need to be and normally, 1.70 will do. "%.2f"% 1.775 From faassen at infrae.com Thu Dec 16 06:12:57 2004 From: faassen at infrae.com (Martijn Faassen) Date: Thu, 16 Dec 2004 11:12:57 GMT Subject: libxml2/xpath In-Reply-To: References: Message-ID: Maxim Khesin wrote: > I am trying to do some xpath on > http://fluidobjects.com/doc.xhtml > but cannot get past 'point A' (that is, I am totally stuck): > > >>>import libxml2 >>>mydoc = libxml2.parseDoc(text) >>>mydoc.xpathEval('/html') >>>[] > > > this returns an empty resultlist, which just seems plain wrong. Can anyone > throw a suggestion to the stupid? Is the html element in a namespace? Regards, Martijn From stephen.thorne at gmail.com Wed Dec 22 16:44:24 2004 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 23 Dec 2004 07:44:24 +1000 Subject: word to digit module In-Reply-To: <41c9cb8f$1@nntp0.pdx.net> References: <1103719672.839535.178010@z14g2000cwz.googlegroups.com> <41c9cb8f$1@nntp0.pdx.net> Message-ID: <3e8ca5c8041222134437f261e6@mail.gmail.com> On Wed, 22 Dec 2004 11:41:26 -0800, Scott David Daniels wrote: > John Machin wrote: > > Stephen Thorne wrote: > > .def toNumber2(s): > > . items = s.replace(',', '').split() > > . numbers = [translation.get(item.strip(), -1) for item in items if > > item.strip()] > > . stack = [0] > > . for num in numbers: > > . if num == -1: > > . raise ValueError("Invalid string '%s'" % (s,)) > > . if num >= 100: > > . stack[-1] *= num > > . if num >= 1000: > > . stack.append(0) > > . else: > > . stack[-1] += num > > . return sum(stack) > > > > Can I play too? > Let's replace the top with some little bit of error handling: > > def toNumber3(text): > s = text.replace(',', '').replace('-', '')# for twenty-three > items = s.split() > try: > numbers = [translation[item] for item in items] > except KeyError, e: > raise ValueError, "Invalid element %r in string %r" % ( > e.args[0], text) > stack = [0] > for num in numbers: > if num >= 100: > stack[-1] *= num > if num >= 1000: > stack.append(0) > else: > stack[-1] += num > return sum(stack) Thankyou for you feedback, both of you. http://thorne.id.au/users/stephen/scripts/eng2num.py contains your suggestions. Stephen. From danb_83 at yahoo.com Thu Dec 23 16:23:15 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 23 Dec 2004 13:23:15 -0800 Subject: list Integer indexing dies?? References: <10sm9po4ddbrca5@corp.supernews.com> Message-ID: <1103836995.130474.86620@z14g2000cwz.googlegroups.com> Jeff Shannon wrote: > Ishwor wrote: > > >On Thu, 23 Dec 2004 13:33:16 -0300, Batista, Facundo > > wrote: > > > > > >>[Ishwor] > >> > >>#- > What should 035[0] cough up? Be carefull it should > >>#- > >>#- >>>035[0] > >>#- 3 # my own opinion. > >> > >> > >why 3? The reason we get 3 and not 0 here is the *fact* that Python > >knows that its an octal rep. and not decimal ;-) > > > > > > Except that, at the point where the indexing takes place, Python > *doesn't* know that it's an octal rep. All integer literals, regardless > of representation, generate exactly the same bytecode. > > >>> def f(): > ... x = 035 > ... y = 29 > ... > >>> dis.dis(f) > 0 SET_LINENO 1 > > 3 SET_LINENO 2 > 6 LOAD_CONST 1 (29) > 9 STORE_FAST 1 (x) > > 12 SET_LINENO 3 > 15 LOAD_CONST 1 (29) > 18 STORE_FAST 0 (y) > 21 LOAD_CONST 0 (None) > 24 RETURN_VALUE > >>> > > Given that Python may not even have access to the .py file, only the > .pyc (which has lost all record of the source representation), there's > no way for the interpreter to do what you suggest. And even if there was, what should (104 + 0x68 + 0150)[0] print? From skip at pobox.com Mon Dec 13 22:10:24 2004 From: skip at pobox.com (Skip Montanaro) Date: Mon, 13 Dec 2004 21:10:24 -0600 Subject: [dictionary] how to get key by item In-Reply-To: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9170@au3010avexu1.global.avaya.com> References: <338366A6D2E2CA4C9DAEAE652E12A1DE4A9170@au3010avexu1.global.avaya.com> Message-ID: <16830.22944.544788.183792@montanaro.dyndns.org> Tim> Python will do what you tell it. In the above case, it will build a Tim> list. Whoops, yeah. I called .iteritems() then forgot to use a generator expression... Skip From fumanchu at amor.org Mon Dec 13 18:17:41 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 13 Dec 2004 15:17:41 -0800 Subject: Suggestion for "syntax error": ++i, --i Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339802D@exchange.hqamor.amorhq.net> Terry Reedy wrote: > "Petr Prikryl" wrote in message > news:F7789324060E8A4E9C765780D6B514B8150AD9 at skil01.skil.mistni... > > >Summary: In my opinion, the C-like prefix > >increment and decrement operators (++i and --i) > > You could propose to the author of Pychecker that he include, > if possible, an option to check for and warn about '++', '--'. +1 FuManChu From python-url at phaseit.net Wed Dec 15 14:08:03 2004 From: python-url at phaseit.net (Cameron Laird) Date: Wed, 15 Dec 2004 19:08:03 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 15) Message-ID: QOTW: "[Python demands more thought in optimization, because i]n other languages, by the time you get the bloody thing working it's time to ship, and you don't have to bother worrying about making it optimal." -- Simon Brunning "One of the best features of c.l.py is how questions phrased in the most ambiguous terms are often slowly elaborated into meaningful enquiries." -- Steve Holden Martin Bless summarizes in an extremely valuable post what you need to know to generate Python-related executable binaries targeted for Windows*. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/73f29284d1e031c7/ John Hunter, Fredrik Lundh, P??draig Brad, and Tim Peters work out in public on a model problem of textual analysis. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/b009627e9a5abc64/7d75f531ba8a7fe2 Amidst the usual combination of heat and light (in this case, on commercial acceptance and applicability of OO), Mike Meyer narrates from his own experience an example of how good object orientation can be. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/16590f4138b6a978/ gDesklets are attention-grabbing Py-scriptable desktop decorations. http://gdesklets.gnomedesktop.org/index.php Sure, a list comprehension can comprise multiple "for"-s. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ee5f7f8c227b22ff/ Mac OS X makes for highly-desired (at least by some) development hosts; moreover "there are three killer features in MacPython that you can't get anywhere else ..." http://mail.python.org/pipermail/pythonmac-sig/2004-December/012298.html ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From fuzzyman at gmail.com Mon Dec 13 11:27:24 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: 13 Dec 2004 08:27:24 -0800 Subject: A problem with list In-Reply-To: References: <1102949381.675816.171660@z14g2000cwz.googlegroups.com> Message-ID: <1102955244.888127.10630@c13g2000cwb.googlegroups.com> An alternative is reading the list into a string and using my 'listquote' module. It will tun strings into lists (and vice versa) - including nested lists (lists of lists) and properly handling quoted elements. http://www.voidspace.org.uk/atlantibots/pythonutils.html It won't do integer conversions though - only strings. Regards, Fuzzy From mwm at mired.org Wed Dec 15 01:39:18 2004 From: mwm at mired.org (Mike Meyer) Date: Wed, 15 Dec 2004 00:39:18 -0600 Subject: gather information from various files efficiently References: <3e96ebd7.0412140111.69244c7c@posting.google.com> <41BEB2CA.8070802@kdart.com> <41bec51a$1_2@newspeer2.tds.net> Message-ID: <86wtvkrrop.fsf@guru.mired.org> Simon Brunning writes: > On Tue, 14 Dec 2004 10:40:56 -0500, Peter Hansen wrote: >> Keith Dart wrote: >> > Sigh, this reminds me of a discussion I had at my work once... It seems >> > to write optimal Python code one must understand various probabilites of >> > your data, and code according to the likely scenario. >> >> And this is different from optimizing in *any* other language >> in what way? > > In other languages, by the time you get the bloody thing working it's > time to ship, and you don't have to bother worrying about making it > optimal. +1 QOTW. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From sean_mcilroy at yahoo.com Sat Dec 18 13:41:55 2004 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: 18 Dec 2004 10:41:55 -0800 Subject: example code sought Message-ID: There's something quite simple I'd like to do, but I'm hampered by lack of knowledge regarding Tkinter. If someone could help me out with a snippet of maximally-simple code showing, in general terms, how to do this, that would be really great. What I want to do is simply to move a shape around on the screen using the mouse. I've looked at Tkdnd.py but I can't seem to extract what I need from the more involved stuff in there. Peace, STM From sf at sf.sf Wed Dec 15 10:55:43 2004 From: sf at sf.sf (sf) Date: Wed, 15 Dec 2004 15:55:43 GMT Subject: Efficient grep using Python? Message-ID: <38Zvd.32503$g4.608727@news2.nokia.com> Just started thinking about learning python. Is there any place where I can get some free examples, especially for following kind of problem ( it must be trivial for those using python) I have files A, and B each containing say 100,000 lines (each line=one string without any space) I want to do " A - (A intersection B) " Essentially, want to do efficient grep, i..e from A remove those lines which are also present in file B. From deetsNOSPAM at web.de Wed Dec 8 13:19:49 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 08 Dec 2004 19:19:49 +0100 Subject: How is Python designed? References: Message-ID: > No, in the depth-traversal implementation, a function > can avoid calling itself (at least in my > implementation it's like this). How so? It has to keep state of which nodes to visit - so instead of calling trav, you call functions to store and fetch nodes in a container like a stl-list. That's the same cost, function-call is function call. There is no difference - you simply decoupled the tree traversal from the evaluation - but combined, its the same effort. It's like in my second example with bytecodes - the traversal is done beforehand (and only once), and then the eval is only done on the nodes in a row. > Because you can write seperate functions: a function > for depth-traversal (say trav()) and another function > for evaluation (say eval()). trav() may call eval(). > And eval() NEVER call other functions. For one > arithmetic tree, trav() is called once, and eval() is > called by trav() at each node. So it is not recursive. >> Now apart from that, I still fail to see where your >> method of evaluation has >> any speed gains. > > And if you inplement eval() as an "inline" function, > there will be no cost for function calls for eval(). > In this way it can gain some speeds. No. Inlining works only when the actual type of your node is known, e.g. like this (Constant and Variable are both of type : { Constant left; Variable right; left.eval(); right.eval(); } Here the compiler can take advantage from the fact that it knows at compiletime which eval to inline But if you have { list nodes; for(nodes::iterator it = nodes.begin(); it != nodes.end(); it++) { (*exp).eval(); } } the compiler can't possibly know which node is in exp- so it has to resort to a vtable-lookup and a method call on the result. -- Regards, Diez B. Roggisch From gman at op.pl Thu Dec 16 13:36:18 2004 From: gman at op.pl (abisofile) Date: Thu, 16 Dec 2004 18:36:18 -0000 Subject: BASIC vs Python Message-ID: hi I'm new to programming.I've try a little BASIC so I want ask since Python is also interpreted lang if it's similar to BASIC. From ebonakDUH at hotmail.com Sun Dec 12 21:19:49 2004 From: ebonakDUH at hotmail.com (Esmail Bonakdarian) Date: Sun, 12 Dec 2004 21:19:49 -0500 Subject: Best book on Python? In-Reply-To: References: Message-ID: <10rpv26jonj3620@corp.supernews.com> Michael McGarry wrote: > Hi, > > What is the best book covering Python? > > Michael I like these: Python Cookbook book Learning Python, 2nd ed Python in a Nutshell Dive Into Python would also make a good choice and the next book I would get (if I were to get one more ;-) I myself am looking for a small portable quick reference, thinking about the O'Reilly pocket guide but I'm not sure how good it is. I read on amazon that it doesn't have an index - that seems odd for any book, and esp a quick ref. Esmail From adam at cognitcorp.com Mon Dec 13 17:25:55 2004 From: adam at cognitcorp.com (Adam DePrince) Date: Mon, 13 Dec 2004 17:25:55 -0500 Subject: how do I "peek" into the next line? In-Reply-To: <1102973071.239704.167280@z14g2000cwz.googlegroups.com> References: <1102964987.812024.5180@c13g2000cwb.googlegroups.com> <1102973071.239704.167280@z14g2000cwz.googlegroups.com> Message-ID: <1102976755.4867.76.camel@localhost.localdomain> On Mon, 2004-12-13 at 16:24, les_ander at yahoo.com wrote: > OK, I am sorry , I did not explain my problem completely. > I can easily break from the loop when I see the character in a line > that I just read; however my problem involves putting back the line I > just read since if I have seen this special character, I have read one > line too many. Let me illustrate > suppose the file has 3 lines > > line1.line1.line1 > >line2.line2.line > line3.line3.line3 > > now suppose I have read the first line already. > then I read the second line and notice > that there is a ">" in front (my special character) > then I want the put back the second line into the > file or the stdin. > > An easy way is if i read all the lines in to an array > and then I can put back the line with the special > character back into this array. However, > this file I am readding is huge! and I can read > it all in one swoop (not enough memory). > > for x in stdin: > if x[0]==">": > #### put back the x some how... <----- > break > else: > print x > > I hope this is clear > thanks class stackfile: def __init__( self, f ): self.f = f self.stack = [] def readline( self ): if len( self.stack ): return self.stack.pop() return self.f.readline() def unreadline( self, lastline ): self.stack.append( lastline ) if __name__=="__main__": import StringIO f = stackfile(StringIO.StringIO("a\nb\nc\nd\ne\nf\ng\n")) # You would say: myfile = stackfile( stdin ) line = f.readline() print line, line = f.readline() print line, line = f.readline() print line, f.unreadline( line ) line = f.readline() print line, line = f.readline() print line, Running this prints: a b c c d Hope this helps. Adam DePrince From tim.golden at viacom-outdoor.co.uk Thu Dec 30 05:54:03 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 30 Dec 2004 10:54:03 -0000 Subject: Is there a better way of listing Windows shares other than us ing "os.listdir" Message-ID: <9A28C052FF32734DACB0A288A353399103596B@vogbs009.gb.vo.local> [Doran_Dermot at emc.com] | I'm currently using "os.listdir" to obtain the contents of | some slow Windows shares. I think I've seen another way of | doing this using the win32 library but I can't find the | example anymore. It may be FindFilesIterator, recently added to the win32file module in pywin32. I don't know if it's any more efficient than an os.listdir (which may use it under the covers, for all I know) but it certainly works: import win32file for file_data in win32file.FindFilesIterator ("c:/temp/*"): ( attr, ctime, atime, wtime, size_hi, size_lo, r0, r1, longname, shortname ) = file_data print longname TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From bokr at oz.net Tue Dec 7 15:54:19 2004 From: bokr at oz.net (Bengt Richter) Date: Tue, 07 Dec 2004 20:54:19 GMT Subject: [BUG] IMO, but no opinions? Uncle Tim? was: int(float(sys.maxint)) buglet ? References: <41b3f08f.105027181@news.oz.net> Message-ID: <41b5f3ba.9062691@news.oz.net> On Mon, 6 Dec 2004 10:30:06 -0500, Tim Peters wrote: >[Bengt Richter] >> Peculiar boundary cases: >> >> >>> 2.0**31-1.0 >> 2147483647.0 >> >>> int(2147483647.0) >> 2147483647L >> >>> int(2147483647L ) >> 2147483647 >> >>> >> >>> -2.0**31 >> -2147483648.0 >> >>> int(-2147483648.0) >> -2147483648L >> >>> int(-2147483648L ) >> -2147483648 >> >> some kind of one-off error? > >It would help if you were explicit about what you think "the error" >is. I see a correct result in all cases there. > >Is it just that sometimes > > int(a_float) > >returns a Python long when > > int(a_long_with_the_same_value_as_that_float) > >returns a Python int? If so, that's not a bug -- there's no promise >anywhere, e.g., that Python will return an int whenever it's >physically possible to do so. Ok, I understand the expediency of that policy, but what is now the meaning of int, in that case? Is it now just a vestigial artifact on the way to transparent unification of int and long to a single integer type? Promises or not, ISTM that if int->float succeeds in preserving all significant bits, then then a following float->int should also succeed without converting to long. > >Python used to return a (short) int in all cases above, but that lead >to problems on some oddball systems. See the comments for float_int() >in floatobject.c for more detail. Slowing float_int() to avoid those >problems while returning a short int whenever physically possible is a >tradeoff I would oppose. The 2.3.2 source snippet in floatobject.c : -------------- static PyObject * float_int(PyObject *v) { double x = PyFloat_AsDouble(v); double wholepart; /* integral portion of x, rounded toward 0 */ (void)modf(x, &wholepart); /* Try to get out cheap if this fits in a Python int. The attempt * to cast to long must be protected, as C doesn't define what * happens if the double is too big to fit in a long. Some rare * systems raise an exception then (RISCOS was mentioned as one, * and someone using a non-default option on Sun also bumped into * that). Note that checking for >= and <= LONG_{MIN,MAX} would * still be vulnerable: if a long has more bits of precision than * a double, casting MIN/MAX to double may yield an approximation, * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would * yield true from the C expression wholepart<=LONG_MAX, despite * that wholepart is actually greater than LONG_MAX. */ if (LONG_MIN < wholepart && wholepart < LONG_MAX) { const long aslong = (long)wholepart; return PyInt_FromLong(aslong); } return PyLong_FromDouble(wholepart); } -------------- But this is apparently accessed through a table of pointers, so would you oppose an auto-configuration that one time tested whether int(float(sys.maxint))==sys.maxint and int(float(-sys.maxint-1))==-sys.maxint-1 (assuming that's sufficient, of which I'm not 100% sure ;-) and if so switched the pointer to a version that tested if(LONG_MIN <= wholepart && wholepart<=LONG_MAX) instead of the safe-for-some-obscure-system version? Of course, if int isn't all that meaningful any more, I guess the problem can be moved to the ctypes module, if that gets included amongst the batteries ;-) Regards, Bengt Richter From trentm at ActiveState.com Fri Dec 3 13:44:29 2004 From: trentm at ActiveState.com (Trent Mick) Date: Fri, 03 Dec 2004 10:44:29 -0800 Subject: pythonwin broke In-Reply-To: <031220040934408194%mrjean1ATcomcastDOTnet@no.spam.net> References: <8uQrd.4000728$yk.610217@news.easynews.com> <031220040934408194%mrjean1ATcomcastDOTnet@no.spam.net> Message-ID: <41B0B40D.3030102@activestate.com> Jean Brouwers wrote: > PPS) It looks like Python 2.4 and Python 2.3 can not co-exist (in > different folders under Program Files) but we did not investigate that > any further. That's not true. I have every version of Python back to 2.0 installed and all running fine on my system. Obviously you can only have one of your Python installations first on your PATH (and hence the one that gets run by simply typing "python"). Also, you can only have one of you Python installations registered as the default handler for .py files (and hence the one that gets run by simple double-clicking on a .py file in explorer or running a Python script without the extension from the command line). It is also possible that there is some little installer bug or detail on your environment that is causing the problem. You could try ActivePython. I regularly install and uninstall ActivePython 2.3 and 2.4 installers and both installs are still working fine. Cheers, Trent -- Trent Mick trentm at activestate.com From radeex at gmail.com Sun Dec 19 04:55:20 2004 From: radeex at gmail.com (Christopher Armstrong) Date: Sun, 19 Dec 2004 20:55:20 +1100 Subject: symbol not found involving dynlink/dlopen/embedding Python Message-ID: <60ed19d404121901556de962bf@mail.gmail.com> With the following situation, Numarray can't find Python's symbols. problematic-Python:: Main dlopens Two Two dynlinks Python Python dlopens Numarray Numarray dynlinks Python I have another pure-C example that tries to mirror this, with:: minimal-C:: Main dlopen Two Two dynlink Middle Middle dlopen Three Three dynlink Middle and it works fine. AFAICT, I'm using the same dlopen flags that Python is. The minimal reproduction code is very small, but broken into several files (to emulate the different parts). It's browsable at http://twistedmatrix.com/users/radix/dynlink-problem , and downloadable at http://twistedmatrix.com/users/radix/dynlink-problem/dynlink-problem.tar.gz After doing some googling, I've found several people that look like they have similar problems. I even found one workaround involving LD_PRELOAD. if you LD_PRELOAD=python2.3.so ./main, then the symbols are found. Does anyone have any idea on how I can solve this? I'd like to not hack CPython, and not have tie the build to a single machine. -- Twisted | Christopher Armstrong: International Man of Twistery Radix | -- http://radix.twistedmatrix.com | Release Manager, Twisted Project \\\V/// | -- http://twistedmatrix.com |o O| | Founding Member, Hobart Hacking Society w----v----w-+ -- http://hackingsociety.org/chapters/hash From ncoghlan at email.com Fri Dec 3 07:56:26 2004 From: ncoghlan at email.com (Nick Coghlan) Date: Fri, 03 Dec 2004 22:56:26 +1000 Subject: help running python in a limited interpreted environment In-Reply-To: <1102019250.812710.249120@c13g2000cwb.googlegroups.com> References: <1102019250.812710.249120@c13g2000cwb.googlegroups.com> Message-ID: <41b06278$0$25772$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Mike wrote: > AttributeError: 'module' object has no attribute 'xxx' > > We know the calling script finds the necessary modules, and the > attribute clearly appears in the module's .py file. > > Can anyone tell me what the problem is or if what we're trying to do is > not possible? Is there something in addition to the .dll that needs to > be present? Are there any circular imports in the scripts (e.g. A imports B which imports C which imports A)? This error message is sometimes seen when attempting to access attributes of a module which is still in the process of being imported. There are a couple of bug reports on Source Forge about it - it hasn't been fixed yet, mainly because it's a damn hard problem in need of a solution that is still to be found ;) The simplest resolution is to find a way to break the circularity (usually by moving the code responsible for the circularity to a different - possibly new - module) If you don't have any circular imports, then I'm out of ideas :) Cheers, Nick. From steven.bethard at gmail.com Sun Dec 26 19:38:33 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 27 Dec 2004 00:38:33 GMT Subject: list addition methods compared. In-Reply-To: References: <34534aed0412252012638c85fd@mail.gmail.com> <34534aed04122615176056a0a9@mail.gmail.com> Message-ID: Ishwor wrote: > Could u run the code in your machine and perhaps and let me know what > the average speed is?? > The code is - [snip code not using timeit] Are you aware of the timeit module? It can do most of these timings for you. Here's the code I used: ------------------------------ extend.py ------------------------------ def add(items): lst = [] for item in items: lst = lst + [item] def iadd(items): lst = [] for item in items: lst += [item] def extend(items): lst = [] for item in items: lst.extend([item]) def extend_ext(items): lst = [] ext = lst.extend for item in items: ext([item]) def append(items): lst = [] for item in items: lst.append(item) ---------------------------------------------------------------------- and here's the commands I ran (using Python 2.4)[1]: $ python -m timeit -s "import extend; items = range(10000)" "extend.add(items)" 10 loops, best of 3: 588 msec per loop $ python -m timeit -s "import extend; items = range(10000)" "extend.iadd(items)" 100 loops, best of 3: 9.68 msec per loop $ python -m timeit -s "import extend; items = range(10000)" "extend.extend(items)" 100 loops, best of 3: 11.5 msec per loop $ python -m timeit -s "import extend; items = range(10000)" "extend.extend_ext(items)" 100 loops, best of 3: 9.09 msec per loop $ python -m timeit -s "import extend; items = range(10000)" "extend.append(items)" 100 loops, best of 3: 4.5 msec per loop A few things worth noting: (1) I didn't see the top of this thread, but I'm assuming that you've got a conditional or something in your real loop or you could just use lst.extend(items) without ever iterating over the items list. Your real code may actually require extend-style functionality, but as the results above show, if you really only have one item to add, list.append is definitely the better way to go. (2) Yes, using += is slightly faster than list.extend, but only because "lst.extend" requires an extra attribute lookup. If you factor that out (like I did with the line "ext = lst.extend") then list.extend is slightly faster. (Not surprising, as the function list_inplace_concat (+=) calls the function listextend (list.extend) in listobject.c) (3) That being said, extend_ext is almost certainly premature optimization. =) Steve [1] You can still use timeit without Python 2.4, but you'll have to call timeit.py directly instead of the "python -m timeit" command I used. From eino at iki.fi Mon Dec 13 07:00:01 2004 From: eino at iki.fi (=?ISO-8859-1?Q?Eino_M=E4kitalo?=) Date: Mon, 13 Dec 2004 14:00:01 +0200 Subject: urllib2 and Set-Cookie with "302 Moved temporarily" Message-ID: <6vfvd.703$aM4.37@reader1.news.jippii.net> It seems that urrlib2 default redirection does not allow me to handle Cookies. Service I'm trying seems to use IP switcher and session id's with cookies. After successful login it changes session id (PD-H_SESSION-ID) in 302 Moved temporarily. Urllib2 is so clever that it handles redirection but with wrong cookies. Some hookings? Just own version from source. What is the most lazy way to handle this. Older urllib? Eino --------------------------------- HTTP/1.x 302 Moved Temporarily Set-Cookie: BIGipServerWWW511_HTTP_Pool=1829440010.20480.0000; expires=Mon, 13-Dec-2004 11:55:59 GMT; path=/ Set-Cookie: PD-H-SESSION-ID=4_w5sBH4QGJ+UqZ0nfWTduFl4yYQj8WToCPG3PO-NPo9sAAslb; Path=/ Set-Cookie: PD-H-SESSION-ID=4_w5sBH4QGJ+UqZ0nfWTduFl4yYQj8WToCPG3PO-NPo9sAAslb; Path=/ Date: Mon, 13 Dec 2004 11:25:59 GMT Message-Id: c365e552-4cf9-11d9-ab36-0a0a0b61aa77 Cache-Control: no-cache Pragma: no-cache Connection: close Location: https://xxx/yyy/xxx/RepresentationApp Content-Type: text/html From simonwittber at gmail.com Sun Dec 19 19:57:53 2004 From: simonwittber at gmail.com (Simon Wittber) Date: Mon, 20 Dec 2004 08:57:53 +0800 Subject: atmosphere on c.l.py (WAS: How about "pure virtual methods"?) In-Reply-To: References: <1gp06r8.10q8off1j9v6nvN%aleaxit@yahoo.com> <1103448439.953120.209950@c13g2000cwb.googlegroups.com> <1gp1415.10zjxtu1cfp9cxN%aleaxit@yahoo.com> <1gp1afn.udxyw81p5gajqN%aleaxit@yahoo.com> <1gp1m3i.1e39lko1nsv2z8N%aleaxit@yahoo.com> Message-ID: <4e4a11f804121916571d4a542d@mail.gmail.com> > I do understand the feeling though; Fredrik Lundh jumped at me only a > few days ago when I said that I personally found list comprehensions > more readable than map. I certainly don't mind being advised or > corrected if I've written incorrect or even just suboptimal code, but > attacking a person's mental processes seems kind of needlessly > aggressive to me. We've just had a Python 2.4 release, and poor Mr Lundh has likely had hundreds of user's clamouring for a binary, 2.4 compatible PIL release. That's enough to make any programmer grumpy. Sw. From dd55 at cornell.edu Fri Dec 3 13:39:32 2004 From: dd55 at cornell.edu (Darren Dale) Date: Fri, 03 Dec 2004 13:39:32 -0500 Subject: question on regular expressions References: <41b0b0f6$1_3@omega.dimensional.com> Message-ID: Michael Fuhr wrote: > Darren Dale writes: > >> I'm stuck. I'm trying to make this: >> >> file://C:%5Cfolder1%5Cfolder2%5Cmydoc1.pdf,file://C >> %5Cfolderx%5Cfoldery%5Cmydoc2.pdf >> >> (no linebreaks) look like this: >> >> ./mydoc1.pdf,./mydoc2.pdf >> >> my regular expression abilities are dismal. > > This works for the example string you gave: > > newstring = re.sub(r'[^,]*%5[Cc]', './', examplestring) > > This replaces all instances of zero or more non-commas that are > followed by '%5C' or '%5c' with './'. Greediness causes the pattern > to replace everything up to the last '%5C' before a comma or the > end of the string. > > Regular expressions aren't the only way to do what you want. Python > has standard modules for parsing URLs and file paths -- take a look > at urlparse, urllib/urllib2, and os.path. > Thanks to both of you. I thought re's were appropriate because the string I gave is buried in an xml file. A more representative example is: [...snip...]file://C:%5Cfolder1%5Cfolder2%5Cmydoc1.pdf[...snip... data]file://C%5Cfolderx%5Cfoldery%5Cmydoc2.pdf[...snip...] From ahaas at airmail.net Tue Dec 21 15:13:36 2004 From: ahaas at airmail.net (Art Haas) Date: Tue, 21 Dec 2004 14:13:36 -0600 Subject: [ANNOUNCE] Twentieth release of PythonCAD now available Message-ID: <20041221201336.GA2725@artsapartment.org> Hi. I'm pleased to announce the twentieth development release of PythonCAD, a CAD package for open-source software users. As the name implies, PythonCAD is written entirely in Python. The goal of this project is to create a fully scriptable drafting program that will match and eventually exceed features found in commercial CAD software. PythonCAD is released under the GNU Public License (GPL). PythonCAD requires Python 2.2 or Python 2.3. The interface is GTK 2.0 based, and uses the PyGTK module for interfacing to GTK. The design of PythonCAD is built around the idea of separating the interface from the back end as much as possible. By doing this, it is hoped that both GNOME and KDE interfaces can be added to PythonCAD through usage of the appropriate Python module. Addition of other PythonCAD interfaces will depend on the availability of a Python module for that particular interface and developer interest and action. The twentieth release of PythonCAD improves the undo/redo abilities of the program by making layer creation and deletion actions that can be undone or redone. Also, the addition and removal of chamfers and fillets is now an undoable and redoable action. The code for managing undo/redo operations has been improved, and various bug fixes for these actions have been applied. Another improvement in this release is a reworked set of file saving operations. The code for saving a file onto disk has been made more robust by adding additional error checks and by ensuring the new version of a file is stored successfully prior to replacing the existing copy. A good number of bug fixes and code improvements are included in this release as well. PythonCAD is now two years old! The first public release was on December 21, 2002. Celebrate PythonCAD's second birthday by downloading and installing the twentieth release! The mailing list for the development and use of PythonCAD is available. Visit the following page for information about subscribing and viewing the mailing list archive: http://mail.python.org/mailman/listinfo/pythoncad Visit the PythonCAD web site for more information about what PythonCAD does and aims to be: http://www.pythoncad.org/ Come and join me in developing PythonCAD into a world class drafting program! Art Haas -- Man once surrendering his reason, has no remaining guard against absurdities the most monstrous, and like a ship without rudder, is the sport of every wind. -Thomas Jefferson to James Smith, 1822 From jeff at ccvcorp.com Thu Dec 9 15:38:09 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 09 Dec 2004 12:38:09 -0800 Subject: How do I do this? (eval() on the left hand side) In-Reply-To: References: <10rh37tt58vv362@corp.supernews.com> Message-ID: <10rhdm078jri91d@corp.supernews.com> Peter Hansen wrote: > The main way I use this is in some sort of a "const" module, which > provides access to a large set of constant information. In other > words, in contrast to what you had in mind when you wrote the > above, I'm dealing with neither "variables" nor information that > _would_ best be put in a dict. > > [...] > > In general I would say that mucking with globals() like this is > probably best restricted to constants like in this case, if at all. Indeed, for almost every rule, there are exceptions.. Legitimate cases also exist for using eval() and exec, though in general both of those are better avoided. The case you describe does sound like a legitimate use of writing to globals(), with realistic expectations of the costs and benefits (Actually, in your provided example, I might have const.py parse the header file into a dict named const, and then have my modules use 'from const import const'. But I will admit that the extra complication on import may not be worth the "cleaner" module internals... As always, it's a tradeoff, and each programmer must decide which costs are worth bearing in their particular situation.) Jeff Shannon Technician/Programmer Credit International From simon.brunning at gmail.com Wed Dec 29 11:15:53 2004 From: simon.brunning at gmail.com (Simon Brunning) Date: Wed, 29 Dec 2004 16:15:53 +0000 Subject: extract news article from web In-Reply-To: <1103736135.209100.28900@z14g2000cwz.googlegroups.com> References: <1103736135.209100.28900@z14g2000cwz.googlegroups.com> Message-ID: <8c7f10c60412290815210f2bac@mail.gmail.com> On 22 Dec 2004 09:22:15 -0800, Zhang Le wrote: > Hello, > I'm writing a little Tkinter application to retrieve news from > various news websites such as http://news.bbc.co.uk/, and display them > in a TK listbox. All I want are news title and url information. Well, the BBC publishes an RSS feed[1], as do most sites like it. You can read RSS feed with Mark Pilgrim's Feed Parser[2]. Granted, you can't read *every* site like this. But I daresay that *most* news related sites publish feeds of some kind these days. Where they do, using the feed is a *far* better idea than trying to parse the HTML. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ [1] http://news.bbc.co.uk/2/hi/help/3223484.stm [2] http://feedparser.org/ From mefjr75 at hotmail.com Thu Dec 30 13:27:42 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 30 Dec 2004 10:27:42 -0800 Subject: need some help with threading module... References: <41cf2610$0$791$8fcfb975@news.wanadoo.fr> <41cf373e$0$786$8fcfb975@news.wanadoo.fr> <1104102769.321923.4140@z14g2000cwz.googlegroups.com> <41d0515b$0$30648$8fcfb975@news.wanadoo.fr> <1104178961.065566.7660@z14g2000cwz.googlegroups.com> <41d3dc20$0$29646$8fcfb975@news.wanadoo.fr> Message-ID: <1104431262.457172.295520@c13g2000cwb.googlegroups.com> chahnaz.ourzikene wrote: > Hi, > > I fixed the code, it runs under Linux but not under windows 0_o ??! i guess > windows and Linux do not handle threads the same way. > > However, i don't have the result i excpect. What did you expect? This is what it did on win 2000/python 2.2.3 ######> controller waiting... 0 loops ######> controller waiting... 1 loops Subject : the counter is now 0 ######> controller waiting... 2 loops Subject : the counter is now 1 ######> controller waiting... 3 loops Subject : the counter is now 2 ######> controller waiting... 4 loops Subject : the counter is now 3 Subject : the counter is now 4 ######> controller waiting... 5 loops Subject : the counter is now 5 ######> controller waiting... 6 loops Subject : the counter is now 6 ######> controller waiting... 7 loops Subject : the counter is now 7 Subject : the counter is now 8 ######> controller waiting... 8 loops Subject : the counter is now ######> controller waiting... 9 loops 9 Subject : the counter is now 10 ######> controller waiting... 10 loops Subject : the counter is now 11 Subject : the counter is now 12 ######> controller waiting... 11 loops Subject : the counter is now 13 ######> controller waiting... 12 loops Subject : the counter is now ######> controller waiting... 13 loops 14 Subject : the counter is now 15 ######> controller waiting... 14 loops Subject : the counter is now 16 ######> controller waiting... 15 loops Subject : the counter is now 17 ######> controller waiting... 16 loops Subject : the counter is now 18 Subject : the counter is now 19 ######> controller waiting... 17 loops Subject : the counter is now 20 controller : threshold 20 reached Subject : the counter is now 21 Subject : the counter is now 22 Subject : the counter is now 23 Subject : the counter is now 24 Subject : the counter is now 25 Subject : the counter is now 26 Subject : the counter is now 27 Subject : the counter is now 28 Subject : the counter is now 29 Subject : the counter is now 30 Subject : the counter is now 31 Subject : the counter is now 32 Subject : the counter is now 33 Subject : the counter is now 34 Subject : the counter is now 35 Subject : the counter is now 36 Subject : the counter is now 37 Subject : the counter is now 38 Subject : the counter is now 39 It seems to be what you were trying to do. M.E.Farmer From bokr at oz.net Wed Dec 29 23:46:25 2004 From: bokr at oz.net (Bengt Richter) Date: Thu, 30 Dec 2004 04:46:25 GMT Subject: Other notes References: <1104287020.804167.9420@f14g2000cwb.googlegroups.com> <863bxpuhlj.fsf@guru.mired.org> <41d35721.1382016815@news.oz.net> Message-ID: <41d380f1.1392720936@news.oz.net> On Thu, 30 Dec 2004 03:37:38 GMT, Andrew Dalke wrote: >Bengt Richter: >> OTOH, there is precedent in e.g. fortran (IIRC) for named operators of the >> form .XX. -- e.g., .GE. for >= so maybe there could be room for both. > >> Hm, you could make >> >> x .infix. y > > >> x .op1. y .op2. z => op2(op1(x, y), z) > >The problem being that that's already legal syntax D'oh ;-) > >>>> class Xyzzy: >... def __init__(self): >... self.op1 = self.op2 = self.y = self >... self.z = "Nothing happens here" >... >>>> x = Xyzzy() >>>> x .op1. y .op2. z >'Nothing happens here' >>>> Ok, well, that's happened to me before ;-) We'll have to find a way to make it illegal, but it's not likely to be quite as clean. x ..OP y x ./OP y x .. y X ._OP_. y x ..OP.. y # for symmetry ;-) X .(OP). y # emphasizes the .expression. returning a function accepting two args That might be the best one. OTOH some time ago I was thinking of .(statements). as a possible tokenizer-time star-gate into a default-empty tokenizer-dynamically-created module which would essentially exec the statements in that module and return the value of the last expression as a string for insertion into the token source code stream at that point being tokenized. Thus e.g. you could have source that said compile_time = .(__import__('time').ctime()). and get a time stamp string into the source text at tokenization time. I had also thought obj.(expr) could be syntactic sugar for obj.__dict__[expr] but that would also interfere ;-) So maybe .(OP). should for infix, and .[stargate exec args]. should be for that ;-) Regards, Bengt Richter From jason at tishler.net Thu Dec 16 07:16:46 2004 From: jason at tishler.net (Jason Tishler) Date: Thu, 16 Dec 2004 07:16:46 -0500 Subject: cygwin python.exe symlink breaks when called from .bat file In-Reply-To: <20041215133603.7622f3bc.gry@ll.mit.edu> References: <1103124090.964619.74430@c13g2000cwb.googlegroups.com> <20041215155617.GA1560@tishler.net> <20041215133603.7622f3bc.gry@ll.mit.edu> Message-ID: <20041216121646.GA420@tishler.net> George, Please keep your replies on-list. On Wed, Dec 15, 2004 at 01:36:03PM -0500, george young wrote: > On Wed, 15 Dec 2004 10:56:17 -0500 > Jason Tishler threw this fish to the penguins: > > On Wed, Dec 15, 2004 at 07:21:31AM -0800, gry wrote: > > > Under cygwin, the python executable is installed as python2.4.exe > > > with a symbolic link to python.exe. This is fine as long as one > > > is operating only withing the cygwin world. But I execute python > > > from a foo.bat file, and windows barfs on the symbolic link. > > > > You can always do the following as a workaround: > > > > C:\> bash -c python > > Hmm, that's fine for typing a command interactively, but try fitting > it into a DOS "ftype" command so that double-clicking a .py file gets > the right thing with the right args -- nasty, I couldn't get it to > work. Since you are looking for tight integration with Windows, maybe you should use Win32 Python? > > > I replaced it with a hard link and all is well. > > > > Note the above will only work as a true hard link under NTFS. IMO, > > the above is a better approach. > > > > > Is there some reason this shouldn't be the standard installation > > > under cygwin? > > > > Because it would require (more) modification of the Unix build to > > accommodate Windows. IMO, it is not worth the effort. If you feel > > differently, then submit a patch for consideration: > > > > http://sf.net/tracker/?func=add&group_id=5470&atid=305470 > > I'll try that... maybe I can light a fire. > > > BTW, many other Cygwin commands have this issue too: > > > > $ find /bin -type l -name '*.exe' > > /bin/awk.exe > > /bin/c++.exe > > /bin/captoinfo.exe > > /bin/cc.exe > > ... Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From google0 at lazytwinacres.net Wed Dec 8 06:00:09 2004 From: google0 at lazytwinacres.net ('Dang' Daniel Griffith) Date: Wed, 08 Dec 2004 06:00:09 -0500 Subject: Python for Palm OS? References: <41b687a6$1@news.unimelb.edu.au> Message-ID: <1102503610.719e8b3b58818b4cc497ed7bab4b30b8@teranews> On Wed, 08 Dec 2004 04:48:42 GMT, Maurice LING wrote: >As mentioned, since Pippy is pretty old or rather based on rather old >code base, can it be assumed that not much is happening at this front? > >This might be dumb to ask then, does anyone know if Pippy had been used >in any noticeable form for Palm development anywhere? Or it's more of an >proof of concept kind of thing? Or has anyone envisioned anything? > >Cheers >Maurice I think their web site (at one time, at least) explicitly said they had stopped development of Pippy. I use it on rare occasions when I need a programmable calculator. But since it only supports 32-bit integer math, i.e., not float or long, that's a pretty limited occasion. It appears to have access to Palm "form" capabilities, but I was never able to figure out how they work. The docs are a little light. Still, I'm impressed that they got it there in the first place. I also saw the Lua port, but have not installed it, yet. I was too busy with Carmen Electra. Or, at least, envisioning Carmen Electra. ;-) --dang From wccppp at yahoo.com Sun Dec 26 04:59:34 2004 From: wccppp at yahoo.com (wccppp at yahoo.com) Date: 26 Dec 2004 01:59:34 -0800 Subject: where is ctypes.py? Message-ID: <1104055174.719604.287630@c13g2000cwb.googlegroups.com> Hello, I'm a complete newbie in learning python. I was testing some sample codes I found in this newsgroup and seems it could not locate the module ctypes.py. I installed python 2.4, wxPython and pywin32. Just could not find this file. I thought it should be in Lib/site-packages/ directory but it is not there. Where can I find this file? Thanks a lot for your help. - wcc From steven.bethard at gmail.com Sun Dec 19 15:03:54 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 19 Dec 2004 20:03:54 GMT Subject: Is this a good use for lambda In-Reply-To: References: Message-ID: Walter S. Leipold wrote: > I've used lambda from time to time, but only socially, and I can quit any > time I want... +1 QOTW Steve From siona at chiark.greenend.org.uk Fri Dec 10 08:28:05 2004 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 10 Dec 2004 13:28:05 +0000 (GMT) Subject: wxPython bug References: <3APtd.4339201$yk.652531@news.easynews.com> Message-ID: Jive wrote: >In wxPython 2.5, run the demo, samples/wxProject/wxProject.py > [ ... ] >TypeError: TreeCtrl_GetFirstChild() takes exactly 2 arguments (3 given) GetFirstChild() changed from taking 2 arguments in wxPython 2.4 to (the more sensible) 1 in wxPython 2.5. Clearly wxProject hasn't been thoroughly 2.5ified. (Looking at it, it's not using the wx namespace, so I'd say it's not been 2.5ified at all.) >What to do? (a) Fix your copy of wxProject.py (someone else has already pointed this out). (b) File a bug report (http://sourceforge.net/tracker/?group_id=9863&atid=109863) with a "wxPython specific" category. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From jcarlson at uci.edu Fri Dec 3 19:28:30 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Fri, 03 Dec 2004 16:28:30 -0800 Subject: using cmd.exe as a telnet client In-Reply-To: References: Message-ID: <20041203162634.ECC3.JCARLSON@uci.edu> Donnal Walter wrote: > > Several months ago I tried using the telnet module (on Windows XP) to > communicate with a proprietary host on our network. This was > unsuccessful due to problems with "option negotiation", and I gave up on > the project for a while. I still have need for this, however, so I > recently started thinking about alternatives. I suppose I could dig deep > enough into option negotiation to use the socket module (with telnet as > a guide), but I am hoping to find a way to use fewer synapses. > > Using the Windows C:> prompt (cmd.exe) I can telnet into this host with > no problems (the Windows telnet client performs option negotiation just > fine). Is there a straightforward way of using os.popen() (or os.fork() > or os.exec*() or os.wait*()) to connect to the host from Python via the > Windows telnet client? I am sure it is possible with a little bit of pywin32 business. You may have better luck with the new subprocess module in Python 2.4, as it is written with communication to/from console applications in mind. - Josiah From rnd at onego.ru Fri Dec 10 15:52:29 2004 From: rnd at onego.ru (Roman Suzi) Date: Fri, 10 Dec 2004 23:52:29 +0300 (MSK) Subject: Decorators for multimethods Message-ID: hi! I've found one more nice use case for decorators. I feel multimethods could be made even nicier by defining multimethods inside special class. But I have not figured out how to do it yet. #!/bin/env python2.4 if "We have Neel Krishnaswami module Multimethod.py": import Multimethod class Foo: pass class Bar(Foo): pass def multimethod(g, *args): def make_multimethod(func): mm = Multimethod.Method(tuple(args), func) g.add_method(mm) return mm return make_multimethod g = Multimethod.Generic() @multimethod(g, Foo, Foo) def m1(a, b): return 'foofoo' @multimethod(g, Foo, Bar) def m2(a, b): return 'foobar' @multimethod(g, Bar, Foo) def m3(a, b): return 'barfoo' try: print 'Argtypes ', 'Result' print 'Foo, Foo:', g(Foo(), Foo()) print 'Foo, Bar:', g(Foo(), Bar()) print 'Bar, Foo:', g(Bar(), Foo()) print 'Bar, Bar:', g(Bar(), Bar()) except Multimethod.AmbiguousMethodError: print 'Failed due to AmbiguousMethodError' Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From paul.dubois at gmail.com Tue Dec 7 00:12:05 2004 From: paul.dubois at gmail.com (Paul Du Bois) Date: 6 Dec 2004 21:12:05 -0800 Subject: Deadlock detection In-Reply-To: References: <361d0$41b440c1$51604868$26492@nf1.news-service-com> Message-ID: <1102395597.917783.13370@z14g2000cwz.googlegroups.com> (warning: pedantic and off-topic response) NP-Complete does not mean "equivalent to the halting problem." It means "poly-time equivalent to any other NP-Complete problem". NP-Complete problems are "only" exponential-time. The halting problem is much harder! And of course, just the fact that a problem is NP-complete doesn't mean that you can't construct algorithms that do a pretty good job a pretty good fraction of the time. From Scott.Daniels at Acm.Org Thu Dec 16 11:34:42 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 16 Dec 2004 08:34:42 -0800 Subject: Best book on Python? In-Reply-To: <10rpv26jonj3620@corp.supernews.com> References: <10rpv26jonj3620@corp.supernews.com> Message-ID: <41c1b804$1@nntp0.pdx.net> Esmail Bonakdarian wrote: > I myself am looking for a small portable quick > reference, thinking about the O'Reilly pocket guide > but I'm not sure how good it is. I read on amazon > that it doesn't have an index - that seems odd for > any book, and esp a quick ref. Look into Python Essential Reference for that kind of book -- no fat, lotsa goodies. --Scott David Daniels Scott.Daniels at Acm.Org From hsivonen at iki.fi Mon Dec 27 10:22:16 2004 From: hsivonen at iki.fi (Henri Sivonen) Date: Mon, 27 Dec 2004 17:22:16 +0200 Subject: Red Robin Jython & JDK classes Message-ID: I am trying to set up the Red Robin Jython Development Tools for Eclipse. It finds the Python libraries of Jython and my own jars. It does not find the JDK classes. If I try to add classes.jar from the JDK to the "Jython Class Path" of the project, the plug-in no longer finds even my own Java classes. How do I make the plug-in see the JDK classes? I am using Eclipse 3.0.1, Mac OS X 10.3.7, Java 1.4.2_05, Jython 2.1 and Red Robin Jython Development Tools 1.3.9. -- Henri Sivonen hsivonen at iki.fi http://iki.fi/hsivonen/ From cm012b5105 at blueyonder.co.uk Fri Dec 3 16:42:37 2004 From: cm012b5105 at blueyonder.co.uk (cm012b5105) Date: Fri, 3 Dec 2004 21:42:37 +0000 Subject: Graphical box /interactive programme Message-ID: <200412032142.37560.cm012b5105@blueyonder.co.uk> Hello i want to put an interactive text programme in to a graphical box this is a small section of my text programme s = raw_input ("Hello whats your name? ") if s=='melvyn': print "your my boss's Dad the one they call in indian language DEEP THOUGHT LITTLE HORSE" if s=='carol': print "ahhh you are my boss's mom the one they call WREATH WOMAN" if s=='rebecca': print "you must be the FLORIST WOMAN" if s=='gareth': print "you must be the one they call the TRUCKER" if s=='carmel': print "you must be my boss's wife" s = raw_input ("what do you do for a living? ") print "Ahh thats easy you dont do much then",s,"my boss is a Truck driver." these are the instructions for a graphical boxfrom Tkinter import * root = Tk() cv = Canvas(root, width=400, height=300, bg="blue") cv.pack() cv.create_rectangle(50,30,320,290,outline="yellow",fill="red",width=10) mainloop() any way what i would like to do is create a programme that would run my text programme from this graphical box i tried to add the code for the box to the top of my text programme but when i run it i get the graphical box come up and my text programme will not work untill i kill the box. i would be graet full if some body can help me acheive this. thanks nige From harry.g.george at boeing.com Wed Dec 1 10:39:28 2004 From: harry.g.george at boeing.com (Harry George) Date: Wed, 1 Dec 2004 15:39:28 GMT Subject: SOAPpy/ZSI/Twisted SOAP over stdin/stdout? References: Message-ID: Harry George writes: > Normally the SOAP Servers are designed to take control of a port and > run their own sockets via inheritance from SocktServer. > > But under inetd and xinetd, the port is controlled elsewhere and the > service just gets the stdin/stdout. I need to configure (or tweak) one > of the SOAP servers to use that connection. > > Has anyone done this with any of the above named SOAP servers? > Recommmendations or hints if I try it myself? First, thanks for the hints - I definitely want to investigate Twisted "basic". Second, I've solved it by doing an xinetd "redirect". Do external control on one port, then pass the data to an internal-only port which is watched by the SOAP server. -- harry.g.george at boeing.com 6-6M21 BCA CompArch Design Engineering Phone: (425) 294-4718 From aleaxit at yahoo.com Thu Dec 30 05:37:37 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 30 Dec 2004 11:37:37 +0100 Subject: GUI with sophisticated Table support References: Message-ID: <1gplurv.1an8odt186rwsbN%aleaxit@yahoo.com> Torsten Mohr wrote: > My question here is rather in detail about Tkinters Table and if it can > show resizable columns tho easily display a list of objects. > > I did not find any help searching for this with google, but i'd really > rather like to use Tkinter over wxPython, that's the background of the > question. Hmmm -- there's a tktable (on sourceforge) which claims to have resizable columns and a Python/Tkinter wrapper, but I haven't tried it, myself. tktable.sourceforge.net for more info... Alex From mcfletch at rogers.com Fri Dec 10 13:44:40 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Fri, 10 Dec 2004 13:44:40 -0500 Subject: Compiling Python 2.4 extensions with free VC++ Toolkit In-Reply-To: <1Qlud.477123$%k.427789@pd7tw2no> References: <1Qlud.477123$%k.427789@pd7tw2no> Message-ID: <41B9EE98.3050109@rogers.com> Jody at bag.python.org wrote: > Hi all, > > I've been wondering if there's anything on the drawing board about > patching distutils/msvccompiler.py so that it can compile Python > extensions using the free Visual C++ toolkit instead of the entire > Visual C++ development environment. I've got a patch for msvccompiler.py as part of my Toolkit recipe here: http://www.vrplumber.com/programming/mstoolkit/ it seems to work fairly well for those who have tried it, and should allow MSVC 7.1 to override MSToolkit if it's installed... i.e. it should work on non-toolkit installs as well (don't have MSVC 7.1 to test that, but the changes shouldn't alter "normal" usage). > I know it's possible, because I was able to compile and install > PyCrypto 2.0 for Python 2.4 today. I did this by commenting out the > part of msvccompiler that checks for VS library paths and manually > adding them to my LIB environment variable. If you feel like it, try with the patch/recipe above. It should avoid any extra work regarding fiddling with paths on a per-package basis (though that's just because it puts the path setup into the vc7.bat file and then tells distutils to look in the environment for them). Have fun, Mike BTW, what is with that funky 7-person garbage "From:" list in your message header? Some messed-up attempt at spam-catching? Rather annoying in Thunderbird, as it generates 7 garbage "To" headers when doing a reply-to-all to catch the mailing-list. Might want to fix that... ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From tim.peters at gmail.com Thu Dec 16 22:22:29 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 16 Dec 2004 22:22:29 -0500 Subject: os.walk bug? In-Reply-To: <1103249819.5175.6.camel@localhost.localdomain> References: <2814F26DA6908F41927A81C410C4991A02079BFC@siamun.server.bl.corp.intranet> <1103249819.5175.6.camel@localhost.localdomain> Message-ID: <1f7befae04121619221ce909c7@mail.gmail.com> [Adam DePrince] > Each iteration of os.walk returns three parameters; one of those, > dirs, is a list of directories within the current directory pointed at > by root. Right. > Am I correct to assume that you beleve that by changing the > contents of dir you will affect how os.walk traverses the > directories. If so, that is your problem. Nope, mutating dirs is the intended way to prune (or even to augment) os.walk's search tree on the fly See the docs. Gabriel's problem was mutating dirs while iterating over it in another level of loop; while os.walk() expects that its caller may mutate dirs, and "does the right thing" if the caller does, Gabriel's own loop wasn't safe against mutation during iteration. From rootshell at gazeta.pl Thu Dec 9 14:10:46 2004 From: rootshell at gazeta.pl (rootshell at gazeta.pl) Date: Thu, 9 Dec 2004 20:10:46 +0100 Subject: [Newby] Problem with compilation. Message-ID: <018e01c4de22$ce0d77e0$83881d53@unqku4k1fl8nea7> Hi folks! Can't compile my file due to some problems with crypt module. My platform is WinXP: First I launch my Python Shell, Than I open the *.py file, Next I press F5 to 'run module' The message is: "ImportError: No module named crypt" Few lines of code for example: ... import posix import posixpath from crypt import * startRecord = 0 inRecord = 1 ... Thanks for help. From gry at ll.mit.edu Fri Dec 10 10:45:47 2004 From: gry at ll.mit.edu (george young) Date: Fri, 10 Dec 2004 10:45:47 -0500 Subject: style query: function attributes for return codes? Message-ID: <20041210104547.209a2b47.gry@ll.mit.edu> [python 2.3.3, x86 linux] I recently found myself writing something like: def get_connection(): if tcp_conn(): if server_allows_conn(): return 'good_conn' else: return 'bad_auth' else: return 'no_server' cn = get_connection() if cn == 'good_con': ... This is obviously just evil, since a misspelling in the string return is treacherous. I'm considering function attributes: def get_connection(): if tcp_conn(): if server_allows_conn(): return get_connection.GOOD else: return get_connection.BAD_AUTH else: return get_connection.NO_SERVER get_connection.GOOD = 1 get_connection.BAD_AUTH = 2 get_connection.NO_SERVER = 3 If I put this function in it's own module, the solution is obvious: GOOD_CONN = 1 def get_connection(): ... return GOOD_CONN But if this is a small utility function that belongs inside a larger module/class, I would like to have it's return values closely associated with the function, not just another value in the parent class. Is anybody using function attributes like this? Is this good python style? -- George Young -- "Are the gods not just?" "Oh no, child. What would become of us if they were?" (CSL) From jepler at unpythonic.net Wed Dec 29 14:25:01 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Wed, 29 Dec 2004 13:25:01 -0600 Subject: copying classes? In-Reply-To: <1104346382.3398.73.camel@localhost.localdomain> References: <9C0FD378-59C7-11D9-927C-003065FB7B26@upf.edu> <1104345746.3398.69.camel@localhost.localdomain> <1104346382.3398.73.camel@localhost.localdomain> Message-ID: <20041229192501.GD15208@unpythonic.net> You copied an instance, not a class. Here's an example of attempting to deepcopy a class: >>> class X: pass ... >>> import copy >>> X is copy.deepcopy(X) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.2/copy.py", line 179, in deepcopy raise error, \ copy.Error: un-deep-copyable object of type In theory, one could provide a metaclass that allows copying of instances of that metaclass. I'll leave this as an exercise to the reader. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From steve at holdenweb.com Wed Dec 22 15:34:11 2004 From: steve at holdenweb.com (Steve Holden) Date: Wed, 22 Dec 2004 15:34:11 -0500 Subject: extract news article from web In-Reply-To: References: <1103736135.209100.28900@z14g2000cwz.googlegroups.com> Message-ID: <3Wkyd.59263$Jk5.44997@lakeread01> Steve Holden wrote: [...] > However, the code to extract the news is pretty simple. Here's the whole > program, modulo newsreader wrapping. It would be shorter if I weren't > stashing the extracted links it a relational database: > [...] I see that, as is so often the case, I only told half the story, and you will be wondering what the "db" module does. The main answer is adapts the same logic to two different database modules in an attempt to build a little portability into the system (which may one day be open sourced). The point is that MySQLdb requires a "%s" in queries to mark a substitutable parameter, whereas mxODBC requires a "?". In order to work around this difference the db module is imported by anything that uses the database. This makes it easier to migrate between different database technologies, though still far from painless, and allows testing by accessing a MySQL database directly and via ODBC as another option. Significant strings have been modified to protect the innocent. -------- # # db.py: establish a database connection with # the appropriate parameter style # try: import MySQLdb as db conn = db.connect(host="****", db="****", user="****", passwd="****") pmark = "%s" print "Using MySQL" except ImportError: import mx.ODBC.Windows as db conn = db.connect("****", user="****", password="****") pmark = "?" print "Using ODBC" -------- regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From johan at pulp.se Fri Dec 3 04:46:38 2004 From: johan at pulp.se (Johan Lindberg) Date: 3 Dec 2004 01:46:38 -0800 Subject: pickle and py2exe References: <35otq0hc4rrb6qb0fef485c562csvtc39s@4ax.com> Message-ID: >>> Im trying to compile a script with py2exe. The pickle module is causing the >>> program to give an error. >>> >>> Traceback (most recent call last): >>> File "SETIstat.pyw", line 330, in ? >>> File "SETIstat.pyw", line 84, in start_up >>> File "SETIstat.pyw", line 79, in config_load >>> File "pickle.pyc", line 1390, in load >>> File "pickle.pyc", line 872, in load >>> File "pickle.pyc", line 985, in load_string >>> LookupError: unknown encoding: string-escape >>> >>> the data in the pickled file is a dictionary containing a couple >>> strings. The >>> strings do contain \n and \t charaters but no other special characters or >>> anything. >>> >>> Does anyone have any suggestions to what I can try to get around this? The >>> pickle module works fine when the .pyw file is run. Its only when I compile >>> this is there an issue. >>> >>> Thanks for any help, >>> >>> Justin >>Have you included string-escape encoding in your setup.py? >>My guess is that you can fix the problem with something similar to: >> >> from distutils.core import setup >> import py2exe >> opts = { "py2exe": { "packages": ["encodings"], } } >> setup(windows= ["spam.py"], options= opts) >> >>in your setup.py. >> >>Hope it helps >>/Johan Lindberg > Thanks Johan, but unfortunately the same traceback is given in the log. > I should have mentioned in my previous post that Im using win2000, if it > matters any. > Hi Justin. I'm assuming that your library.zip now has several encoding-files in it? And more specifically that you have a file called "string_escape.pyc" in path "encodings". Right? I don't think it's got anything to do with your windows version but it might be helpful to know your python and py2exe versions. Unfortunately I haven't been able to reproduce the error on either of my windows machines (using python 2.3.4 and py2exe 0.5.3 on both, one is win2k and the other XP). Line 985 in pickle.py says: self.append(rep.decode("string-escape")) so that's why you need the encoding, even though you "don't use it". Will the same lookup error show up in a smallest possible program, such as: # encoding= iso-8859-1 spam= "Det h?r ?r svenska" print spam.decode("string-escape") What happens when you compile that script to an exe using the above setup.py? (don't forget to change windows= ["spam.py"] to console= ["spam.py"]) Also you might want to try the py2exe-users list (see http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/py2exe-users). BR /Johan Lindberg From sf_kersteinroie at bezeqint.net Fri Dec 3 05:11:57 2004 From: sf_kersteinroie at bezeqint.net (Roie Kerstein) Date: Fri, 03 Dec 2004 12:11:57 +0200 Subject: Galois field References: Message-ID: Terry Reedy wrote: > Googling python 'galois fields' gives over 500 hits, the most recent being > your identical question on catalog-sig.??Have?you?looked?at?them? Yes. Nothing there is a module. only discussions. :( -- Best regards Roie Kerstein From ncoghlan at iinet.net.au Thu Dec 30 08:33:00 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 30 Dec 2004 23:33:00 +1000 Subject: Computer text recognition (was. Re: Why tuples use parentheses ()'s instead of something else like <>'s?) In-Reply-To: <84BE0DF9-5A66-11D9-B350-003065B11E84@leafe.com> References: <1104299822.394489.161500@z14g2000cwz.googlegroups.com> <84BE0DF9-5A66-11D9-B350-003065B11E84@leafe.com> Message-ID: <41D4038C.1060406@iinet.net.au> Ed Leafe wrote: > Exactly! Now can we clear anything else up for you? ;-) How about a computer program than can correctly count the number of letter E's in your signature? :) Cheers, Nick. I like the sig, if you hadn't guessed. . . -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ebonakDUH at hotmail.com Wed Dec 15 16:33:31 2004 From: ebonakDUH at hotmail.com (Esmail Bonakdarian) Date: Wed, 15 Dec 2004 16:33:31 -0500 Subject: Is Python good for graphics? Message-ID: <10s1bdaj7gbin8e@corp.supernews.com> First of all, I *really* like Python ;-) I need some help with the graphical side of things. I would like to do some basic graphics with Python, but I am not sure what the best/most effective way for me to do what I want. Basically, I would like to be able to create some basic animations where I can help visualize various sorting algorithms (for instance http://ciips.ee.uwa.edu.au/~morris/Year2/PLDS210/sorting.html#insert_anim) or graph searches (coloring nodes as each gets visited). (Something like this: http://cs.smith.edu/~thiebaut/java/graph/Welcome.html) Or to create and manipulate programmatically a simple 2-D block puzzle (like this: http://www.johnrausch.com/SlidingBlockPuzzles/quzzle.htm). Note, the ability to do this via the web would be nice, but definitely is *not* required at the moment. These would be used to help in learning/teaching. I am aware of Tkinter and wxPython (by aware I mean I know of their existence :-) Before investing (a lot?) of time to learn these, I thought I?d ask the more experienced folks around here what would be the best way to invest my time to get basic graphics going. I really am not concerned so much with efficiency as easy of use. Can anyone recommend what would suit my rather limited needs best? Are there other graphics libraries I should consider that would be more suitable? Or is Python not the way to go for this? Thanks! Esmail From __peter__ at web.de Sat Dec 11 18:20:45 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 12 Dec 2004 00:20:45 +0100 Subject: thread/queue bug References: Message-ID: phil wrote: > And sorry I got ticked, frustrating week > > >And I could help more, being fairly experienced with > >threading issues and race conditions and such, but > >as I tried to indicate in the first place, you've > >provided next to no useful (IMHO) information to > >let anyone help you more than this > > This is about 5% of the code. > Uses no locks. A lock is acquired in Queue.__init__(). > I am mystified, I have written probably 100,000 lines > of Python and never seen a thread just lock up and quit > running. It happens on a Queue() statement so my suspicion > is a bug. ?? > > I have kludged around it by putting all the thread/queue stuff > in the main program and import the stuff I don't want to > distribute. But mysteries haunt your dreams, sooo... What I believe to be a minimal example: import Queue import threading import time q = Queue.Queue(4) def proc(): while True: q.get(1) Queue.Queue() print "YADDA" threading.Thread(target=proc).start() while True: print "yadda" q.put(None) time.sleep(1) import freeze Invoking freezemain.py produces yadda yadda yadda yadda yadda yadda i. e. consistently q.maxsize + 2. One item about to be put, one already taken before Queue.Queue(). Deferring execution of the module-level code until after the import import Queue import threading import time q = Queue.Queue(4) def proc(): while True: q.get(1) Queue.Queue() print "YADDA" def start(): threading.Thread(target=proc).start() while True: print "yadda" q.put(None) time.sleep(1) import nofreeze nofreeze.start() and invoking nofreezemain.py produces yadda YADDA yadda YADDA yadda YADDA yadda YADDA apparently ad infinitum. Conclusion? None so far, though you might welcome the confirmation that this is not a "once in a blue moon" accident as Bengt Richter surmised. Import _is_ a sensitive phase... As an experiment I moved try: import thread except ImportError: import dummy_thread as thread from the Queue.Queue.__init__() method to the module body -- and now freezemain.py seems to work, too. So that would be an easy remedy, but sure there is a reason why that import statement is in such an unusual place? Peter From hps3 at seritt.org Tue Dec 21 20:27:38 2004 From: hps3 at seritt.org (Harlin Seritt) Date: Tue, 21 Dec 2004 20:27:38 -0500 Subject: how to start a new process while the other ist running on References: Message-ID: Quickie: os.system("/path/to/script.sh &") More elegant, have a look at threads ------------ Harlin Seritt Erik Geiger wrote: > Hi, > > sorry, my english ist not that got but I'll try. > > I have a running python script (capisuit incoming.py). This script shall > start a linux shell script. If I start this script like os.system(/paht/to > shellscipt.sh) the python scipt waits for the exit of the shell script and > then goes on with the rest of the python script. > > How to start a shell script without waiting for the exit of that shell > script? It shall start the shell script and immediately execute the next > python command. > > Thanks for any hints > > Erik From ilya at cray.glas.net Thu Dec 16 16:10:32 2004 From: ilya at cray.glas.net (Ilya Etingof) Date: Thu, 16 Dec 2004 21:10:32 +0000 (UTC) Subject: High level SNMP References: Message-ID: Jeremy Sanders wrote: > On Thu, 09 Dec 2004 15:34:14 +0200, Petri Laakso wrote: [skipped] > The old versions of PySNMP (version 2.XX), seem to be a lot simpler to > use than later ones, so I might do that. That's if I can work out how to Recent versions tend to be more complex because they're following SNMPv3 model, which is complex. However, a simplistic high-level layer is scheduled for implementation. > convert the random string it produces to a floating point number. Somehow > it manages to gain 3 bytes over a float... Basic SNMP types don't seem to include floating point numbers. Maybe you're decoding something defined by a TEXTUAL-CONVENTION at a MIB? The protocol (for packing floating point value into some native SNMP type) might be specified by the TC then. If you provide more details I'm willing to help. -ilya From beliavsky at 127.0.0.1 Sat Dec 18 21:52:25 2004 From: beliavsky at 127.0.0.1 (beliavsky@aol.com) Date: 18 Dec 2004 20:52:25 -0600 Subject: Use macros in Excel via win32com References: <1103420907.055741.6370@f14g2000cwb.googlegroups.com> Message-ID: <41c4ece9$1_1@127.0.0.1> "chris" wrote: >I'm creating an excel document dynamically from scratch using Python >and the win32com module. All is well, but now I need to add a macro to >the spreadsheet and run it (to enable some sorting features in the >spreadsheet). I think I know how to run a macro once it's installed >(using the Run method of the excel application object...I think), but I >can't figure out how to "install" the VBA macro code into the >spreadsheet to begin with from my Python script. >Any tips appreciated. Here is a manual solution for Excel 2003. At the bottom of the spreadsheet, right-click on one of the tabs (default names sheet1 sheet2 sheet3). Click "view code" on the menu, which should bring up a Microsoft Visual Basic editor. Select Module from the Insert menu at the top, and paste the VBA code there. ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =--- From insert at spam.here Sun Dec 19 18:39:31 2004 From: insert at spam.here (Doug Holton) Date: Sun, 19 Dec 2004 17:39:31 -0600 Subject: input record seperator (equivalent of "$|" of perl) In-Reply-To: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> Message-ID: les_ander at yahoo.com wrote: > Hi, > I know that i can do readline() from a file object. > However, how can I read till a specific seperator? > for exmple, > if my files are > > name > profession > id > # > name2 > profession3 > id2 > > I would like to read this file as a record. > I can do this in perl by defining a record seperator; > is there an equivalent in python? > thanks > To actually answer your question, there is no equivalent to $| in python. You need to hand code your own record parser, or else read in the whole contents of the file and use the string split method to chop it up into fields. From jim.vickroy at noaa.gov Thu Dec 9 15:26:08 2004 From: jim.vickroy at noaa.gov (j vickroy) Date: Thu, 9 Dec 2004 13:26:08 -0700 Subject: [Newby] Problem with compilation. References: Message-ID: The Python modules documentation indicates crypt is only available on Unix platforms. wrote in message news:mailman.7425.1102619458.5135.python-list at python.org... > Hi folks! > > Can't compile my file due to some problems with crypt module. > My platform is WinXP: > First I launch my Python Shell, > Than I open the *.py file, > Next I press F5 to 'run module' > The message is: "ImportError: No module named crypt" > > Few lines of code for example: > > ... > import posix > import posixpath > from crypt import * > > startRecord = 0 > inRecord = 1 > ... > > Thanks for help. > > From itsme at yahoo.com Thu Dec 30 12:31:44 2004 From: itsme at yahoo.com (It's me) Date: Thu, 30 Dec 2004 17:31:44 GMT Subject: Problem in threading References: <94NAd.4468$5R.2863@newssvr21.news.prodigy.com> Message-ID: <4YWAd.4705$5R.4096@newssvr21.news.prodigy.com> That's an OT topic. :=) There were lots of discussions about this topic in the old days. No need to dive into it again. Windows context switching overhead is very high. You would be lucky to get it down to the mid-30ms. OS/2 can get it down to less then 10. And for OS/2, thread swithing time is only a few machine instructions....OT.OT. "David Bolen" wrote in message news:uacrvhfdh.fsf at fitlinxx.com... > "It's me" writes: > > > It depends on what "help" means to you. Both Windows and Unix (and it's > > variances) are considered "thread-weak" OSes. So, using thread will come > > with some cost. The long gone IBM OS/2 is a classic example of a > > "thread-strong" OS. > (...) > > Interesting - can you clarify what you perceive as the differences > between a thread-weak and thread-strong OS? If given the choice, I > would probably refer to Windows (at least NT based systems, let's > ignore 9x) as thread-strong, and yes, often think of Windows as > preferring thread based solutions, while Unix would often prefer > process based. > > Windows is far more efficient at handling large numbers of threads > than it is processes, with much less overhead and there is lots of > flexibility in terms of managing threads and their resources. Threads > are first class OS objects at the kernel and scheduler level (waitable > and manageable). > > I can't think of anything offhand specific that OS/2 did with respect > to threads that isn't as well supported by current Win32 systems. > > -- David From peter at engcorp.com Thu Dec 9 14:04:55 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 09 Dec 2004 14:04:55 -0500 Subject: How do I do this? (eval() on the left hand side) In-Reply-To: <10rh37tt58vv362@corp.supernews.com> References: <10rh37tt58vv362@corp.supernews.com> Message-ID: Jeff Shannon wrote: > Of course, just because modifications of the dict returned by globals() > *do* reliably result in modifications to the global namespace, doesn't > mean it's a good idea. ;) "The" global namespace misses the possibility that doing this in "a" global namespace might be a good idea. For example, in the namespace of a special module intended to be used as a convenient way of accessing global information. See below. > Personally, I don't *want* to create variables by "magic" like that. > I'd rather pass a few extra parameters around, and explicitly create any > global names I need. If I really need to store objects under arbitrary > names, then I probably should be using a regular dict (and passing it > around as need be) instead of dumping stuff into globals(). The main way I use this is in some sort of a "const" module, which provides access to a large set of constant information. In other words, in contrast to what you had in mind when you wrote the above, I'm dealing with neither "variables" nor information that _would_ best be put in a dict. The last time I did this I had a .h header file from C which I wanted to wrap up for Python. Rather than convert once, statically, I had a const.py module which loaded the .h file contents and converted all lines which it recognized (mostly lines of the form "#define XXX nnn") into Python names stuck into that module's globals(). Other modules just do "import const" and then things like "const.DAQmx_Val_Volts" to get access to any of the over 1700 defined values. In general I would say that mucking with globals() like this is probably best restricted to constants like in this case, if at all. -Peter From bokr at oz.net Fri Dec 10 14:54:11 2004 From: bokr at oz.net (Bengt Richter) Date: Fri, 10 Dec 2004 19:54:11 GMT Subject: Find Items & Indices In A List... References: Message-ID: <41b9fe6e.273946914@news.oz.net> On Fri, 10 Dec 2004 16:27:29 GMT, Steven Bethard wrote: >andrea.gavana at agip.it wrote: >> Hello NG, >> >> I was wondering if there is a faster/nicer method (than a for loop) >> that will allow me to find the elements (AND their indices) in a list that >> verify a certain condition. For example, assuming that I have a list like: >> >> mylist = [0, 1, 1, 1, 1, 5, 6, 7, 8, 1, 10] >> >> I would like to find the indices of the elements in the list that are equal >> to 1 (in this case, the 1,2,3,4,9 elements are equal to 1). I could easily >> use a for loop but I was wondering if there is a faster method... > >Everyone has already given you the answer (enumerate in a LC or GE), I'd >just comment that it's easy enough to extend their answers to any given >condition: > > >>> def getindices(sequence, predicate): >... return [i for i, v in enumerate(sequence) if predicate(v)] >... > >>> getindices([0,1,1,1,1,5,6,7,8,1,10], bool) >[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > >>> def equalsone(v): >... return v == 1 >... > >>> getindices([0,1,1,1,1,5,6,7,8,1,10], equalsone) >[1, 2, 3, 4, 9] > >>> def f(v): >... return pow(v, 3, 4) == 3 >... > >>> getindices([0,1,1,1,1,5,6,7,8,1,10], f) >[7] > Conclusion: Python is programmer's Lego ;-) Regards, Bengt Richter From timr at probo.com Wed Dec 29 02:35:36 2004 From: timr at probo.com (Tim Roberts) Date: Tue, 28 Dec 2004 23:35:36 -0800 Subject: Python on Linux References: <41cf6fac$1@news.seeder.net> Message-ID: "Austin" wrote: > >On Red Hat 9, Python is installed by default and it's version is 2.2.2 >If I want to upgrade Python to 2.3.4(newer version), how could I do? >If I compile source code of Python, how do I uninstall the old version? You don't want to uninstall the old version. Red Hat installs packages that are needed for its configuration scripts. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From fuzzyman at gmail.com Thu Dec 16 06:09:40 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: 16 Dec 2004 03:09:40 -0800 Subject: Avaliable free modules In-Reply-To: References: Message-ID: <1103195380.447522.306390@f14g2000cwb.googlegroups.com> No.... but a lot of people would like there to be. No one has (to my knowledge) come forward to do the work on it yet though.... (or offered the bandwidth). There is a *list* of packages available - with information and liks - called the Python Package Index. See http://www.python.org/pypi Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From peter at engcorp.com Mon Dec 27 13:29:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 27 Dec 2004 13:29:25 -0500 Subject: python metrics program/script sample In-Reply-To: References: Message-ID: Philippe C. Martin wrote: > "true" lines of code meant no blanks or comment - pycount calls those "normal > source code": Pycount does not treat a blank line as "normal source code", at least in the version I'm using. It quite clearly differentiates between various types of lines, including a header in the output which reads as follows: lines code doc comment blank file (doc and comment are two separate columns, as it distinguishes between doc-comments, which are comments only by convention, and real comments). >>There are a couple of minor known bugs with pycount like: Doc strings must be >>tripple-quoted ones otherwise they are classified as normal source code. Interesting, but I believe it's a nearly universal convention to use triple-quoted strings for doc-comments. I guess if you don't do that, however, pycount might not be for you. >>Continuation lines ending with a backslash are not treated at all. Complex >>regular expressions (as in pycount itself) can knock the parser down, >>quickly. There is a built-in quick-and-dirty solution to this which might >>work whenever the problem is on one line only. But in "most cases" it >>works... In areas like this, I consider most attempts to make a line counter "more sophisticated" are, while well-meaning, often a waste of time. For example, if I have a line that is long enough (read "complex enough") to warrant a line-continuation, I'm quite happy if a simple line counter decides to call it two lines (or three, or whatever). Or one. It shouldn't be that big a deal. "Source lines of code" has at best a tenuous connection to complexity or other abstract characteristics of code, so I don't see any reason to spend time on making a line counter "perfect". It should probably be used only for comparative analysis anyway, so as long as it does the same thing on your entire code base, it ought to be good enough, IMHO. > I'll try pycount but the above bugs might mean a lot of rewriting. I've been using it for quite some time, successfully, without even being aware there were problems with certain types of source. Maybe my code is just relatively standard-looking, so pycount doesn't have trouble with it... -Peter From imbosol at aerojockey.com Tue Dec 14 21:23:04 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 14 Dec 2004 18:23:04 -0800 Subject: lies about OOP References: <1102995205.949964.76020@c13g2000cwb.googlegroups.com> Message-ID: <1103077384.851353.60840@z14g2000cwz.googlegroups.com> projecktzero wrote: > He thinks that OOP has more overhead.... I think he's just confusing programming with marriage. -- CARL BANKS From tim.golden at viacom-outdoor.co.uk Wed Dec 8 10:22:29 2004 From: tim.golden at viacom-outdoor.co.uk (Tim G) Date: 8 Dec 2004 07:22:29 -0800 Subject: os.path.islink() In-Reply-To: References: Message-ID: <1102519349.140077.77170@f14g2000cwb.googlegroups.com> You may well be able to do it with the win32file module functions: GetFileAttributesEx or GetFileInformationByHandle It's not my area of expertise, but usually a bit of poking around in msdn.microsoft.com yields some results, as does Googling around for other people (often VB or Delphi-based) who have done the same thing. TJG From roy at panix.com Fri Dec 17 23:23:17 2004 From: roy at panix.com (Roy Smith) Date: Fri, 17 Dec 2004 23:23:17 -0500 Subject: Why are tuples immutable? References: <41BE1644.8050906@freemail.gr> <10s4a4rso24vb83@corp.supernews.com> <10s6aadbs66o8f0@corp.supernews.com> <10s6se2m73b47f5@corp.supernews.com> Message-ID: In article <10s6se2m73b47f5 at corp.supernews.com>, Jeff Shannon wrote: > Roy Smith wrote: > >All that's needed is to define __hash__() and __cmp__() methods which > >only look at some subset of the object's data atrributes. You can > >keep those attributes constant (perhaps enforced with __setattr__() > >hooks) and let others mutate. > > In which case, one could argue that your __cmp__() is not fulfilling the > semantics of mathematical equality, because even though the objects > compare the same, they are not interchangeable. (They may be "close > enough to equal for this particular purpose", but that's a different > thing regardless of whether or not it's useful in practice.) I'm not sure what "mathematical equality" means, but we're not talking math here, we're talking programming. Or at least I am :-) What better definition of "equality" in a programming language could there be other than the == operator returns true? I'm also not sure what you mean by "interchangeable". Are 1 and 1.0 interchangeable? They're equal: >>> 1 == 1.0 True They hash the same: >>> hash (1) 1 >>> hash (1.0) 1 They work the same as a dictionary key: >>> d = {} >>> d [1] = "one" >>> d [1.0] 'one' They don't act the same in other respects, though: >>> 1 / 2 0 >>> 1.0 / 2 0.5 Are they "interchangeable"? Beats me. I guess it depends on how you define "interchangeable". I know Python defines equality (==) and identity (is), but I don't believe it defines interchangeability. If I give you a $100 bill, and you give me back a different $100 bill, are the two bills equal? They may have different serial numbers, but for any financial purpose, they're equal. Are they interchangeable? I think most people would argue they are. But that's only because most people's definition of equality for money only deals with monetary value, and ignores other attributes of the banknote such as date of issue and serial number. > It is possible to create mutable objects for which one can arrange > things so that they can act like they're hashable. Unless I'm > completely mistaken about the mathematical principles involved, however, > then the mathematics implied by the terms "hash function" and "equality" > cannot be universally fulfilled by mutable objects. Again, all I can say is we're not talking about some abstract mathematical concept, we're talking about objects in a programming environment. Hash is not a "mathematical principle", it's a function you can call to get a result. From davidf at sjsoft.com Fri Dec 3 04:07:24 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 03 Dec 2004 11:07:24 +0200 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 2) In-Reply-To: References: <41AED7FC.50606@jessikat.fsnet.co.uk> Message-ID: Rocco Moretti wrote: > >> For some reason I can't seem to make use of the google links. When I >> use the above eg >> >> http://groups.google.com/groups?frame=right&th=e562a771d1c827c9 >> >> I get a not found google page with url >> http://groups-beta.google.com/groups?frame=right&th=e562a771d1c827c9 >> >> really wanted to spell file in a sickly manner :) > > > It seems Google recently redid their groups interface. By searching for > "group:comp.lang.python Coghlan" on http://groups.google.com, I was able > to find the probable post (Sort by Date, titled "Restricted Execution on > the cheap", about four down) Nicely, google seems to have reverted their main google groups page to the original system, and left the new one at groups-beta.google.com > I'm sorry I'm not able to give a direct URL, but it seems they've > switched over to a horrendously long, stateful URL system which doesn't > lend itself to direct linkage. Doesn't seem stateful to me, just has different thread / message ids to the old system: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1db72429a2b05ce0/2c1679d365ffe9dd#2c1679d365ffe9dd The syntax is thread/$threadid/$messageid#$messageid At least for me, these URLs are transferable between computers / browsers You can also access the message directly: http://groups-beta.google.com/group/comp.lang.python/msg/2c1679d365ffe9dd David From peter at somewhere.com Wed Dec 8 04:23:13 2004 From: peter at somewhere.com (Peter Maas) Date: Wed, 08 Dec 2004 10:23:13 +0100 Subject: os.path.islink() In-Reply-To: References: Message-ID: Egor Bolonev schrieb: > far file manager said 'C:\Documents and Settings\????\My > Documents\Scripts\Antiloop\' is link > > how to detect ntfs links? There are no ntfs links. What appears as a link on GUI level is nothing but a plain file with special content, so that os.path.islink() tells the truth. Windows "links" are a special Windows feature (shortcuts) and must be detected via Win32 api calls or by searching for content characteristics of shortcuts. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From philippecmartin at sbcglobal.net Thu Dec 23 03:11:22 2004 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Thu, 23 Dec 2004 09:11:22 +0100 Subject: Killing a python thread with a signal Message-ID: <200412230911.22039.philippecmartin@sbcglobal.net> On Thu, 2004-12-23 at 04:51, James Lamanna wrote: > So I've created a thread with the threading.Thread class, but I want to > be able to kill this thread because it does a select() with a timeout of > None. I do not know what type of information your thread reads from the sockets, but I added a 'QUIT-STYLE' command in my script when I want the thread to exit so it wakes up. Regards, Philippe -- ********************* Philippe C. Martin SnakeCard LLC www.snakecard.com ********************* From fredrik at pythonware.com Tue Dec 14 06:13:15 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Dec 2004 12:13:15 +0100 Subject: How can i send 8-bit data or binary data with pyserial? References: Message-ID: "ouz as" wrote: > i have an electronic module which only understand binary data. > i use python pyserial. > for example the module starts when 001000000 8-bit binary data sent.but that's nine bits... > pyserial sent only string data. in computers, bits are combined into bytes (or longer machine words). the strings you pass to pyserial are treated as byte sequences. this might help you figure out how to convert between bit patterns and byte values: http://www.math.grin.edu/~rebelsky/Courses/152/97F/Readings/student-binary.html > Can i send this binary data with pyserial or another way with python. convert the bitpattern to a byte, and send it to pyserial. 01000000 = 0x40 (hex) = 64 (dec) so ser.write(chr(64)) or ser.write(chr(0x40)) or even ser.write("\x40") to go from a byte to a bitpattern, use ord(byte): ord(chr(0x40)) = 0x40 hardware-oriented code often represent bitpatterns as hex constants. by using constants, it's easy to combine different bits: FLAG1 = 0x40 FLAG2 = 0x20 ser.write(chr(FLAG1)) # set first flag ser.write(chr(FLAG1|FLAG2)) # set both flags flags = getstatus() ser.write(flags ^ FLAG2) # toggle flag 2 etc. From steve at holdenweb.com Mon Dec 13 11:42:12 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 13 Dec 2004 11:42:12 -0500 Subject: anybody know how to use python to communicate with UART? In-Reply-To: References: Message-ID: Arnold wrote: > I want to use python to communicate with UART port in my PC, how can I > achieve this? any modules need to be installed? > > Thanks > > pyserial is the usual solution. See http://pyserial.sourceforge.net/ regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From ch.list at US-HAMPTON.mail.SAIC.com Thu Dec 16 10:29:05 2004 From: ch.list at US-HAMPTON.mail.SAIC.com (Chris) Date: Thu, 16 Dec 2004 10:29:05 -0500 Subject: datetime In-Reply-To: References: Message-ID: <41C1A9C1.9030403@us-hampton.mail.saic.com> >>Okay, I searched www.python.org for a date handler and found datetime. >>http://www.python.org/dev/doc/devel/lib/module-datetime.html However, >>whenever I try to import datetime, I get a No module named datetime >>error. What am I missing? > The module documentation says "New in version 2.3". > Is that what you're running ? Doh! No, I'm still running 2.2. Anyways, I managed to do what I needed using time. Thanks for the help, though. Chris From craig at postnewspapers.com.au Sun Dec 19 01:56:06 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sun, 19 Dec 2004 14:56:06 +0800 Subject: regular expression for javadoc style comment In-Reply-To: References: Message-ID: <1103439366.7642.0.camel@albert.localnet> On Fri, 2004-12-17 at 09:40, Alessandro Crugnola wrote: > Hi all, > i need to use a regular expression to match javadoc style comments in a file, > something like > > /** > * Constructs a new Call instance. > * > * @param object the object the Function shall be executed on > * @param func the Function that shall be executed > * @throws IllegalArgumentException if neigther the object or the function is not available. > */ > > i'm finiding many difficulties to write a valid regular expression It would be good if you could post some of the things you've tried, and perhaps a little more detail about what you're trying to match. Are you trying to match the comment as a whole, eg "this is a javadoc comment", or are you trying to extract parts of it? -- Craig Ringer From mwm at mired.org Fri Dec 17 21:48:59 2004 From: mwm at mired.org (Mike Meyer) Date: Fri, 17 Dec 2004 20:48:59 -0600 Subject: better lambda support in the future? References: <10s6qnfd172kuaf@corp.supernews.com> <10s71g62jiq0572@corp.supernews.com> Message-ID: <868y7w48ys.fsf@guru.mired.org> Jeff Shannon writes: > Steven Bethard wrote: > Hm, possibly. I must confess that my direct knowledge is limited to a > fairly narrow set of languages, and that C and C++ are the only > statically-compiled languages I've used. Still, I'm not sure that > it's just a matter of functions as first-class objects. Would OCaml > (or some other static language) have something that's equivalent to > this? > > def f(x): > if x < 0: > def g(y): > return y * -1 > else: > def g(y): > return y > return g > > foo = f(1) This is really no different than: def f(x): if x < 0: g = -y else: g = y return g The only difference is that you're binding the variable g to a y type instead of a function type. That's what "first class functions" means. You can treat functions like any other object, assign them to variables, pass them as parameters, and so on. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From ncoghlan at iinet.net.au Sat Dec 4 08:20:57 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 04 Dec 2004 23:20:57 +1000 Subject: [Python-Dev] PEP: __source__ proposal In-Reply-To: References: <41B0F629.4040100@v.loewis.de> Message-ID: <41B1B9B9.4000800@iinet.net.au> Stelios Xanthakis wrote: > It appears that there are the 'module people' who > find this feature irrelevant. Indeed. If we are interested > in distributing modules and increasing the number of > people who use python programs,then __source__ is redundant. > OTOH, programming python is easy and fun and I think > the proposed feature will make it even more fun and it > aims in increasing the number of people who program > python for their every day tasks. It'd be interesting to > hear if the developers of IDLE/ipython/etc could use this. The feedback here (and the initial response on py-dev a while back) suggests to me that you should look at making this a feature of the interactive mode. Something that affects both Python's main interactive shell, plus the relevant class in the standard library (CommandInterpreter or whatever it is called). A late-night-train-of-thought example of what might be handy is below - keep in mind that I haven't looked at what enhanced Python shells like IPython can do, so it may be there are tools out there that do something like this already. It would be handy to have a standard library module that supported "on-the-fly" editing, though (this capability would then be available to anyone embedding Python as a scripting engine). Cheers, Nick. ============================== >>>import source >>>class bob: ... def mary(): ... pass ... def tim(): ... print 'Tim' ... >>>print bob.__source__ class bob: def mary(): pass def tim(): print 'Tim' >>>print bob.mary.__source__ def mary(): pass >>> source.edit(bob.mary) bob.mary(1)>def mary(text): # [1] bob.mary(2)> print "Mary:", text bob.mary(3)>\save >>> source.edit(bob.tim) bob.tim(1)>\help Commands: \help \cancel \save \deleteline bob.tim(2)>\cancel >>>print bob.__source__ "class bob: def mary(text): print "Mary:", text def tim(): print 'Tim' " >>> bob().mary("Hi!") Mary: Hi! The basic ideas of the above: "import source" triggers the storage of the __source__ attributes (e.g. via installation of appropriate hooks in the class and function definition process) The 'edit' function is then able to take advantage of the stored source code to present each line of the original source for modification (e.g. to fix a minor bug in one function of a class definition). When the 'edit' is complete, it can be saved or cancelled. 1. The feature mentioned in the last paragraph is hard to show in the expected output :) -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From lutherrevisited at aol.com Sat Dec 25 21:29:45 2004 From: lutherrevisited at aol.com (LutherRevisited) Date: 26 Dec 2004 02:29:45 GMT Subject: Complementary language? References: Message-ID: <20041225212945.06450.00001890@mb-m22.aol.com> I'm a big fan of C# myself, it kinda takes the good from C++ and Java and combines them in a way. From ishwor.gurung at gmail.com Wed Dec 22 16:42:13 2004 From: ishwor.gurung at gmail.com (Ishwor) Date: Thu, 23 Dec 2004 08:12:13 +1030 Subject: list IndexError In-Reply-To: References: <34534aed04122211413845b33e@mail.gmail.com> <41C9D224.7050902@rogers.com> <34534aed041222122441a43901@mail.gmail.com> Message-ID: <34534aed041222134227a0850c@mail.gmail.com> On Thu, 23 Dec 2004 07:27:52 +1000, Egor Bolonev wrote: > On Thu, 23 Dec 2004 06:56:02 +1030, Ishwor wrote: > > >>>> l > > ['a', 'b', 'c', 'd', 'e'] > >>>> for x in l[:]: > > if x == 'd': > > l.remove('d'); > > > >>>> l > > ['a', 'b', 'c', 'e'] > > This code is so clean and looks very healthy. Python will live a > > long way because its a cute language. > > imho the code is very unhealthy, i would write > l = ['a', 'b', 'c', 'd', 'e'] > l.remove('d') > print l > > btw what are you using ';' for I am learning Python. I used 'for' specifically so that i could iterate over the list and delete the values. It was a dumb one.. thanx for pointing it out but i specifically wanted to understand how slicing work. :-) thanks anyway. -- cheers, Ishwor Gurung From craig at postnewspapers.com.au Wed Dec 15 08:52:19 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Wed, 15 Dec 2004 21:52:19 +0800 Subject: Import trouble In-Reply-To: <1103118275.1192.1.camel@bucket.localnet> References: <200412151345.13717.frans.englich@telia.com> <1103118275.1192.1.camel@bucket.localnet> Message-ID: <1103118739.1194.3.camel@bucket.localnet> On Wed, 2004-12-15 at 21:44, Craig Ringer wrote: > def import_xml: > try: > import libxml > except ImportError,err: > # handle the error > return libxml > > libxml = import_xml() Though my personal approach would actually be: try: import libxml except ImportError,err: handle_import_error("libxml", err) -- Craig Ringer From bulba at bulba.com Fri Dec 31 07:43:38 2004 From: bulba at bulba.com (Bulba!) Date: Fri, 31 Dec 2004 13:43:38 +0100 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> Message-ID: On 31 Dec 2004 03:49:44 -0800, Paul Rubin wrote: >It's not just a matter of attitude or politics. Python is an >excellent choice for many projects. For some other projects, it's >clearly unsuitable. For yet other projects, it's a plausible choice >but there are sound technical reasons to be wary of it. (being the usual me, I can't resist putting a stick into a nest of pythons) OK, so what projects and why would you consider Python: 1. "clearly unsuitable" 2. "plausible but there are sound technical reasons to be wary" BTW, I don't think I agree with your statement elsewhere about unit tests - if you write a prototype (in any language), why bother with unit tests, and if you write security-critical app, maybe the tests should be written anyway (again, whatever is the language chosen for a project). -- It's a man's life in a Python Programming Association. From chriskreuzer at hotmail.com Sat Dec 4 10:44:06 2004 From: chriskreuzer at hotmail.com (chriskreuzer at hotmail.com) Date: 4 Dec 2004 07:44:06 -0800 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 2) In-Reply-To: References: <41AED7FC.50606@jessikat.fsnet.co.uk> Message-ID: <1102175046.297102.62950@z14g2000cwz.googlegroups.com> David Fraser wrote: > Rocco Moretti wrote: > > I'm sorry I'm not able to give a direct URL, but it seems they've > > switched over to a horrendously long, stateful URL system which doesn't > > lend itself to direct linkage. > > Doesn't seem stateful to me, just has different thread / message ids to > the old system: Using different message IDs is bad. Usenet already has a header for this: Message ID. > http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1db72429a2b05ce0/2c1679d365ffe9dd#2c1679d365ffe9dd > > The syntax is thread/$threadid/$messageid#$messageid > At least for me, these URLs are transferable between computers / browsers But if Google ever moves away from maintaining a Usenet archive, then any links involving Google IDs will be broken. This happened with DejaNews and will happen with links to old URLs with the GG1 (Google Groups 1) system (unless they maintain continuity). Even then, all was not lost because you could extract the Usenet message ID from the URL. It looks like you can't do this with the new GG2 message references. > You can also access the message directly: > > http://groups-beta.google.com/group/comp.lang.python/msg/2c1679d365ffe9dd I would also *always* add the Usenet message ID. This timeproofs it against any future changes. Christopher From philippecmartin at sbcglobal.net Sun Dec 12 07:03:25 2004 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Sun, 12 Dec 2004 13:03:25 +0100 Subject: Named pipes in threads Message-ID: <200412121303.26012.philippecmartin@sbcglobal.net> >>Replace the sockets with a queue of strings. >>http://docs.python.org/lib/module-Queue.html >>Write your Send and Recv functions in terms of Queue.get() and Queue.put(); And those entry points seem to reentrant too !!!!!!! Thanks a lot, you made my day (I say that a lot on this mailing list :-)))))) Regards, Philippe From kent3737 at yahoo.com Fri Dec 10 08:04:23 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Fri, 10 Dec 2004 08:04:23 -0500 Subject: Wrapper objects In-Reply-To: References: <8c7f10c60412090647a7785ee@mail.gmail.com> Message-ID: <41b99d43$1_1@newspeer2.tds.net> Nick Coghlan wrote: > Simon Brunning wrote: >> This work - >> ? >> > > Only for old-style classes, though. If you inherit from object or > another builtin, that recipe fails. Could you explain, please? I thought __getattr__ worked the same with new- and old-style classes? Thanks, Kent From mwm at mired.org Sun Dec 26 23:07:36 2004 From: mwm at mired.org (Mike Meyer) Date: Sun, 26 Dec 2004 22:07:36 -0600 Subject: Optional Static Typing - Haskell? References: <1103795375.843649.286620@c13g2000cwb.googlegroups.com> <1gpaypu.hp5icf1tvg99cN%aleaxit@yahoo.com> <41cc504b$1_1@127.0.0.1> <1gpbe96.1ioa9lt1t622shN%aleaxit@yahoo.com> <41ccbefb$1_2@127.0.0.1> <1gpcl19.13v2d481su0if2N%aleaxit@yahoo.com> <86d5wx93ra.fsf@guru.mired.org> <1gpedy7.1kwy16r153aiw1N%aleaxit@yahoo.com> Message-ID: <86zn005qpj.fsf@guru.mired.org> aleaxit at yahoo.com (Alex Martelli) writes: > Mike Meyer wrote: >> aleaxit at yahoo.com (Alex Martelli) writes: >> > Mind you, I personally _like_ the concept of describing >> > an interface separately, even in a different language (Corba's IDL, say) >> > that's specialized for the task. But it doesn't seem to be all that >> > popular... without such separation, modularity plus static checking >> > appears to imply bottom->up coding: you need to compile modules in some >> > topologically sorted order compatible with the "X uses Y" relation. >> Personally, I hate declaring the interface separately, whether in the >> same language or another language. > Yeah, so do many people -- as I mentioned, it's not all that popular. > Personally, I don't see _why_ Because it violates the principle of "Once and only once". If the interface is described in two places, that means it's possible to update one and forget to update the other. That's not possible if the interface is defined once and only once. I've forgotten to update my IDL more than once. > But then, the above criticism applies: if interface and implementation > of a module are tightly coupled, you can't really do fully modular > programming AND static typing (forget type inferencing...). I beg to differ. Eiffel manages to do this quite well. Then again, every Eiffel environment comes with tools to extract the interface information from the code. With SmartEiffel, it's a command called "short". Doing "short CLASSNAME" is like doing "pydoc modulename", except that it pulls routine headers and DbC expression from the code, and not just from comments. >> On the other hand, generating the >> interface information from the code for type checking (and >> documentation) purposes makes an incredible amount of sense. A type >> inferencing engine to generate that information from Python code - >> with possible a bit of human assistance - would make it possible to >> use pychecker to catch duck typing errors without having to import an >> entire module. > And why should it be a problem to "import an entire module", pray? It isn't. I was just thinking out loud. If you had a type inferencing engine that created the type signatures of everything in a module, that would let you do type checking without importing the module. It's actually more interesting for compiled languages than for interpreted ones. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From vze4rx4y at verizon.net Tue Dec 14 05:05:17 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Tue, 14 Dec 2004 10:05:17 GMT Subject: Performance (pystone) of python 2.4 lower then python 2.3 ??? References: Message-ID: "Lucas Hofman > This machine benchmarks at 38167.9 pystones/second Pystone is an abyssmally bad benchmark for comparing the relative speeds of different versions of python (it nets out all eval loop improvements and it exercises only a microscopic portion of the language). I would be interested in seeing other people's comparitive results for pybench, test_decimal, and parrotbench. To run test_decimal.py, you first have to copy Lib/test/decimal.py into Py2.3's lib directory. On an old PentiumIII running WinMe, I get 48.940 sec in Py2.3 and 44.820 sec in Py2.4, a 8.4% improvement. For pybench, I get 7418.90ms in Py2.3 and 6320.07 ms in Py2.4, a 14.8% improvement. For parrotbench, I get 54.517 seconds in Py2.3 and 45.009 seconds in Py2.4, a 17.4% improvement. It is also interesting to time specific features not covered by the above benchmarks. For example, list comprehensions got a nice 60% boost on my machine: C:\py24\Lib>\python23\python timeit.py -r9 "[i for i in xrange(1000)]" 100 loops, best of 9: 1.11 msec per loop C:\py24\Lib>\python24\python timeit.py -r9 "[i for i in xrange(1000)]" 1000 loops, best of 9: 417 usec per loop Raymond Hettinger From no at spam.please Wed Dec 22 12:02:44 2004 From: no at spam.please (Doug Holton) Date: Wed, 22 Dec 2004 11:02:44 -0600 Subject: [Re: newbie question] In-Reply-To: References: <3e8ca5c804122020157b89fb9b@mail.gmail.com> <1103637612.657658.67350@f14g2000cwb.googlegroups.com> <32tm7qF3gha75U1@individual.net> Message-ID: Steve Holden wrote: > 'Scuse me? This group has a long history of off-topic posting, and > anyway who decided that CPython should be the exclusive focus? Even > on-topic we can talk about Jython and PyPy as well as CPython. > > Off-topic we can talk about what we damned well please. Even boo :-) Thankyou, that's the most intelligent thing you've said all week. From itsme at yahoo.com Fri Dec 31 16:52:59 2004 From: itsme at yahoo.com (It's me) Date: Fri, 31 Dec 2004 21:52:59 GMT Subject: Parsing a search string References: <1104526960.929218.119480@c13g2000cwb.googlegroups.com> Message-ID: <%SjBd.5006$5R.1387@newssvr21.news.prodigy.com> "John Machin" wrote in message news:1104526960.929218.119480 at c13g2000cwb.googlegroups.com... > Andrew Dalke wrote: > > "It's me" wrote: > > > Here's a NDFA for your text: > > > > > > b 0 1-9 a-Z , . + - ' " \n > > > S0: S0 E E S1 E E E S3 E S2 E > > > S1: T1 E E S1 E E E E E E T1 > > > S2: S2 E E S2 E E E E E T2 E > > > S3: T3 E E S3 E E E E E E T3 > > > > Now if I only had an NDFA for parsing that syntax... > > Parsing your sentence as written ("if I only had"): If you were the > sole keeper of the secret?? > > Parsing it as intended ("if only I had"), and ignoring the smiley: > Looks like a fairly straight-forward state-transition table to me. Exactly. > The > column headings are not aligned properly in the message, b means blank, > a-Z is bletchworthy, but the da Vinci code it ain't. > > If only we had an NDFA (whatever that is) for guessing what acronyms > mean ... > I believe (I am not a computer science major): NDFA = non-deterministic finite automata and: S: state T: terminal E: error So, S1 means State #1..T1 means Terminal #1, so forth.... You are correct that parsing that table is not hard. a) Set up a stack and place the buffer onto the stack, start with S0 b) For each character that comes from the stack, looking up the next state for that token c) If it's not a T or E state, jump to that state d) If it's a T or E state, finish From usenet_spam at janc.invalid Fri Dec 10 17:03:20 2004 From: usenet_spam at janc.invalid (JanC) Date: Fri, 10 Dec 2004 22:03:20 GMT Subject: Help beautify ugly heuristic code References: Message-ID: Stuart D. Gathman schreef: > I have a function that recognizes PTR records for dynamic IPs. There > is no hard and fast rule for this - every ISP does it differently, and > may change their policy at any time, and use different conventions in > different places. Nevertheless, it is useful to apply stricter > authentication standards to incoming email when the PTR for the IP > indicates a dynamic IP (namely, the PTR record is ignored since it > doesn't mean anything except to the ISP). This is because Windoze > Zombies are the favorite platform of spammers. Did you also think about ISPs that use such a PTR record for both dynamic and fixed IPs? -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From steven.bethard at gmail.com Tue Dec 28 17:40:54 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 28 Dec 2004 22:40:54 GMT Subject: objects as mutable dictionary keys In-Reply-To: <33e3k7F3ulad0U1@individual.net> References: <41BE1644.8050906@freemail.gr> <33bdosF3qm2j6U1@individual.net> <33e3k7F3ulad0U1@individual.net> Message-ID: Peter Maas wrote: > Peter Maas schrieb: > >> There was a huge and sometimes heated debate about tuples, lists and >> dictionaries recently, and the mainstream opinion was that dictionary >> keys must not be mutable, so lists are not allowed as dictionary keys. > > > Warning, long posting (~ 100 lines) > [snip summary] Yeah, that looks like a pretty decent summary to me. I wonder if this would be worth posting on the Wiki somewhere? Maybe: http://www.python.org/moin/DictionaryKeys That makes it easy to point to when this issue comes up again. Steve From janeaustine50 at hotmail.com Wed Dec 15 23:19:45 2004 From: janeaustine50 at hotmail.com (Jane Austine) Date: 15 Dec 2004 20:19:45 -0800 Subject: Efficient grep using Python? Message-ID: [Fredrik Lundh] >>> bdict = dict.fromkeys(open(bfile).readlines()) >>> >>> for line in open(afile): >>> if line not in bdict: >>> print line, >>> >>> [Tim Peters] >> Note that an open file is an iterable object, yielding the lines in >> the file. The "for" loop exploited that above, but fromkeys() can >> also exploit it. That is, >> >> bdict = dict.fromkeys(open(bfile)) >> >> is good enough (there's no need for the .readlines()). [/F] > (sigh. my brain knows that, but my fingers keep forgetting) > > and yes, for this purpose, "dict.fromkeys" can be replaced > with "set". > > bdict = set(open(bfile)) > > (and then you can save a few more bytes by renaming the > variable...) [Tim Peters] > Except the latter two are just shallow spelling changes. Switching > from fromkeys(open(f).readlines()) to fromkeys(open(f)) is much more > interesting, since it can allow major reduction in memory use. Even > if all the lines in the file are pairwise distinct, not materializing > them into a giant list can be a significant win. I wouldn't have > bothered replying if the only point were that you can save a couple > bytes of typing . fromkeys(open(f).readlines()) and fromkeys(open(f)) seem to be equivalent. When I pass an iterator instance(or a generator iterator) to the dict.fromkeys, it is expanded at that moment, thus fromkeys(open(f)) is effectively same with fromkeys(list(open(f))) and fromkeys(open(f).readlines()). Am I missing something? Jane From RyanMorillo at gmail.com Thu Dec 30 14:07:58 2004 From: RyanMorillo at gmail.com (RyanMorillo at gmail.com) Date: 30 Dec 2004 11:07:58 -0800 Subject: OT: novice regular expression question In-Reply-To: <4MWAd.4695$5R.2506@newssvr21.news.prodigy.com> References: <4MWAd.4695$5R.2506@newssvr21.news.prodigy.com> Message-ID: <1104433678.660415.84530@z14g2000cwz.googlegroups.com> check jgsoft dot com, they have2 things witch may help. Edit pad pro (the test version has a good tutorial) or power grep (if you do a lot of regexes, or the mastering regular expressions book from Orielly (if yo do a lot of regex work) Also the perl group would be good for regexes (pythons are Perl 5 compatable) From craig at postnewspapers.com.au Mon Dec 13 15:32:28 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Tue, 14 Dec 2004 04:32:28 +0800 Subject: Read a gzip file from inside a tar file In-Reply-To: <1102963189.938054.125970@z14g2000cwz.googlegroups.com> References: <1102954477.014206.273180@f14g2000cwb.googlegroups.com> <1102963189.938054.125970@z14g2000cwz.googlegroups.com> Message-ID: <1102969948.13915.20.camel@rasputin.localnet> On Tue, 2004-12-14 at 02:39, Rohit wrote: > if I change fileText = fileLike.read() to fileText = > fileLike.readLines(). > > It works for a while before it gets killed of out of memory. > > These are huge files. My goal is to analyze the content of the gzip > file in the tar file without having to un gzip. If that is possible. As far as I know, gzip is a stream compression algorithm that can't be decompressed in small blocks. That is, I don't think you can seek 500k into a 1MB file and decompress the next 100k. I'd say you'll have to progressively read the file from the beginning, processing and discarding as you go. It looks like a no-brainer to me - see zlib.decompressobj. Note that you _do_ have to ungzip it, you just don't have to store the whole decompressed thing in memory / on disk at once. If you need to do anything to it that does require the entire thing to be loaded (or anything that means you have to seek around the file), I'd say you're SOL. -- Craig Ringer From aleaxit at yahoo.com Sat Dec 25 06:05:56 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 25 Dec 2004 12:05:56 +0100 Subject: Optional Static Typing - Haskell? References: <1103795375.843649.286620@c13g2000cwb.googlegroups.com> <1gpaypu.hp5icf1tvg99cN%aleaxit@yahoo.com> <41cc504b$1_1@127.0.0.1> <1gpbe96.1ioa9lt1t622shN%aleaxit@yahoo.com> <41ccbefb$1_2@127.0.0.1> Message-ID: <1gpcl19.13v2d481su0if2N%aleaxit@yahoo.com> Donn Cave wrote: ... > | making a really modular system work with static typing and inferencing > | is probably impossible; in practice, the type inferencer must examine > | all code, or a rather copious summary of it... it can't really work > | module by module in a nice, fully encapsulated way...). > > Well, I would assume that a modules in a static system would present > a typed external interface, and inference would apply only within the > module being compiled. ... > There might be tricky spots, but I imagine the Objective CAML > folks would object to an assertion like "making a really modular > system work with static typing and inferencing is probably > impossible"! It seems to me that you just restated in the first part I quoted what you say in the second part OCAML folks would object to. If you give up on type inferencing across modules, and only have type inferencing inside each module, then you're getting little mileage out of the inferencing if your modules are many and small. But let me quote Van Roy and Haridi, rather than paraphrasing them, lest I fail to do them justice -- I think quoting 8 lines out of a book of over 800 pages is "fair use" (anecdote: my Xmas gift is said book, my wife's a real-bargain Powerbook 15" Titanium laptop -- yesterday we weighed them against each other and determined the book's heavier;-)... """ Dynamic typing makes it a trivial matter to do separate compilation, i.e. modules can be compiled without knowing anything about each other. This allows truly open programming, in which independently written modules can come together at runtime and interact with each other. It also makes program development scalable, i.e., extremely large programs can be divided into modules that can be recompiled individually without recompiling other modules. This is harder to do with static typing because the type discipline must be enforced across module boundaries. """ I see that by paraphrasing and summarizing by heart I was changing their argument a bit, from 'enforcing the type discipline' (which is what they're discussing, and is obviously mandatory if you want to talk about static typing) to 'type inferencing' (which they don't discuss in this specific paragraph). Nor do they claim 'probably impossible', since they're only discussing enforcement, not inferencing -- just 'harder'. Essentially, to compile a module under static typing you need full type information for other modules -- the "without knowing anything about each other" condition of fully separate compilation can't hold, and thus neither can the "truly open programming" and "scalable development" consequences. Mind you, I personally _like_ the concept of describing an interface separately, even in a different language (Corba's IDL, say) that's specialized for the task. But it doesn't seem to be all that popular... without such separation, modularity plus static checking appears to imply bottom->up coding: you need to compile modules in some topologically sorted order compatible with the "X uses Y" relation. Alex From jb_perin at yahoo.fr Tue Dec 21 04:19:57 2004 From: jb_perin at yahoo.fr (Jean-Baptiste PERIN) Date: Tue, 21 Dec 2004 10:19:57 +0100 Subject: extending python with a C-written dll In-Reply-To: <41c71eab$0$16129$a1866201@visi.com> References: <41c6e784$0$16084$a1866201@visi.com> <41c6f353$0$16095$a1866201@visi.com> <1xdldj1h.fsf@python.net> <41c71eab$0$16129$a1866201@visi.com> Message-ID: > > That's got nothing to do with Python. You have to compile > extensions using a compiler that has an ABI that's compatible > with the ABI of the compiler used to compile Python. > > You appear to be using a binary distribution of Python that was > compiled with MSVS 6.0, therefore, you have to compile > extensions with a compiler that has an ABI compatible with MSVS > 6.0. > > It's no use complaining to us bout your C compiler not being > ABI compatible with MSVS 6.0. > > If you don't like MSVS, then your options are to either use a > different Python binary distro that was compiled with an ABI > that's compatible with your C compiler, or build just build it > yourself using whatever compiler you want. I suspect the latter > will also require re-compiling Blender. > According to what I read in this forum, MinGW is an interesting option.. do you know if it is ABI compatible with MSVC? otherwise.. I'm gonna explore the solution which consist in building the dll with cygwin's gcc .. I've already recompiled Blender with gcc .. I know that, in Blender code, there are C++ function that are available from Blender's python .. I've started exploring the makefile.. apparently they are using dlltool in conjonction with gcc .. thank you very much for your help .. From Michel Claveau - abstraction meta-galactique non triviale en fuite Fri Dec 24 04:00:39 2004 From: Michel Claveau - abstraction meta-galactique non triviale en fuite (Michel Claveau - abstraction meta-galactique non triviale en fuite) Date: Fri, 24 Dec 2004 10:00:39 +0100 Subject: [PIL] is there a downloadable docs for PIL References: Message-ID: <41cbdac7$0$15843$8fcfb975@news.wanadoo.fr> Is that ? http://www.pythonware.com/products/pil/pil-handbook.pdf From philippecmartin at sbcglobal.net Sun Dec 12 05:00:56 2004 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Sun, 12 Dec 2004 11:00:56 +0100 Subject: Named pipes in threads Message-ID: <200412121100.56852.philippecmartin@sbcglobal.net> HI, I currently have a "working" script that uses sockets to handle threads communications - the problem is that it gives me obvious problems in handling free ports (launching the script more than once ....). Is thread named pipes communication allowed ? Regards, Philippe From steve at holdenweb.com Wed Dec 1 18:14:00 2004 From: steve at holdenweb.com (Steve Holden) Date: Wed, 01 Dec 2004 18:14:00 -0500 Subject: non blocking read() In-Reply-To: References: Message-ID: Donn Cave wrote: > In article , > Gustavo C??rdova Avila wrote: > > >>David Bolen wrote: >> >> >>>Jp Calderone writes: >>> >>> >>>> def nonBlockingReadAll(fileObj): >>>> bytes = [] >>>> while True: >>>> b = fileObj.read(1024) >>>> bytes.append(b) >>>> if len(b) < 1024: >>>> break >>>> return ''.join(bytes) >>>> >>> >>>Wouldn't this still block if the input just happened to end at a >>>multiple of the read size (1024)? >>> >>>-- David >>> >> >>No, it'll read up to 1024 bytes or as much as it can, and >>then return an apropriatly sized string. > > > Depends. I don't believe the original post mentioned > that the file is a pipe, socket or similar, but it's It did actually specifically mention files. > kind of implied by the use of select() also mentioned. > It's also kind of implied by use of the term "block" - > disk files don't block. > Erm, you mean they operate at infinite speed? Wrong. There's a definite risk that a process will block when reading from disk, and the reason that (Unix) files can be the object of select() calls is to allow users to perform non-blocking reads and continue to process while waiting for disk data to arrive. I agree the blocking period is *more predictable* than for network data, but "disk file access won't cause a process to block" is a misleading and incorrect, though frequent, assumption. I agree that it's difficult to actually write asynchronous disk I/O in such a way as to improve performance, but it can be done. Except on platforms where select() can't be applied to disk files, of course. In practice most applications that need the scalability will use threading or multiple processes. > If we are indeed talking about a pipe or something that > really can block, and you call fileobject.read(1024), > it will block until it gets 1024 bytes. > > Donn Cave, donn at u.washington.edu Disk access can block. When access is made to a file object in non-blocking mode it will return whatever data there are immediately available in the buffers, up to the number of bytes requested. If the buffers are currently empty the process will generate an error (which in Python becomes an exception). regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From Scott.Daniels at Acm.Org Thu Dec 23 10:22:07 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 23 Dec 2004 07:22:07 -0800 Subject: Why are tuples immutable? In-Reply-To: References: <41BE1644.8050906@freemail.gr> <10s1si0fb0l4pae@corp.supernews.com> <10s4a4rso24vb83@corp.supernews.com> <10sgqefdb77nn5a@corp.supernews.com> <10sjct6d3e85m6d@corp.supernews.com> Message-ID: <41cae042$1@nntp0.pdx.net> Antoon Pardon wrote: > Op 2004-12-22, Jeff Shannon schreef : >>The problem is that once the object has mutated, you *don't know* what >>bucket it used to sort into. There is no point at which a dictionary >>can see "before" and "after" -- it just sees two different lists. This is half the problem. In the period where an element is in the wrong hash bucket, a new entry for the same value can be created in the proper hash bucket. Then the code will have to determine how to merge two entries at rehash time. --Scott David Daniels Scott.Daniels at Acm.Org From kdart at kdart.com Sat Dec 11 06:03:21 2004 From: kdart at kdart.com (Keith Dart) Date: Sat, 11 Dec 2004 11:03:21 GMT Subject: High level SNMP In-Reply-To: References: Message-ID: <41BAD3F8.1070209@kdart.com> Jeremy Sanders wrote: > Hi - > > I'd like to write a program which basically does a few snmpgets. I haven't > been able to find a python package which gives you a nice high-level and > simple way of doing this (like PHP has). Everything appears to be > extremely low level. All I need is SNMPv1. > > Does anyone know of a simple python package for doing this? I'd rather > have something written in pure python, so that it is easily cross-platform. > > Jeremy > The pyNMS package at sourceforge has a complete SNMP (v1, v2c) implementation. In pure Python, and fairly self contained. See http://sourceforge.net/projects/pynms There are few docs, sorry. If you want to use it and have any questions then please let me know (I wrote it). BTW, you can also read MIB files if you have libsmi installed. But the pyNMS package contains a utility called mib2py that converts MIB objects to Python, and the pyNMS package has most standard MIBS pre-compiled. So, you don't really need libsmi to use the standard MIBs. The name means Python Network Management System, and will become a complete network management system with GUI and scriptability soon. ;-) There is some support for creating XHTML reports, NMS web interface, SNMP get/set, SNMP trap receiver, Ping/ICMP module, process management, MIB browser, CLI construction kit, web protocols, easy email interface, and asyncio framework. Works well with Linux or FreeBSD. (PS. It can also answer your phone and take a message) -- \/ \/ (O O) -- --------------------oOOo~(_)~oOOo---------------------------------------- Keith Dart vcard: public key: ID: F3D288E4 URL: ============================================================================ From mwm at mired.org Thu Dec 30 16:21:00 2004 From: mwm at mired.org (Mike Meyer) Date: Thu, 30 Dec 2004 15:21:00 -0600 Subject: Other notes References: <1104287020.804167.9420@f14g2000cwb.googlegroups.com> <863bxpuhlj.fsf@guru.mired.org> <41D2F35F.7050808@holdenweb.com> <86acrxt0e7.fsf@guru.mired.org> Message-ID: <86is6jscsj.fsf@guru.mired.org> "Terry Reedy" writes: > "Mike Meyer" wrote in message > news:86acrxt0e7.fsf at guru.mired.org... >> Steve Holden writes: >>> Well, perhaps you can explain how a change that's made at run time >>> (calling the decorator) can affect the parser's compile time behavior, >>> then. At the moment, IIRC, the only way Python code can affect the >>> parser's behavior is in the __future__ module, which must be imported >>> at the very head of a module. >> >> By modifying the parsers grammer at runtime. After all, it's just a >> data structure that's internal to the compiler. > > Given that xx.py is parsed in its entirety *before* runtime, that answer is > no answer at all. Runtime parser changes (far, far from trivial) could > only affect the result of exec and eval. and import. I.e., you could do: import french import python_with_french_keywords http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From francisl at aei.ca Sun Dec 12 14:57:50 2004 From: francisl at aei.ca (Francis Lavoie) Date: Sun, 12 Dec 2004 14:57:50 -0500 Subject: newsgroups In-Reply-To: References: <41b89738$0$11034$a1866201@visi.com> <41b8a6f9$0$9757$a1866201@visi.com> Message-ID: <41BCA2BE.8040907@aei.ca> Do we need a special account or something to use the newsgroup instead of the mailling list? From steven.bethard at gmail.com Fri Dec 17 12:18:46 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 17 Dec 2004 17:18:46 GMT Subject: Cool object trick In-Reply-To: References: Message-ID: Robert Brewer wrote: > Alex Stapleton wrote: > >>you can't do >> >>var = "varA" >>obj = struct(varA = "Hello") >>print obj.var >> >>and expect it to say Hello to you. > > Did you mean "print obj.varA"? I believe he meant that he wanted the equivalent of: getattr(obj, var) Steve From peter at engcorp.com Mon Dec 13 12:59:23 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 13 Dec 2004 12:59:23 -0500 Subject: uptime for Win XP? In-Reply-To: References: Message-ID: Andrey Ivanov wrote: > [Peter Hanson] >>For the life of me, however, I can't figure out how to do it. > > Here's how. :-) > > ================================================================= > import win32pdh > > query = win32pdh.OpenQuery() > counter = win32pdh.AddCounter(query, r"\System\System Up Time") Argh! A _leading backslash_ !! :-( (Thanks. :-) -Peter From grumman at example.com Thu Dec 16 20:20:09 2004 From: grumman at example.com (Grumman) Date: Thu, 16 Dec 2004 20:20:09 -0500 Subject: Accessing DB2 with Python In-Reply-To: References: Message-ID: Jarek Zgoda wrote: > Be aware, that it's a module for "normal" DB2, not a DB2/400. To access > DB2/400 you have to use ClientAccess ODBC (from Windows or *nix > platform) driver or iSeries port of Python (from AS/400). > And just to be complete, under windows, using win32all, you can also use the OLE DB driver supplied with ClientAccess (IBMDA400), which offers some improvements over plain ODBC. Its been a long time since I did this, but it was *very* simple. I could probably dig up an example or two if necessary. Connection string basically looks like: Provider=IBMDA400;User ID=USERNAME;Password=PASSWORD;Initial Catalog=DATABASE_NAME;Data Source=AS_400_SERVER_NAME Provider,User ID, Password, and Data Source are required. Data Source can be either an IP address, or a DNS defined hostname. I've never bothered with 'Initial Catalog', but it would be one of the database names visible via WRKDBR. (Usually defaults to the default system name, which is shipped set to the system serial#) Optionally, you can add 'Catalog Library List=Lib1 Lib2 Lib3' to add additional libraries to the current library list for the connection. Last I knew, there were a few methods exposed by ADO that weren't supported via this driver, but like I said, its been a long time. I'm sure there's a pretty complete python ADO wrapper out there as well. From chazen at gmail.com Tue Dec 7 11:52:16 2004 From: chazen at gmail.com (Charlie DeTar) Date: Tue, 07 Dec 2004 11:52:16 -0500 Subject: embedded python and interpreter threads In-Reply-To: References: Message-ID: Woohoo, fixed my problem. It had to do with the way I was handling the methods which overwrote stderr and stdout. Yeehaw! =Charlie Charlie DeTar wrote: > Quick correction, sorry - the command should read like this (I had > omitted the "log" before 'CaptureStdout' and 'CaptureStderr'). Same > problems exist. > > PyRun_SimpleString( > "import log\n" > "import sys\n" > "class StdoutCatcher:\n" > "\tdef write(self, str):\n" > "\t\tlog.CaptureStdout(str)\n" > "class StderrCatcher:\n" > "\tdef write(self, str):\n" > "\t\tlog.CaptureStderr(str)\n" > "sys.stdout = StdoutCatcher()\n" > "sys.stderr = StderrCatcher()\n"); > > =Charlie > > Charlie DeTar wrote: > >> So, I have an amazing, functioning foobar class that embeds python. >> Only trouble is, I want to be able to have multiple foobar objects at >> once, each with their own interpreters, stdouts, and stderrs. >> >> My initialization of the python interpreter in the class "x" is as >> follows: >> [snip] >> if (!Py_IsInitialized()) { >> PyEval_InitThreads(); >> Py_Initialize(); >> } // Start and switch to a new interpreter thread. >> x->thread = Py_NewInterpreter(); >> >> // initialize the module 'logMethods', defined elsewhere, >> // which contains my stdout and stderr definitions >> Py_InitModule("log", logMethods); >> // overwrite Python's stdout and stderr >> PyRun_SimpleString( >> "import log\n" >> "import sys\n" >> "class StdoutCatcher:\n" >> "\tdef write(self, str):\n" >> "\t\t.CaptureStdout(str)\n" >> "class StderrCatcher:\n" >> "\tdef write(self, str):\n" >> "\t\t.CaptureStderr(str)\n" >> "sys.stdout = StdoutCatcher()\n" >> "sys.stderr = StderrCatcher()\n"); From fperez528 at yahoo.com Tue Dec 7 22:35:25 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Tue, 07 Dec 2004 20:35:25 -0700 Subject: memoize factorial example (was Re: decorators ?) References: <1102458244.004fc0dc548f5536ec77f769e501ff1e@teranews> Message-ID: Fernando Perez wrote: > No, fact(0)==1 simply because any proper definition of a factorial has to > match > up with the gamma function (offset by one) at all non-negative integers. So > there's no room for any ambiguity here. I should have added a link to the ever-useful mathworld: http://mathworld.wolfram.com/Factorial.html This has as much detail about n! and Gamma(z) as you'll ever want to know :) Cheers, f From greg.lindstrom at novasyshealth.com Wed Dec 8 18:29:19 2004 From: greg.lindstrom at novasyshealth.com (Greg Lindstrom) Date: Wed, 08 Dec 2004 17:29:19 -0600 Subject: Creating Fixed Length Records Message-ID: <41B78E4F.6030608@novasyshealth.com> Hello- I'm creating fixed-length record layouts for various record translations I need to perform. I have been using a home-grown object, "FixedLengthRecord" for about 4 years now and am very happy with it. Almost. The burr under my saddle occurs when I serialize the record. Currently, I create an empty text field and for each record in my database (all record layouts, data types, lengths, defaults, etc. are held in an SQL server) I concatenate the field to the text segment. I have been led to believe this is bad form because Python will copy the entire segment each time I add a field. Up until now, it was not a big deal because the segments had at most 20 fields. I have just been handed a record layout that is almost 5000 bytes long with 350 fields in it. Gulp!! Although I could let my object churn away on this bad boy, I'd like to know if there is a more pythonic way to serialize the record. One thought I had, which might lead to an addition to the language, was to use the struct module. If I could feed the pack method a format string then a tuple of values (instead of individual values), then I could create the format string once, then pass it a tuple with the values for that record. Just a thought. So, gurus, what are your suggestions to tame this record? Are there easier ways that I'm just not seeing? Thanks, --greg From bulba at bulba.com Thu Dec 30 19:41:13 2004 From: bulba at bulba.com (Bulba!) Date: Fri, 31 Dec 2004 01:41:13 +0100 Subject: Speed ain't bad Message-ID: <0189t05r3226bkp5e1vtmp0gd6odcsf2qp@4ax.com> One of the posters inspired me to do profiling on my newbie script (pasted below). After measurements I have found that the speed of Python, at least in the area where my script works, is surprisingly high. This is the experiment: a script recreates the folder hierarchy somewhere else and stores there the compressed versions of files from source hierarchy (the script is doing additional backups of the disk of file server at the company where I work onto other disks, with compression for sake of saving space). The data was: 468 MB, 15057 files, 1568 folders (machine: win2k, python v2.3.3) The time that WinRAR v3.20 (with ZIP format and normal compression set) needed to compress all that was 119 seconds. The Python script time (running under profiler) was, drumroll... 198 seconds. Note that the Python script had to laboriously recreate the tree of 1568 folders and create over 15 thousand compressed files, so it had more work to do actually than WinRAR did. The size of compressed data was basically the same, about 207 MB. I find it very encouraging that in the real world area of application a newbie script written in the very high-level language can have the performance that is not that far from the performance of "shrinkwrap" pro archiver (WinRAR is excellent archiver, both when it comes to compression as well as speed). I do realize that this is mainly the result of all the "underlying infrastructure" of Python. Great work, guys. Congrats. The only thing I'm missing in this picture is knowledge if my script could be further optimised (not that I actually need better performance, I'm just curious what possible solutions could be). Any takers among the experienced guys? Profiling results: >>> p3.sort_stats('cumulative').print_stats(40) Fri Dec 31 01:04:14 2004 p3.tmp 580543 function calls (568607 primitive calls) in 198.124 CPU seconds Ordered by: cumulative time List reduced from 69 to 40 due to restriction <40> ncalls tottime percall cumtime percall filename:lineno(function) 1 0.013 0.013 198.124 198.124 profile:0(z3()) 1 0.000 0.000 198.110 198.110 :1(?) 1 0.000 0.000 198.110 198.110 :1(z3) 1 1.513 1.513 198.110 198.110 zmtree3.py:26(zmtree) 15057 14.504 0.001 186.961 0.012 zmtree3.py:7(zf) 15057 147.582 0.010 148.778 0.010 C:\Python23\lib\zipfile.py:388(write) 15057 12.156 0.001 12.156 0.001 C:\Python23\lib\zipfile.py:182(__init__) 32002 7.957 0.000 8.542 0.000 C:\PYTHON23\Lib\ntpath.py:266(isdir) 13826/1890 2.550 0.000 8.143 0.004 C:\Python23\lib\os.py:206(walk) 30114 3.164 0.000 3.164 0.000 C:\Python23\lib\zipfile.py:483(close) 60228 1.753 0.000 2.149 0.000 C:\PYTHON23\Lib\ntpath.py:157(split) 45171 0.538 0.000 2.116 0.000 C:\PYTHON23\Lib\ntpath.py:197(basename) 15057 1.285 0.000 1.917 0.000 C:\PYTHON23\Lib\ntpath.py:467(abspath) 33890 0.688 0.000 1.419 0.000 C:\PYTHON23\Lib\ntpath.py:58(join) 109175 0.783 0.000 0.783 0.000 C:\PYTHON23\Lib\ntpath.py:115(splitdrive) 15057 0.196 0.000 0.768 0.000 C:\PYTHON23\Lib\ntpath.py:204(dirname) 33890 0.433 0.000 0.731 0.000 C:\PYTHON23\Lib\ntpath.py:50(isabs) 15057 0.544 0.000 0.632 0.000 C:\PYTHON23\Lib\ntpath.py:438(normpath) 32002 0.431 0.000 0.585 0.000 C:\PYTHON23\Lib\stat.py:45(S_ISDIR) 15057 0.555 0.000 0.555 0.000 C:\Python23\lib\zipfile.py:149(FileHeader) 15057 0.483 0.000 0.483 0.000 C:\Python23\lib\zipfile.py:116(__init__) 151 0.002 0.000 0.435 0.003 C:\PYTHON23\lib\site-packages\Pythonwin\pywin\framework\winout.py:171(write) 151 0.002 0.000 0.432 0.003 C:\PYTHON23\lib\site-packages\Pythonwin\pywin\framework\winout.py:489(write) 151 0.013 0.000 0.430 0.003 C:\PYTHON23\lib\site-packages\Pythonwin\pywin\framework\winout.py:461(HandleOutput) 76 0.087 0.001 0.405 0.005 C:\PYTHON23\lib\site-packages\Pythonwin\pywin\framework\winout.py:430(QueueFlush) 15057 0.239 0.000 0.340 0.000 C:\Python23\lib\zipfile.py:479(__del__) 15057 0.157 0.000 0.157 0.000 C:\Python23\lib\zipfile.py:371(_writecheck) 32002 0.154 0.000 0.154 0.000 C:\PYTHON23\Lib\stat.py:29(S_IFMT) 76 0.007 0.000 0.146 0.002 C:\PYTHON23\lib\site-packages\Pythonwin\pywin\framework\winout.py:262(dowrite) 76 0.007 0.000 0.137 0.002 C:\PYTHON23\lib\site-packages\Pythonwin\pywin\scintilla\formatter.py:221(OnStyleNeeded) 76 0.011 0.000 0.118 0.002 C:\PYTHON23\lib\site-packages\Pythonwin\pywin\framework\interact.py:197(Colorize) 76 0.110 0.001 0.112 0.001 C:\PYTHON23\lib\site-packages\Pythonwin\pywin\scintilla\control.py:69(SCIInsertText) 76 0.079 0.001 0.081 0.001 C:\PYTHON23\lib\site-packages\Pythonwin\pywin\scintilla\control.py:333(GetTextRange) 76 0.018 0.000 0.020 0.000 C:\PYTHON23\lib\site-packages\Pythonwin\pywin\scintilla\control.py:296(SetSel) 76 0.006 0.000 0.018 0.000 C:\PYTHON23\lib\site-packages\Pythonwin\pywin\scintilla\document.py:149(__call__) 227 0.003 0.000 0.012 0.000 C:\Python23\lib\Queue.py:172(get_nowait) 76 0.007 0.000 0.011 0.000 C:\PYTHON23\lib\site-packages\Pythonwin\pywin\framework\interact.py:114(ColorizeInteractiveCode) 532 0.011 0.000 0.011 0.000 C:\PYTHON23\lib\site-packages\Pythonwin\pywin\scintilla\control.py:330(GetTextLength) 76 0.001 0.000 0.010 0.000 C:\PYTHON23\lib\site-packages\Pythonwin\pywin\scintilla\view.py:256(OnBraceMatch) 1888 0.009 0.000 0.009 0.000 C:\PYTHON23\Lib\ntpath.py:245(islink) --- Script: #!/usr/bin/python import os import sys from zipfile import ZipFile, ZIP_DEFLATED def zf(sfpath, targetdir): if (sys.platform[:3] == 'win'): tgfpath=sfpath[2:] else: tgfpath=sfpath zfdir=os.path.dirname(os.path.abspath(targetdir) + tgfpath) zfpath=zfdir + os.path.sep + os.path.basename(tgfpath) + '.zip' if(not os.path.isdir(zfdir)): os.makedirs(zfdir) archive=ZipFile(zfpath, 'w', ZIP_DEFLATED) sfile=open(sfpath,'rb') zfname=os.path.basename(tgfpath) archive.write(sfpath, os.path.basename(zfpath), ZIP_DEFLATED) archive.close() ssize=os.stat(sfpath).st_size zsize=os.stat(zfpath).st_size return (ssize,zsize) def zmtree(sdir,tdir): n=0 ssize=0 zsize=0 sys.stdout.write('\n ') for root, dirs, files in os.walk(sdir): for file in files: res=zf(os.path.join(root,file),tdir) ssize+=res[0] zsize+=res[1] n=n+1 #sys.stdout.write('.') if (n % 200 == 0): print " %.2fM (%.2fM)" % (ssize/1048576.0, zsize/1048576.0) #sys.stdout.write(' ') return (n, ssize, zsize) if __name__=="__main__": if len(sys.argv) == 3: if(os.path.isdir(sys.argv[1]) and os.path.isdir(sys.argv[2])): (n,ssize,zsize)=zmtree(os.path.abspath(sys.argv[1]),os.path.abspath(sys.argv[2])) print "\n\n Summary:\n Number of files compressed: %d\n Total size of original files: %.2fM\n \ Total size of compressed files: %.2fM" % (n, ssize/1048576.0, zsize/1048576.0) sys.exit(0) else: print "Incorrect arguments." if (not os.path.isdir(sys.argv[1])): print sys.argv[1] + " is not directory." if (not os.path.isdir(sys.argv[2])): print sys.argv[2] + " is not directory." print "\n Usage:\n " + sys.argv[0] + " source-directory target-directory" -- It's a man's life in a Python Programming Association. From hasan at in2p3.fr Sun Dec 12 19:47:48 2004 From: hasan at in2p3.fr (Adil Hasan) Date: Mon, 13 Dec 2004 01:47:48 +0100 (CET) Subject: Best book on Python? In-Reply-To: Message-ID: hello, Just my 2 farthings worth... Although Python and Tkinter is a good book it was written at the time of Python 1.5 (so there may be some transformation that needs to be done on some of the examples) you may want to take a look at Python in a Nutshell by A. Martelli published by O'Reilly. It has a section on Tkinter and many other things that you may find useful. ah On Mon, 13 Dec 2004, Rod Haper wrote: > Michael McGarry wrote: > > I have many years of programming experience and know a little bit of > > Tcl. I am looking for a book to detail on the features including GUI in > > a reference style. > > Given that you have some acquaintance with Tcl, if you want a reference > that caters toward GUI programming in Python using Tk, you might find > this book of interest: "Python and Tkinter Programming" by John Grayson. > Manning Publications, 2000, 658p > > -- > Rod > -- > http://mail.python.org/mailman/listinfo/python-list > From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Wed Dec 15 11:39:09 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Wed, 15 Dec 2004 17:39:09 +0100 Subject: Small Problem P 2.4 (line>2048 Bytes) References: <41bfeff9$0$10232$8fcfb975@news.wanadoo.fr> Message-ID: <41c0894b$0$9558$8fcfb975@news.wanadoo.fr> Hi ! You are a very good soothsayer (*) ! With # -*- coding: cp-1252 -*- it's bugging With # -*- coding: utf-8 -*- it's OK ! (*) soothsayer is the masculine of pythoniss (good english term ?) -- Michel Claveau From simon.brunning at gmail.com Tue Dec 14 11:42:19 2004 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 14 Dec 2004 16:42:19 +0000 Subject: gather information from various files efficiently In-Reply-To: References: <3e96ebd7.0412140111.69244c7c@posting.google.com> <41BEB2CA.8070802@kdart.com> <41bec51a$1_2@newspeer2.tds.net> Message-ID: <8c7f10c60412140842639c8cd@mail.gmail.com> On Tue, 14 Dec 2004 10:40:56 -0500, Peter Hansen wrote: > Keith Dart wrote: > > Sigh, this reminds me of a discussion I had at my work once... It seems > > to write optimal Python code one must understand various probabilites of > > your data, and code according to the likely scenario. > > And this is different from optimizing in *any* other language > in what way? In other languages, by the time you get the bloody thing working it's time to ship, and you don't have to bother worrying about making it optimal. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From jstroud at mbi.ucla.edu Mon Dec 13 19:54:25 2004 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 13 Dec 2004 16:54:25 -0800 Subject: Organising data within a program In-Reply-To: References: Message-ID: <200412131654.25782.jstroud@mbi.ucla.edu> Python is an object oriented (OO) language. The very best thing if you have a lot of time is to learn the language fully, read several books on database design, and implement a gui driven app, OO from top to bottom. If you need to get something to work before you have time to become a pythonologist, try an array of dictionaries (AoD), a datastructure I find very handy in a pinch. Here are some patterns for you to think about (also have some masochistic fun trying to do something similar in perl--now try in perl without pointers if you cheated!): # # my_aod.py : an aod example module # # top of your module import pickle # saving your database (3 steps recommended) def my_save_aod(aod,filename): afile = open(filename,"w") pickle.dump(aod,afile) afile.close() # load your database (3 steps recommended) def my_load_aod(filename): afile = open(filename) an_aod = pickle.load(afile) afile.close() return an_aod # get a subset whose records match the key def my_aod_find(aod,akey,avalue): sub_aod = [] for element in aod: if element[akey] == avalue: sub_aod.append(element) return sub_aod # a simple key based sort def my_aod_sort(aod,akey): return_aod = aod[:] return_aod.sort(lambda x,y : cmp(x[akey],y[akey])) return return_aod # # methinks a module hath I begun # # end my_aod.py ########################################################### # example usage of an aod (new file) # from my_aod import * # some records to start you off bob = {"name":"Bob","spouse":"Carol","phone":"8675309"} carol = {"name":"Ted","spouse":"Alice","phone":"5551212"} ted = {"name":"Alice","spouse":"Ted","phone":"5551212"} alice = {"name":"Carol","spouse":"Bob","phone":"8675309"} # adding records arbitrarily database = [bob] database.extend([carol,ted]) database.append(alice) # playing with find and sort for person in my_aod_find(database,"name","Bob"): print "name:", person["name"], "; spouse:", person["spouse"] for person in my_aod_sort(database,"name"): print "name:", person["name"] for person in my_aod_sort(database,"spouse"): print "name:", person["name"], "; spouse:", person["spouse"] my_save_aod(database,"people.pkl") new_db = my_load_aod("people.pkl") for person in new_db: print "name:", person["name"], "; spouse:", person["spouse"] On Monday 13 December 2004 03:06 pm, Nick Evans wrote: > Hey all, > I am currently working on a simple program (small group membership > database) just to get to grips with the language (bit of a newbie here :-)) > and am wondering about the best way of organising the data within the > program. > > >From my understanding I would have something like person1 > > =("name","address","phone","subs-due") > Then you would put membershipdatabase = (person1, person2, personX....) > etc > Now is this the best way of organising this data within the program or is > there a better "known" way? > > Also I want to just store this info to a standard txt file. Probably CSV or > something. Is there any particular way I should be saving this data to > file? > > > Thanks in advance > > Nick -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics 611 Charles E. Young Dr. S. MBI 205, UCLA 951570 Los Angeles CA 90095-1570 http://www.jamesstroud.com/ From Norbert.Klamann at klamann-software.de Wed Dec 22 06:38:17 2004 From: Norbert.Klamann at klamann-software.de (Norbert) Date: 22 Dec 2004 03:38:17 -0800 Subject: Threading Problem Message-ID: <1103715496.971145.215260@z14g2000cwz.googlegroups.com> Hello *, i am experimenting with threads and get puzzling results. Consider the following example: #-------------------- import threading, time def threadfunction(): ....print "threadfunction: entered" ....x = 10 ....while x < 40: ........time.sleep(1) # time unit is seconds ........print "threadfunction x=%d" % x ........x += 10 print "start" th = threading.Thread(target = threadfunction()) th.start() print "start completed" #-------------------- (the dots are inserted becaus Google mangles the lines otherwise) This program gives the following result : ---- start threadfunction: entered threadfunction x=10 threadfunction x=20 threadfunction x=30 start completed ---- My aim was that the main program should continue to run while threadfunction runs in parallel. That's the point of threads after all, isn't it ? I awaited something like the following : start threadfunction: entered start completed <------------------- threadfunction x=10 threadfunction x=20 threadfunction x=30 Does anyone know what's going on here ? Thanks for listening ! Norbert From steve at holdenweb.com Mon Dec 20 10:18:24 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 20 Dec 2004 10:18:24 -0500 Subject: Newbie: A very basic problem related to cgi.py In-Reply-To: References: <1103550481.686003.172960@f14g2000cwb.googlegroups.com> <41C6E649.5050004@holdenweb.com> Message-ID: <_5Cxd.57045$Jk5.33655@lakeread01> Peter Hansen wrote: > Steve Holden wrote: > >> Traceback (most recent call last): >> File "cgi.py", line 2, in ? >> import cgi >> File "/c/steve/cgi.py", line 12, in ? >> main() >> File "/c/steve/cgi.py", line 6, in main >> form = cgi.FieldStorage() >> AttributeError: 'module' object has no attribute 'FieldStorage' >> >> Ha! There's a naming confusion between the imported cgi module and >> your main program. Rename it to something else and all should be well >> (or at least better ;-) > > > I suspected that too, Steve, but why would it be showing > the library cgi.py in the traceback if he had a local > one with the same name? Weird. (Unless, as I wondered > in my redundant reply, the traceback he posted wasn't > the real traceback...) > It *is* a little puzzling. I suspect that the problem might have been due to repeated imports or some such. But I don't know. Only Ali can tell us how he got that traceback. I wondered whether it could have been an IDE, but neither IDLE nor PythonWin exhibit such strangeness. Very odd. Ali? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From mwm at mired.org Sat Dec 11 01:32:14 2004 From: mwm at mired.org (Mike Meyer) Date: Sat, 11 Dec 2004 00:32:14 -0600 Subject: newbie questions References: <41ba6511$1@nntp.zianet.com> Message-ID: Adam DePrince writes: > Alright. Now, as Erik pointed out if you assign to the variable the > computer will add that to the local name space. This happens at > "compile" time (which is right after you hit enter twice at the CPython > command line.) > > For an example of this: > >>>> a = 0 >>>> def b(): > ... print a > ... >>>> def c(): > ... print a > ... a = 1 > ... >>>> b() > 0 >>>> c() > Traceback (most recent call last): > File "", line 1, in ? > File "", line 2, in c > UnboundLocalError: local variable 'a' referenced before assignment > > In b(), a was taken as being from the line above. In c, it was from the > local name space. > > So, how do we affect what you want? I *have* to point out here that you can write c as: >>> a = 2 >>> def c(): ... global a ... print a ... a = 1 ... >>> c() 2 >>> The one (and so far only) place you can declare a variable in Python. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From philippecmartin at sbcglobal.net Mon Dec 6 09:00:37 2004 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Mon, 6 Dec 2004 08:00:37 -0600 Subject: byte code generated under linux ==> bad magic number under windows Message-ID: <200412060800.37358.philippecmartin@sbcglobal.net> Hi, I understand from my reading that a .pyc generated by python anywhere should run anywhere else - is that true ? If I generate 'compile.all' a pyc with python 2.3.3 under Linux, I get a 'bad magic number' trying to execute it under windows (2.4). What am I doing wrong ? are the pyc plateform dependant ? and if so must I generate one version for each version of Linux, windows ...... ? Regards, Philippe -- ********************* Philippe C. Martin SnakeCard LLC www.snakecard.com ********************* From csgcsg39 at hotmail.com Wed Dec 8 06:39:37 2004 From: csgcsg39 at hotmail.com (C Gillespie) Date: Wed, 8 Dec 2004 11:39:37 -0000 Subject: spawn or fork References: Message-ID: "Miki Tebeka" wrote in message news:mailman.7359.1102503309.5135.python-list at python.org... > Hello Colin, > > > I have a function > > def printHello(): > > fp = open('file','w') > > fp.write('hello') > > fp.close() > > > > I would like to call that function using spawn or fork. My questions are: > > > > 1. Which should I use > spawn and fork are very different functions. Read the documentation on > each. > Note the "fork" is available only in Unix like systems. > > > 2. How do I call that function if it is defined in the same file. > Just call it. > > def foo(): > print 1 > Thanks, but can I call it using spawn? From kdart at kdart.com Mon Dec 20 02:24:45 2004 From: kdart at kdart.com (Keith Dart) Date: Mon, 20 Dec 2004 07:24:45 GMT Subject: Python To Send Emails Via Outlook Express In-Reply-To: <1103521500.427846.238790@c13g2000cwb.googlegroups.com> References: <1103519604.987664.117400@c13g2000cwb.googlegroups.com> <1103521500.427846.238790@c13g2000cwb.googlegroups.com> Message-ID: <41C67E3D.5040205@kdart.com> ian at kirbyfooty.com wrote: > Hi Ganesan > I tried changing s.Send to s.Send(). It now comes up with an exception > error.. > > The details are below. Looks like the COM part works, but sending mail has an error from the SMTP host. But, slightly off topic, FYI, Python can send email directly with the email and snmplib modules. -- -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Keith Dart public key: ID: F3D288E4 ===================================================================== From robin at reportlab.com Fri Dec 10 06:13:06 2004 From: robin at reportlab.com (Robin Becker) Date: Fri, 10 Dec 2004 11:13:06 +0000 Subject: PIL for Windows for Python 2.4 In-Reply-To: <1102587036.703951.63690@z14g2000cwz.googlegroups.com> References: <1102587036.703951.63690@z14g2000cwz.googlegroups.com> Message-ID: <41B984C2.4000604@chamonix.reportlab.co.uk> Fuzzyman wrote: > So you've built PIL for windows, Python 2.4 ? > > Any chance of sharing it ? What compiler have you configured distutils > to use ? > > Regards, > > Fuzzyman > I have compiled 1.1.4's _imaging & _imagingft for 2.4 and have placed them at http://www.reportlab.org/ftp/win32-dlls/2.4 Don't have a decent TCL any more so haven't compiled that stuff. -- Robin Becker From exarkun at divmod.com Thu Dec 23 09:37:04 2004 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 23 Dec 2004 14:37:04 GMT Subject: Lambda going out of fashion In-Reply-To: Message-ID: <20041223143704.10762.1626930663.divmod.quotient.393@ohm> On Thu, 23 Dec 2004 13:36:08 GMT, rzed wrote: >Stephen Thorne wrote in > news:mailman.8299.1103775211.5135.python-list at python.org: > > [snip] > > > > { > > 'one': lambda x:x.blat(), > > 'two': lambda x:x.blah(), > > }.get(someValue, lambda x:0)(someOtherValue) > > > > The alternatives to this, reletively simple pattern, which is a > > rough parallel to the 'switch' statement in C, involve creating > > named functions, and remove the code from the context it is to > > be called from (my major gripe). > > > > [snip] > > Not addressing lambdas per se, but something similar to your pseudo- > switch statement can be done without using them at all. One way might > be to use a function dictionary wrapped in an accessor function, such > as this: > > def dofns(key): > fd2 = { > 0:'print "Key 0"', > 1:'print "one"', > 4:"\n".join(['for ix in range(15):', > ' print "%s%d" % (" "*ix,ix)']), > } > try: > exec(fd2[key]) > except KeyError: > print 'Key',key,'not found' > I hate to be nasty, but *ugh* what a horrible way to start the day. There are so many things wrong with this. By exec'ing code strings you lose compile-time _syntax_ checking. I'm all for dynamicism, but it really is nice to let the compiler do _something_ things for you. By exec'ing code strings you slow down the entire function by forcing a slower name-lookup code path in the interpreter. By exec'ing code strings you lose the ability to pass values back to your caller (oh, you could "return" in one of those, but *ugg* that'd be even more terrible, and probably not what you want in most cases, since it doesn't let you get at the value except from your caller. you could also set names in the local namespace but that's pretty messed up too, python already has a function return convention, making up your own is no fun). There are probably more reasons this is bad too. Even using `def' to define a function for each of these would be preferable. Aside from that, exec() isn't a function. You "exec foo", not "exec(foo)". The latter works simply because parens act as to set precedent instead of as part of function call syntax when used this way. Also, you should do the dictionary lookup first, in a try/except, and then execute it later, _outside_ the try/except, otherwise you risk masking KeyErrors from exec'd code. Jp From fredrik at pythonware.com Mon Dec 20 01:43:43 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Dec 2004 07:43:43 +0100 Subject: Is this a good use for lambda References: <41c654b9.529432724@news.oz.net> Message-ID: Bengt Richter wrote: >>Ahem. If you name the function, you can reuse the name (or just forget about it) >>as soon as you've used the function object. >> >>If you don't want to reuse the name because you might want to reuse the function >>object, you have to name it anyway. >> > Are you forgetting that all bindings are not directly name bindings as created by def? ;-) > (See also various tkinter-related uses). > > >>> funs = [lambda:'one', lambda:'two', lambda:'three'] now you've used the function objects once each. > >>> for use in xrange(2): > ... for i in xrange(3): > ... print '%susing fun[%s] => %r' %('re'*(use>0), i, funs[i]()) and now you're using the data structure you built... at this point, it doesnt matter if the functions had distinct names to start with. (coming up with a contrived example where it matters is trivial, of course, but by then, we've moved into "whitespace" or "static typing leads to more reliable code" country) From __peter__ at web.de Wed Dec 8 15:17:11 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 08 Dec 2004 21:17:11 +0100 Subject: Recursive list comprehension References: Message-ID: Adam DePrince wrote: > def flatten( i ): > try: > i = i.__iter__() > while 1: > j = flatten( i.next() ) > try: > while 1: > yield j.next() > except StopIteration: > pass > except AttributeError: > yield i While trying to break your code with a len() > 1 string I noted that strings don't feature an __iter__ attribute. Therefore obj.__iter__() is not equivalent to iter(obj) for strings. Do you (plural) know whether this is a CPython implementation accident or can be relied upon? Peter From hancock at anansispaceworks.com Sat Dec 11 01:44:12 2004 From: hancock at anansispaceworks.com (Terry Hancock) Date: Sat, 11 Dec 2004 00:44:12 -0600 Subject: Drawing Cogwheels and Combinatoric diagrams In-Reply-To: <41ADF3D0.2060308@gremlinhosting.com> References: <41ADF3D0.2060308@gremlinhosting.com> Message-ID: <200412110044.12194.hancock@anansispaceworks.com> On Wednesday 01 December 2004 10:39 am, Andrew James wrote: > Gentlemen, > I'm looking for a graphing or drawing python package that will allow me > to draw complex geometric shapes. I need to be able to create shapes > like cogwheels and Venn diagrams: > > http://encyclopedia.thefreedictionary.com/Venn > > The library must support alpha blending and the ability to return x,y > co-ordinates for a shape, as I want to draw an imagemap on top of parts > of the shape. > > Can PIL do this, or do I need to go the way of GnuPlot or Gri? Can > anyone give me an example of a complex shape drawn like this? Although I believe PIL can do some of this in principle, it isn't really designed for it. You might want to look into Skencil. Although it is usually regarded as a GUI application, it is also a python vector graphics package. See http://skencil.org. The one thing I think will be a problem is the alpha-blending, as Skencil either doesn't support it or hasn't for very long (so you'd need the very latest version). However, you can, of course, use PIL to alpha blend graphics after they've been rastorized, which might work for you. Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From aleaxit at yahoo.com Fri Dec 24 03:23:51 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 24 Dec 2004 09:23:51 +0100 Subject: Global variables and modules References: <1103867020.615307.16240@z14g2000cwz.googlegroups.com> Message-ID: <1gpajuq.b0b5i81ho3dfpN%aleaxit@yahoo.com> wrote: ... > and here is the test script, test1.py > ------------------------------------- > > from test2 import glbl, inc_glbl, get_glbl Think of this as roughly equivalent to: import locl glbl = test2.glbl and so on. That is, after the 'from test2 import', the two names test1.glbl and test2.glbl refer to the same object. But if you now rebind name test2.glbl to refer to a distinct object, that of course has no effect on name test1.glbl. > I would expect the three values to be ( 25, 26, 26 ), but what I get is Why? Take an equivalent: a = 25 b = a a = 26 would you now expect name b to be magically rebound to 26? If so, then you have a very peculiar mental model for name/value correspondences, one that doesn't happen to hold in any language I know, surely not in Python. To repeat a commonly used metaphor: think of names as post-it notes that may be attached to some piece of furniture, and moved from one to another. The notes are NOT attached to each other, but rather to the objects: moving one post-it does not affect other post-its. > It seems that the references to 'glbl' are seeing a local copy, rather No copy whatsoever is involved. After the assignment (binding) you do with 'from test2 import', names test1.glbl and test2.glbl refer to the same object (value). If you now rebind either name, the other is unaffected. > than the original. This is not what the literature says should be > happening. If you can point to sentences in "the literature" which have misled you into believing a different behavior would be expected, I'll do my best to fix those sentences (as a book and article author, editor, reviewer, and Python contributor). While the Python docs, including books &c, are far from perfect, I doubt there is any such blooper left in them. > I am looking for a way to share data between modules. Can If you really must, consider using a container object. The most suitable container object for these tasks is often a module. I.e., code, in test1: import test2 and then refer to test2.glbl throughout. I.e., forget 'from', use 'import'. As I wrote in Python in a Nutshell, p. 120, last paragraph before "Module Loading": """ In general, the import statement is a better choice than the from statement. I suggest you think of the from statement [...] as [a] convenience meant only for occasional use in interactive Python sessions. If you always access module M with the statement import M, and always access M's attributes with explicit syntax M.A, your code will be slightly less concise, but far clearer and more readable. """ I don't know how I could have put this advice more strongly or more directly (I continue with explanations about the cases in which 'from' is instead appropriate, chiefly getting single modules from packages). Giving strong direct advice, rather than just reference info, in a book of the "in a Nutshell" series, is not common, but I do it quite a bit; after all, "how does Python work exactly", e.g. the fact that 'from X import Y' is almost the same as 'Y = X.Y', is pretty simple to explain, and so takes up little space -- OTOH, the consequences of this, such as "thus, generally, don't use 'from', use 'import'" may not be obvious to readers, so I point them out directly. Of course, that doesn't help much if people don't _read_ it;-). Alex From rnd at onego.ru Fri Dec 10 16:26:58 2004 From: rnd at onego.ru (Roman Suzi) Date: Sat, 11 Dec 2004 00:26:58 +0300 (MSK) Subject: A puzzle Re: Decorators for multimethods In-Reply-To: References: Message-ID: For those who want to exercize Python skills, there is a problem below for defining multimethod g with as simple syntax as possible: @MULTIMETHOD def g(x, y): @PART(Foo, Foo) def m1(a, b): return 'foofoo' @PART(Foo, Bar) def m2(a, b): return 'foobar' @PART(Bar, Foo) def m3(a, b): return 'barfoo' What are definitions of MULTIMETHOD and PART in this case? (if such are at all possible). My best result was with class G(MMCLASS): def define(self): @self.PART(Foo, Foo) def m1(a, b): return 'foofoo' @self.PART(Foo, Bar) def m2(a, b): return 'foobar' @self.PART(Bar, Foo) def m3(a, b): return 'barfoo' g = G() where class MMCLASS(Multimethod.Generic): def __init__(self): Multimethod.Generic.__init__(self) def PART(*args): def make_multimethod(func): mm = Multimethod.Method(tuple(args), func) print func self.add_method(mm) return mm return make_multimethod self.PART = PART self.define() On Fri, 10 Dec 2004, Roman Suzi wrote: > >hi! > >I've found one more nice use case for decorators. I feel multimethods >could be made even nicier by defining multimethods inside special >class. But I have not figured out how to do it yet. > >#!/bin/env python2.4 >if "We have Neel Krishnaswami module Multimethod.py": > > import Multimethod > > class Foo: pass > > class Bar(Foo): pass > > def multimethod(g, *args): > def make_multimethod(func): > mm = Multimethod.Method(tuple(args), func) > g.add_method(mm) > return mm > return make_multimethod > > g = Multimethod.Generic() > > @multimethod(g, Foo, Foo) > def m1(a, b): return 'foofoo' > > @multimethod(g, Foo, Bar) > def m2(a, b): return 'foobar' > > @multimethod(g, Bar, Foo) > def m3(a, b): return 'barfoo' > > try: > print 'Argtypes ', 'Result' > print 'Foo, Foo:', g(Foo(), Foo()) > print 'Foo, Bar:', g(Foo(), Bar()) > print 'Bar, Foo:', g(Bar(), Foo()) > print 'Bar, Bar:', g(Bar(), Bar()) > except Multimethod.AmbiguousMethodError: > print 'Failed due to AmbiguousMethodError' > > >Sincerely yours, Roman Suzi > Sincerely yours, Roman Suzi -- rnd at onego.ru =\= My AI powered by GNU/Linux RedHat 7.3 From aut_gbarros at uolinc.com Mon Dec 20 11:55:40 2004 From: aut_gbarros at uolinc.com (Gabriel Cosentino de Barros) Date: Mon, 20 Dec 2004 14:55:40 -0200 Subject: Best GUI for small-scale accounting app? Message-ID: <2814F26DA6908F41927A81C410C4991A02079C0B@siamun.server.bl.corp.intranet> ( sorry about top posting) 1. Ever avoid web based. unless you have to do it webbased. I've been doing web based apps for 5 years now. it simple don't pay off! usability within a browser sucks, unless you can spend time re-writting the whell on javascript. then you have to deal with things like the back button going to a POST page, user cancel actions... it simple don't pay off unless you really has to access it from diferent machines. But ok, i think this will became a flame war if i go on... 2. from my ridiculously short experience with python-client-sided: gtk is way too clumsy. wxWindows has a weird way of handling events and such. tk is very simple. Qt i didn't even considered because of license and mainly because it's less cross plataform then java ;-) So. i did all my programs in tk. But i subclassed a lot so in the future it would be easy to just snap in another gui toolkit. -----Original Message----- From: Paul Rubin [mailto:"http://phr.cx"@NOSPAM.invalid] Sent: segunda-feira, 20 de dezembro de 2004 10:43 To: python-list at python.org Subject: Re: Best GUI for small-scale accounting app? Bulba! writes: > I'll soon start development of a specialized small app and need > to choose GUI for it. > > I have narrowed the choice to wxPython/PythonCard and QT/PyQT What does the app need to do? I'd try to make it web based unless there's a good reason not to. That's even if it just runs on the user's desktop; run the http listener on the localhost and let the user connect to it with a browser. However, between those two you mention, wxPython seems easier to use and runs on more platforms. On the other hand, it may be less well maintained than QT. For example, its current installation script seems to assume an older version of GTK is installed, and it fails with newer GTK versions. -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From jimhill at swcp.com Mon Dec 20 00:57:00 2004 From: jimhill at swcp.com (Jim Hill) Date: Mon, 20 Dec 2004 05:57:00 +0000 (UTC) Subject: Easy "here documents" ?? References: <41C5C19E.80000@kdart.com> Message-ID: Keith Dart wrote: >Jim Hill wrote: >> Is there a way to produce a very long multiline string of output with >> variables' values inserted without having to resort to this wacky > >I was thinking about this. But I can't think of any reason why you would >want to do this in Python. What's wrong with a regular parameterized >function? I'm trying to write a script that writes a script for a rather specialized task. I know that seems weird, but the original version was written in Korn shell and most of my team are familiar with the way it does things even though they don't read Korn. (The original author has since decamped for greener pastures.) Since we're trying to standardize all our scripts on Python I got the task of rewriting. Once I have the simple port done I'll see if I can't figure out A Better Way. Jim -- "I regard NASCAR the same way I regard gay porn: I know it exists and I know some guys like it; I just don't want to see it." -- Z. B. Goode From martin at v.loewis.de Tue Dec 7 02:32:43 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 07 Dec 2004 08:32:43 +0100 Subject: Python in debug version? In-Reply-To: <31l1tvF3dad3pU1@individual.net> References: <31l1tvF3dad3pU1@individual.net> Message-ID: <41b55c91$0$196$9b622d9e@news.freenet.de> mep wrote: > I view my python 2.3.4 from python.org by VC6's dependency walker tool. > What suprise me is that python.exe and python32.dll are built into *DEBUG* > version. What precisely did the tool report? To my knowledge, the DLLs are not in the debug version. Regards, Martin From tjreedy at udel.edu Tue Dec 28 01:26:19 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 28 Dec 2004 01:26:19 -0500 Subject: deriving from str References: <43ABC325.9030704@yahoo.it> <41D015C9.3050005@kzoo.edu> Message-ID: "dataangel" wrote in message news:41D015C9.3050005 at kzoo.edu... > Paolo Veronelli wrote: > >> I want to add some methods to str class ,but when I change the __init__ >> methods I break into problems Immutable types cannot be changed in __init__. They are initialized in __new__, which is normally invisible. So you have to overide that if you wish to affect the value. Google previous posts for its calling sequence. int, str, tuple, etc do not have __init__ methods since there is nothing more to once instances are initialized. Terry J. Reedy From kartic.krishnamurthy at gmail.com Sun Dec 26 09:00:29 2004 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 26 Dec 2004 06:00:29 -0800 Subject: WxListCtrl In-Reply-To: <20041226061435.11425.00002510@mb-m29.aol.com> References: <20041226061435.11425.00002510@mb-m29.aol.com> Message-ID: <1104069629.131976.189310@z14g2000cwz.googlegroups.com> You might want to try using the SetColumnWidth method and give the column width in pixels. The user (or you) can the read the entire contents by dragging the column marker to the right (or you can give a tooltip that displays the entire list control item when the moused over) self.lc.SetColumnWidth(0, 200) # Set the first list control column to 200 pixels. If you want the column to "auto adjust" to the length of the column header, no matter how long the row contents are, you cann use self.lc.SetColumnWidth(0, wx.LIST_AUTOSIZE_USEHEADER) But when you drag out the column to read more the Horizontal Scroll bar might appear. In my limited knowledge, I can not tell whether or not there is anything you can do about it. I don't think there is a way to just prevent the H. Scroll Bar from appearing at all. Thanks, --Kartic From j_belbo at hotmail.com Fri Dec 10 12:41:36 2004 From: j_belbo at hotmail.com (news.easynet.be) Date: Fri, 10 Dec 2004 18:41:36 +0100 Subject: UrlLib2 Proxy and Https Message-ID: <41b9e057$0$2027$6c56d894@feed0.news.be.easynet.net> Hello, I would like to access an HTTPS site via a proxy The following code is working for HTTP://www.hotmail.com but not for HTTPS I have try with other sites without success l_proxy_info = { 'user' : mylogin, 'pass' : mypassword, 'host' : myproxy, 'port' : 8080 } l_proxy_support = urllib2.ProxyHandler({"http" : \ "http://%(user)s:%(pass)s@%(host)s:%(port)d" % l_proxy_info}) l_opener = urllib2.build_opener(l_proxy_support, urllib2.HTTPHandler) urllib2.install_opener(l_opener) l_req = urllib2.urlopen('https://www.hotmail.com/') print l_req.headers print l_req.read() Thanks for your help, ;-) Jacobo From steve at holdenweb.com Fri Dec 24 09:21:50 2004 From: steve at holdenweb.com (Steve Holden) Date: Fri, 24 Dec 2004 09:21:50 -0500 Subject: Creating Image Maps In-Reply-To: References: Message-ID: <5FVyd.59650$Jk5.21223@lakeread01> Aaron wrote: > I know this is a thing used primarily on websites..but since python can do > anything ;) > > I'm trying to make a clickable image map for my wxPython program. > Basically, I know how to organize the images into one large image in a > panel, but how do I make the individual pieces clickable like webpage > links(in wxPython)? The goal is to add an event handler that displays the > image piece in a different panel, along with attributes. Which I could do > if only I could make the pieces clickable > > Any ideas? > > Also, if you have any hard to find links on the general area I'm talking > about, I'd like to learn as much as possible. > Basically, your approach can be completely different under wxPython - you can use a single image, and then query the mouse click events to determine which location (and therefore which portion of the image) was clicked. You *could* use separate images as well, in which case you would need to provide callback functions to be called for clicks on the various sub-portions. Take a look at the docs for wxEvent, and see if that leads you to something you can understand. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From reinhold-birkenfeld-nospam at wolke7.net Tue Dec 21 17:09:18 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 21 Dec 2004 23:09:18 +0100 Subject: input record sepArator (not sepErator) In-Reply-To: References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com><1103501833.632076.74050@f14g2000cwb.googlegroups.com><1103504587.796518.245030@f14g2000cwb.googlegroups.com><41c6386e$1@nntp0.pdx.net> <32nmqtF3ninrdU1@individual.net> <41c6fe6b$1@nntp0.pdx.net> <32r5cfF3m90glU1@individual.net> Message-ID: <32rl8eF3o4b49U2@individual.net> Peter Otten wrote: > Reinhold Birkenfeld wrote: > >>> the web: 4% >>> python: 9% >>> slashdot: 26% >>> perl: 29% * >> >> How did you get these data points? > > I copied the numbers from these pages: > > http://www.google.com/search?q=separate > http://groups-beta.google.com/group/comp.lang.python/search?group=comp.lang.python&q=separate > http://www.google.com/search?q=site%3Aslashdot.org+separate > http://groups-beta.google.com/group/comp.lang.perl.misc/search?group=comp.lang.perl.misc&q=separate > > Same thing for the "alternative" spelling. Thanks. A pity that there is no de.comp.lang.python, as for German posts the "Standard/Standart" relation could be more accurate... or-just-count-the-misplaces-apostrophs-ly yours, Reinhold -- [Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs- mitteln inkompatibel. -- Florian Diesch in dcoulm From tdelaney at avaya.com Thu Dec 2 19:48:32 2004 From: tdelaney at avaya.com (Delaney, Timothy C (Timothy)) Date: Fri, 3 Dec 2004 11:48:32 +1100 Subject: How is Python designed? Message-ID: <338366A6D2E2CA4C9DAEAE652E12A1DE4A913A@au3010avexu1.global.avaya.com> Roy Smith wrote: > As far as I can tell, the process works like this: > > Guido has an idea for something he wants to do and announces it. > > Everybody beats him up about it. > > He goes ahead and does it anyway. > > It's a strange process, but it seems to work. It's not quite that straightforward. For example, sometimes we beat someone else up as well. Tim Delaney From mwm at mired.org Thu Dec 30 16:34:04 2004 From: mwm at mired.org (Mike Meyer) Date: Thu, 30 Dec 2004 15:34:04 -0600 Subject: Features for a Python package manager? References: <3351ouF3rt1lgU1@individual.net> Message-ID: <86brcbsc6r.fsf@guru.mired.org> Bulba! writes: > On Sat, 25 Dec 2004 11:37:42 +0100, Georg Brandl > wrote: > >>what features would you expect of a Python package manager, similar to >>CPAN or rubygems? > > IMVHO it would be nice if it had a feature for "upload package/module > I have just developed" - maybe PyPi would fill up faster if it would. Distutils already has a feature to do that for you. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From mariox19 at mac.com Wed Dec 29 20:13:15 2004 From: mariox19 at mac.com (mariox19) Date: 29 Dec 2004 17:13:15 -0800 Subject: Tkinter OptionMenu: width of items in menu Message-ID: <1104369195.086852.200880@z14g2000cwz.googlegroups.com> Hello, The Tkinter OptionMenu widget has me a bit confused. I have set up an OptionMenu to expand along the X axis as the window expands. What I find though is that the width of the submenu displaying the list of items in the menu does not expand. This is the object I'm talking about: popup = OptionMenu(master, StringVar(), "") theObjectIAmTalkingAbout = popup["menu"] When I click on the OptionMenu, I notice that the list of items is only about as wide as the longest word in the list, even if the OptionMenu width extends for the entire width of the screen. This not only looks funny, but interferes with usability. (If you click on the right side of the OptionMenu, you have to move the mouse over to the left to highlight one of the choices in the list.) Am I missing something? Does anyone know how to get the submenu (the list) of an OptionMenu to expand as well? Thanks! Mario From redhog at takeit.se Fri Dec 10 16:27:53 2004 From: redhog at takeit.se (redhog at takeit.se) Date: 10 Dec 2004 13:27:53 -0800 Subject: Wrapper objects In-Reply-To: <1102700031.276079.36580@f14g2000cwb.googlegroups.com> References: <41b9021b.209351251@news.oz.net> <1102700031.276079.36580@f14g2000cwb.googlegroups.com> Message-ID: <1102714073.100719.138310@z14g2000cwz.googlegroups.com> As to what I want to use this for, I today have a huge program in which several objects are wrapped up with comments (made up by some DOMish structre) which are displayed to the user at various times. For example, a list of users may be represented as as comment "List of users" and a python list of elements, each being a user id (represented as an integer), with a comment being the username. This means the list is usable both for user-output and for machine-handling. Hm, this wasn't prolly such a good example, but hopefully, it shows enought of the idea... Tody, the comment-value-pair is an ordinary object with two member variables, and there are two functions, getComment and getValue, which extracts a comment if its argument is such an object, or None otherwise, and the wrapped value if its argument is such an object, and the argument itself otherwize, respectively. This means my code is literally filled with calls to getValue(), which I would like to be able to remove by making the comment-value pair more transparent. The wrapper objects needs to work as dictionary keys, to support printing, concatenation/addition, getitem/setitem and such things... From jeff at ccvcorp.com Wed Dec 22 12:54:17 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 22 Dec 2004 09:54:17 -0800 Subject: Why are tuples immutable? In-Reply-To: References: <41BE1644.8050906@freemail.gr> <10s1si0fb0l4pae@corp.supernews.com> <10s4a4rso24vb83@corp.supernews.com> <10sgqefdb77nn5a@corp.supernews.com> Message-ID: <10sjct6d3e85m6d@corp.supernews.com> Antoon Pardon wrote: >Op 2004-12-21, Jeff Shannon schreef : > > >>Antoon Pardon wrote: >> >> >>So show us a dictionary (i.e. hash table) implementation that can do >>this. >> >> > >Why should I, Do you doubt that it is possible? > > Yes. >>You'll need to be able to derive the old hash from the new hash, >>of course, so that you can correctly associate the values already stored >>under that key. And you'll have to be able to do that without referring >>to the pre-modified object again, because dicts can't track every Python >>operation that might modify a key object. And it needs to deal properly >>with equivalent-but-different-ID list literals, because using literals >>(and not references stored elsewhere) is an important and common dict >>key usage. >> >>If you can show me how you plan to accomplish this, I'll accept that >>you're right on this. Until then... >> >> > >I don't have to accomplish all that in order to be able to clean up >a mutated dictionary key. All I need to do is go over the keys, see >if they hash to the same bucket as they are in now and otherwise >put them in the new bucket. Sure that would be costly, but so would >allowing arbitrary mutation in a sorted list and resorting everytime >or in a heapqueue and reheapifying. > > The problem is that once the object has mutated, you *don't know* what bucket it used to sort into. There is no point at which a dictionary can see "before" and "after" -- it just sees two different lists. >>>And yes I know what to do if I want to use mutable keys as objects. I'm >>>just argueing against those who think that should be somehow forbidden. >>> >>> >>> >>> >>We're not arguing that it should be arbitrarily forbidden. We're >>arguing that doing anything else makes it impossible to behave >>sensibly. >> >> > >How does having stable keys in a mutable objects makes it impossible >to behave sensible for dictionaries? > > What you are calling "stable keys in a mutable object" simply cannot be done while allowing comparison-by-value. Sensible behavior for dictionary keys requires that it be possible to compare keys by value. Overall sensible behavior for lists also provides a strong suggestion (though not an absolute requirement) that lists should normally compare by value. Your suggestion requires that lists *not* compare by value, and provides very little practical benefit in return for complicating all other list-comparison code everywhere. >>So prove us wrong, >> >> > >I don't have to prove you wrong. If you want to argue something, >you have to provide reasoning that shows you right. > > You're the one that's saying that the current behavior is flawed. You're the one making the extraordinary claim that things could be done better. I'm not even claiming that *I'm* right -- I'm claiming that GvR and Tim Peters are smarter and far more likely to be right than either of us. ;) >>by implementing something that behaves >>sensibly in the face of mutating keys (which compare by value, as lists >>do, rather than by identity). >> >> > >You are confusing two things with each other. That is 1) a mutable object >that is a key and 2) a mutating key. Even if an object is mutable it can >be stable for some duration and thus unmutating. There is IMO nothing >wrong with using such mutable objects as dictionary keys or in other >structures that require an invariant. Requiring that such objects be >immutable and thus can't even mutate during periods they are not so >used, creates an unnecessary burden. > > Requiring that programmers track which objects have been used as dictionary keys somewhere and may still be in a dictionary creates an unnecessary burden, and one which *WILL* be forgotten. If you allow mutable objects as keys, then key objects *WILL* mutate underneath the dictionary -- it's blindness to think otherwise. That means that dicts would need to handle that in *some* way -- at bare minimum, throwing a meaningful error. In essence, you're saying that programmers should mentally enforce invariants, rather than having the language enforce them. Which has about as much chance of success as C's malloc/free() has of never being misused. And I still say that there's a big difference between the invariant condition of a *core language feature* that is used everywhere internally in the langauge, and which therefore requires rock-solid and blazing-fast performance, making restrictions to prevent cases where it cannot behave unsurprisingly (because mutating keys, however they're handled, *will* surprise people), and your so-called comparison case of an informally-organized non-language-standard data format, done on top of language features rather than as part of the core, in which mutations are not only less surprising but much easier (i.e. actually possible) to compensate for. Jeff Shannon Technician/Programmer Credit International From mwm at mired.org Thu Dec 16 20:25:09 2004 From: mwm at mired.org (Mike Meyer) Date: Thu, 16 Dec 2004 19:25:09 -0600 Subject: BASIC vs Python References: Message-ID: <86fz251zt6.fsf@guru.mired.org> "Philippe C. Martin" writes: >>>and it was the only interpreter I've ever used that had no compilation >>>phase whatsoever) is no easier to deal with than compiled C. Ditto for >>>the various flavors of LISP I've worked with. > I do find working with an interpreter easier than with a compiler. A _long_ > time ago, I recall a boss telling me that I should write 5 lines of C a day > and compile/debug them twice at most (since it was so slow to get the stuff > compiled/linked anyway). Have you tried working with an interpreter without an interactive mode? And if your compiled code takes more than a few seconds to build the program, then somethings wrong. Either your files are to big, or your build system sucks. > _one_ of the reasons why I intend to stick with python is because it's > interpreted/interactive I still wish it had a compiler. My favorite work environment ever was a Scheme system coupled with emacs. I'd write functions in emacs, ship them to schem for instant evaluation and run a test. When I was done, I'd compile the results to get a nice, fast binary. I've got all that in Python, except the compiler. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From ncoghlan at iinet.net.au Thu Dec 23 07:04:27 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 23 Dec 2004 22:04:27 +1000 Subject: Mutable objects which define __hash__ (was Re: Why are tuples immutable?) In-Reply-To: References: <20041215152606.1029.1225319887.divmod.quotient.10976@ohm> <10s48r5hbse5o57@corp.supernews.com> <41c350ef.331854992@news.oz.net> <41c9103e.708509723@news.oz.net> <1Miyd.695395$mD.58375@attbi_s02> Message-ID: <41CAB44B.6010808@iinet.net.au> Antoon Pardon wrote: > I don't understand why the ease of mutating an object that should remain > stable should cause more unease in a person just because the subject > is dictionary keys, except maybe because of custom. > > But I'm obviously in the minority here. Nah - just fighting against long-held assumptions. Those don't get changed overnight - it takes at least a couple of days :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From ncoghlan at iinet.net.au Thu Dec 9 03:51:35 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 09 Dec 2004 18:51:35 +1000 Subject: a newbie question In-Reply-To: References: <1102545539.234273.279270@c13g2000cwb.googlegroups.com> Message-ID: <41B81217.6050201@iinet.net.au> Peter Hansen wrote: > If that's not what you wanted, try specifying what you mean > by "preinstalled python libraries". I can think of at least > two things that this phrase might refer to... For the "where's the standard library" interpretation, the following works on any platform: python -c "import pdb; print pdb.__file__" The rest of the standard library will be in the same directory as pdb.pyc. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From exarkun at divmod.com Fri Dec 17 14:39:30 2004 From: exarkun at divmod.com (Jp Calderone) Date: Fri, 17 Dec 2004 19:39:30 GMT Subject: Why no list heritable type? In-Reply-To: <86hdmkzq10.fsf@guru.mired.org> Message-ID: <20041217193930.1029.990298915.divmod.quotient.12347@ohm> On Fri, 17 Dec 2004 13:24:43 -0600, Mike Meyer wrote: >Jeff Shannon writes: > > > Sion Arrowsmith wrote: > > Additionally, as I understand it UserList and UserDict are implemented > > entirely in Python, which means that there can be significant > > performance differences as well. > > Actually, UserList and UserDict are just wrappers around the builtin > types. So the performance hit is one Python function call - pretty > much neglible. But new code should still subclass the builtins. Only tangentially related, but I'll bring it up anyway: method calls are more expensive than function calls: exarkun at boson:~$ timeit -s "def foo(): pass" "foo()" 1000000 loops, best of 3: 0.382 usec per loop exarkun at boson:~$ timeit -s "class Foo: def foo(self): pass f = Foo()" "f.foo()" 1000000 loops, best of 3: 0.611 usec per loop exarkun at boson:~$ This is due to the attribute lookup as well as the creation and destruction of a bound method object for each call. Jp From steven.bethard at gmail.com Wed Dec 22 13:03:33 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 22 Dec 2004 18:03:33 GMT Subject: Why are tuples immutable? In-Reply-To: References: <20041215152606.1029.1225319887.divmod.quotient.10976@ohm> <10s48r5hbse5o57@corp.supernews.com> <41c350ef.331854992@news.oz.net> <41c9103e.708509723@news.oz.net> Message-ID: Antoon Pardon wrote: > Well the only suggestion I would make now is that it would be nice to > have a second dict type that would make a copy of a key and insert > that copy in the dictionary. (At least) two options here, depending on what you really need. (1) Use current dicts. They will still give you a key error if you mutate a list that is hashed by value: py> class hashablelist(list): ... def __hash__(self): ... return hash(tuple(self)) ... py> hlist = hashablelist([0]) py> hlist [0] py> d = {hlist:1} py> d {[0]: 1} py> d[hlist] 1 py> hlist[0] = 1 py> d[hlist] Traceback (most recent call last): File "", line 1, in ? KeyError: [1] Since you've said yourself that you don't think people should be mutating keys while they're in a dict, this behavior should serve most purposes. If you do care what the errors are when someone does mutate a key, using a dict means that you could potentially "lose" values after mutating a key. Continuing the example above: py> d {[1]: 1} py> d[hashablelist([0])] Traceback (most recent call last): File "", line 1, in ? KeyError: [0] py> d[hashablelist([1])] Traceback (most recent call last): File "", line 1, in ? KeyError: [1] (2) If you want something that meets your specs better, sit down and write the 10 lines of code: =) py> class copydict(object, UserDict.DictMixin): ... def __init__(self, *args, **kwds): ... self._dict = {} ... self.update(*args, **kwds) ... def __getitem__(self, key): ... return self._dict[key] ... def __setitem__(self, key, value): ... self._dict[copy.deepcopy(key)] = value ... def __iter__(self): ... return iter(self._dict) ... py> hlist = hashablelist([0]) py> cdict = copydict({hlist:1}) py> cdict[hlist] 1 py> hlist[0] = 1 py> cdict[hlist] Traceback (most recent call last): File "", line 1, in ? File "", line 6, in __getitem__ KeyError: [1] py> cdict[hashablelist([0])] 1 py> list(cdict) [[0]] I personally, have zero need for such a class, but if you think that it's useful, and you think a lot of other people might use it, put together a PEP and ask for it to be added to, say, collections, in the standard library. Steve From timh at zute.net Thu Dec 23 10:56:29 2004 From: timh at zute.net (Tim Hoffman) Date: Thu, 23 Dec 2004 23:56:29 +0800 Subject: Python for Series 60 update In-Reply-To: References: <41c9faae@news.highway1.com.au> Message-ID: <41CAEAAD.9010509@zute.net> HI Jukka Laurila wrote: > On Thu, 23 Dec 2004 06:52:28 +0800, Tim Hoffman wrote: > > >>I did find a problem with it on my 7610. > > >>It works, but I had to hard code my bluetooth mac address (I assume >>thats what it is called in bluetooth). The bt_discover() call >>didn't seem to find my host. > > > How did it fail? Did it simply not show your computer in the list or > did it hang indefinitely when connecting to it? Bluetooth discovery > has always been problematic, but connecting to a host directly using > the mac address has worked perfectly for months now. (I am one of the > developers in this project.) It always came back saying there where no bluetooth devices around. Interestingly if I then ran ControlFreak (bluetooth remote control for Winamp) it would connect to the HyperTerm that was still running. So I am at a bit of a loss as to why the bt_discover call never found the host Also normal sync type operations where working fine (as in install apps etc) I will try again on the discover but connecting to the host directly is enough for me at the moment. Tim > > Try doing the discovery again. Sometimes the phone just magically > discovers hosts it did not see ten seconds earlier. The discovery will > also fail if there already is a Bluetooth connection open, for example > the PC Suite can leave connections open that mess up the > discovery. You can force all connections to be terminated by turning > bluetooth on and off from the phone menu. > > >>from the console I could immediatly do xml-rpc calls >>to my favourite Zope/CMF instance over GPRS and it just worked. >> >>This is cool. > > > Yes, very :) From kdart at kdart.com Tue Dec 14 02:48:09 2004 From: kdart at kdart.com (Keith Dart) Date: Mon, 13 Dec 2004 23:48:09 -0800 Subject: Python vs. Perl In-Reply-To: <41BE95BC.4000903@kdart.com> References: <3xFud.92980$EZ.11077@okepread07> <1102788801.234322.270430@f14g2000cwb.googlegroups.com> <1102792461.096337.187440@c13g2000cwb.googlegroups.com> <%eKud.93473$EZ.63638@okepread07> <3269p0F3h9rnaU1@individual.net> <41BE95BC.4000903@kdart.com> Message-ID: <41BE9AB9.2050305@kdart.com> Keith Dart wrote: > Ian Bicking wrote: > >> Jon Perez wrote: >> >>> Michael McGarry wrote: >>> >>>> I intend to use a scripting language for GUI development and front >>>> end code for my simulations in C. I want a language that can support >>>> SQL, Sockets, File I/O, and shell interaction. >>> >>> >>> >>> >>> In my experience, Python is definitely much more suitable than Perl >>> for the first four areas mentioned in the last sentence. For the >>> last area, I'm not sure, but Python's capabilities in this area are >>> also quite good. >> >> >> >> Shell interaction (or rather, external process interaction) is a lot >> better with Python 2.4's subprocess module. Better or worse than >> Perl? I'm not sure; generally I'd guess better, as it avoids the >> shell with all the shell's issues, and provides a more controlled >> programmatic way of interacting with subprocesses. OTOH, Perl might >> have perfectly good modules for doing the same thing. I can only say >> it's been missing for a while in Python, and it's good to see this >> done right. >> > > Yow, I must not get picked up in Google enough. ;-) The "proctools" > module in the pyNMS package has > been around for years. I use it all the time for shell-like stuff. There > is also an "expect" module, and the "termtools" module. If you need a > more complete process spawning and controlling framework then use pyNMS. > It can "juggle" multiple processes, reaps child status (no > zombies), operates asynchronously (The ProcManager object is a SIGCHLD > handler), and works with pty's and pipes. It also offers a "thread-like" > interface for Python subprocesses (uses fork). Can leave some fd's open > that you specify, can run the subprocess as a different user, and more... > > > Check it out. Oh, I forgot to mention that it also has a more user- and programmer-friendly ExitStatus object that processess can return. This is directly testable in Python: proc = proctools.spawn("somecommand") exitstatus = proc.wait() if exitstatus: print "good result (errorlevel of zero)" else: print exitstatus # prints message with exit value -- \/ \/ (O O) -- --------------------oOOo~(_)~oOOo---------------------------------------- Keith Dart vcard: public key: ID: F3D288E4 URL: ============================================================================ From ncoghlan at iinet.net.au Fri Dec 10 23:59:39 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 11 Dec 2004 14:59:39 +1000 Subject: Wrapper objects In-Reply-To: <1102714073.100719.138310@z14g2000cwz.googlegroups.com> References: <41b9021b.209351251@news.oz.net> <1102700031.276079.36580@f14g2000cwb.googlegroups.com> <1102714073.100719.138310@z14g2000cwz.googlegroups.com> Message-ID: <41BA7EBB.7040303@iinet.net.au> redhog at takeit.se wrote: > The wrapper objects needs to work as dictionary keys, to support > printing, concatenation/addition, getitem/setitem and such things... In that case, identifying exactly which operations you want to support, and using a metaclass based approach like mine or Bengt's should work. However, I highly recommend the 'opt-in' approach to delegating magic methods. As Bengt discovered, there are a number of them that can break your class badly if you inadvertently delegate them (e.g. if you delegate __new__ or __init__, your class cannot be instantiated). The Python Language Reference can tell you which methods need to be delegated to support a given operation: http://docs.python.org/ref/specialnames.html The delegation may still not be completely transparent, since the delegated methods may not know how to deal with your wrapper objects. So you may require calls to methods like int() or str() in your application code to make the types work out correctly. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From mcfletch at rogers.com Tue Dec 7 23:20:04 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Tue, 07 Dec 2004 23:20:04 -0500 Subject: 3D plotting library / OpenGL In-Reply-To: References: Message-ID: <41B680F4.8060809@rogers.com> I've got a collection of 3D libraries here: http://www.vrplumber.com/py3d.py?category=retained http://www.vrplumber.com/py3d.py?category=science My own OpenGLContext would likely handle what you've described. It's scenegraph based, can handle fairly large-ish worlds, allows for writing mouse-over and mouse-click handlers. It has text support using either 2D or 3D text, and can load VRML97 for defining geometry (spheres, crosses, and the like). It runs under wxPython, GLUT, PyGame, or (with some limitations) Tkinter. On the other hand, scientific visualisation *isn't* it's focus, so one of the items from the science category might be more appropriate. Anyway, HTH, Mike Andrew Dalke wrote: >I've been looking for a decent 3D plotting library with support >for user selection that works under OpenGl, preferable with wxPython. > > ... >What I was hoping for was a toolkit that worked cross-platform >and assumed OpenGL is available, leaving me to pass it the >OpenGL context and a few other essentials, or something that >made a scene graph that I could render as I wish. > > ... ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From sjmachin at lexicon.net Wed Dec 22 18:15:28 2004 From: sjmachin at lexicon.net (John Machin) Date: 22 Dec 2004 15:15:28 -0800 Subject: word to digit module In-Reply-To: References: <1103719672.839535.178010@z14g2000cwz.googlegroups.com> <41c9cb8f$1@nntp0.pdx.net> Message-ID: <1103757328.052131.98310@z14g2000cwz.googlegroups.com> Stephen Thorne wrote: > Thankyou for you feedback, both of you. No wuckas. > http://thorne.id.au/users/stephen/scripts/eng2num.py contains your suggestions. This points to some javascript which prints "No." From bradtilley at gmail.com Wed Dec 1 10:23:40 2004 From: bradtilley at gmail.com (Brad Tilley) Date: Wed, 01 Dec 2004 10:23:40 -0500 Subject: Python 2.4 Uninstall Entry in WinXP Registry In-Reply-To: <41ad87a5$0$23342$9b622d9e@news.freenet.de> References: <41ad87a5$0$23342$9b622d9e@news.freenet.de> Message-ID: <41ADE1FC.2060105@gmail.com> Martin v. L?wis wrote: > Brad Tilley wrote: > >> Python 2.3 placed a registry key under: >> >> 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Python2.3' > > > [...] > >> Python 2.4 does not use this registry entry on the two machines I have >> installed it on... any tips on how to locate this? > > > It's under > > HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{82D9302E-F209-4805-B548-52087047483A} > > > which is the product code of Python 2.4. Notice that Python 2.4.1 > will use a different product code. > > However, if you merely want to avoid that users remove the package, > you can set the ARPNOREMOVE property during installation, e.g. > > msiexec /i python24.msi ARPNOREMOVE=1 > > You might want to set ARPNOMODIFY and ARPNOREPAIR as well. > > If you cannot readily pass that property on the command line during > installation, you can use orca.exe (or a python script) to add this > property to the Property table of python24.msi. > > If you have W2k or later, you can also set the "NoRemove" registry > value under the key above, to hide the remove feature after > installation. > > HTH, > Martin That's very helpful, thanks Martin! How do I set the install path to c:\Program Files? From steve at holdenweb.com Tue Dec 14 11:15:02 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 14 Dec 2004 11:15:02 -0500 Subject: while 1 vs while True In-Reply-To: References: <1102903165.589419.323000@z14g2000cwz.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Steve Holden wrote: > > >>It was unfortunate that so many people chose to use that for compatibility, when if they'd used >>the same code that the win32all extensions did they could have retained backward compatibility >>even across a change to constants: >> >>try: >> True >>except AttributeError: >> True, False = (1==1), (1!=1) > > > that doesn't work, though: > > $ python2.1 test.py > Traceback (most recent call last): > File "test.py", line 2, in ? > True > NameError: name 'True' is not defined > Well, OK. But, lest people should think the worse of win32all because of my laziness in not finding the exact quote, I should point out that the code I meant to quote actually says: # Pre 2.2.1 compat. try: True, False except NameError: True = 1==1; False = 1==0 I believe this should work for all versions up to 2.4, and would also work with a 2.5 that made True and False constants. But if anyone can prove me wrong it would be you ... :-) regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From fperez528 at yahoo.com Tue Dec 21 00:26:52 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 20 Dec 2004 22:26:52 -0700 Subject: expression form of one-to-many dict? References: <863by22gqs.fsf@guru.mired.org> Message-ID: Doug Holton wrote: > Mike Meyer wrote: > >> Personally, I'd love a language feature that let you create a function >> that didn't evaluate arguments until they were actually used - lazy >> evaluation. That lets you write the C ?: operator as a function, for >> a start. >> >> Hmmm. No, iterators can't be used to fake it. Oh well. > > That is a brilliant idea. I would suggest requesting such a feature for > Python 3.0: http://www.python.org/cgi-bin/moinmoin/Python3.0 Just as a reference, Mathematica does have such a feature, in the form of the HoldAll, HoldFirst, etc. function attributes. It can come in quite handy. I actually used it to write a little routine to auto-generate python modules for mathematica variables of certain types, without having to specify a list of strings for their names. The evaluation control allowed me to give it a very clean interface, while the equivalent python2mathematica routine requires a list of variable names (strings) as input, and plays sys._getframe tricks with it. Not very pleasant. So yes, I think it would be a really nifty feature to have, though I haven't really thought about how well it meshes (or not) with the rest of python's design. Cheers, f From tim.peters at gmail.com Sat Dec 18 14:14:27 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 18 Dec 2004 14:14:27 -0500 Subject: A rational proposal In-Reply-To: <20041218185556.1029.415545259.divmod.quotient.12903@ohm> References: <86y8fvqwl7.fsf@guru.mired.org> <20041218185556.1029.415545259.divmod.quotient.12903@ohm> Message-ID: <1f7befae04121811144e940b43@mail.gmail.com> [Jp Calderone] ... > The Decimal type seems to define min and max so that NaNs > can be treated specially, but I glean this understanding from only > a moment of reading decimal.py. Perhaps someone more well > informed can declare definitively the purpose of these methods. To conform to the semantics of the min and max operations defined in IBM's proposed standard for decimal arithmetic: http://www2.hursley.ibm.com/decimal/ and in particular: http://www2.hursley.ibm.com/decimal/daops.html#refmax and http://www2.hursley.ibm.com/decimal/daops.html#refmin Note that this is a moving target. From alexs at advfn.com Fri Dec 17 04:32:41 2004 From: alexs at advfn.com (Alex Stapleton) Date: Fri, 17 Dec 2004 09:32:41 +0000 Subject: Cool object trick In-Reply-To: <97B6410BE753D411894E00D0B77E6F7F0340BF53@neam2mx1.corp.emc.com> References: <97B6410BE753D411894E00D0B77E6F7F0340BF53@neam2mx1.corp.emc.com> Message-ID: <41C2A7B9.1020606@advfn.com> Except what if you want to access elements based on user input or something? you can't do var = "varA" obj = struct(varA = "Hello") print obj.var and expect it to say Hello to you. objects contain a __dict__ for a reason :P > Certainly makes writing 'print obj.spam, obj.spam, obj.eggs, obj.bacon, > obj.sausages, "and", obj.spam' a lot easier ;-) then why dont you have a breakfast class? if you have this many properties associated with the same thing you might as well stick them in a class anyway. Doran_Dermot at emc.com wrote: > I rather like it! I prefer writing obj.spam to obj["spam"]! I wonder if > there is a technical downside to this use of Python? > > P.S. > > Certainly makes writing 'print obj.spam, obj.spam, obj.eggs, obj.bacon, > obj.sausages, "and", obj.spam' a lot easier ;-) > > -----Original Message----- > From: python-list-bounces+doran_dermot=emc.com at python.org > [mailto:python-list-bounces+doran_dermot=emc.com at python.org] On Behalf Of > Jive > Sent: 17 December 2004 06:29 > To: python-list at python.org > Subject: Re: Cool object trick > > Kinda cool. > > It's occured to me that just about everything Pythonic can be done with > dicts and functions. Your Obj is just a dict with an alternate syntax. You > don't have to put quotes around the keys. But that's cool. > > > class struct(object): > def __init__(self, **kwargs): > self.__dict__.update(kwargs) > > # Indented this way, it looks like a struct: > obj = struct( saying = "Nee" > , something = "different" > , spam = "eggs" > ) > > print obj.spam > > # Is that really much different from this? > > obj2 = { "saying" : "Nee" > , "something" : "different" > , "spam" : "eggs" > } > > print obj2["spam"] > > From adam at cognitcorp.com Fri Dec 3 08:52:21 2004 From: adam at cognitcorp.com (Adam DePrince) Date: Fri, 03 Dec 2004 08:52:21 -0500 Subject: Newbie alert ! In-Reply-To: References: Message-ID: <1102081941.4790.15.camel@localhost.localdomain> On Fri, 2004-12-03 at 06:38, Jean Montambeault wrote: > I am not only learning Python but programming itself ; reading your > posts makes me believe that nobody is that much of a beginner here. Is > there a newgroup or list for my type somewhere I can't find it ? > > To illustrate my case this script : > > > > # function to draw rings for an Olympic flag > def rings(size,offsetX,offsetY,coul): > x1,y1,x2,y2 = 170, 103, 170, 103, > can1.create_oval(x1-size-offsetX,y1+size+offsetY,\ > x2+size-offsetX,y2-size+offsetY,\ > width=8, outline=coul) > > # **main****main****main****main****main****main** > > fen1=Tk() > can1=Canvas(fen1, bg='white', height=206, width=340) > can1.pack(side=LEFT) > > bou_europe=Button(fen1, text='Europe',\ > command=rings(41, 100, -22, 'blue')) > bou_europe.pack( ) > > bou_asia=Button(fen1, text='Asia',\ > command=rings(size=41, offsetX=50,offsetY=22, > coul='yellow')) > bou_asia.pack( ) > > bou_africa=Button(fen1, text='Africa',\ > command=rings(size=41, offsetX=0,offsetY=-22, > coul='black')) > bou_africa.pack( ) > > bou_australia=Button(fen1, text='Australia',\ > command=rings(size=41, offsetX=-50,offsetY=22, > coul='dark green')) > bou_australia.pack( ) > > bou_america=Button(fen1, text='America',\ > command=rings(size=41, offsetX=-100,offsetY=-22, > coul='Red')) > bou_america.pack( ) > > bou_quit=Button(fen1, text='Quit', command=fen1.quit) > bou_quit.pack(side=BOTTOM) > > fen1.mainloop() > fen1.destroy() > > > > I just cannot figure out why the rings are draw right from the start and > don't wait for their buttons to be pressed before being drawn : I've > written similar functions before to draw lines, rectangles and whatever > else with success. Because Button creates a button on the screen and moves on. Would it be correct to say that you want the program to block on the creation of each button until it was pressed? Typically, GUI's rely on the notion of a callback. You create a widget, assign some function to be called when something happens and then enter your "mainloop" where you wait. If you want your rings to be created with button presses then you should be creating them in the button callbacks ... - Adam > > Using Python 2.3, IDLE and Win2k. > > Thanks for your time > > Jean Montambeault Adam DePrince 973-723-8597 cell voice/tdd 973-983-7576 home voice/tdd From FBatista at uniFON.com.ar Mon Dec 20 15:58:07 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 20 Dec 2004 17:58:07 -0300 Subject: A rational proposal Message-ID: [Mike Meyer] #- Good point. Currently, objects now how to convert themselves to int, #- float and complex. Should Rational now how to convert itself to #- Decimal (and conversely, decimal now how to convert itself to #- Rational)? To convert a Decimal to Rational, just take the number and divide it by 1E+n: Decimal(5) -> Rational(5) Decimal("5.35") -> Rational(535, 100) To convert a Rational to a Decimal, it would be a good idea to have a method that converts the Rational to a Decimal string... Rational(5).tostring(6) -> "5.00000" Rational(4, 5).tostring(3) -> "0.80" Rational(5321351343, 2247313131).tostring(5000) -> whatever ... and then take that string as input to Decimal and it will work. . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sun Dec 5 19:31:00 2004 From: http (Paul Rubin) Date: 05 Dec 2004 16:31:00 -0800 Subject: Help With Hiring Python Developers References: <388e4edd.0411302107.79140dfb@posting.google.com> <41b3a317$1_2@omega.dimensional.com> Message-ID: <7x8y8cxo6z.fsf@ruckus.brouhaha.com> mfuhr at fuhr.org (Michael Fuhr) writes: > Indeed. An acquaintance of mine advocates writing code that only > skilled programmers can maintain (he favors a language that shall > remain nameless but that has been known to resemble modem noise or > cartoon swearing). TECO? Some of the best programmers I know used it, but I hadn't heard of anything being done in it in quite a while. From craig at postnewspapers.com.au Sat Dec 25 08:13:00 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sat, 25 Dec 2004 21:13:00 +0800 Subject: Multiple Inheritance __slots__ problem In-Reply-To: <00a101c4e9b1$205b15e0$bfc013ac@pwit.com> References: <00a101c4e9b1$205b15e0$bfc013ac@pwit.com> Message-ID: <1103980380.9310.2.camel@albert.localnet> On Fri, 2004-12-24 at 20:07, Nitin Shukla wrote: > Hello, > > Can anyone tell why am I getting this error and how to work around this > problem. > > >>> class Klass(object): > ... __slots__ = ( 'x' ) > ... > >>> class Klass1(object): > ... __slots__ = ( 'y' ) > ... > >>> class Klass(Klass, Klass1): > ... __slots__ = ( 'z' ) > ... > Traceback (most recent call last): > File "", line 1, in ? > TypeError: multiple bases have instance lay-out conflict > > I need to define slots in these classes and also need to inherit them in > Derived class. If I recall correctly, the standard advice in this situation is "don't use __slots__. If you think you need __slots__, still don't use __slots__." I've made use of __slots__ once myself for an optimisation when subclassing `str', but if you're not using it for a serious optimisation need it's probably best to steer clear. -- Craig Ringer From spamerom at niet.com Wed Dec 22 19:33:21 2004 From: spamerom at niet.com (JZ) Date: Thu, 23 Dec 2004 01:33:21 +0100 Subject: PHP vs. Python References: <1103753016.780533.137480@f14g2000cwb.googlegroups.com> Message-ID: Dnia 22 Dec 2004 14:03:36 -0800, stephen.mayer at gmail.com napisa?(a): > Anyone know which is faster? I'm a PHP programmer but considering > getting into Python ... Python application servers (Webware, Skunkweb) can work much faster than php. But it is true only for non-trivial code. Benchmark for "Hello world" is a nonsense of course. But pure speed is not the all. Python can scale better, has cleaner and consistent syntax, better standard libraries and is a common language rather than specific script language for web only. -- JZ From steven.bethard at gmail.com Sat Dec 4 04:23:01 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 04 Dec 2004 09:23:01 GMT Subject: pre-PEP generic objects In-Reply-To: <36adnSijGrtxnSzcRVn-vg@giganews.com> References: <36adnSijGrtxnSzcRVn-vg@giganews.com> Message-ID: Istvan Albert wrote: > but what are you saying? that a man cannot exaggerate and > fudge the facts in order to embellish his argument? :-) Heh heh. Yeah, something like that. ;) Steve From aut_gbarros at uolinc.com Wed Dec 29 16:57:53 2004 From: aut_gbarros at uolinc.com (Gabriel Cosentino de Barros) Date: Wed, 29 Dec 2004 19:57:53 -0200 Subject: vga output Message-ID: <2814F26DA6908F41927A81C410C4991A02079C27@siamun.server.bl.corp.intranet> i'm writting an app to display images without X... i'm scared just to think about writting it in C... The hardware won't run X. and the CPU is very humble, around 20Mhz (and it must have fade outs). it run a minimalisc OpenBSD kernel. Anyone already did something similar and/or have any recomendations? Thanks, Gabriel -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Thu Dec 2 19:33:54 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 2 Dec 2004 19:33:54 -0500 Subject: How is Python designed? References: <20041202203209.67390.qmail@web80904.mail.scd.yahoo.com> Message-ID: "Limin Fu" wrote in message news:20041202203209.67390.qmail at web80904.mail.scd.yahoo.com... > Is there any technical description on internet of how > python is designed? Or can somebody give a short > description about this? I'm just curious. One answer is that Python is currently designed by a group of voluntary developers 'chaired' by Guido van Rossum and communicating via the python-dev mailing list (gatewayed to gmane.comp.python.devel), the SourceForge tracker, and other means (technical details omitted). But if you meant 'how' differently, perhaps you could clarify what you want after looking around comp.lang.python and perhaps googling the newgroup archives. Terry J. Reedy From steve at holdenweb.com Mon Dec 27 10:37:19 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 27 Dec 2004 10:37:19 -0500 Subject: A Revised Rational Proposal In-Reply-To: References: <86llbl7kvv.fsf@guru.mired.org> <1104071161.355661.10550@f14g2000cwb.googlegroups.com> <10stv7mnuf7h9e8@news.supernews.com> <86r7lc5pu3.fsf@guru.mired.org> Message-ID: <72Wzd.61256$Jk5.4359@lakeread01> Skip Montanaro wrote: > Mike> ... or making them old-style classes, which is discouraged. > > Since when is use of old-style classes discouraged? > Well, since new-style classes came along, surely? I should have thought the obvious way to move forward was to only use old-style classes when their incompatible-with-type-based-classes behavior is absolutely required. Though personally I should have said "use of new-style classes is encouraged". I agree that there's no real need to change existing code just for the sake of it, but it would be interesting to see just how much existing code fails when preceded by the 1.5.2--to-2.4-compatible (?) __metaclass__ = type guessing-not-that-much-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From flupke at nonexistingdomain.com Tue Dec 14 04:01:00 2004 From: flupke at nonexistingdomain.com (flupke) Date: Tue, 14 Dec 2004 09:01:00 GMT Subject: xmlrpclib or twisted? In-Reply-To: References: Message-ID: flupke wrote: Thanks for the info. Benedict From dalke at dalkescientific.com Fri Dec 24 17:39:05 2004 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 24 Dec 2004 22:39:05 GMT Subject: Lambda going out of fashion References: <1Rtyd.549053$wV.296842@attbi_s54> <1103786497.565595.85070@z14g2000cwz.googlegroups.com> Message-ID: Terry Reedy wrote: > As far as I know, apply(func, args) is exactly equivalent to func(*args). After playing around a bit I did find one difference in the errors they can create. >>> def count(): ... yield 1 ... >>> apply(f, count()) Traceback (most recent call last): File "", line 1, in ? TypeError: apply() arg 2 expected sequence, found generator >>> f(*count()) Traceback (most recent call last): File "", line 1, in ? TypeError: len() of unsized object >>> That led me to the following >>> class Blah: ... def __len__(self): ... return 10 ... def __getitem__(self, i): ... if i == 0: return "Hello!" ... raise IndexError, i ... >>> blah = Blah() >>> len(*blah) 6 >>> apply(len, *blah) Traceback (most recent call last): File "", line 1, in ? TypeError: len() takes exactly one argument (6 given) >>> Is that difference a bug? Andrew dalke at dalkescientific.com From davidjh at gmail.com Tue Dec 28 14:06:29 2004 From: davidjh at gmail.com (David JH) Date: 28 Dec 2004 11:06:29 -0800 Subject: Python IDE References: Message-ID: <1104258599.128255.69190@z14g2000cwz.googlegroups.com> On the subject.... can somebody here who uses SPE (or just has some python knowledge) help me out with the installation process? I tried following http://spe.pycs.net/extra/manual/manual.html#windows but end up with the error: python /c/system/python24/Lib/site-packages/_spe/winInstall.py Traceback (most recent call last): File "/c/system/python24/Lib/site-packages/_spe/winInstall.py", line 1, in ? import info File "/c/system/python24/Lib/site-packages/_spe/info.py", line 1, in ? import os,sys,sm.osx ImportError: No module named sm.osx interestingly enough there is an osx.py in PYTHON_DIR/Lib/site-packages/sm so I figure I may just have python configured poorly somehow. Any ideas on where I should look? From miki.tebeka at zoran.com Thu Dec 16 07:00:49 2004 From: miki.tebeka at zoran.com (miki) Date: 16 Dec 2004 04:00:49 -0800 Subject: Step by step: Compiling extensions with MS Visual C++ Toolkit 2003 - msvccompiler-patch.txt (0/1) In-Reply-To: <41c02d3b.12311765@news.versatel.de> References: <41c02d3b.12311765@news.versatel.de> Message-ID: <1103198449.068675.180950@z14g2000cwz.googlegroups.com> Hello Martin, Martin Bless wrote: [Something very long ...] Why don't just use MingW32? Download it from http://prdownloads.sf.net/mingw/MinGW-3.1.0-1.exe?download (14.8MB) and install. Write your extension module and setup.py and then run: python setup.py build --compiler=mingw32 That's all! You'll have a working .pyd ready to rock. Miki From johng2001 at rediffmail.com Thu Dec 2 03:19:54 2004 From: johng2001 at rediffmail.com (johng2001 at rediffmail.com) Date: 2 Dec 2004 00:19:54 -0800 Subject: Microsoft Patents 'IsNot' In-Reply-To: References: Message-ID: <1101975594.890833.119640@c13g2000cwb.googlegroups.com> All the VB fans I know have not experienced Delphi. They just don't know what they are missing. I am sure there are people who actually chose VB, but not any one I know. When I marvelled at VB myself, it was back when I myself was unaware of Delphi/C++ Builder. I used to think C++ programming on Windows had to be with VC++ and MFC and VB was the only sane choice for most of my apps. When I first tried Delphi, it only took me a couple of hours to realize that I will never use VB again. From itsme at yahoo.com Tue Dec 28 15:22:12 2004 From: itsme at yahoo.com (It's me) Date: Tue, 28 Dec 2004 20:22:12 GMT Subject: A scoping question References: Message-ID: Thanks, Steve. So, global is only to within a module (I was afraid of that). Those words flashed by me when I was reading it but since the word "module" didn't translate to "file" in my C mind, I didn't catch that. In that case, you are correct that I have to do an import of file1 in file2. Not that this is not real code, I am still trying to learn the ins and outs of Python by writing some silly code - but will be important to help me understand how I would write the real code. Regarding the question of not placing everything in one module, I wouldn't think that that's how I would do it. I might get ambitous later and write code for a larger project. In that case, I will need to know more about scoping across multiple modules. So, this helps me understand what to do. Thanks again. "Steven Bethard" wrote in message news:I5jAd.246742$5K2.73425 at attbi_s03... > > I think you're confused about what the global keword does. Declaring a > name as global makes that name global *to the module*: > > http://docs.python.org/ref/global.html > http://docs.python.org/lib/built-in-funcs.html#l2h-32 > > What you probably want instead is: > > -------------------- file1.py -------------------- > import file2 > myBaseClass = file2.BaseClass() > myBaseClass.AddChild(file2.NextClass()) > -------------------------------------------------- > > -------------------- file2.py -------------------- > class BaseClass: > def __init__(self): > self.MyChilds = [] > def AddChild(self, NewChild): > self.MyChilds.append(NewChild) > class NextClass: > def __init__(self): > from file1 import myBaseClass # IMPORT > for eachChild in myBaseClass.MyChilds: > pass > -------------------------------------------------- > > Note that I import myBaseClass in __init__. If I imported it at the top > of the module, then file1 would import file2 which would then import > file1 and you'd have a circular dependency. > > As it is, your code is very tightly coupled. Why don't you put all this > code into a single module? > > Steve From mf1987 at arcor.de Sat Dec 25 04:56:27 2004 From: mf1987 at arcor.de (Markus Franz) Date: 25 Dec 2004 01:56:27 -0800 Subject: Execute code after death of all child processes - (corrected posting) Message-ID: <576fb15a.0412250156.325fff8e@posting.google.com> Hallo! I have a problem with this little script written in Python: import sys, os, time texts = ['this is text1', 'this is text 2'] for current_text in env_sources[0:]: pid = os.fork() if pid == 0: time.sleep(2) print current_text break As you is create some child processes depending on the number of vars in ?texts?. My problem is: How can I run some code after all child processes have been finished? (The code should be run only in the parent process.) I tried: import sys, os, time texts = ['this is text1', 'this is text 2'] for current_text in texts[0:]: pid = os.fork() if pid == 0: time.sleep(2) print current_text break os.waitpid(-1, 0) print 'this is the end' But this didn't work, 'this is the end' will be showed several times. Can you help me? Tanks. Markus From apardon at forel.vub.ac.be Wed Dec 22 06:21:59 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 22 Dec 2004 11:21:59 GMT Subject: Why are tuples immutable? References: <41BE1644.8050906@freemail.gr> <10s1si0fb0l4pae@corp.supernews.com> <10s4a4rso24vb83@corp.supernews.com> <10sgqefdb77nn5a@corp.supernews.com> Message-ID: Op 2004-12-22, Fredrik Lundh schreef : > Antoon Pardon wrote: > >> But this was another subthread. > > oh, sorry, I was under the flawed assumption that the first few posts to a > thread should be seen in the context of the original post. So? In the mean time there have been more than 50 articles in this thread. "First few" seems hardly still appropiate. > I guess I'm a bit > too old-fashioned for these new-fangled "let's change the subject for each > new post without changing the subject" thread thingies... Having a few subthreads after more than 50 articles hardly seems to warrant the remark: "let's change the subject for each new post without changing the subject" Those subthread had more in common with the original subject than your remarks here and yet you didn't change the Subject header. -- Antoon Pardon From rkern at ucsd.edu Sat Dec 25 23:13:23 2004 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 25 Dec 2004 23:13:23 -0500 Subject: Features for a Python package manager? In-Reply-To: <868y7l93o4.fsf@guru.mired.org> References: <3351ouF3rt1lgU1@individual.net> <868y7l93o4.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > Nick Coghlan writes: > > >>I don't know enough about Portage to answer that question. I do know >>any package manager which made it into the standard distribution would >>need to work for at least the big three platforms (Windows/Mac/*nix) :) > > > Being written in python - and hopefully integrated into Distutils - > why shouldn't it work on any platform that Python worked on? Assumptions about directory structures, and the like. IIRC, Portage was written for the Gentoo project, so it could assume that it was installing stuff to a Gentoo system. Package management systems have a distressing habit of infecting their *architecture* with these assumptions. It makes adapting them difficult. Also, Portage needs to execute subprocesses, something which is notoriously platform dependent. 2.4's subprocess module should probably be used here, but I don't think Portage does, yet. OTOH, it's Gentoo, so it wouldn't surprise me, either. :-) -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From apardon at forel.vub.ac.be Thu Dec 23 10:46:34 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 23 Dec 2004 15:46:34 GMT Subject: Why are tuples immutable? References: <41BE1644.8050906@freemail.gr> <10s1si0fb0l4pae@corp.supernews.com> <10s4a4rso24vb83@corp.supernews.com> <10sgqefdb77nn5a@corp.supernews.com> <10sjct6d3e85m6d@corp.supernews.com> <41cae042$1@nntp0.pdx.net> Message-ID: Op 2004-12-23, Scott David Daniels schreef : > Antoon Pardon wrote: >> Op 2004-12-22, Jeff Shannon schreef : >>>The problem is that once the object has mutated, you *don't know* what >>>bucket it used to sort into. There is no point at which a dictionary >>>can see "before" and "after" -- it just sees two different lists. > > This is half the problem. In the period where an element is in the > wrong hash bucket, a new entry for the same value can be created in > the proper hash bucket. Then the code will have to determine how to > merge two entries at rehash time. But similar problems can happen in a sorted list, where the sort is done on a "key" of the data and where you don't want duplicate "keys". If you then mutate a "key", it may be possible to insert a duplicate "key" in the sorted list because the list isn't sorted anymore. If you then resort your list you also have to determine how to merge the two items with the same "key" This just to show that repairing sorted lists can be just as troublesome as repairing dictionaries. People who think sorted lists of mutable objects is less bothersome as dictionaries with mutable keys, haven't thought things through IMO. -- Antoon Pardon From cold_fusion at fastmail.fm Mon Dec 27 20:45:08 2004 From: cold_fusion at fastmail.fm (Avi Berkovich) Date: Tue, 28 Dec 2004 03:45:08 +0200 Subject: Python Interactive Shell - outputting to stdout? In-Reply-To: <41cca862$1@news.012.net.il> References: <41cb23ff@news.012.net.il> <41cca862$1@news.012.net.il> Message-ID: <41d0bae6$1@news.012.net.il> Avi Berkovich wrote: > Hey, > > I can't make it work, I don't get any data from either stdout nor stderr. > If I send lines and then close the stdin pipe, I may get an exception > message from several lines up. > > I tried manually reading from the stdout pipe, but it just blocks and > hangs no matter what I send over via the stdin pipe. > > This behavior isn't presented by the command line interpreter by any > chance. > > Any suggestions? Well, I didn't manage to get the pipes working, and finally decided to embed the interpreter into the program, though another option is to embed it into a simple console program consisting of the interpreter initialization and input reading, and just pipe into that. Code for simple interpreter embedded program: #include #include int main() { char execString[128]; Py_Initialize(); while (1) { gets(execString); if (!strcmp(execString, "QUIT PROGRAM")) break; PyRun_SimpleString(execString); } Py_Finalize(); } This program works well with pipes, though in order to issue the command I have to write "\n\r\n" (not "\r\n" or "\n" ?!) to the pipe. Avi. From itsme at yahoo.com Wed Dec 29 21:14:45 2004 From: itsme at yahoo.com (It's me) Date: Thu, 30 Dec 2004 02:14:45 GMT Subject: Using Python in my programs References: Message-ID: Assuming your program is written in C/C++, I would recommend that you start with SWIG. http://www.swig.org You can play around with that as a start. If later you decided that SWIG is not for you, you can always do it natively. There are plenty of information at www.python.org. "Squirrel Havoc" wrote in message news:Xns95CEBEA7A75D8squirrelhavoctakeout at 151.164.30.44... > Hello. I am sorry if this has been asked before, > but I am new here. > > If I recall correctly, Python can be used as a > scripting language for other programs, as if > the program had a builtin Python interpreter. > I wish to extend my programs by making them > scriptable with Python scripts. > > Is this possible? If so, does anyone know where > I can find documentation on it? I searched the > python.org site and didnt find anything useful > > Thanks > > SH From fredrik at pythonware.com Wed Dec 29 03:51:35 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 29 Dec 2004 09:51:35 +0100 Subject: Problem in threading References: Message-ID: Gurpreet Sachdeva wrote: > for i in nloops: # wait for all > threads[i].join threads[i].join() From dscottr at bellatlantic.net Sat Dec 18 22:35:28 2004 From: dscottr at bellatlantic.net (Scott Robinson) Date: Sun, 19 Dec 2004 03:35:28 GMT Subject: BASIC vs Python References: <41C342A0.3040700@users.ch> <86sm64tzax.fsf@guru.mired.org> <86d5x849bs.fsf@guru.mired.org> Message-ID: <1as9s09gf5nh5f8n338odj5akphd0smegb@4ax.com> On Fri, 17 Dec 2004 20:41:11 -0600, Mike Meyer wrote: >Scott Robinson writes: > >> Forth seems better than basic, but is *weird* (I tried it for a >> while). I'm not sure going from Forth to C (or Python) would be much >> easier than Basic to C or Python. The biggest disappointment for >> Forth was that no significant Forth chips were made (and none until it >> was too late). A machine designed to be run on Forth would have been >> unbelievably powerful from the late 70s to the mid 90s (it would be >> more painful now than the x86 legacy, but still). > >I think you overestimate how long the Forth chip would have been a >serious competitor to x`the x86 line. LISP chips - which should have >all the same advantages - didn't last that long. > > References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> <1103657476.495700.191020@f14g2000cwb.googlegroups.com> Message-ID: <1103671235.093738.198680@z14g2000cwz.googlegroups.com> Steven Bethard wrote: > John Machin wrote: > > Nick Coghlan wrote: > > [snip] > > > >>delimeter. > > > > Hey, Terry, another varmint over here! > > No, no. He's talking about a deli-meter. It's the metric standard for > measuring subs and sandwiches. ;) > Nobody mention the wurst! I did once, but I think I got away with it. Subtle distinction: A metER is a measuring device. A MetRE is a unit of distance. From __peter__ at web.de Thu Dec 23 03:32:35 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 23 Dec 2004 09:32:35 +0100 Subject: list IndexError References: Message-ID: Steven Bethard wrote: > I thought it might be helpful to code some of the alternatives you've > been given and look at the timings to put things into perspective. The > code: > > -------------------- remove.py -------------------- > def remove_lc(x, lst): > lst[:] = [item for item in lst if item != x] [snip] > $ python -m timeit -s "import remove; lst = [x % 1000 for x in > xrange(10000)]" "remove.remove_(500, lst)" I do not think it measures what you think it measures. A statement in the -s option is only run once, so you have to be careful with mutable data and pass a copy of your sample to the function about to be timed. The following example illustrates the problem: $ py24 -m timeit -n5 -r1 -s"r=[0]" -s"def f(r): print r; r[0] += 1" "f(r)" [0] [1] [2] [3] [4] 5 loops, best of 1: 106 usec per loop Peter From adekel at ort.org.il Thu Dec 16 12:18:44 2004 From: adekel at ort.org.il (Amir Dekel) Date: Thu, 16 Dec 2004 19:18:44 +0200 Subject: Adding paths to sys.path permanently, and another problem... Message-ID: Hi everyone, I have two problems: 1. How can I keep my changes in sys.path after closing the interpreter? 2. os.path.expanduser("~") always gives me "C:\\" instead of my homepath. I have tried to change my homepath in WinXP using set homepath(in command line), and alsaw using the "Environment Variables" in WinXP system properties, non helped. I really have to fix this somehow. Thanks, Amir From Erik.geiger at gmx.de Wed Dec 22 15:47:35 2004 From: Erik.geiger at gmx.de (Erik Geiger) Date: Wed, 22 Dec 2004 21:47:35 +0100 Subject: how to start a new process while the other ist running on References: Message-ID: Donn Cave schrieb: > In article , Erik Geiger > wrote: [...] > > Thats what I've tried, but it did not work. Maybe it's because I want to > > start something like su -c '/path/to/skript $parameter1 $parameter2' > > user > Unfortunately this particular case kind of dilutes the advantages > of spawnv. In the common case, parameter1 et al. would be submitted > directly as the parameter list. I believe it may be clearer to start > with to think about the spawnv() function - > os.spawnv(os.P_NOWAIT, path, [cmdname, parameter1, parameter2]) > > If one of the parameters is itself another command, then of course > it has to be rendered as a string > os.spawnv(os.P_NOWAIT, '/bin/su', ['su', '-c', '%s %s %s' % (cmd, > parameter1, parameter2)]) > so you have almost as much work to scan the parameters for shell > metacharacters as you would have with system(). > > Donn Cave, donn at u.washington.edu OK, thats too high for me ;-) Is the %s the variable for the following commands/parameters? If I have three parameters, I'll need one more %s? Where to write the user for the su command? Well, I've given up ;-) Thanks for the explanation! Erik -- Jemanden wie ein rohes Ei zu behandeln kann auch bedeuten, ihn in die Pfanne zu hauen. From hansa at tihlde.org.invalid Tue Dec 14 10:30:30 2004 From: hansa at tihlde.org.invalid (Hans =?iso-8859-1?q?Alm=E5sbakk?=) Date: 14 Dec 2004 16:30:30 +0100 Subject: Regexp problem, which pattern to use in split References: Message-ID: "Fredrik Lundh" writes: > >>> import csv > > http://online.effbot.org/2003_08_01_archive.htm#librarybook-csv-module > This seems be just the thing I need. Now ofcourse, another problem arouse: The csv module is new in Python 2.3. hans:~# python -V Python 2.1.3 Is there a relatively hassle-free way to get the csv module working with 2.1? The server is running Debian stable/woody, and it also seemed 2.2 can coexist with 2.1, when I checked the distro packages, if that is any help. Regards -- Hans Alm?sbakk -remove .invalid for correct email From bounces at foo.org Wed Dec 15 22:24:49 2004 From: bounces at foo.org (Dan) Date: Thu, 16 Dec 2004 03:24:49 GMT Subject: Performance (pystone) of python 2.4 lower then python 2.3 ??? In-Reply-To: References: Message-ID: <5e7wd.99$5m3.65@trndny04> Skip Montanaro wrote: > Dan> I also see an 8-10% speed decrease in 2.4 (I built) from 2.3.3 > Dan> (shipped w/Fedora2) in the program I'm writing (best of 3 trials > Dan> each). Memory use seems to be about the same. > > How do you how the compiler flags were the same if you didn't compile both > versions yourself? I don't, and I also don't know if the Redhat folks modified the sources in some way. That's why I mentioned the difference in builds. But I suppose that makes this as good as no data. /Dan -- dedded att verizon dott net From araspus at gmail.com Mon Dec 6 12:04:26 2004 From: araspus at gmail.com (araspus at gmail.com) Date: 6 Dec 2004 09:04:26 -0800 Subject: any good, free web hosts supporting python cgi scripts? In-Reply-To: References: Message-ID: <1102352666.283043.42020@f14g2000cwb.googlegroups.com> please come to my website www.arasp.net You may be qualified. for my hosting plans. From __peter__ at web.de Sun Dec 19 06:48:37 2004 From: __peter__ at web.de (Peter Otten) Date: Sun, 19 Dec 2004 12:48:37 +0100 Subject: dot products References: <1103454255.371143.95030@z14g2000cwz.googlegroups.com> Message-ID: Rahul wrote: > I want to compute dot product of two vectors stored as lists a and b.a > and b are of the same length. > > one simple way is > sum(a[i]*b[i] for i in range(len(a))) > > another simple way is > ans=0.0 > for i in range(len(a)): > ans=ans+a[i]*b[i] > > But is there any other way which is faster than any of the above. (By > the way profiling them i found that the second is faster by about 30%.) You could try sigma = 0 for ai, bi in itertools.izip(a, b): sigma += ai * bi or sum(itertools.starmap(operator.mul, itertools.izip(a, b))) but if you are really concerned about number-crunching efficiency, use Numarray. Peter From jeff at ccvcorp.com Fri Dec 17 18:33:52 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 17 Dec 2004 15:33:52 -0800 Subject: Why no list heritable type? In-Reply-To: <86hdmkzq10.fsf@guru.mired.org> References: <86vfb13jpl.fsf@guru.mired.org> <10s66kql5vf5dd@corp.supernews.com> <86hdmkzq10.fsf@guru.mired.org> Message-ID: <10s6qvqa6b34166@corp.supernews.com> Mike Meyer wrote: >Jeff Shannon writes: > > > >>Additionally, as I understand it UserList and UserDict are implemented >>entirely in Python, which means that there can be significant >>performance differences as well. >> >> > >Actually, UserList and UserDict are just wrappers around the builtin >types. So the performance hit is one Python function call - pretty >much neglible. But new code should still subclass the builtins. > > Ah. I suppose that makes sense, now that the builtins are subclassable. Originally, they had to be implemented in Python in order to make them subclassable, but now the type/class unification has changed all that... Jeff Shannon Technician/Programmer Credit International From FBatista at uniFON.com.ar Tue Dec 14 11:58:11 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Tue, 14 Dec 2004 13:58:11 -0300 Subject: Python IDE Message-ID: [Chris] #- -chuckle- Hopefully I don't start off a full fledged war.-grin- Too late, :p #- Why didn't you like Eclipse? Was it that the Python modules #- were bad, #- or just Eclipse in general? I use it for my Java developement and #- haven't had any problems with it. I use Eclipse to code in Python when working in a project that has more than 20 modules because all its features (CVS integration, etc.). But for edit one file, I normally use gedit or vim. . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jegenye2001 at HAM-ONLY-PLEASE-SO-REMOVE-THIS.parkhosting.com Sat Dec 4 19:59:02 2004 From: jegenye2001 at HAM-ONLY-PLEASE-SO-REMOVE-THIS.parkhosting.com (Miklós P) Date: Sun, 5 Dec 2004 01:59:02 +0100 Subject: Need help on program!!! References: <41b0b87c$0$250$edfadb0f@dread12.news.tele.dk> Message-ID: "Dan Perl" wrote in message news:I7-dnVVVF8squizcRVn-2g at rogers.com... > > > I'm not sure what you mean by "benignity" here, but I think I agree with > you. Sympathy for TAs is not really my reason for how I feel towards I meant that I think the real (or long term) interest of the OP is to *learn* things as opposed to (the short term interest in) submitting that homework without his devoting any effort. > reason to give him the solution). I guess that is not the best argument I > could have made. > > Dan > Yes, I agree and I had thought you actually meant it similarly like I do. Best regards, Mikl?s From martin at v.loewis.de Tue Dec 7 02:30:57 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 07 Dec 2004 08:30:57 +0100 Subject: Win32 Libs for 2.4 In-Reply-To: References: Message-ID: <41b55c28$0$196$9b622d9e@news.freenet.de> Robin Becker wrote: > I thought that static .libs didn't make reference to the dll's they > need; isn't that done at load time? Unfortunately, thanks to Microsoft's infinite wisdom, static libs *do* reference DLLs. The C lib headers contain things like #pragma lib("msvcrt.lib") // or some such The compiler translates this into a reference to the DLL in the object file, which the linker will then translate into a reference to the DLL when linking, even if the DLL was not giving on the linker command line. However, I am uncertain how this works with multiple VC versions - whether the DLL reference is CRT version independent or not. You should view the resulting extension module in depends.exe, and check whether it refers to multiplce CRT dlls (which would be bad). Regards, Martin From fumanchu at amor.org Fri Dec 17 11:18:10 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 17 Dec 2004 08:18:10 -0800 Subject: Cool object trick Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398078@exchange.hqamor.amorhq.net> Alex Stapleton wrote: > you can't do > > var = "varA" > obj = struct(varA = "Hello") > print obj.var > > and expect it to say Hello to you. Did you mean "print obj.varA"? I can't think of any use case for the way you wrote it, so I'm naively guessing you've got a typo. Feel free to correct me. ;) >>> class struct(object): ... def __init__(self, **kwargs): ... self.__dict__.update(kwargs) ... >>> var = "varA" >>> obj = struct(**{str(var): "Hello"}) >>> print obj.varA Hello Robert Brewer MIS Amor Ministries fumanchu at amor.org From lac at strakt.com Tue Dec 7 10:00:47 2004 From: lac at strakt.com (Laura Creighton) Date: Tue, 07 Dec 2004 16:00:47 +0100 Subject: ANN: Wing IDE 2.0.1 released In-Reply-To: Your message of "Tue, 07 Dec 2004 00:57:45 EST." References: Message-ID: <200412071500.iB7F0l86012662@ratthing-b246.strakt.com> Congratulations! Laura From whitekid at gmail.com Sun Dec 19 19:53:49 2004 From: whitekid at gmail.com (Choe, Cheng-Dae) Date: Mon, 20 Dec 2004 09:53:49 +0900 Subject: Web forum (made by python) In-Reply-To: <32m5g1F3on6drU1@individual.net> References: <32m5g1F3on6drU1@individual.net> Message-ID: <38c00bae04121916532506b2f@mail.gmail.com> try http://kldp.net/projects/pybb/ example site is http://bbs.pythonworld.net:9080/pybbs.py On Sun, 19 Dec 2004 22:09:52 +0200, Gezer Punta wrote: > hi all > I am looking for a forum which was produced by python > > link pls > -- > http://mail.python.org/mailman/listinfo/python-list > -- Choe, Cheng-Dae(???) Blog: http://www.comdongin.com/ From danperl at rogers.com Sun Dec 12 18:40:04 2004 From: danperl at rogers.com (Dan Perl) Date: Sun, 12 Dec 2004 18:40:04 -0500 Subject: Persistent objects References: <7xis77q1t7.fsf_-_@ruckus.brouhaha.com> Message-ID: <6bmdnZbija5HSyHcRVn-sw@rogers.com> "Paul Rubin" wrote in message news:7xis77q1t7.fsf_-_ at ruckus.brouhaha.com... > I've had this recurring half-baked desire for long enough that I > thought I'd post about it, even though I don't have any concrete > proposals and the whole idea is fraught with hazards. > > Basically I wish there was a way to have persistent in-memory objects > in a Python app, maybe a multi-process one. So you could have a > persistent dictionary d, and if you say > d[x] = Frob(foo=9, bar=23) > that creates a Frob instance and stores it in d[x]. Then if you > exit the app and restart it later, there'd be a way to bring d back > into the process and have that Frob instance be there. I haven't used it myself, but this sounds to me a lot like metakit (http://www.equi4.com/metakit.html). Have you considered that and does it fit your needs? Dan From FBatista at uniFON.com.ar Fri Dec 17 11:55:12 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 17 Dec 2004 13:55:12 -0300 Subject: A completely silly question Message-ID: [Amir Dekel] #- What about user input in Python? (like stdin) #- Where can I find it? I can't find any references to it in #- the documentation. sys.stdin http://docs.python.org/lib/module-sys.html . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From danperl at rogers.com Mon Dec 13 22:36:25 2004 From: danperl at rogers.com (Dan Perl) Date: Mon, 13 Dec 2004 22:36:25 -0500 Subject: from string to raw string Message-ID: Is there a way to convert a regular string to a raw string so that one could get from '\bblah' to r'\bblah' other than parsing the string and modifying the escapes? I am interested in this for the use of regular expressions. I would like to be able to accept re patterns as inputs either from a file or from a GUI tool and I would like to allow those inputs as regular strings and not force users to write patterns with double escapes. I naively thought there could be utilities for such a conversion either in the string module or the StringIO module but I don't see any utilities like that. So, any suggestions? Dan From irmen at -NOSPAM-REMOVETHIS-xs4all.nl Thu Dec 23 06:24:46 2004 From: irmen at -NOSPAM-REMOVETHIS-xs4all.nl (Irmen de Jong) Date: Thu, 23 Dec 2004 12:24:46 +0100 Subject: Python on Linux Cluster In-Reply-To: References: Message-ID: <41caaaff$0$152$e4fe514c@news.xs4all.nl> Gurpreet Sachdeva wrote: > I have shifted my python script on a 4 node open ssi cluster. Please > guide me what changes do I have to do in my python scripts to fully > utilize the cluster. How do we introduce parralel processing in > python??? There was a very recent thread about this subject: http://tinyurl.com/5247f --Irmen From philippecmartin at sbcglobal.net Sun Dec 12 07:01:00 2004 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Sun, 12 Dec 2004 13:01:00 +0100 Subject: Named pipes in threads Message-ID: <200412121301.00813.philippecmartin@sbcglobal.net> >>What are you trying to do? ?Perhaps if you backed up and described >>the "what" we could make better recommendations about the "ho Just trying to have a GUI thread (tkinter) talk back and forth with a debugger derived object threaded (bdb). No I have not tried yet as sometimes things seem to work until .... Regards, Philippe From lutherrevisited at aol.com Sun Dec 26 22:30:32 2004 From: lutherrevisited at aol.com (LutherRevisited) Date: 27 Dec 2004 03:30:32 GMT Subject: WxButton References: <1104115850.408978.259170@z14g2000cwz.googlegroups.com> Message-ID: <20041226223032.07924.00002931@mb-m07.aol.com> Yes I have actually, I still can't figure out how to have my application detect if a control has focus. If I could, I could just use the keydown event with an if statement to push my button when it has focus and enter is pressed. From nid_oizo at yahoo.com_removethe_ Thu Dec 30 01:57:11 2004 From: nid_oizo at yahoo.com_removethe_ (Nicolas Fleury) Date: Thu, 30 Dec 2004 01:57:11 -0500 Subject: Why would I use inspect.isclass()? In-Reply-To: <5NKAd.4441$5R.1919@newssvr21.news.prodigy.com> References: <5NKAd.4441$5R.1919@newssvr21.news.prodigy.com> Message-ID: It's me wrote: >>I guess another example would be an assert on the type of argument: >>def foo(someClass): >> assert inspect.isclass(someClass) >> # rest of code >> > But that would always fail! (I just tried it). Are you sure you haven't pass an instance instead of a class? Remember, classes are also objects in Python: >>> import inspect >>> class A: pass ... >>> def foo(a): assert inspect.isclass(a) ... >>> foo(A) >>> Works fine and makes sense, no? Of course, if I pass an instance instead of a class it would fail: >>> myA = A() >>> foo(myA) Traceback (most recent call last): File "", line 1, in ? File "", line 1, in foo AssertionError Maybe your question is in what situations passing a class can be useful? There's many examples and once you're used to that capability it can be powerful. One simple example could be the generation of documentation; since you usually want to doc your classes, not instances. So it would make sense to do something like: def writeHtmlDoc(file, someClass): ... Regards, Nicolas From mwm at mired.org Sun Dec 26 22:50:49 2004 From: mwm at mired.org (Mike Meyer) Date: Sun, 26 Dec 2004 21:50:49 -0600 Subject: Complementary language? References: <1gpe9k5.6a1iczjyid9xN%aleaxit@yahoo.com> Message-ID: <864qi8761y.fsf@guru.mired.org> aleaxit at yahoo.com (Alex Martelli) writes: > Objective-C is cool... on the Mac; I'm not sure how well-supported it is > elsewhere, though. In addition to C's advantages, it would let you make > Cocoa GUIs on the Mac easily (with PyObjC &c). But then, the right way > to study Obj-C from scratch is no doubt to start with C, anyway. Objective-C is part of the Gnu Compiler Collection. As such, it's probably easy to find a working compiler. But I agree - you probably want to start with C. As an aside, if you want to study Eiffel, the book to buy is _Object Oriented Software Construction_, second edition, by Bertrand Meyer. Everybody doing OO software should read this book, as the lessons about constructing inheritance hierarchies are invaluable, even if the language won't enforce them for you. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steven.bethard at gmail.com Sat Dec 25 12:45:02 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 25 Dec 2004 17:45:02 GMT Subject: IDLE problem :-( In-Reply-To: References: Message-ID: Ishwor wrote: > I don't know if this has been a problem with other people using IDLE > but when i press the home key then the cursor jumps to the beginning > of the line and not after the prompt. If google prints the right > indentation then here how i want the IDLE prompt to work -> > > |>>> |(r,b,g).__class__ > ^ ^ > ^ ^-----> want cursor here instead. > cursor > goes > here > > Any work around?? If you're on windows, you can try PythonWin instead. The first time you hit home, the cursor will go your second |. If you then hit home again, the cursor will go to your first |. Steve From jcarlson at uci.edu Mon Dec 6 15:45:38 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Mon, 06 Dec 2004 12:45:38 -0800 Subject: Mean, median, and mode In-Reply-To: <41b4ac5b$1_1@omega.dimensional.com> References: <41b4ac5b$1_1@omega.dimensional.com> Message-ID: <20041206123200.ECEA.JCARLSON@uci.edu> mfuhr at fuhr.org (Michael Fuhr) wrote: > > Josiah Carlson writes: > > > > "Robert Brewer" wrote: > > > > > > Josiah Carlson wrote: > > > > > > > > median = lambda x: x.sort() or x[len(x)//2] > > > > > > That...is a really sneaky use of null return values. I like. :) > > > > Thank you, I'm just using a paradigm (exploiting lambdas) that I picked > > up while going through various functional programming modules. > > print median([1, 2, 3, 4, 5, 6]) > 4 > > Shouldn't the median be 3.5? The wikipedia entry (as mentioned by Peter Hanson in another post) is incomplete. There are 3 valid medians for even-lengthed sequences: sorted(seq)[len(seq)//2] sorted(seq)[len(seq)//2-1] sum(sorted(seq)[len(seq)//2-1:len(seq)//2+2])/2.0 All are correct, what is /desired/ is generally application specific. If you want the statistical median, 3.5 is the answer. If you want a computer science median (for quicksort, etc.), 3 or 4 is sufficient. I chose the shortest implementation (using the author's style, without sorted, because I forgot about the new builtin), which gives the greater (or equal) of the two possible computer science median values. - Josiah From kbk at shore.net Fri Dec 17 22:21:15 2004 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 17 Dec 2004 22:21:15 -0500 (EST) Subject: Weekly Python Patch/Bug Summary Message-ID: <200412180321.iBI3LFlA022448@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 259 open ( +0) / 2707 closed ( +2) / 2966 total ( +2) Bugs : 822 open (+22) / 4685 closed (+23) / 5507 total (+45) RFE : 160 open ( +0) / 139 closed ( +2) / 299 total ( +2) New / Reopened Patches ______________________ repair typo (2004-12-08) CLOSED http://python.org/sf/1080684 opened by George Yoshida Description of message_set and command option to store() (2004-12-13) http://python.org/sf/1084092 opened by Sean Reifschneider Patches Closed ______________ repair typo (2004-12-07) http://python.org/sf/1080684 closed by jlgijsbers fix inspect.getsource breaking with line-continuation & more (2004-08-19) http://python.org/sf/1011890 closed by jlgijsbers New / Reopened Bugs ___________________ Inplace set merge produces wrong results (2004-12-07) CLOSED http://python.org/sf/1080424 opened by Matthias Klose float issue for NaN type in .pyc file (2004-12-07) http://python.org/sf/1080440 opened by Dileep Nirala Python Icon in system Tray (2004-12-07) CLOSED http://python.org/sf/1080634 opened by Dileep Nirala thread.error: release unlocked lock on Queue put (2004-12-07) CLOSED http://python.org/sf/1080660 opened by John Speno os.ttyname() accepts wrong arguments (2004-12-07) http://python.org/sf/1080713 opened by Christian H?ltje full test with all unicode text files (2004-12-07) CLOSED http://python.org/sf/1080811 opened by Grzegorz Makarewicz locale.py doesn't recognize valid locale setting (2004-12-07) CLOSED http://python.org/sf/1080864 opened by stas Z readline module doesn't build on MacOSX (2004-12-07) http://python.org/sf/1081045 opened by Skip Montanaro Bad reference in whrandom docs (2004-12-08) CLOSED http://python.org/sf/1081370 opened by Lars Marius Garshol LDAP search segfaults on RedHat FC3 (2004-12-08) CLOSED http://python.org/sf/1081633 opened by Tessa Lau Rewrite of docs for compiler.visitor (2004-12-09) http://python.org/sf/1081824 opened by Kent Johnson Pydoc can't find browser (bug+solution!) (2004-12-08) http://python.org/sf/1081879 opened by Stewart Midwinter PyString_AsString() segfaults when passed a unicode string (2004-12-09) CLOSED http://python.org/sf/1082085 opened by Andreas Jung Documentation for PyUnicode_TailMatch incorrrectly says it r (2004-12-10) CLOSED http://python.org/sf/1082944 opened by Jim Fulton truncated gzip file triggers zlibmodule segfault (2004-12-10) http://python.org/sf/1083110 opened by Sam Rushing Change in signal function in the signal module (2004-12-10) http://python.org/sf/1083177 opened by Gary H. Loechelt Unable to see Python binary (2004-12-10) http://python.org/sf/1082874 opened by Prabal Rakshit UnboundLocalError raised by atexit module (2004-12-10) CLOSED http://python.org/sf/1083202 opened by Gary H. Loechelt Distutils doesn't pick up all the files it should. (2004-12-10) http://python.org/sf/1083299 opened by Mike Meyer font lock keyword regular expressions (2004-12-09) http://python.org/sf/1082487 opened by Robert Brown Tests fail instead of skip (2004-12-12) http://python.org/sf/1083645 opened by Detlef Vollmann Python 2.4 crashes (2004-12-12) http://python.org/sf/1083793 opened by Axel Kaiser functions replaced should point to its docs (2004-12-12) http://python.org/sf/1083895 opened by Johannes Gijsbers status of small floats in xml-rpc ? (2004-12-13) CLOSED http://python.org/sf/1084279 opened by Antoine Pitrou ossaudiodev no longer undocumented (2004-12-13) CLOSED http://python.org/sf/1084457 opened by Gregory H. Ball sys.stdin segfaults on invalid stdin (2004-12-13) http://python.org/sf/1084766 opened by Mihai Ibanescu list initialization bug (2004-12-14) CLOSED http://python.org/sf/1084906 opened by py_py gethostbyaddr on redhat for multiple hostnames (2004-12-14) http://python.org/sf/1085069 opened by Dave Kirby Fix stale link in PEP (2004-12-14) CLOSED http://python.org/sf/1085096 opened by Michael Chermside Uninstaller unclear about the app it's uninstalling (2004-12-14) CLOSED http://python.org/sf/1085168 opened by Giles Antonio Radford Uninstaller should restore file associations if possible (2004-12-14) http://python.org/sf/1085172 opened by Giles Antonio Radford Installation ends prematurely (2004-12-14) http://python.org/sf/1085208 opened by anamh0001 binascii.b2a_qp oddities (2004-12-14) http://python.org/sf/1085283 opened by DSM Mac Library Modules 1.1.1 Bad Info (2004-12-14) http://python.org/sf/1085300 opened by Walrus Make array.array pickle-able (2004-12-14) CLOSED http://python.org/sf/1085304 opened by Nicolas Fleury Bad interaction between PySequence_Fast and itertools (2004-12-15) CLOSED http://python.org/sf/1085744 opened by Nick Coghlan subprocess.Popen feature request (2004-12-15) http://python.org/sf/1085861 opened by Michele Simionato PySequence_Tuple not as fast as PySequence_List (2004-12-15) http://python.org/sf/1085744 reopened by rhettinger two strings holding the same value have different id (2004-12-15) CLOSED http://python.org/sf/1086096 opened by Stefan Seefeld Typo in module os documentation (2004-12-15) CLOSED http://python.org/sf/1086127 opened by Connelly refcount problem in syslog (2004-12-16) CLOSED http://python.org/sf/1086555 opened by DSM segfault in readline (2004-12-16) http://python.org/sf/1086603 opened by DSM Compile of _socket fails on 2.4 (2004-12-16) http://python.org/sf/1086642 opened by A. Stocker optparse docs missing section on Extending (2004-12-16) http://python.org/sf/1086675 opened by Kent Johnson "slots" member variable in object.h confuses Qt moc utility (2004-12-17) http://python.org/sf/1086854 opened by Jeremy Friesner datetime module documentation missing critical detail (2004-12-17) http://python.org/sf/1087216 opened by Mike Meyer Bugs Closed ___________ Inplace set merge produces wrong results (2004-12-07) http://python.org/sf/1080424 closed by tim_one thread.error: release unlocked lock on Queue put (2004-12-07) http://python.org/sf/1080660 closed by rhettinger full test with all unicode text files (2004-12-07) http://python.org/sf/1080811 closed by makaron locale.py doesn't recognize valid locale setting (2004-12-07) http://python.org/sf/1080864 closed by lemburg Bad reference in whrandom docs (2004-12-08) http://python.org/sf/1081370 closed by rhettinger PythonWin Tray Icon in system Tray on Windows platform (2004-12-07) http://python.org/sf/1080634 closed by loewis LDAP search segfaults on RedHat FC3 (2004-12-08) http://python.org/sf/1081633 closed by loewis PyString_AsString() segfaults when passed a unicode string (2004-12-09) http://python.org/sf/1082085 closed by dcjim Documentation for PyUnicode_TailMatch incorrrectly says it r (2004-12-10) http://python.org/sf/1082944 closed by rhettinger UnboundLocalError raised by atexit module (2004-12-10) http://python.org/sf/1083202 closed by rhettinger Python 1.5.2 security vulnerability still present in 2.3.4 (2004-08-05) http://python.org/sf/1003471 closed by aimacintyre test_subprocess fails on cygwin (2004-11-22) http://python.org/sf/1071516 closed by jlt63 Error building _bsddb extension (2004-12-01) http://python.org/sf/1077040 closed by greg status of small floats in xml-rpc ? (2004-12-13) http://python.org/sf/1084279 closed by rhettinger ossaudiodev no longer undocumented (2004-12-13) http://python.org/sf/1084457 closed by rhettinger list initialization bug (2004-12-14) http://python.org/sf/1084906 closed by rhettinger Fix stale link in PEP (2004-12-14) http://python.org/sf/1085096 closed by jlgijsbers Uninstaller unclear about the app it's uninstalling (2004-12-14) http://python.org/sf/1085168 closed by loewis Bad interaction between PySequence_Fast and itertools (2004-12-15) http://python.org/sf/1085744 closed by rhettinger Signal reception problem. FreeBSD 4.8 and 4.9 after forkpty (2004-04-28) http://python.org/sf/944119 closed by levis501 PySequence_Tuple not as fast as PySequence_List (2004-12-15) http://python.org/sf/1085744 closed by rhettinger two strings holding the same value have different id (2004-12-15) http://python.org/sf/1086096 closed by goodger Typo in module os documentation (2004-12-16) http://python.org/sf/1086127 closed by doerwalter refcount problem in syslog (2004-12-16) http://python.org/sf/1086555 closed by rhettinger New / Reopened RFE __________________ Add encoding to DocFileSuite (2004-12-07) http://python.org/sf/1080727 opened by Bjorn Tillenius RFE Closed __________ ignore element format character for PyArg_ParseTuple (2004-11-30) http://python.org/sf/1075902 closed by rhettinger Make array.array pickle-able (2004-12-14) http://python.org/sf/1085304 closed by rhettinger From tim.peters at gmail.com Sat Dec 4 11:46:08 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 4 Dec 2004 11:46:08 -0500 Subject: assymetry between a == b and a.__eq__(b) In-Reply-To: References: <9YNsBls/K7gH089yn@the-wire.com> Message-ID: <1f7befae041204084676885043@mail.gmail.com> [Mel Wilson] > :) Seems to: > > > Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> class Eq(object): > ... def __eq__(self, other): > ... return True > ... > >>> class Neq(Eq): > ... def __eq__(self, other): > ... print "(according to Neq)" > ... return False > ... > >>> eq,neq=Eq(),Neq() > >>> eq==neq > (according to Neq) > False > >>> neq==eq > (according to Neq) > False > >>> See the Python (language, not library) reference manual, section 3.3.8 ("Coercion rules"), bullet point starting with: Exception to the previous item: if the left operand is an instance of a built-in type or a new-style class, and the right operand is an instance of a proper subclass of that type or class, ... From itsme at yahoo.com Thu Dec 30 12:59:14 2004 From: itsme at yahoo.com (It's me) Date: Thu, 30 Dec 2004 17:59:14 GMT Subject: Why would I use inspect.isclass()? References: <5NKAd.4441$5R.1919@newssvr21.news.prodigy.com> <0ATAd.63675$Jk5.14829@lakeread01> <55WAd.4686$5R.2345@newssvr21.news.prodigy.com> Message-ID: "Steve Holden" wrote in message news:ecXAd.64160$Jk5.21357 at lakeread01... > Well the basic idea is "treat what you've been passed as though it is > the type you wanted". When it's only you writing the code that's likely > going to be the case. When it's others, you have to be a little more > careful to catch the exceptions (except when you don;t bother, in which > case the users will have to understand the tracebacks). > I grew up in an environment that believes in prevention, rather then after-the-fact fixing. That's why it's hard for me to delegate error checking tasks to exception, rather then assert - it just feel so...."nake". :=) Anyway, points taken. From kamilche at mad.scientist.com Thu Dec 30 20:26:20 2004 From: kamilche at mad.scientist.com (Kamilche) Date: Thu, 30 Dec 2004 17:26:20 -0800 Subject: getattr() woes In-Reply-To: <87hdm5hnet.fsf@thomas.local> References: <87hdm5hnet.fsf@thomas.local> Message-ID: <33jo6eF3vqhr9U1@individual.net> Thomas Rast wrote: > I've found out about a fundamental problem of attribute lookup, the > hard way... Is there anything that can be done about this? It seems to me that the main problem is you're raising an AttributeError when an attribute is private. AttributeError is only raised when an attribute is not found. If you found it, but it's private, that's a different problem. Try raising a custom exception instead of an AttributeError, if you can. From g_will at cyberus.ca Thu Dec 2 16:46:58 2004 From: g_will at cyberus.ca (Gordon Williams) Date: Thu, 2 Dec 2004 16:46:58 -0500 Subject: efficient intersection of lists with rounding Message-ID: <000701c4d8b8$735c08d0$0200a8c0@amd950> Hi, I have to lists that I need to find the common numbers (2nd rounded to nearest integral) and I am wondering if there is a more efficient way of doing it. >>> a= [(123,1.3),(123,2.4),(123,7.8),(123,10.2)] >>> b= [(123, 0.9), (123, 1.9), (123, 8.0)] >>> [ (i,round(j)) for i,j in a for l,m in b if (i,round(j)) == (l,round(m))] [(123, 1.0), (123, 2.0), (123, 8.0)] >>> This works but a and b can be in the order of 30K long. A couple of other bits of info. - a and b are ordered smallest to largest (could bisect module be used?) - in the future I will want to round the second number of closest 0.25 rather than whole number. Would the sets module be more efficient? I'm using python 2.3. Thanks for any ideas. Regards, Gordon Williams From ShawnMilo at runbox.com Fri Dec 3 09:54:36 2004 From: ShawnMilo at runbox.com (Shawn Milo) Date: Fri, 03 Dec 2004 09:54:36 -0500 (EST) Subject: How did you learn Python? Message-ID: I was just wondering what the best books were for learning Python. Which books are good for getting started, and which should be saved for later, or or not useful except as a reference for the learned? I have a decent programming background in VB, JavaScript, VBScript, Net.Data (IBM's macro language), regular expressions, and a teensy bit of Perl. My point is, I don't want something that is going to explain the basic programming concepts, but does give a good introduction to Python-specific things. Then, once I know how to get the job done, I would like a good book or two at the intermediate to advanced level, to learn how to write really good code. I understand that resources such as this list and Google searches have all the answers, but it seems like a more structured tool, such as a book or formal class, would be of great benefit to me. The other languages I have used were picked up because of the need to get a job done. As a result, I am able to get the job done, but any experienced coder can show me six more efficient ways to do what I'm doing. I'm new to Python, and I want to do this one right. I believe that Python will be around for a good, long time, and it matches my values as an Open-Source/Linux supporter, while having relevance in the Windows and Mac world, as well. Plus, it looks like it was designed extremely well, and I'm excited about the principles I've read about. Thanks, Shawn From guettli at thomas-guettler.de Tue Dec 14 10:31:41 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 14 Dec 2004 16:31:41 +0100 Subject: need some help quickly References: <1103028384.783802.109120@z14g2000cwz.googlegroups.com> Message-ID: Am Tue, 14 Dec 2004 04:46:24 -0800 schrieb Allan Irvine: > HI > > Hope this is the right place for this, I am new. I have a spec to > create > a (dual screen) framework application that > > 1 displays mp3, flash, jpegs etc. on top screen > 2: displays buttons on bottom screen which alter image when a key is > pressed. What operating system do you use? Please choose a better subject next time. "need some help quickly": I don't think the application you are looking for is done quickly. Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From programmer.py at gmail.com Tue Dec 21 12:41:09 2004 From: programmer.py at gmail.com (Jaime Wyant) Date: Tue, 21 Dec 2004 11:41:09 -0600 Subject: Should I always call PyErr_Clear() when an exception occurs? In-Reply-To: <1f7befae04122022177a47bf98@mail.gmail.com> References: <1f7befae04122022177a47bf98@mail.gmail.com> Message-ID: On Tue, 21 Dec 2004 01:17:52 -0500, Tim Peters wrote: > [Jaime Wyant] > > I've found that the code below will crash if I don't have the > > PyErr_Clear() function call. Should I always call PyErr_Clear()? > > That's not the right approach. Nearly all Python C API calls can > fail. They return a special value if they do, primarily NULL for a > call that returns a pointer, or -1 for a call that returns an int. > The correct thing to do is to explicitly check every call that *might* > fail to see whether it *did* fail. If it did, then you also have to > explictly decide what to do about it: either pass the exception on to > your caller (by returning your function's error value), or suppress > the exception via PyErr_Clear(), or replace it with another exception. > You have to do one of those before making another Python C API call. > Ignoring these issues always leads to bad problems eventually. > What exactly "happens" if I leave the exception hanging out there? It looked as if the garbage collector was trying to do something with them. Anyway, thanks big time for that paragraph above. I don't seem to recall the manual telling me when to call PyErr_Clear(), but I was RTFM'n late into the night. And you're right, programming in C stinks. Especially for the novice Python-C hacker who keeps having to refer to the manual to determine if I have a borrowed or new reference! Thanks! jw From grebe at bigfoot.com Wed Dec 22 20:46:41 2004 From: grebe at bigfoot.com (George van den Driessche) Date: Thu, 23 Dec 2004 01:46:41 +0000 Subject: (Mac-specific) AppScript bug Message-ID: (This is really for Hamish Sanderson, I think, but I can't find an e-mail address for him.) On OS X 10.3.7, with XCode 1.5 and all the latest AppScript packages installed, writing this: a = appscript.app( 'XCode.app' ) causes a crash in terminology.py: /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/site-packages/appscript/terminology.py in parse(self, path) 102 osat.parse(path, self) 103 for code in self._elements.values(): --> 104 name = self._pluralClassNames.get(code, self._singularClassNames[code]) 105 self.referencebycode[code] = (kElement, name) 106 self.referencebyname[name] = (kElement, code) KeyError: '****' code is a FourCC identifying some part of XCode's script interface. You would imagine that every such part would have either a plural name or a singular name, but in this case somehow the FourCC '****' has ended up in self._elements and it has neither. Any idea how that might arise? I didn't investigate the origins of the FourCC, which looks like a placeholder or error. If you change the marked line (104) to read: name = self._pluralClassNames.get(code, self._singularClassNames.get(code, '____'+code)) then the rest of the terminology seems to run fine, and you just end up with one bogus entry called '____****' in the app's attributes. Cheers, George From craig at postnewspapers.com.au Sun Dec 5 04:40:41 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Sun, 05 Dec 2004 17:40:41 +0800 Subject: [Python-Help] (fwd) In-Reply-To: <000c01c4da88$60a68630$840880ca@Alfred> References: <000c01c4da88$60a68630$840880ca@Alfred> Message-ID: <1102239641.7591.48.camel@albert.localnet> On Sun, 2004-12-05 at 13:07, Alfred Canoy wrote: > a.. Compute the average of a list of numbers > b.. Finds the statistical median value of a list of numbers > c.. Finds the mode of a list of numbers > > count = 0 > sum = 0 > number = 1 > > print 'Enter 0 to exit the loop' > while number != 0: > number = input ('Enter a number: ') > count = count + 1 > sum = sum + number > count = count -1 > print ' The average is:', sum/count It looks to me like you'd be better off reading each input number into a list. (tip: in the interactive interpreter, run 'help(list)' ). Once you have a list, you can perform all sorts of computations on it to determine the information you need. >>> from __future__ import division >>> x = [] >>> x.append(1) >>> x [1] >>> x.append(5) >>> x [1,5] >>> sum(x) 6 >>> sum(x) / len(x) 3 As you can see, it's much easier to work with data in lists. Some of the other methods, like list.sort() and list "slices" will also be useful to you, but I'll let you figure out the details ;-) . Remember that Python is rather well documented, so that (usually) once you know what you need you can find out about it... -- Craig Ringer From elbows at spamcop.net Mon Dec 6 10:00:50 2004 From: elbows at spamcop.net (elbows at spamcop.net) Date: 6 Dec 2004 07:00:50 -0800 Subject: Book Recommendations In-Reply-To: References: <58ef839a.0412031306.301fd8a0@posting.google.com> Message-ID: <1102345250.408136.284810@z14g2000cwz.googlegroups.com> Manuzhai wrote: > Check this thread currently going on: > http://groups.google.com/groups?hl=en&lr=&c2coff=1&safe=off&threadm=coqd91%246m2%241%40news.doit.wisc.edu&prev=/groups%3Fhl%3Den%26lr%3D%26c2coff%3D1%26safe%3Doff%26group%3Dcomp.lang.python > The link doesn't work -- maybe because of the new google groups interface? Can you repost with a working link? Thanks, Nathan From __peter__ at web.de Mon Dec 20 17:13:36 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 20 Dec 2004 23:13:36 +0100 Subject: input record sepArator (not sepErator) References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com><1103501833.632076.74050@f14g2000cwb.googlegroups.com><1103504587.796518.245030@f14g2000cwb.googlegroups.com><41c6386e$1@nntp0.pdx.net> <32nmqtF3ninrdU1@individual.net> <41c6fe6b$1@nntp0.pdx.net> Message-ID: Terry Reedy wrote: > 'separate' (se-parate == take a-part) and its derivatives are perhaps the > most frequently misspelled English word on clp. Seems to be 'par' for the > course. It has 2 e's bracketing 2 a's. It derives from the Latin > 'parare', as does pare, so 'par' is the essential root of the word. > > My gripe for the day, just to let non-native writers know what not to > imitate. I hereby suggest seperate/(separate+seperate) as the hamburger standard (see http://www.oanda.com/products/bigmac/bigmac.shtml) for technical communities. Some data points, adjectives only, s.e.e.o.: the web: 4% python: 9% slashdot: 26% perl: 29% * Now draw your conclusions... Peter (*) Do you really believe I would have posted that if the outcome were in favour of perl? No, definately not... lest you run out of gripes... From nick at craig-wood.com Wed Dec 22 12:30:04 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 22 Dec 2004 17:30:04 GMT Subject: regular expression: perl ==> python References: <1103692329.420064.257540@f14g2000cwb.googlegroups.com> Message-ID: > 1) In perl: > $line = "The food is under the bar in the barn."; > if ( $line =~ /foo(.*)bar/ ) { print "got <$1>\n"; } > > in python, I don't know how I can do this? > How does one capture the $1? (I know it is \1 but it is still not clear > how I can simply print it. > thanks Fredrik Lundh wrote: > "JZ" wrote: > > > import re > > line = "The food is under the bar in the barn." > > if re.search(r'foo(.*)bar',line): > > print 'got %s\n' % _.group(1) > > Traceback (most recent call last): > File "jz.py", line 4, in ? > print 'got %s\n' % _.group(1) > NameError: name '_' is not defined I've found that a slight irritation in python compared to perl - the fact that you need to create a match object (rather than relying on the silver thread of $_ (etc) running through your program ;-) import re line = "The food is under the bar in the barn." m = re.search(r'foo(.*)bar',line) if m: print 'got %s\n' % m.group(1) This becomes particularly irritating when using if, elif etc, to match a series of regexps, eg line = "123123" m = re.search(r'^(\d+)$', line) if m: print "int",int(m.group(1)) else: m = re.search(r'^(\d*\.\d*)$', line) if m: print "float",float(m.group(1)) else: print "unknown thing", line The indentation keeps growing which looks rather untidy compared to the perl $line = "123123"; if ($line =~ /^(\d+)$/) { print "int $1\n"; } elsif ($line =~ /^(\d*\.\d*)$/) { print "float $1\n"; } else { print "unknown thing $line\n"; } Is there an easy way round this? AFAIK you can't assign a variable in a compound statement, so you can't use elif at all here and hence the problem? I suppose you could use a monstrosity like this, which relies on the fact that list.append() returns None... line = "123123" m = [] if m.append(re.search(r'^(\d+)$', line)) or m[-1]: print "int",int(m[-1].group(1)) elif m.append(re.search(r'^(\d*\.\d*)$', line)) or m[-1]: print "float",float(m[-1].group(1)) else: print "unknown thing", line -- Nick Craig-Wood -- http://www.craig-wood.com/nick From dscottr at bellatlantic.net Tue Dec 21 11:26:57 2004 From: dscottr at bellatlantic.net (Scott Robinson) Date: Tue, 21 Dec 2004 16:26:57 GMT Subject: BASIC vs Python References: <41C342A0.3040700@users.ch> <86sm64tzax.fsf@guru.mired.org> <86d5x849bs.fsf@guru.mired.org> <86ekhm2hk8.fsf@guru.mired.org> Message-ID: <8djgs0lk5fdvbd0h5pe3avqq06cvpbud5a@4ax.com> On Mon, 20 Dec 2004 08:46:14 +0000 (UTC), Alan Gauld wrote: >> >>> was too late). A machine designed to be run on Forth would have been >> >>> unbelievably powerful from the late 70s to the mid 90s (it would be >> >>> more painful now than the x86 legacy, but still). > >A small data point here is that Sun still use Forth in their >Sparc workstations. Their system prompt is really a Forth >interpreter... I don;t know where the interpreter resides, >presumably not in Sparc since its a RISC but interesting that >they still use it. (Or they did last time I used a >Sparc - 4 years ago?) > >Alan G. >Author of the Learn to Program website >http://www.freenetpages.co.uk/hp/alan.gauld It was still there three years ago. While debugging some Sun based hardware I tried playing with it after it crashed. Forth was still there. It certainly is useful for a hardware independent bios, but I was making the point it would be good for general purpose. I suspect that it would quickly run up against memory limitations and would go no faster than the machine driving the memory market (with a possible last gasp when Rambus came online). Scott Robinson From ben.champion at gmail.com Sun Dec 26 17:18:21 2004 From: ben.champion at gmail.com (FLChamp) Date: 26 Dec 2004 14:18:21 -0800 Subject: anit alias and vpython Message-ID: <1104099501.917903.125080@z14g2000cwz.googlegroups.com> I have created a simulation of the solar system which is graphically represented using vpython. I was wondering in there is some way to make the orbit paths look better (I was thinking of anti aliasing the lines). I havent been able to find any information on this so I assume its not supported but just wanted to check, or see if anyone had suggestions on how to make the graphics look better Many Thanks From Scott.Daniels at Acm.Org Tue Dec 7 17:19:34 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 07 Dec 2004 14:19:34 -0800 Subject: Sorting in huge files In-Reply-To: <1102451253.319822.126980@f14g2000cwb.googlegroups.com> References: <1102451253.319822.126980@f14g2000cwb.googlegroups.com> Message-ID: <41b62b97@nntp0.pdx.net> Paul wrote: > I have a large database of 15GB, consisting of 10^8 entries of > approximately 100 bytes each. or 10 gigabytes of data. > A few thoughts on this: > - Space is not going to be an issue. I have a Tb available. I presume this is disk space, not memory. If you do have a Tb of RAM and you are using CrayPython, just do it. From the above, I'd figure (very hand-wavishly), that you want about 20G RAM (maybe as little as 15). That's a lot to me. > Any comments? I'd draw a random sample of data to work with. The python cookbook has some good recipes fro drawing an unbiased sample. If you work with about 10,000 elements, you can probably still see patterns, but can try all kinds of weird stuff experimentally. Once you have a feel for key distributions, cut the distribution into key ranges that "guarantee" (not really, but in a statistical sense) the data will fit comfortably in memory (say a third of your available RAM), and process each range separately. The sort should then be duck soup: ordered_dest = open('ordered_by_key1', 'w') for interval in ranges_in_order(): data = extract_data(interval) data.sort(key=key1) for entry in data: ordered_dest.write(data) data = [] # avoid having older interval data during extract > How long should I hope this sort will take? It will sound weird, but I > actually have 12 different key maps and I want to sort this with > respect to each map, so I will have to sort 12 times. Well, good sorting is O(N * log(N)), so you should be able to calculate from a sample timing (once you get out of cache effects). If you use a variant of the above, simply time a few of the intervals you've chosen and do a nice linear extrapolation. --Scott David Daniels Scott.Daniels at Acm.Org From tanghaibao at gmail.com Thu Dec 23 12:27:58 2004 From: tanghaibao at gmail.com (tanghaibao at gmail.com) Date: 23 Dec 2004 09:27:58 -0800 Subject: Lambda going out of fashion In-Reply-To: References: <1103787058.7586.34.camel@albert.localnet> <1103821176.262563.123820@z14g2000cwz.googlegroups.com> Message-ID: <1103822877.985636.101580@f14g2000cwb.googlegroups.com> Thanks. :-) Two remarks. o One-liner fits the eyes & brains of a portion of people. o Why don't you just say all python can be written in equivalent java, can I assert that Guido doesn't want to get mixed with those mainstream>? From aleaxit at yahoo.com Sat Dec 18 22:08:14 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 18 Dec 2004 19:08:14 -0800 Subject: A rational proposal References: <864qik472n.fsf@guru.mired.org> Message-ID: <1gp07ii.lietva1td9uyoN%aleaxit@yahoo.com> Raymond L. Buvel wrote: > Mike Meyer wrote: > > PEP: XXX > > Title: A rational number module for Python > > > I think it is a good idea to have rationals as part of the standard > distribution but why not base this on the gmpy module > (https://sourceforge.net/projects/gmpy)? That module already provides gmpy wraps GMP, which is covered by LGPL; therefore, gmpy itself is LGPL, and thus, sadly, cannot be included with python (otherwise, speaking as gmpy's author, I'd be glad to fix its design to meet your objections). Alex From niemeyer at conectiva.com Mon Dec 13 11:30:38 2004 From: niemeyer at conectiva.com (Gustavo Niemeyer) Date: Mon, 13 Dec 2004 14:30:38 -0200 Subject: Another RegEx Question... In-Reply-To: References: Message-ID: <20041213163038.GA7835@burma.localdomain> Hello Andrea, > I'm quite new to Python and I don't know if this is a FAQ (I > can't find it) or an obvious question. I'm using the RE module > in python, and I would like to be able to contruct something > like the Window$ "Find Files Or Folders" engine. As the Window$ > users know, you can filter the file names using the character > "*", as: [...] You're looking for the fnmatch module. > import re > mystring = "*yf*nam*" > mystring.replace("*","\w+") > php = re.compile(mystring + "\w+") > > But it does not work... >>> re.compile("*yf*nam*".replace("*", ".*")+"$").match("myfilename") <_sre.SRE_Match object at 0xb7ab3b10> > Is there a way to let the user of my application use the "*" character and > to do a Regular Expression search inside a Python code? >>> import fnmatch >>> fnmatch.fnmatch("myfilename", "*yf*nam*") True >>> fnmatch.translate("*") '.*$' >>> fnmatch.translate("?yf*nam?") '.yf.*nam.$' -- Gustavo Niemeyer http://niemeyer.net From bjourne at gmail.com Sun Dec 12 19:31:50 2004 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 13 Dec 2004 01:31:50 +0100 Subject: Best book on Python? In-Reply-To: <41BCE01C.6080208@acm.org> References: <41bcc295$1@news.unimelb.edu.au> <1d6cdae30412121612680d3ed4@mail.gmail.com> <41BCE01C.6080208@acm.org> Message-ID: <740c3aec0412121631746af108@mail.gmail.com> I haven't read any Python paper books myself but as Christmas is coming up, I've checked up on what Python books other people recommend. Everyone who has reviewed Python books seem to like these books: * Python Essential Reference * Python Cookbook * Python in a Nutshell The last two are both written by Alex Martelli and the cookbook is IMHO really awesome. -- mvh Bj?rn From peter at somewhere.com Thu Dec 2 09:29:53 2004 From: peter at somewhere.com (Peter Maas) Date: Thu, 02 Dec 2004 15:29:53 +0100 Subject: installing wxPython on Linux and Windows In-Reply-To: References: Message-ID: Diez B. Roggisch schrieb: >>Same task on Win2k: download wxPython-setup.exe, double-click, done. >>Took me approx. 1 minute. This strikes me. Why are some tasks so hard >>on Linux and so easy on Windows? After all wxPython/Win and wxPython/Lin >>are made by the same developers. My guess: the software deployment >>infrastructure on Linux needs to be improved. > > > On debian, it > > apt-get install wxPython2.5.3 > I have heard praises of Debian's install system but Debian is quite conservative with latest versions. There are some packages (e.g. Python, PostgreSQL, Subversion) where I'd like to have the latest versions. I don't want to be too tightly bound to the update cycles of the Linux distribution. > All the points are of course only an explanation, no excuse - there _could_ > be better installers. As I showed, in parts that's already available, e.g. > for debian which handles dependencies usually much better and is easier to > use for online updates. I think we have to wait until consistent dependency > checking and so on are established - maybe LSB helps us there. If there would be a common specification how to query and change configuration data of the system and applications this would be really helpful. -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From http Sun Dec 12 04:54:28 2004 From: http (Paul Rubin) Date: 12 Dec 2004 01:54:28 -0800 Subject: Persistent objects Message-ID: <7xis77q1t7.fsf_-_@ruckus.brouhaha.com> I've had this recurring half-baked desire for long enough that I thought I'd post about it, even though I don't have any concrete proposals and the whole idea is fraught with hazards. Basically I wish there was a way to have persistent in-memory objects in a Python app, maybe a multi-process one. So you could have a persistent dictionary d, and if you say d[x] = Frob(foo=9, bar=23) that creates a Frob instance and stores it in d[x]. Then if you exit the app and restart it later, there'd be a way to bring d back into the process and have that Frob instance be there. Please don't suggest using a pickle or shelve; I know about those already. I'm after something higher-performance. Basically d would live in a region of memory that could be mmap'd to a disk file as well as shared with other processes. One d was rooted into that region, any entries created in it would also be in that region, and any objects assigned to the entries would also get moved to that region. There'd probably have to be a way to lock the region for update, using semaphores. Ordinary subscript assignments would lock automatically, but there might be times when you want to update several structures in a single transaction. A thing like this could save a heck of a lot of SQL traffic in a busy server app. There are all kinds of bogus limitations you see on web sites, where you can't see more than 10 items per html page or whatever, because they didn't want loading a page to cause too many database hits. With the in-memory approach, all that data could be right there in the process, no TCP messages needed and no context switches needed, just ordinary in-memory dictionary references. Lots of machines now have multi-GB of physical memory which is enough to hold all the stuff from all but the largest sites. A site like Slashdot, for example, might get 100,000 logins and 10,000 message posts per day. At a 1k bytes per login (way too much) and 10k bytes per message post (also way too much), that's still just 200 megabytes for a full day of activity. Even a low-end laptop these days comes with more ram than that, and multi-GB workstations are no big deal any more. Occasionally someone might look at a several-day-old thread and that might cause some disk traffic, but even that can be left in memory (the paging system can handle it). On the other hand, there'd either have to be interpreter hair to separate the persistent objects from the non-persistent ones, or else make everything persistent and then have some way to keep processes sharing memory from stepping on each other. Maybe the abstraction machinery in PyPy can make this easy. Well, as you can see, this idea leaves a lot of details not yet thought out. But it's alluring enough that I thought I'd ask if anyone else sees something to pursue here. From claudio.grondi at freenet.de Wed Dec 15 10:53:28 2004 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Wed, 15 Dec 2004 15:53:28 -0000 Subject: AsmL/Python relationship? Anyone using AsmL? What for? Message-ID: <32b1feF3m1vtpU1@individual.net> Hi, I have just by chance discovered, that Microsoft research works on a kind of programming language called AsmL, and I'm just curious if AsmL, which is using same concept of significant indentation as Python language, was developed fully independently or is there a kind of relationship (same person in developer team, etc.)? Maybe someone can give here some hints? Is anyone of you using AsmL? What for? Claudio P.S. What is AsmL can be checked out at: http://research.microsoft.com/fse/asml/ or directly in the tutorial: http://research.microsoft.com/fse/asml/doc/AsmL2_Tutorial.doc Here an excerpt from online available information: "AsmL is the Abstract State Machine Language. It is an executable specification language based on the theory of Abstract State Machines. The current version, AsmL 2 (AsmL for Microsoft .NET), is embedded into Microsoft Word and Microsoft Visual Studio.NET. It uses XML and Word for literate specifications. It is fully interoperable with other .NET languages. AsmL generates .NET assemblies which can either be executed from the command line, linked with other .NET assemblies, or packaged as COM components. AsmL is useful in any situation where you need a precise, non-ambiguous way to specify a computer system, either software or hardware. AsmL specifications are an ideal way for teams to communicate design decisions. Program managers, developers, and testers can all use an AsmL specification to achieve a single, unified understanding. One of the greatest benefits of an AsmL specification is that you can execute it. That means it is useful before you commit yourself to coding the entire system." From jzgoda at gazeta.usun.pl Fri Dec 24 08:43:52 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Fri, 24 Dec 2004 14:43:52 +0100 Subject: Python and Delphi In-Reply-To: References: Message-ID: Kristofer Carlson wrote: > I'm curious about the long term trends chart on the TIOBE Programming > Community Index chart at http://www.tiobe.com/tpci.htm. It shows the > prevalence of Delphi and Python have tracked roughly equivalent usage paths > for some years now. Does anyone know why, or is this just an interesting > but insignificant anomaly? I tend to accept this as coincidence, not an anomaly[1]. [1] If we call something "anomaly", we should also define "norm" for purpose of comparison. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From fuzzyman at gmail.com Thu Dec 23 09:38:09 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: 23 Dec 2004 06:38:09 -0800 Subject: urllib and sites that require passwds In-Reply-To: <1103810824.320164.258500@z14g2000cwz.googlegroups.com> References: <1103810824.320164.258500@z14g2000cwz.googlegroups.com> Message-ID: <1103812689.820017.267270@f14g2000cwb.googlegroups.com> USe urllib2 which will fail with an exception. You can trap this exception and using the code attribute of the exception object, determine why it failed. The error code for 'authentication required' is 401. Off the top of my head : import urllib2 req = urllib2.Request(theurl) try: handle = urllib2.urlopen(req) except IOError, e: if not e.hasattr('code'): print 'The url appears to be invalid.' print e.reason else: if e.code == 401: print theurl, 'is protected with a password.' else: print 'We failed with error code', e.code HTH Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From adam at cognitcorp.com Wed Dec 8 16:14:16 2004 From: adam at cognitcorp.com (Adam DePrince) Date: Wed, 08 Dec 2004 16:14:16 -0500 Subject: 2D array In-Reply-To: References: <20041207215721.06175.00001064@mb-m27.aol.com> <11vtd.625769$mD.522514@attbi_s02> Message-ID: <1102540456.3709.77.camel@localhost.localdomain> On Wed, 2004-12-08 at 15:06, Steven Bethard wrote: > Adam DePrince wrote: > > If your data is sparse you might want to consider using a dictionary > > where the key is a tuple representing the coordinates. > > > > a = {} > > a[(0,0)] = 0 > > a[(0,1)] = 1 > [snip] > >>>>print a.get( (5,0), None ) > > Good point. Note that you don't need the parentheses in the assignments > or item accesses: > > >>> a = {} > >>> a[0,0] = 10 > >>> a[0,0] > 10 > > Also note that you don't need to specify None as the default value when > you call dict.get -- None is assumed if no default value is supplied: The use of None as the default parameter was on purpose; the lack of "magic" in python is often cited in religious wars between python and perl aficionados. Use of get(something, None) was on purpose, the level of familiarity with the language implied by the original question suggested that the notion of optional parameters, and specifically those of get, may not have been immediately obvious. As for a[0,0] instead of a[(0,0)] ... the former just *looks* so aesthetically wrong to me that I've never used it, and had forgotten that it was even possible. > > >>> print a.get((5, 2)) > None > > Steve Adam DePrince From les_ander at yahoo.com Mon Dec 13 17:26:04 2004 From: les_ander at yahoo.com (les_ander at yahoo.com) Date: 13 Dec 2004 14:26:04 -0800 Subject: how do I "peek" into the next line? In-Reply-To: References: <1102964987.812024.5180@c13g2000cwb.googlegroups.com> <1102973071.239704.167280@z14g2000cwz.googlegroups.com> Message-ID: <1102976764.236637.101600@z14g2000cwz.googlegroups.com> I should have also said that I am using the same file handle. So suppose the file handle is fp then I read some lines from fp and I hand it over to other functions that read other things from fp (in an ordered manner). les From http Thu Dec 9 05:55:39 2004 From: http (Paul Rubin) Date: 09 Dec 2004 02:55:39 -0800 Subject: Ideas for projects References: <2004120821300416807%pbowden@stxrrcom> Message-ID: <7xis7baggk.fsf@ruckus.brouhaha.com> Phillip Bowden writes: > I feel that I've learned the language pretty well, but I'm having > trouble thinking of a medium to large project to start. What are some > projects that you have written in the past with Python? Why don't you say what areas interest you, and how much experience you have with programming in general. That will help choose a response. Most programmers who have been at it for a while, don't have trouble thinking of projects. They have far more ideas than they can ever possibly get around to working on. From rroberts at adobe.com Wed Dec 22 18:02:38 2004 From: rroberts at adobe.com (Read Roberts) Date: Wed, 22 Dec 2004 15:02:38 -0800 Subject: Problem with os.listdir and delay with unreachable network drives on Windows Message-ID: I wrote my own directory browser in order to get around a bug where tkFileDialog.askdirectory() can't handle non-ascii paths. However, I have a problem where I call os.listdir() on a mapped network drive, e.g. os.listdir("Z:\\"), and if the network drive is unavailable, the UI hangs until the OS returns with an exception because the network shared drive is unavailable. I would like to work around this by simply not looking into mapped drives that are not currently mounted. Is there some way to check the status of mapped drive to see if it is currently mounted, or a better solution? ( I use the call win32api.GetLogicalDriveStrings() to get the list of available drives). Also, is there any way to enumerate remote volumes that are mounted by not mapped? I can't easily find this in the win32 stuff or via googling. The win32net calls to enumerate servers and shares sound likely, but don't show such volumes on my system, although I may not be using the right arguments. I have the current Windows binary install of Python 2.3.4 on my Windows XP system. From mail at manuzhai.nl Fri Dec 3 17:01:33 2004 From: mail at manuzhai.nl (Manuzhai) Date: Fri, 03 Dec 2004 23:01:33 +0100 Subject: How did you learn Python? In-Reply-To: References: Message-ID: > I've not read all of it, and it overlaps a fair bit with Learning > Python, but the free Dive Into Python reads well and is often cited as a > good intro for those with programming experience. > . It is also available as a dead-tree > product from APress. I found Dive Into Python to be very useful when I got my hands wet with Python. It's a great read by a funny author, very much recommended. Regards, Manuzhai From aahz at pythoncraft.com Wed Dec 29 18:04:59 2004 From: aahz at pythoncraft.com (Aahz) Date: 29 Dec 2004 18:04:59 -0500 Subject: learning about threads and processes References: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> <1gpkcn8.1ukbssevczr9mN%aleaxit@yahoo.com> <1gpkwc1.npm4ab1rhkak1N%aleaxit@yahoo.com> Message-ID: In article <1gpkwc1.npm4ab1rhkak1N%aleaxit at yahoo.com>, Alex Martelli wrote: >Aahz wrote: >> In article <1gpkcn8.1ukbssevczr9mN%aleaxit at yahoo.com>, >> Alex Martelli wrote: >>> >>>Hmmm - have you looked at Deitel, Deitel, Liperi, Wiedermann, "Python >>>how to program", chapters 18 (Process Management) and 19 >>>(Multithreading), pages 613-687? They seem to do a rather workmanlike >>>job -- of course, they can't do full justice to the subjects in 75 >>>pages; and if you don't want to buy a vast, costly 1300-pages tome for >>>the sake of those 75 pages, I can't really blame you, either. >> >> Except that it's a really, really piss-poor book. That's an opinion >> which I believe you've agreed with previously. > >Overall, yes, it's not a book I'd heartily recommend. But, is anything >wrong, specifically, with chapters 18 and 19? They seem OK to me. Don't know, and I'm not checking. I'm already behind on too many things... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From ninotchka at teleline.es Fri Dec 10 19:57:42 2004 From: ninotchka at teleline.es (frau_Gertrude) Date: Sat, 11 Dec 2004 01:57:42 +0100 Subject: OT-Test References: <1102542673.956058.27570@c13g2000cwb.googlegroups.com><7016c$41b82709$51604868$28467@nf1.news-service.com> Message-ID: Ver si aparece la frau From insert at spam.here Mon Dec 20 19:09:12 2004 From: insert at spam.here (Doug Holton) Date: Mon, 20 Dec 2004 18:09:12 -0600 Subject: How about "pure virtual methods"? In-Reply-To: References: Message-ID: Doug Holton wrote: >> Noam Raphael wrote: >> even in the best solution that I know of, >> >>> there's now way to check if a subclass has implemented all the >>> required methods without running it and testing if it works. > > > I think there are some solutions like PyProtocols, see section 2.2 on > this page: http://www.python.org/cgi-bin/moinmoin/MetaClasses Let me rephrase the rest of my answer. This is something we could use in Python. You should add a feature request to have this in Python 3.0, a.k.a. Python 3000: http://www.python.org/cgi-bin/moinmoin/Python3.0 You might have simple code such as: inteface ICallable: def Call(args) However, Python 3.0 is likely years away. If you want to know how to run code like this and have real interfaces, abstract classes and virtual methods today, consult Fredrik Lundh. From __peter__ at web.de Wed Dec 1 15:57:56 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 01 Dec 2004 21:57:56 +0100 Subject: recombination variations References: Message-ID: David Siedband wrote: > The problem I'm solving is to take a sequence like 'ATSGS' and make all > the DNA sequences it represents. The A, T, and G are fine but the S > represents C or G. I want to take this input: > > [ [ 'A' ] , [ 'T' ] , [ 'C' , 'G' ], [ 'G' ] , [ 'C' , 'G' ] ] > > and make the list: > > [ 'ATCGC' , 'ATCGG' , 'ATGGC' , 'ATGGG' ] [...] The code you provide only addresses the first part of your problem, and so does mine: >>> def disambiguate(seq, alphabet): ... return [list(alphabet.get(c, c)) for c in seq] ... >>> alphabet = { ... "W": "AT", ... "S": "CG" ... } >>> disambiguate("ATSGS", alphabet) [['A'], ['T'], ['C', 'G'], ['G'], ['C', 'G']] Note that "identity entries" (e. g. mapping "A" to "A") in the alphabet dictionary are no longer necessary. The list() call in disambiguate() is most likely superfluous, but I put it in to meet your spec accurately. Now on to the next step :-) Peter From seefeld at sympatico.ca Tue Dec 14 09:44:50 2004 From: seefeld at sympatico.ca (Stefan Seefeld) Date: Tue, 14 Dec 2004 09:44:50 -0500 Subject: lies about OOP In-Reply-To: References: <1102995205.949964.76020@c13g2000cwb.googlegroups.com> <41be9e31$0$7078$afc38c87@news.optusnet.com.au> Message-ID: Craig Ringer wrote: > On Tue, 2004-12-14 at 16:02, Mike Thompson wrote: > > >>>I would pick the publication of "Design Patterns" in 1995 by the Gang of >>>Four (Gamma, Helm, Johnson, and Vlissides), to be the herald of when "the >>>Joy of OOP" would be "widely known." DP formalized a taxonomy for many of >>>the heuristics that had evolved only intuitively up until then. Its >>>emergence reflects a general maturation of concept and practice, sufficient >>>to say that the Joy of OOP could be said to be "widely known." > > >>In actual fact, virtually all the design patterns came from the >>Interviews C++ GUI toolkit written in the early '90s. What an utterly >>brilliant piece of work that was. > > > As somebody who has just been bowled over by how well Qt works, and how > it seems to make OOP in C++ work "right" (introspection, properties, > etc), I'd be interested in knowing what the similarities or lack thereof > between Qt and Interviews are. Qt provides widgets that a client app. can compose into a GUI. InterViews provides 'glyphs' [*] that form a scene graph in a display server. Although InterViews usually was compiled into a client-side library, it provided all the functionality required by a display server such as redisplay and pick traversals. Indeed, the X Consortium supported InterViews (and its successor Fresco) for a while as the next generation for its 'X Windowing System', until it was dropped (for mostly political reasons, as usual) about '95. (Fresco had been nominated, together with OpenDoc, as candidates for an 'Compound Document Architecture' RFP on the Object Management Group. OpenDoc won.) [*] The term 'glyph' reflexts the fact that the scene graph nodes in InterViews are extremely fine-grained, i.e. glyphs can represent individual characters or elements of vector graphics such as paths. That's unlike any conventional 'toolkit' such as Qt, where a 'widget' is quite coarse-grained, and the display of such 'widgets' is typically not that of a structured graphic, but procedural. Regards, Stefan From tjreedy at udel.edu Wed Dec 15 16:27:19 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 15 Dec 2004 16:27:19 -0500 Subject: while 1 vs while True References: <1102903165.589419.323000@z14g2000cwz.googlegroups.com> <7xllc1p3q4.fsf@ruckus.brouhaha.com> <7xsm6983rx.fsf@ruckus.brouhaha.com> <41C006E1.5090309@iinet.net.au> Message-ID: > >>> import pdb > >>> pdb.x = "Darn writeable module dictionaries" > >>> from pdb import x > >>> x > >>>'Darn writeable module dictionaries' > If Python really does behave that way, that bug should be fixed > immediately. The fact that the attributes of Python modules, like those of classes (and functions and instances) are externally mutable is a design feature, not a bug. (Call Python's dynamicity a design bug if you will, but that is different from a plain 'bug'.) This allows, for instance, programs to have an in-memory blackboard module with across-module variables that all other modules can write to as well as read. This design has been recommended several times on this list. We would, of course, all agree that having modules arbitrarily poking each others attributes is a bad idea. Indeed, that is the rationale for isolating all such pokes into a single blackboard module. Terry J. Reedy From eugene at boardkulture.com Mon Dec 6 15:03:37 2004 From: eugene at boardkulture.com (EuGeNe) Date: Mon, 06 Dec 2004 21:03:37 +0100 Subject: Any affordable Python-based CRM & ERP solutions? In-Reply-To: References: Message-ID: Will wrote: > Hi all, > > Please excuse the longish post. I'm new to Python (and programming), > but love what I see and believe it to be an important language. > > I have (at least) one retail client (with single outlet at present) > that requires a total business solution for their operation, > preferably open source. They need: > > - an ecommerce website providing sales, customer service, order > tracking and an opt-in newsletter > - system for tracking inventory > - full accounting system, tied-into the ecommerce website-- so full > front-end and back-end system integration > - possibly even point of sale tied-into the above. > > They've been using Windows up until now, but are happy to consider > Linux, BSD, Mac, etc, as long as there's not a huge learning curve > (they merely want a solution that works and is cost-effective). Other > than standard accounting reporting requirements, they need the ability > to add tax to local transactions. > > I have Googled with not a lot of contenders (Compiere-- > http://www.compiere.org/index.html -- not Python and an Oracle license > is required to run it; and I've just started reading about Bizar > Shop-- http://www.bizarshop.com.au/). Anything else I've seen is > either really expensive, doesn't fit the bill, or are not Python-based > (which I'd ultimately like to promote). > > Because of the above requirements I was thinking something quite > modular (that could be added to in future) would be the way to go. I > like what I have seen with Plone and Zope but am unsure at present > (given limited experience with these products) how one would integrate > something into those solutions (if package didn't come from one > 'vendor'), so that at least on the surface, everything appeared pretty > seamless. > > Is this wishful thinking in Python at present? If so, have you > encountered any other open source solutions that cover part of the > above with Python handling the rest (and being easily integrated)? > > I look forward to any feedback. Thanks very much in advance. > > Cheers, > > Will :) Maybe http://www.erp5.org/ is what you are looking for! From usenet_spam at janc.invalid Fri Dec 31 00:19:40 2004 From: usenet_spam at janc.invalid (JanC) Date: Fri, 31 Dec 2004 05:19:40 GMT Subject: Unicode entries on sys.path References: <41CB0D7A.3080107@v.loewis.de> <7jn3ag8b.fsf@python.net> <41d03bc3$0$1677$9b622d9e@news.freenet.de> Message-ID: vincent wehren schreef: > Normally I would have thought this would require using the Microsoft > Layer for Unicode (unicows.dll). If Python is going to use unicows.dll, it might want to use libunicows for compatibility with mingw etc.: -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From ronaldoussoren at mac.com Fri Dec 31 06:26:48 2004 From: ronaldoussoren at mac.com (Ronald Oussoren) Date: Fri, 31 Dec 2004 12:26:48 +0100 Subject: py2app on Mac OS X 10.3 In-Reply-To: <41d5260a@news.seeder.net> References: <41d5260a@news.seeder.net> Message-ID: On 31-dec-04, at 11:12, Austin wrote: > """ > Minimal setup.py example, run with: > % python setup.py py2app > """ > > from distutils.core import setup > import py2app > setup( > app = ['main.py'], > ) > > That is a sample code of wiki. > I have a file 'main.py' and several sub-folders. > After I execute 'pythonw setup.py py2exe', I see 2 folders, 'dist' & > 'build' > which is the same as py2exe. > I open the 'dist' folder and see a file 'main'. Then I double-click the > 'main' and appeared the error message. > 'IOError:[Errno 2] No such file or directory: > '/user/austin/Desktop/disk/main.app/Contents/Resources/log/eventlog.xml > I feel so wildered because 'main.app' should be a file not a folder. It's an application bundle, which is a folder. All '.app'-s on OS X are folders, it is a neat way of bundling the application program and all data files it needs. > > I was wondering if some extra codes needed by setup.py > Could anyone give me an advice? What is 'eventlog.xml' supposed to be? If you're going to write to it, it is in the wrong location. If it is a datafile that is used by your application you should mention it in the setup.py script (the data_files argument). Ronald From matthew.s at orcon.net.nz Thu Dec 30 14:48:46 2004 From: matthew.s at orcon.net.nz (matiu) Date: 30 Dec 2004 11:48:46 -0800 Subject: what would you like to see in a 2nd edition Nutshell? In-Reply-To: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> References: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> Message-ID: <1104436126.786397.32880@c13g2000cwb.googlegroups.com> I enjoyed the first edition. Please include: vpython.org, twisted and pygame and if you'll consider a gui toolkit do pygtk, we use it to develop and deploy on both windows and linux, with glade gui designer and libglade (loads the glade xml files in runtime). It's much easier to use than wx and looks nicer than tk :) Thanks for reading. From frans.englich at telia.com Wed Dec 15 08:49:20 2004 From: frans.englich at telia.com (Frans Englich) Date: Wed, 15 Dec 2004 13:49:20 +0000 Subject: KeyError In-Reply-To: <005001c4e2aa$b2ccf230$b88e1d53@unqku4k1fl8nea7> References: <005001c4e2aa$b2ccf230$b88e1d53@unqku4k1fl8nea7> Message-ID: <200412151349.20700.frans.englich@telia.com> On Wednesday 15 December 2004 13:33, rootshell at gazeta.pl wrote: > Hello. > Maybe someone will help me with this KeyError: > > ............................ > Traceback (most recent call last): > File "C:\Python\tabla.py", line 929, in -toplevel- > tablesDirectory = tablesDirectoryPrefix + os.environ['REMOTE_ADDR'] > File "C:\Python23\lib\os.py", line 417, in __getitem__ > return self.data[key.upper()] > KeyError: 'REMOTE_ADDR' > .......................... What trouble do you have? AFAICT, The key REMOVE_ADDR wasn't in the dictionary, meaning that the environment variable doesn't exist. Cheers, Frans From R.Brodie at rl.ac.uk Thu Dec 16 06:08:03 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 16 Dec 2004 11:08:03 -0000 Subject: Help need with converting Hex string to IEEE format float References: <1103038606.112242.106700@f14g2000cwb.googlegroups.com> Message-ID: wrote in message news:1103038606.112242.106700 at f14g2000cwb.googlegroups.com... > One example I tried was: > > wibble = struct.unpack("f", struct.pack("l", long(conv_str, 16))) > OverflowError: long int too large to convert to int You can't fit 0x80000000L into a signed 32-bit integer, use 'L' for an unsigned one. > If I follow the examples I have found on the net using a set value of > 0x80000000 in them, everything works fine from the interpreter line. This depends on the Python version: before 2.4 0x80000000 corresponds to the bit pattern you expect but will be negative. That's why it's happy as a signed 32-bit integer. >>> 0x80000000 == 0x80000000L :1: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up ... False From usenet at horvath.com Fri Dec 31 17:47:03 2004 From: usenet at horvath.com (Bob Horvath) Date: Fri, 31 Dec 2004 16:47:03 -0600 Subject: Zope newsgroups? Need help with POSKeyError Message-ID: I have a Zope/Plone combination that I have been having POSKeyErrors with for a while now. Are there any newsgroups that deal with Zope? From bart at oceanic.wsisiz.edu.pl Mon Dec 6 05:47:17 2004 From: bart at oceanic.wsisiz.edu.pl (Bartlomiej Rymarski) Date: Mon, 6 Dec 2004 10:47:17 +0000 (UTC) Subject: Curses programming, threads? References: <60dfb6f6.0412031044.f39c133@posting.google.com> Message-ID: Carl Banks wrote: > (...) > But I recommend threads for this. It's one of the easiest possible > uses of threads. There's no complex communication involved; locks and > semaphores and stuff aren't required. Just connect to the database in > a subthread, and have it set a global flag just before it exits. > Animate in a loop in the main thread, checking the flag every > iteration, and when it's true, you're done. > (...) I'll try to do this with threads then. Thanks for the answer. -- Bartek Rymarski $ %blow bash: fg: %blow: no such job From steve at holdenweb.com Thu Dec 16 13:47:58 2004 From: steve at holdenweb.com (Steve Holden) Date: Thu, 16 Dec 2004 13:47:58 -0500 Subject: module file length limitations on windows? In-Reply-To: <1103219197.399879.309910@z14g2000cwz.googlegroups.com> References: <1103219197.399879.309910@z14g2000cwz.googlegroups.com> Message-ID: Lonnie Princehouse wrote: > I've run into some eccentric behavior... It appears that one of my > modules is being cut off at exactly 2^14 characters when I try to > import it. Has anyone else encountered this? I can't find any mention > of such a bug, and stranger yet, other modules that exceed 16384 > characters seem to work just fine. > > In particular, suppose that my module foo.py contains the following as > its last line: > > thing = "goodbye world" > > Now, suppose that the length of the file is 16383 characters. It works > just fine: > > Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import foo >>>> > > > But if I make the string longer, it explodes: > > thing = "goodbye world spam spam spam spam spam" > > Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import foo > > Traceback (most recent call last): > File "", line 1, in ? > File "foo.py", line 583 > thing = "goodbye world sp > ^ > SyntaxError: EOL while scanning single-quoted string > > > What in the world is going on here?! > > This happens with Python 2.4 and 2.3.4 on win2k (under vmware), but it > does _not_ happen with 2.3.4 on Linux. Very strange! Could vmware be > the problem? > > I have also tried replacing my unix newlines with DOS \r\n with the > exact same result. > > I don't want to spend much time on this, since the workaround of > splitting the code into smaller files works just fine, but wow.. weird. > As a further data point, it doesn't appear to happen under Cygwin with 2.4 either: sholden at dellboy ~ $ wc module.py 8177 2 8191 module.py sholden at dellboy ~ $ python Python 2.4 (#1, Dec 4 2004, 20:10:33) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import module hello >>> sholden at dellboy ~ $ vi module.py sholden at dellboy ~ $ wc module.py 8177 5 8206 module.py sholden at dellboy ~ $ python Python 2.4 (#1, Dec 4 2004, 20:10:33) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import module hello spam spam spam Is it possible you've somehow inserted non-printing characters? Seems bizarrely improbable to me that 2^14 would be a significant boundary to the interpreter. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From luismgz at gmail.com Sun Dec 26 17:14:06 2004 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 26 Dec 2004 14:14:06 -0800 Subject: Optional Static Typing In-Reply-To: References: <1103795375.843649.286620@c13g2000cwb.googlegroups.com> <1103952924.715051.44540@f14g2000cwb.googlegroups.com> Message-ID: <1104099246.695286.109390@z14g2000cwz.googlegroups.com> Robert Kern wrote: > Automatic type inferencing is great, but sometimes the inference is > "object". Being able to supply more information about types helps > Starkiller keep the inferences tight and specific. Hmm... I'm not an expert in this subject at all, but I think that when the inference is "object", as you said, is because the type couldn't be inferred so it defaults to object, which is the more general type of all. For example, this is what happens in Boo, which is the only language I know (a little bit) that uses type inference. From insert at spam.here Mon Dec 20 18:51:41 2004 From: insert at spam.here (Doug Holton) Date: Mon, 20 Dec 2004 17:51:41 -0600 Subject: Web forum (made by python) In-Reply-To: References: <41C6C152.5090203@iinet.net.au> Message-ID: Fredrik Lundh wrote: > ask yourself if that thing you read really was a vicious attack by bunch of nasty > trolls, or if, perhaps, you missed the point. You still do not even acknowledge your behavior then? If it is your wish that I never mention boo again, then I will not, even though you and not I are the one with a financial conflict of interest in the matter. From ncoghlan at iinet.net.au Thu Dec 30 22:31:38 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 31 Dec 2004 13:31:38 +1000 Subject: what would you like to see in a 2nd edition Nutshell? In-Reply-To: References: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> <1gpkxzx.fu7ild1r7602uN%aleaxit@yahoo.com> <200412301319.10987.drlinux@columbus.rr.com> Message-ID: <41D4C81A.5030401@iinet.net.au> Mariano Draghi wrote: > I think that somehow Python's "J2EE" equivalent is already out there > (sort of...), I think it's called PEAK. . . Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From kay.schluehr at gmx.net Sun Dec 12 04:36:00 2004 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 12 Dec 2004 01:36:00 -0800 Subject: Overriding properties - Javaesque property rant In-Reply-To: <321m0tF3ghij8U1@individual.net> References: <321m0tF3ghij8U1@individual.net> Message-ID: <1102844160.623548.63680@z14g2000cwz.googlegroups.com> > There are several ways to fix it. The simplest would be to create a new > property object in CC's definition: > > class CC(C): > def set_value(self, val): > if val < 0: > self.__val = 1 > else: > self.__val = val > value = property(C.get_value, set_value) It won't fix because __val is defined as a class variable in C, but as an instance variable in CC. The set_value method creates a new __val. A typical Python pitfall. C.get_value would still return _C__val. > But an easier, more flexible method would be to use a metaclass which > automatically adds properties for specially-named methods. One example > of such a metaclass is autoprop from Guido van Rossum's descrintro > essay; see . Yes, but i dislike it either. This powerfull metaclass approach obscures the property creation right in the place. And it supports the tendency to create fat frameworks. A few weeks ago i talked to someone who avoided propertys completely because they seemed to Javaesque to him. I first agreed and understood his ranting about this awkward get_bla, set_blubb stuff. Then I rembebered that the property() function is just a descriptor-creator and one can easily wrap around it for simplification. So i defined defprop() def defprop(name, default = None, modify=None, check=None, types=[]): name = "__"+name def get(obj): if not hasattr(obj,name): setattr(obj,name, default) return getattr(obj,name) def set(obj,value): if types: if not True in [isinstance(value,t) for t in types]: raise TypeError, "Can't assign %s to property %s."%(value,name[2:]) if check: if not check(value): raise TypeError, "Can't assign %s to property %s."%(value,name[2:]) if modify: setattr(obj,name,modify(value)) else: setattr(obj,name,value) return property(get,set,None) I left out to define delete. It was for demonstration purposes only. Now define Your own classes: class X(object): a = defprop("a") b = defprop("b",types=(tuple,list)) c = defprop("c",check = lambda x:hasattr(x,"__len__")) d = defprop("d",default=0) class XX(X): def set_d(val): if val<0: return 1 return val d = defprop("d",default=0,modify=set_d) # overwrite d It would be nice also to refuse the redundant naming a = defprop("a") and write a = defprop() instead. But it's actually not possible at the moment ( or only with deep introspection ). Session on: >>> x = X() >>> x.d 0 >>> xx = XX() >>> xx.d 0 >>> xx.d = -1 >>> xx.d 1 Ciao Kay From frans.englich at telia.com Fri Dec 17 10:57:59 2004 From: frans.englich at telia.com (Frans Englich) Date: Fri, 17 Dec 2004 15:57:59 +0000 Subject: Time Difference In-Reply-To: References: Message-ID: <200412171557.59866.frans.englich@telia.com> On Friday 17 December 2004 15:40, Fredrik Lundh wrote: > "GMane Python" wrote: > > I was wondering if there is an existing function that would let me > > determine the difference in time. To explain: > > > > Upon starting a program: > > > > startup = time.time() > > > > After some very long processing: > > now = time.time() > > > > print , now - startup > > > > So, to print in a formatted way (D-H-M-S) the difference in time of > > startup and now. > > now - startup gives you the difference in seconds; turning that into (days, > hours, minutes, seconds) isn't that hard (hint: lookup the divmod function > in the manual). I've been struggling with that too. Here's some more documentation: http://pleac.sourceforge.net/pleac_python/datesandtimes.html I have a followup question on this, slightly off-topic: What is the best/simplest method to transfer a time to W3C XML Schema's type duration[1]? Is there any helper function for that? Cheers, Frans 1. http://www.w3.org/TR/xmlschema-2/#duration From P at draigBrady.com Thu Dec 16 09:28:21 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Thu, 16 Dec 2004 14:28:21 +0000 Subject: Efficient grep using Python? In-Reply-To: References: <38Zvd.32503$g4.608727@news2.nokia.com> Message-ID: <41C19B85.5020300@draigBrady.com> Christos TZOTZIOY Georgiou wrote: > On Wed, 15 Dec 2004 16:10:08 +0000, rumours say that P at draigBrady.com > might have written: > > >>>Essentially, want to do efficient grep, i..e from A remove those lines which >>>are also present in file B. >> >>You could implement elegantly using the new sets feature >>For reference here is the unix way to do it: >> >>sort a b b | uniq -u > > > No, like I just wrote in another post, he wants > > $ grep -vf B A > > I think that > > $ sort A B B | uniq -u > > can be abbreviated to > > $ sort -u A B B > > which is the union rather than the intersection of the files wrong. Notice the -u option to uniq. http://marc.free.net.ph/message/20021101.043138.1bc24964.html > wastes some time by considering B twice I challenge you to a benchmark :-) > and finally destroys original line > order (should it be important). true -- P?draig Brady - http://www.pixelbeat.org -- From fredrik at pythonware.com Tue Dec 14 10:41:55 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Dec 2004 16:41:55 +0100 Subject: Regexp problem, which pattern to use in split References: Message-ID: Hans Alm?sbakk wrote: > Is there a relatively hassle-free way to get the csv module working with > 2.1? The server is running Debian stable/woody, and it also seemed 2.2 can > coexist with 2.1, when I checked the distro packages, if that is any help. 2.3 and 2.4 can also coexist with 2.1 (use "make altinstall" to leave "python" alone, so if you're using a pure-Python application, upgrading might be a good idea. alternatively, the following module (with a slightly different API) should work under 2.1: http://www.object-craft.com.au/projects/csv/ From ch.list at US-HAMPTON.mail.SAIC.com Fri Dec 10 15:28:27 2004 From: ch.list at US-HAMPTON.mail.SAIC.com (Chris) Date: Fri, 10 Dec 2004 15:28:27 -0500 Subject: Fun with Outlook and MAPI In-Reply-To: References: <41b9fe25$0$1061$db0fefd9@news.zen.co.uk> Message-ID: <41BA06EB.8050601@us-hampton.mail.saic.com> >> Alas, I dont think that there is much you can do to prevent the >> confirmation dialogs with Outlook's MAPI dll. MS added them in a >> service pack as an anti-virus measure, so no work-around. Not all >> clients show these anoying dialogs though. Thunderbird definately >> doesn't. > There is actually a workaround. You're using Simple MAPI which has a > nice easy interface. The confirmation dialogs are only for Simple MAPI. > Using Extended MAPI can work around the problem but its a lot more tricky. > See the initial discussion here: > http://aspn.activestate.com/ASPN/Mail/Message/Python-win32/2160646 > > This code has now been included in pywin32 somehow but I can't remember > where and its late. Should also be a cookbook entry. Maybe Google can > help :-) Cool. I'll take a look an' see if I can get it to work. MAPI has turned out to be a major PITA. Especially when trying to learn it and Python at the same time. :) Chris From eric_brunel at despammed.com Fri Dec 3 07:15:35 2004 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 03 Dec 2004 13:15:35 +0100 Subject: Newbie alert ! In-Reply-To: References: Message-ID: <41b0572d$0$3438$8fcfb975@news.wanadoo.fr> Jean Montambeault wrote: > I am not only learning Python but programming itself ; reading your > posts makes me believe that nobody is that much of a beginner here. Is > there a newgroup or list for my type somewhere I can't find it ? > > To illustrate my case this script : > > > > # function to draw rings for an Olympic flag > def rings(size,offsetX,offsetY,coul): > x1,y1,x2,y2 = 170, 103, 170, 103, > can1.create_oval(x1-size-offsetX,y1+size+offsetY,\ > x2+size-offsetX,y2-size+offsetY,\ > width=8, outline=coul) > > # **main****main****main****main****main****main** > > fen1=Tk() > can1=Canvas(fen1, bg='white', height=206, width=340) > can1.pack(side=LEFT) > > bou_europe=Button(fen1, text='Europe',\ > command=rings(41, 100, -22, 'blue')) Here is what you do here: you *call* your "rings" function with the given parameters, and you assign the *result* of the function (which is None, since you do not have any "return" statement in rings) to the "command" option of your button. Since you do that for all buttons, all circles are drawn right away and no command is attached to any of your buttons. The basic solution would be to create 5 different functions - one for each ring - and assign the function to the button's command option: def ringEurope(): rings(41, 100, -22, 'blue') bou_europe = Button(fen1, text='Europe', command=ringEurope) And so on... Another shorter, but more difficult to understand solution would be to use an anonymous function built with lambda. Here is how it goes: bou_europe = Button(fen1, text='Europe', command=lambda: rings(41, 100, -22, 'blue')) There are however some issues with lambda, so you'd probably better stick to the first solution. [snip] > bou_africa=Button(fen1, text='Africa',\ > command=rings(size=41, offsetX=0,offsetY=-22, > coul='black')) (BTW, why do you pass the function arguments as positional parameters in the first call and as named parameters in the following ones? IMHO, since the parameters are positional in the function definition, you'd better pass them as such in the calls, i.e: rings(41, 0, -22, 'black') (Et sinon, il existe un newsgroup Python francophone (fr.comp.lang.python) sur lequel tu seras le bienvenu si jamais tu pr?f?res discuter en fran?ais) HTH -- - Eric Brunel - PragmaDev : Real Time Software Development Tools - http://www.pragmadev.com From sjmachin at lexicon.net Sat Dec 11 23:25:59 2004 From: sjmachin at lexicon.net (John Machin) Date: 11 Dec 2004 20:25:59 -0800 Subject: Upgrade woes: Numeric, gnuplot, and Python 2.4 In-Reply-To: References: Message-ID: <1102825559.847708.62080@c13g2000cwb.googlegroups.com> Jive wrote: > Here's my sitch: > > I use gnuplot.py at work, platform Win32. I want to upgrade to Python 2.4. > Gnuplot.py uses extension module Numeric. Numeric is now "unsupported." > The documentation says "If you are new to Numerical Python, please use > Numarray.". It's not that easy, dangit. The download page for numpy does > not contain a 2.4 version of Numeric, and I suspect they do not intend to > release one, because there IS a 2.4 version of Numarray. > > So here are my choices: > > 1) Switch from gnuplot.py to some other plotting package. > 2) Convince, bribe, or cajole someone to implement gnuplot.py using > Numarray. > 3) Hack on gnuplot.py myself. (Learning curve alert!) > 4) Buy a copy of the VC++ 7.1 and port Numeric myself. (I still don't know > what to buy from Mr. Gates -- VC++ .net Standard?) > 5) Do something else I haven't thought of. > > Any suggestions would be welcome. > > Jive "I speet on backwards incompatibility" Dadson Why do you want to "upgrade to 2.4"? What do you mean by "upgrade to 2.4"? Choice (5a) Install Python 2.4 and use that for whatever while continuing to use 2.3 for gnuplot. Choice (5b) Ask politely of the Numeric camp when/if they will make a 2.4-compatible Windows release. Choice (5c) Ask politely of the Python community if anyone else is contemplating making a 2.4 Windows distribution of Numeric. Choice (5d) Read replies to your fulminations in another thread -- in particular the one that says you need no truck with Mr Gates; in fact you can use free non-MS compilers to make Python extensions for Windows. From steven.bethard at gmail.com Sun Dec 26 17:02:39 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 26 Dec 2004 22:02:39 GMT Subject: Python 3000, zip, *args and iterators Message-ID: <3yGzd.289258$HA.962@attbi_s01> So, as I understand it, in Python 3000, zip will basically be replaced with izip, meaning that instead of returning a list, it will return an iterator. This is great for situations like: zip(*[iter1, iter2, iter3]) where I want to receive tuples of (item1, item2, item3) from the iterables. But it doesn't work well for a situation like: zip(*tuple_iter) where tuple_iter is an iterator to tuples of the form (item1, item2, item3) and I want to receive three iterators, one to the item1s, one to the item2s and one to the item3s. I don't think this is too unreasonable of a desire as the current zip, in a situation like: zip(*tuple_list) where tuple_list is a list of tuples of the form (item1, item2, item3), returns a list of three tuples, one of the item1s, one of the item2s and one of the item3s. Of course, the reason this doesn't work currently is that the fn(*itr) notation converts 'itr' into a tuple, exhausting the iterator: >>> def g(x): ... for i in xrange(x): ... yield (i, i+1, i+2) ... print "exhausted" ... >>> zip(*g(4)) exhausted [(0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5)] >>> it.izip(*g(4)) exhausted >>> x, y, z = it.izip(*g(4)) exhausted >>> x, y, z ((0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5)) What I would prefer is something like: >>> zip(*g(4)) >>> x, y, z = zip(*g(4)) >>> x, y, z (, >> def h(x, y, *args): ... print x, y, args ... print list(it.islice(args, 4)) ... >>> h(*it.count()) 0 1 count(2) [2, 3, 4, 5] So I guess my real question is, should I expect Python 3000 to play nicely with *args and iterators? Are there reasons (besides backwards incompatibility) that parsing *args this way would be bad? Steve [1] In fact, with the help of the folks from this list, I did: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302325 From peter at engcorp.com Fri Dec 10 16:30:50 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Dec 2004 16:30:50 -0500 Subject: sources for DOS-16bit In-Reply-To: <1102711703.270284.317730@z14g2000cwz.googlegroups.com> References: <1102711703.270284.317730@z14g2000cwz.googlegroups.com> Message-ID: McBooCzech wrote: > I am looking for Python binaries for DOS-16bit!!!! > Not for Win-16bit or DOS-32 which are the only DOS availabele sources > on Python official site and on the other sites as well!!! > I will prefere sources for Borland C 3.x. > > I was trying to use Python 1.0.1 (16python.exe file) for my > application, > but I realized it doesn't work on NEC V25 CPU (8086/8088 compatible > CPU developed by NEC). > > I was involved in to our school computer "research" :) and we need > this piece of code to reach our goal. > > We have to demonstrate the power of the free software (mainly its > compatiblity for different platforms)!!! > > Can you please search your archives or route me somewhere? Does it have to be Python? There are other languages that are arguably as portable, and certainly more compact. Lua, for example, has been ported to quite small devices. See http://www.lua.org/ for more on that, but note there are other options as well. Python's not the only "free portable software" around, though it's the best in many ways. -Peter From ishwor.gurung at gmail.com Thu Dec 23 11:50:20 2004 From: ishwor.gurung at gmail.com (Ishwor) Date: Fri, 24 Dec 2004 03:20:20 +1030 Subject: list Integer indexing dies?? In-Reply-To: References: Message-ID: <34534aed0412230850aa130ff@mail.gmail.com> On Thu, 23 Dec 2004 13:33:16 -0300, Batista, Facundo wrote: > > > [Ishwor] > > #- > What should 035[0] cough up? Be carefull it should > #- > #- >>>035[0] > #- 3 # my own opinion. why 3? The reason we get 3 and not 0 here is the *fact* that Python knows that its an octal rep. and not decimal ;-) 035[2] could return error here. Same for hex. No idea for binary. ~;-( > #- > #- > cough up the same as 29[0]. > #- > #- >>>29[0] > #- 2 #again my own opinion since it's decimal its fine to get 2 which is at offset 0. [snip] -- cheers, Ishwor Gurung From Scott.Daniels at Acm.Org Mon Dec 6 16:08:15 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 06 Dec 2004 13:08:15 -0800 Subject: GUI Frames and classmethod In-Reply-To: References: <41b0ffbc$1@nntp0.pdx.net> Message-ID: <41b4c968$1@nntp0.pdx.net> Zak Arntson wrote: > On Fri, 03 Dec 2004 14:48:30 -0800, Scott David Daniels > <> wrote: > .... question: A dictionary of dictionaries is slower than a > dictionary of tuples, right? Because when Python accesses a > dictionary, it produces a hash from the key and finds that in its hash > table. Producing a hash from a tuple is much faster than producting > two hashes and doing two lookups. At least that's what I'm assuming. Most likely so. Possibly an equal amount of has work -- hash of a pair is a function of hashes of the lelements, but fewer trips in and out of the interpretter. So, one less lookup, less refcount fiddling, and fewer dispatches through the interpretter. The real advantage is clarity: the inner dictionaries in a dict-of-dict implementation have no real "meaning." The extra overhead (in the mind of the program reader) involved in creating inner dictionaries at appropriate times makes the code harder to understand. --Scott David Daniels Scott.Daniels at acm.org From craig at postnewspapers.com.au Wed Dec 1 02:00:18 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Wed, 01 Dec 2004 15:00:18 +0800 Subject: Run an python method from C++ In-Reply-To: <7A977E70F2DA7446B6F631A8A66CF18F01754C47@deep.cadtech> References: <7A977E70F2DA7446B6F631A8A66CF18F01754C47@deep.cadtech> Message-ID: <1101884417.7561.40.camel@albert.localnet> On Wed, 2004-12-01 at 06:59, Mark Doberenz wrote: > pyRunFile =PyRun_File(pythonFileP,filename,Py_file_input,globals,globals); > runMethod = PyObject_CallMethod(pyRunFile,"proc1","s","Blah"); > --- It's crashing when I try to do the PyObject_CallMethod. (I'm going to assume 'crashing' means 'segmentation fault' as you have given no more detailed information, such as the error message or the backtrace...) Have you checked to ensure that pyRunFile is not NULL? According to the documentation, PyRun_File: "Returns the result of executing the code as a Python object, or NULL if an exception was raised." So you MUST check for and handle a NULL value. Separately, I don't think what you're doing with PyRunFile makes much sense. If you want to return the class, you need to do so explicitly with return dc at the end of your Python script. It might be worth using PyMapping_GetAttrString() to retrieve it out of the global namespace after your script runs, rather than trying to return it, though. I've been working with the Python/C API for a bit now, and I'm still finding it pretty hard going, so I understand your difficulties. There's actually another major bug in your code that you'll run into sooner or later. Try running a script that just contains: import sys sys.exit(1) and you'll see what I mean. To work around that and the difficulty of getting the exception text from the Python interpreter, I generate a small Python program as a C++ string, then PyRun_String() it. That program performs some setup and then execfile()s the real Python program inside a try block. I'll include the block I use below. I'm using a Qt-based C++ app, so it's all done with QString, but the concept is the same. If you're not familar with Qt, QString::arg() works pretty similarly to Python's % string substitution. fileDir is the directory the file to be run is stored in, and fileName is the path to to the script file to run. QString cm = QString("import sys,StringIO,traceback\n"); cm += QString("sys.path[0] = \"%1\"\n").arg(fileDir); cm += QString("try:\n"); cm += QString(" execfile(\"%1\")\n").arg(fileName); cm += QString("except SystemExit:\n"); cm += QString(" pass\n"); // Capture the text of any other exception that's raised by the interpreter // into a StringIO buffer for later extraction. cm += QString("except Exception, err:\n"); cm += QString(" f=StringIO.StringIO()\n"); cm += QString(" traceback.print_exc(file=f)\n"); cm += QString(" errorMsg = f.getvalue()\n"); cm += QString(" del(f)\n"); // We re-raise the exception so the return value of PyRun_String reflects // the fact that an exception has ocurred. cm += QString(" raise\n"); // Get the thing as a char* char* python_wrapper = cm.latin1().data(); When I later need to retrieve an exception (after I run this with PyRun_String) I get to it with (error checking omitted): PyObject* errorMsgPyStr = PyMapping_GetItemString(globals, "errorMsg") QString errorMsg = PyString_AsString(errorMsgPyStr); (I'd love to be told there's a nicer way to do this). This could easily be the wrong way to go about things, buggy, or just stupid, so be warned. It does work well here, however. I would be interested in knowing how to tell Python what encoding is used for program text passed using PyRun_String() if anybody knows. -- Craig Ringer From Prikryl at skil.cz Mon Dec 13 11:28:08 2004 From: Prikryl at skil.cz (Petr Prikryl) Date: Mon, 13 Dec 2004 17:28:08 +0100 Subject: Suggestion for "syntax error": ++i, --i Message-ID: Hi Christian, The suggestion is to mark PREFIX version ++i as syntax error. It is not related to the postfix version of the ++ operator. For prefix in/decrement, there is no extra variable behind. But again, it is not related to the suggestion. The postfix version is already marked as "syntax error". The suggestion is to do the same with the prefix version of the operators that are not used in Python. Petr "Christian Ergh" wrote... > Hmm, i never liked the i++ syntax, because there is a value asignment > behind it and it does not show - except the case you are already used to it. > > >>> i = 1 > >>> i +=1 > >>> i > 2 > > I like this one better, because you see the assignment at once, it is > easy to read and inuitive usability is given - in my opinion. > Chris > > > > > Petr Prikryl wrote: > > Hi, > > > > Summary: In my opinion, the C-like prefix > > increment and decrement operators (++i and --i) > > should be marked as "syntax error". > > > > > > Current situation: try... (Python 2.4 (#60, ...)) > > > >>>>i = 1 > >>>>i > > > > 1 > > > >>>>i++ > > > > File "", line 1 > > i++ > > ^ > > SyntaxError: invalid syntax > > > >>>>++i > > > > 1 > > > >>>>--i > > > > 1 > > > > > > Reason for how ++i and --i behaves in Python is > > that it is probably treated as (-(-i)) and (+(+i)) > > respectively. > > > > Rationale: My guess is that many Python users > > do use other languages at the same time. > > The C-family languages do use the prefix increment > > and decrement operators. When used in Python > > no warning appears -- the code simply does not work > > as expected. In the same time, there is probably no > > reason to use the increment and decrement > > prefix operators. On the other hand, the newcommer > > or the programmer that "types ++i automatically > > because of brain synapses say he/she should..." > > is not warned until something does not work. > > > > Con: The situation must be recognized by the parser > > (i.e. someone have to implement it). > > > > Pro: No runtime overhead except of the detection > > of the situation. As Python is a good candidate > > to be used as the language for teaching, the "syntax > > error" would be the pedagogical plus. > > > > Personal experience: Many things in Python work > > intuitively. My C++ experience "forced me" to use > > ++i as described above. I use iteration more these > > days and I know about the ++i problem invisibility > > in Python. But I had to learn by mistake. The ++i > > behaviour is not intuitive for me. > > > > Your opinion? > > > > From deetsNOSPAM at web.de Sat Dec 11 14:10:39 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 11 Dec 2004 20:10:39 +0100 Subject: newbie questions References: <41ba6511$1@nntp.zianet.com> <%eHud.90239$ha.15906@news.chello.at> Message-ID: > Thanks I will try all of that, but what does really means mutating in > python? It's the first time I hear this word in programming :)) An object is called mutable if you can alter it - immutable otherwise. In java and python e.g. strings are immutable. In python, tuples are immutable: >>> a = (1,2) >>> a[0] = 3 TypeError: object doesn't support item assignment but lists are mutable: >>> a = [1,2] >>> a[0] = 3 >>> a [3,2] But objects in tuples can be mutable: >>> a = (1, [2,3]) >>> a[1].append(4) >>> a (1,[2,3,4]) Numbers are also immutable. 1 is 1 always. The most important thing to know about python and variables is that variables are only names pointing/referring to values. You might be able to modify the values if they are mutable, but assigning a value to a variable means that you simply rebind its name to a new value - not that you alter it. Consider this: >>> a = 1 >>> b = a >>> a = 2 >>> print a, b 2 1 -- Regards, Diez B. Roggisch From hongqn at gmail.com Mon Dec 13 09:14:03 2004 From: hongqn at gmail.com (Qiangning Hong) Date: Mon, 13 Dec 2004 22:14:03 +0800 Subject: predict directory write permission under windows? Message-ID: I want to know if I can write files into a directory before I actually perferm the write behavor. I found os.access(path, os.W_OK) but it uses real uid/gid to check instead of euid/egid so it doesn't fit my problem. I don't know how to get euid/egid under windows so I cannot use the mode infomation returned by os.stat(). Anybody give me a hint? From brian.bird at securetrading.com Tue Dec 21 08:52:56 2004 From: brian.bird at securetrading.com (brian.bird at securetrading.com) Date: 21 Dec 2004 05:52:56 -0800 Subject: Keyword arguments - strange behaviour? References: <1103622331.247762.161750@f14g2000cwb.googlegroups.com> Message-ID: <1103637176.450940.243500@c13g2000cwb.googlegroups.com> Thanks, this makes perfect sense. The phrase which sums it up neatly is "Default parameter values are evaluated when the function definition is executed" However, is there a good reason why default parameters aren't evaluated as the function is called? (apart from efficiency and backwards compatibility)? Is this something that's likely to stay the same in python3.0? I'm really looking for a neat way to do the following: def method(a,b,opt1=None,opt2=None,opt3="",opt4=None): if opt1 is None: opt1=[] if opt2 is None: opt2={} if opt4 is None: opt4=[] Python syntax is normally so neat but this just looks a mess if there are lots of parameters. From jgv-home at comcast.net Thu Dec 9 06:39:10 2004 From: jgv-home at comcast.net (j vickroy) Date: Thu, 9 Dec 2004 04:39:10 -0700 Subject: Python 2.4 Tix failing on Windows XP Message-ID: Hello, I've just installed (accepted all installation defaults) Python 2.4 (final) on my Microsoft Windows XP (home edition - service pack 2) computer, and I am experiencing the following behavior regarding Tix: >>> import sys >>> sys.version '2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)]' >>> import Tix >>> root = Tix.Tk() Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\lib\lib-tk\Tix.py", line 210, in __init__ self.tk.eval('package require Tix') TclError: couldn't load library "tix8184.dll": this library or a dependent library could not be found in library path >>> import os >>> os.environ['TIX_LIBRARY'] 'C:\\Python24\\tcl\\tix8.1' >>> "tix8184.dll" is definitely not in the 'C:\Python24\tcl\tix8.1' folder; its in the 'C:\Python24\DLLs' folder. I placed a copy of "tix8184.dll" in the 'C:\Python24\tcl\tix8.1' folder, but I still get the same error. I next tried: >>> os.environ['TIX_LIBRARY'] = 'C:\\Python24\\DLLs' but I still get the same error. Could someone tell me what I am doing incorrectly? Thanks. From usenet-spam-trap at brachttal.net Mon Dec 6 17:41:41 2004 From: usenet-spam-trap at brachttal.net (Andreas Volz) Date: Mon, 6 Dec 2004 23:41:41 +0100 Subject: cut strings and parse for images References: <20041206203456.251c6d85@frodo.mittelerde> Message-ID: <20041206234141.3787521b@frodo.mittelerde> Am Mon, 06 Dec 2004 20:36:36 GMT schrieb Paul McGuire: > Check out the urlparse module (in std distribution). For images, you > can provide a default addressing scheme, so you can expand > "images/marine.jpg" relative to the current location. Ok, this looks good. But I'm a really newbie to python and not able to create a minimum example. Could you please give me a very small example how to use urlparse? Or point me to an example in the web? regards Andreas From peter at engcorp.com Fri Dec 3 06:44:44 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 03 Dec 2004 06:44:44 -0500 Subject: installing 2.4 In-Reply-To: References: Message-ID: Matt Gerrans wrote: > "Peter Hansen" wrote: > >>Only pure Python code can run without change on a newer interpreter. > > Is the interpreter smart enough to rebuild a pyc (if the corresponding py > file is there of course) file that was built by a previous version? Yes. The .pyc files contain a magic cookie that is different in each major version, so 2.4 will recompile your 2.3 .pyc files. .pyc files are not portable between versions, generally, excepting maintenance releases. -Peter From godoy at ieee.org Tue Dec 21 13:14:00 2004 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Tue, 21 Dec 2004 16:14:00 -0200 Subject: how to pass globals across modules (wxPython) References: <87u0qij6qn.fsf@web.de> <1168398.J14ASI0oEJ@strongwill.g2ctech> Message-ID: <4969081.Tc9PZ3E6WB@strongwill.g2ctech> Fredrik Lundh, Ter?a 21 Dezembro 2004 14:02, wrote: > or a single "application context class" instance, which is passed to > various parts of the system as necessary. Wouldn't that cause a chicken & egg problem? How, then, would one pass such an instance across modules? I'm sorry for my ignorance, but I'm a lot more slow than usually today and I might have missed your point :-) Be seeing you, Godoy. From bokr at oz.net Thu Dec 30 05:06:00 2004 From: bokr at oz.net (Bengt Richter) Date: Thu, 30 Dec 2004 10:06:00 GMT Subject: Mutable objects which define __hash__ (was Re: Why are tuples immutable?) References: <20041215152606.1029.1225319887.divmod.quotient.10976@ohm> <10s48r5hbse5o57@corp.supernews.com> <41c350ef.331854992@news.oz.net> <41c9103e.708509723@news.oz.net> <41cd0b3d.969372353@news.oz.net> <41d1a888.1271783127@news.oz.net> <41d33bec.1375051930@news.oz.net> Message-ID: <41d3c336.1409685901@news.oz.net> On Thu, 30 Dec 2004 17:36:57 +1000, Nick Coghlan wrote: >Bengt Richter wrote: >> Essentially syntactic sugar to avoid writing id(obj) ? (and to get a little performance >> improvement if they're written in C). I can't believe this thread came from the >> lack of such sugar ;-) > >The downside of doing it that way is you have no means of getting from the id() >stored as a key back to the associated object. Meaningful iteration (including >listing of contents) becomes impossible. Doing the id() call at the Python level >instead of internally to the interpreter is also relatively expensive. ISTM d[id(obj)] = obj, classifier_func(obj) gets around the iteration problem (IIRC a very similar suggestion was somewhere in thread). But if the id call is a significant portion of the cycle budget, yeah, might want to "pursue" a collections solution ;-) > >> Or, for that matter, (if you are the designer) giving the objects an >> obj.my_classification attribute (or indeed, property, if dynamic) as part >> of their initialization/design? > >The main mutable objects we're talking about here are Python lists. Selecting an and really non-mutated Python lists? >alternate classification schemes using a subclass is the current recommended >approach - this thread is about alternatives to that. I'm getting the impression your meaning of "classification" is less about classifying objects according their interesting features than how to associate the resulting kind-of-thing info with the objects for more efficient access that recalculating. In which case ISTM to be an optimization problem that depends intimately on the particular features of interest in the data, etc. > >I generally work with small enough data sets that I just use lists for >classification (sorting test input data into inputs which worked properly, and >those which failed for various reasons). However, I can understand wanting to >use a better data structure when doing frequent membership testing, *without* >having to make fundamental changes to an application's object model. > The DYFR thing ever lurks ;-) >> Or subclass your graph node so you can do something readable like >> if node.is_leaf: ... >> instead of >> if my_obj_classification[id(node)] == 'leaf': ... >I'd prefer: > if node in leaf_nodes: > ... Which is trivial to code, except for optimization issues, right? ;-) > >Separation of concerns suggests that a class shouldn't need to know about all >the different ways it may be classified. And mutability shouldn't be a barrier >to classification of an object according to its current state. Agreed. I didn't mean to imply otherwise. I did mention possibly memoizing classification functions as an optimization approach ;-) > >>>Hence why I suggested Antoon should consider pursuing collections.identity_dict >>>and collections.identity_set if identity-based lookup would actually address his >>>requirements. Providing these two data types seemed like a nice way to do an end >>>run around the bulk of the 'potentially variable hash' key problem. >> >> I googled for those ;-) I guess pursuing meant implementing ;-) > >Yup. After all, the collections module is about high-performance datatypes for >more specific purposes than the standard builtins. identity_dict and >identity_set seem like natural fits for dealing with annotation and >classification problems where you don't want to modify the class definitions for >the objects being annotated or classified. Well, at least they ought to be comparatively easy to do. > >I don't want the capability enough to pursue it, but Antoon seems reasonably >motivated :) Let's see what happens ;-) Regards, Bengt Richter From fredrik at pythonware.com Mon Dec 6 17:04:17 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 6 Dec 2004 23:04:17 +0100 Subject: Mean, median, and mode References: <3A81C87DC164034AA4E2DDFE11D258E3245339@exchange.hqamor.amorhq.net> <7xoeh7f6gw.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > > > median = lambda x: x.sort() or x[len(x)//2] > > Yucch!! > > median = x.sorted()[len(x)//2] that doesn't do the same thing, and doesn't work on pre-2.4 releases. try again. (learning how "or" and "and" works in Python doesn't hurt, either; "value or value" is a very common idiom in Python code) From km at mrna.tn.nic.in Fri Dec 3 13:45:04 2004 From: km at mrna.tn.nic.in (km) Date: Sat, 4 Dec 2004 00:15:04 +0530 Subject: installer Message-ID: <20041203184504.GA25493@mrna.tn.nic.in> Hi all, does python have a default module installer inbuilt as for perl in windows ? tia , KM From mefjr75 at hotmail.com Sun Dec 26 15:12:57 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 26 Dec 2004 12:12:57 -0800 Subject: Configuration Files In-Reply-To: <1104086141.835176.236000@c13g2000cwb.googlegroups.com> References: <1104086141.835176.236000@c13g2000cwb.googlegroups.com> Message-ID: <1104091977.106872.272260@c13g2000cwb.googlegroups.com> >thanks for the replies, guys! Your welcome, glad I could help. >(Spending time on these newsgroups is giving me more questions that >answers heh ) Thats good as long as it motivates you to learn ;) M.E.Farmer From tchur at optushome.com.au Fri Dec 24 01:19:25 2004 From: tchur at optushome.com.au (Tim Churches) Date: Fri, 24 Dec 2004 17:19:25 +1100 Subject: Koolaid (was Re: Optional Static Typing) Message-ID: <200412240619.iBO6JPYH009424@mail18.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From finite.automaton at gmail.com Fri Dec 3 13:10:24 2004 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 3 Dec 2004 10:10:24 -0800 Subject: Newbie alert ! References: Message-ID: <4b39d922.0412031010.5e2d62e1@posting.google.com> > bou_asia=Button(fen1, text='Asia',\ > command=rings(size=41, offsetX=50,offsetY=22, > coul='yellow')) You're calling the rings function when you create the button. What you really want is for "command" to be a callable object that the button will invoke when it's clicked, e.g.: def mycallback(): print 'click' mybutton = Button(parent, text='a button', command = mycallback) Notice that there are no parentheses after mycallback -- it's not being called, but the function itself is being passed as an argument. In your case, you need to find a way to pass arguments to rings, so you'll have to curry the function. Here's one way to do it: def rings_callback(**keywords): # return an anonymous function that calls rings when invoked. return lambda k=keywords: rings(**k) bou_asia = Button(fen1, text='Asia', command=rings_callback(size=41, offsetX=50,offsetY=22, coul='yellow')) Hope that helps. From peter at somewhere.com Mon Dec 27 16:37:56 2004 From: peter at somewhere.com (Peter Maas) Date: Mon, 27 Dec 2004 22:37:56 +0100 Subject: objects as mutable dictionary keys In-Reply-To: References: <41BE1644.8050906@freemail.gr> Message-ID: <33bdosF3qm2j6U1@individual.net> There was a huge and sometimes heated debate about tuples, lists and dictionaries recently, and the mainstream opinion was that dictionary keys must not be mutable, so lists are not allowed as dictionary keys. BUT: objects are allowed as dictionary keys, aren't they? See the interpreter session below: class x(object): ... pass ... >>> x1 = x() >>> x1.prop = 'a' >>> d = {} >>> d[x1] = 'x1' >>> for i in d.iteritems(): ... if i[0].prop == 'a': ... print i ... (<__main__.x object at 0x011AC330>, 'x1') >>> x1.prop = 'b' >>> for i in d.iteritems(): ... if i[0].prop == 'b': ... print i ... (<__main__.x object at 0x011AC330>, 'x1') This strikes me because if one can do this with instances of user defined classes why not with lists? Trying to use lists as dict keys yields "TypeError: list objects are unhashable". So why are list objects unhashable and user defined objects hashable? For user defined objects hash(x1) = id(x1), why not do the same with lists? I think it's because of the existence of list literals. If you would use id() as a hash function for lists how should d[[1,2,3]] be stored? For instances of user defined classes there is no literal and accordingly no problem to use id() as a hash function and instances as dictionary keys. Is that correct? -- ------------------------------------------------------------------- Peter Maas, M+R Infosysteme, D-52070 Aachen, Tel +49-241-93878-0 E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64') ------------------------------------------------------------------- From craig at postnewspapers.com.au Fri Dec 31 05:45:26 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 31 Dec 2004 18:45:26 +0800 Subject: Speed ain't bad In-Reply-To: References: <0189t05r3226bkp5e1vtmp0gd6odcsf2qp@4ax.com> Message-ID: <1104489925.23788.19.camel@rasputin.localnet> On Fri, 2004-12-31 at 11:17, Jeremy Bowers wrote: > I would point out a couple of other ideas, though you may be aware of > them: Compressing all the files seperately, if they are small, may greatly > reduce the final compression since similarities between the files can not > be exploited. True; however, it's my understanding that compressing individual files also means that in the case of damage to the archive it is possible to recover the files after the damaged file. This cannot be guaranteed when the archive is compressed as a single stream. -- Craig Ringer From ncoghlan at iinet.net.au Thu Dec 23 06:43:37 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 23 Dec 2004 21:43:37 +1000 Subject: deriving from str In-Reply-To: <43ABC325.9030704@yahoo.it> References: <43ABC325.9030704@yahoo.it> Message-ID: <41CAAF69.5040205@iinet.net.au> Paolo Veronelli wrote: > I want to add some methods to str class ,but when I change the __init__ > methods I break into problems > > class Uri(str): > def __init__(self,*inputs): > print inputs > if len(inputs)>1: > str.__init__(self,'<%s:%s>'%inputs[:2]) > else: > str.__init__(self,inputs[0]) > print inputs > a=Uri('ciao','gracco') > > Traceback (most recent call last): > File "prova.py", line 9, in ? > a=Uri('ciao','gracco') > TypeError: str() takes at most 1 argument (2 given) > > > where is the str() wrong call.I suppose It's the __new__ method which > is wrong or me .Thanks for help Strings are immutable, so you need to override __new__ rather than __init__. Py> class Uri(str): ... def __new__(cls, *inputs): ... print inputs ... if len(inputs) > 1: ... self = str.__new__(cls, '<%s:%s>'% inputs[:2]) ... else: ... self = str.__new__(cls, inputs[0]) ... return self ... Py> Uri('ciao', 'gracco') ('ciao', 'gracco') '' Note that the first argument is the class object rather than the new instance. The __new__ method *creates* the instance, and returns it. See here for the gory details of overriding immutable types: http://www.python.org/doc/newstyle.html Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From jepler at unpythonic.net Sat Dec 25 09:20:24 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Sat, 25 Dec 2004 08:20:24 -0600 Subject: Execute code after death of all child processes - (corrected posting) In-Reply-To: <576fb15a.0412250156.325fff8e@posting.google.com> References: <576fb15a.0412250156.325fff8e@posting.google.com> Message-ID: <20041225142022.GA12707@unpythonic.net> First, you'll want to exit from each forked copy, or else it will reach the code-after-the-for-loop: import sys, os, time texts = ['this is text1', 'this is text 2'] for current_text in texts[0:]: pid = os.fork() if pid == 0: time.sleep(2) print current_text raise SystemExit Next, you'll want to wait for each process you started: for current_text in texts: os.waitpid(-1, 0) print 'this is the end' $ python /tmp/franz.py this is text1 this is text 2 this is the end Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From faassen at infrae.com Thu Dec 16 05:58:15 2004 From: faassen at infrae.com (Martijn Faassen) Date: Thu, 16 Dec 2004 10:58:15 GMT Subject: lies about OOP In-Reply-To: References: <1102995205.949964.76020@c13g2000cwb.googlegroups.com> <29Evd.32591$Jk5.26287@lakeread01> <41c026e6$0$78279$e4fe514c@news.xs4all.nl> <_j2wd.97962$lN.16566@amsnews05.chello.com> Message-ID: Peter Hansen wrote: > Martijn Faassen wrote: > >> Peter Hansen wrote: >> >>> Well, in any case, thanks for setting the record straight, Martjin. >> >> That of course also happens to me once every while. I can take care of >> myself though -- Dijkstra however needs an advocate for the correct >> spelling of his name in this earthly realm. > > > Then there's us Danes, with "sen" instead of "son" (as many people > think it ought to be). And I can't even claim the wrong form > sounds noticably different, making any defense seem petty. Obviously -sen is the only real suffix, as it's -sen in Dutch as well, as in Faas-sen. :) > (Darn those Norwegians, influencing people's ideas of how a > name like Hansen ought to be spelled, grumble, grumble. > If they'd just invent a cell phone that used Python, as the > Swedish have, they might deserve all that extra attention.) > > ;-) That's not the Swedes, it's the Finnish that did that. They typically don't like being mistaken for Swedes. :) Regards, Martijn From noamr at remove.the.dot.myrea.lbox.com Fri Dec 31 06:59:45 2004 From: noamr at remove.the.dot.myrea.lbox.com (Noam Raphael) Date: Fri, 31 Dec 2004 13:59:45 +0200 Subject: How about "pure virtual methods"? In-Reply-To: <86zn017miy.fsf@guru.mired.org> References: <10shetjeo2cbpfa@corp.supernews.com> <1gp9wjb.18uqvfi1ibk5wxN%aleaxit@yahoo.com> <86zn017miy.fsf@guru.mired.org> Message-ID: Thanks for your suggestion, but it has several problems which the added class solves: * This is a very long code just to write "you must implement this method". Having a standard way to say that is better. * You can instantiate the base class, which doesn't make sense. * You must use testing to check whether a concrete class which you derived from the base class really implemented all the abstract methods. Testing is a good thing, but it seems to me that when the code specifies exactly what should happen, and it doesn't make sense for it not to happen, there's no point in having a separate test for it. About the possibility of implementing only a subset of the interface: You are perfectly welcomed to implement any part of the interface as you like. Function which use only what you've implemented should work fine with your classes. But you can't claim your classes to be instances of the base class - as I see it, subclasses, even in Python, guarantee to behave like their base classes. Have a good day, Noam From binux.lists at gmail.com Thu Dec 16 03:36:50 2004 From: binux.lists at gmail.com (Binu K S) Date: Thu, 16 Dec 2004 14:06:50 +0530 Subject: temp file name In-Reply-To: <20041217115153.GA7506@mrna.tn.nic.in> References: <20041217115153.GA7506@mrna.tn.nic.in> Message-ID: <2b7d8b42041216003668f897a0@mail.gmail.com> Use the tempfile module instead. It is more secure. Check the documentation for tempfile.NamedTemporaryFile. If you are only looking to get a unique name and want to do the file management yourself, you may have to close the file opened by this function and reopen it. On Fri, 17 Dec 2004 17:21:53 +0530, km wrote: > Hi all, > Is there a way to create a unique file name; safely > i have used os.tmpnam() with python2.4, i warns that the usage is a potential security risk. > tia > KM > > -- > http://mail.python.org/mailman/listinfo/python-list > From martin.drautzburg at web.de Mon Dec 20 02:18:16 2004 From: martin.drautzburg at web.de (Martin Drautzburg) Date: 20 Dec 2004 08:18:16 +0100 Subject: accessing module global vars by name Message-ID: <87pt15jv47.fsf@web.de> Withing a module I can assign a value to a global var by assigning to it in the outermost scope. Fine. But how can I do this if the attribute name itself is kept in a variable. Once the module is loaded I can access the module's namespace no problem, but inside the module the dictionary is not yet present right ? IOW how can I write something like # xxx.py for varName in ("foo", "bar"): magic.varName = 1 so I can later refer to them as # yyy.py import xxx x = xxx.foo y = xxx.bar From ishwor.gurung at gmail.com Sat Dec 25 21:05:56 2004 From: ishwor.gurung at gmail.com (Ishwor) Date: Sun, 26 Dec 2004 12:35:56 +1030 Subject: Clearing the screen In-Reply-To: <34534aed04122518032d564b7c@mail.gmail.com> References: <34534aed041224151134aa4f4@mail.gmail.com> <20041224234701.GA1707@unpythonic.net> <41ce04a4$1@nntp0.pdx.net> <2Lozd.16203$k25.9717@attbi_s53> <34534aed04122518032d564b7c@mail.gmail.com> Message-ID: <34534aed04122518053dc38b37@mail.gmail.com> heres the shell i forgot to show PythonWin 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2004 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> clear.cls() [40 more lines of "\n"] >>> -- cheers, Ishwor Gurung From evenprimes at gmail.com Fri Dec 3 10:45:50 2004 From: evenprimes at gmail.com (Chris Cioffi) Date: Fri, 3 Dec 2004 10:45:50 -0500 Subject: disk based dictionaries In-Reply-To: References: Message-ID: I'd like to second this suggestion. While there are a few things you need to be aware of when writing your code (mostly taken care of in the latest release) it's a mostly trivial code change. (For me it was replacing a few dictionaries with PersistentMap objects and changing the base class of a few objects to Persistant from object. FWIW, I'm using ZODB to help track EDI transactions for a help desk application. Right now my database hovers in the 100MB range with several ten of thousands of objects. I also use it for single object temp storage, so I feel it works well from both the small and mid-size scale. (It probably works fine for large projects as well, I just don't have one right now...) Chris On Thu, 02 Dec 2004 18:53:44 -0600, Larry Bates wrote: > You may also want to take a look at ZODB (Zope database). > It handles the pickling, storage and retrieval of all > Python objects (including dictionaries) very well. And yes > you can use ZODB without using Zope proper. > > http://www.zope.org/Products/StandaloneZODB > > http://zope.org/Members/adytumsolutions/HowToLoveZODB_PartII/HowToLoveZODB_PartI > > http://www.h7.dion.ne.jp/~harm/ZODB-Tutorial.py > > > Larry Bates > > > > > Shivram U wrote: > > Hi, > > > > I want to store dictionaries on disk. I had a look at a few modules > > like bsddb, shelve etc. However would it be possible for me to do the > > following > > > > hash[1] = [1, 2, 3] where the key is an int and not a string > > > > bsddb requires that both the key,value are string. > > shelve does support values being object but not the keys. Is there any > > module which support keys which are not strings > > > > Also how do i use disk based hashes for multidimensional hashes such as > > below > > > > #!/usr/bin/python > > > > dict={} > > dict['key1'] = {} > > dict[('key1')][('key2')] = 'value' > > > > key1=dict['key1'] > > print key1['key2'] > > > > I have read of mxBeeDict but was unable to get it work properly. I am > > not sure if it supports what i need as i was unable to get any > > documentation about it. Is the module used widely ? > > > > Below is how i am using the module > > > > bdict = BeeDict('/tmp/beedict') > > > > bdict[1] = 1 > > print bdict.keys() > > > > bdict.commit() > > bdict.close() > > > > bdict1 = BeeDict('/tmp/beedict') > > print bdict1.keys() > > print bdict1.values() > > > > > > Would it be that using disk based dictionaries once opened are as fast > > as in memory dictionaries ? > > > > Thanks in advance, > > > > Best Regards, > > Shivram U > > > > > > > > > > Confidentiality Notice > > > > The information contained in this electronic message and any attachments to this message are intended > > for the exclusive use of the addressee(s) and may contain confidential or privileged information. If > > you are not the intended recipient, please notify the sender at Wipro or Mailadmin at wipro.com immediately > > and destroy all copies of this message and any attachments. > -- > http://mail.python.org/mailman/listinfo/python-list > -- "It is our responsibilities, not ourselves, that we should take seriously." -- Peter Ustinov From mszpadzik at o2.pl Sun Dec 19 10:27:49 2004 From: mszpadzik at o2.pl (Michal Szpadzik) Date: Sun, 19 Dec 2004 16:27:49 +0100 Subject: Data reading problem Message-ID: <41C59DF5.2040401@o2.pl> I'm a newbie. I have some problems with bits data reading. I have binary data file where data is written as 12bits pack. I need to read it becouse there are saved values which have to processed later by my program. I was wandering about reading 3bytes=24bits and split it by bits moving. If anyone know how to do that please tell me or give me some code. My data example: 101001000101111010100101 etc i need to split it: x=101001000101 y=111010100101 and then do: mydata=x*a+b where a and b are a float point numbers mydata2=y*a+b Sorry for my poor english. I wish You understand what I mean. THX for any answer. -- Mike Szpadzik From lbates at syscononline.com Tue Dec 14 12:47:46 2004 From: lbates at syscononline.com (Larry Bates) Date: Tue, 14 Dec 2004 11:47:46 -0600 Subject: Emailing in Python In-Reply-To: References: Message-ID: Great class for making this very easy located here: http://motion.sourceforge.net/related/send_jpg.py And is supports list of binary attachments that is pretty tricky by hand. Larry Bates Syscon, Inc. Philippe Reynolds wrote: > Hi, > > I'm learning python...one of my tasks is to send out emails... > I can send emails to one person at a time but not as groups.... > > Do you think you can help. > > Cheers > Philippe Reynolds > > Here is the section of code: > # me == the sender's email address > me = 'phil_ren at hotmail.com' > # you == the recipient's email address > > email_list= 'preyn085 at uottawa.ca, phil_ren at hotmail.com' > > msg['Subject'] = 'EVENT REPORT' > msg['From'] = me > msg['To'] = email_list > > # Send the message via our own SMTP server, but don't include the > # envelope header. > s = smtplib.SMTP() > s.connect() > s.sendmail(me, [email_list], msg.as_string()) > s.close() > > From programmer.py at gmail.com Tue Dec 21 00:28:28 2004 From: programmer.py at gmail.com (Jaime Wyant) Date: Mon, 20 Dec 2004 23:28:28 -0600 Subject: Should I always call PyErr_Clear() when an exception occurs? Message-ID: I've found that the code below will crash if I don't have the PyErr_Clear() function call. Should I always call PyErr_Clear()? The error message I get has to do with garbage collection --> Exception exceptions.ImportError: 'No module named badmodule' in 'garbage collec tion' ignored Fatal Python error: unexpected exception during garbage collection /* Code that fails if PyErr_Clear() is removed */ #include "python.h" int main() { PyObject *pName, *pModule; int i; Py_Initialize(); for (i = 0 ; i < 30; i++) { // First, import the module pName = PyString_FromString("badmodule"); pModule = PyImport_Import(pName); Py_DECREF(pName); if (!pModule) { fprintf(stderr, "couldn't import badmodule\n"); PyErr_Clear(); } } Py_Finalize(); } /* End code */ Thanks, jw From mmcgarry at nospam.org Sun Dec 12 19:56:43 2004 From: mmcgarry at nospam.org (Michael McGarry) Date: Sun, 12 Dec 2004 17:56:43 -0700 Subject: Best book on Python? In-Reply-To: References: Message-ID: Adil Hasan wrote: > hello, > Just my 2 farthings worth... > Although Python and Tkinter is a good book it was written at the time of > Python 1.5 (so there may be some transformation that needs to be done > on some of the examples) you may want to take a look at Python in > a Nutshell by A. Martelli published by O'Reilly. It has a section on > Tkinter and many other things that you may find useful. > ah > > On Mon, 13 Dec 2004, Rod Haper wrote: > > >>Michael McGarry wrote: >> >>>I have many years of programming experience and know a little bit of >>>Tcl. I am looking for a book to detail on the features including GUI in >>>a reference style. >> >>Given that you have some acquaintance with Tcl, if you want a reference >>that caters toward GUI programming in Python using Tk, you might find >>this book of interest: "Python and Tkinter Programming" by John Grayson. >> Manning Publications, 2000, 658p >> >>-- >>Rod >>-- >>http://mail.python.org/mailman/listinfo/python-list >> > > Thanks, in terms of GUI programming I am leaning towards Qt, since I can use this stuff in C++ as well. There is also a program called Qt designer that makes GUI design a drag and drop process. Michael From jeremy+plusnews at jeremysanders.net Thu Dec 9 09:39:56 2004 From: jeremy+plusnews at jeremysanders.net (Jeremy Sanders) Date: Thu, 09 Dec 2004 14:39:56 +0000 Subject: High level SNMP References: Message-ID: On Thu, 09 Dec 2004 15:34:14 +0200, Petri Laakso wrote: >> have you tested twistedsnmp? > http://twistedsnmp.sourceforge.net/ I looked at it, but it needs Twisted compiled and installed, which is a pain. The old versions of PySNMP (version 2.XX), seem to be a lot simpler to use than later ones, so I might do that. That's if I can work out how to convert the random string it produces to a floating point number. Somehow it manages to gain 3 bytes over a float... Jeremy From faltet at carabos.com Sat Dec 4 06:09:07 2004 From: faltet at carabos.com (Francesc Altet) Date: Sat, 4 Dec 2004 12:09:07 +0100 Subject: ANN: PyTables 0.9.1 is out Message-ID: <200412041209.07177.faltet@carabos.com> Announcing PyTables 0.9.1 ------------------------- This release is mainly a maintenance version. In it, some bugs has been fixed and a few improvements has been made. One important thing is that chunk sizes in EArrays has been re-tuned to get much better performance and compression rations. Besides, it has been tested against the latest Python 2.4 and all test units seems to pass fine. What it is ---------- PyTables is a solid hierarchical database package designed to efficiently manage extremely large amounts of data (with support for full 64-bit file addressing). It features an object-oriented interface that, combined with C extensions for the performance-critical parts of the code, makes it a very easy-to-use tool for high performance data storage and retrieval. It is built on top of the HDF5 library and the numarray package, and provides containers for both heterogeneous data (Tables) and homogeneous data (Array, EArray) as well as containers for keeping lists of objects of variable length (like Unicode strings or general Python objects) in a very efficient way (VLArray). It also sports a series of filters allowing you to compress your data on-the-fly by using different compressors and compression enablers. But perhaps the more interesting features are its powerful browsing and searching capabilities that allow you to perform data selections over heterogeneous datasets exceeding gigabytes of data in just tenths of second. Besides, all the PyTables I/O is buffered, implemented in C and carefully tuned so that you can reach much better performance with PyTables than with your own home-grown wrappings to the HDF5 library. Changes more in depth --------------------- Improvements: - The chunksize computation for EArrays has been re-tuned to allow better performance and *much* better compression rations. - New --unpackshort and --quantize flags has been added to nctoh5 script. --unpackshort unpack short integer variables to float variables using scale_factor and add_offset netCDF variable attributes. --quantize quantize data to improve compression using least_significant_digit netCDF variable attribute (not active by default). See http://www.cdc.noaa.gov/cdc/conventions/cdc_netcdf_standard.shtml for further explanation of what this attribute means. Thanks to Jeff Whitaker for providing this. - Table.itersequence has received a new parameter called "sort". This allows to disable the sorting of the sequence in case the user wants so. Backward-incompatible changes: - Now, the AttributeSet class throw an AttributeError on __getattr__ for nonexistent attributes in it. Formerly, the routine returned None, which is pretty much against convention in Python and breaks the built-in hasattr() function. Thanks to Norbert Nemec for noting this and offering a patch. - VLArray.read() has changed its behaviour. Now, it always returns a list, as stated in documentation, even when the number of elements to return is 0 or 1. This is much more consistent when representing the actual number of elements on a certain VLArray row. API additions: - A Row.getTable() has been added. It is an accessor for the associated Table object. - A File.copyAttrs() has been added. It allows copying attributes from one leaf to other. Properly speaking, this was already there, but not documented :-/ Bug fixes: - Now, the copy of hierarchies works even when there are scalar Arrays (i.e. Arrays which shape is ()) on it. Thanks to Norbert Nemec for providing a patch. - Solved a memory leak regarding the Filters instance associated with the File object, that was not released after closing the file. Now, there are no known leaks on PyTables itself. - Fixed a bug in Table.append() when the table was indexed. The problem was that if table was in auto-indexing mode, some rows were lost in the indexation process and hence, not indexed correctly. - Improved security of nodes name checking. Closes #1074335 Important note for Python 2.4 and Windows users ----------------------------------------------- If you are willing to use PyTables with Python 2.4 in Windows platforms, you will need to get the HDF5 library compiled for MSVC 7.1, aka .NET (and possible LZO and UCL as well, if you want support for LZO and UCL at all). It can be found at: ftp://ftp.ncsa.uiuc.edu/HDF/HDF5/current/bin/windows/5-163-winxp-net2003.zip Where can PyTables be applied? ------------------------------ PyTables is not designed to work as a relational database competitor, but rather as a teammate. If you want to work with large datasets of multidimensional data (for example, for multidimensional analysis), or just provide a categorized structure for some portions of your cluttered RDBS, then give PyTables a try. It works well for storing data from data acquisition systems (DAS), simulation software, network data monitoring systems (for example, traffic measurements of IP packets on routers), very large XML files, or for creating a centralized repository for system logs, to name only a few possible uses. What is a table? ---------------- A table is defined as a collection of records whose values are stored in fixed-length fields. All records have the same structure and all values in each field have the same data type. The terms "fixed-length" and "strict data types" seem to be quite a strange requirement for a language like Python that supports dynamic data types, but they serve a useful function if the goal is to save very large quantities of data (such as is generated by many scientific applications, for example) in an efficient manner that reduces demand on CPU time and I/O resources. What is HDF5? ------------- For those people who know nothing about HDF5, it is a general purpose library and file format for storing scientific data made at NCSA. HDF5 can store two primary objects: datasets and groups. A dataset is essentially a multidimensional array of data elements, and a group is a structure for organizing objects in an HDF5 file. Using these two basic constructs, one can create and store almost any kind of scientific data structure, such as images, arrays of vectors, and structured and unstructured grids. You can also mix and match them in HDF5 files according to your needs. Platforms --------- I'm using Linux (Intel 32-bit) as the main development platform, but PyTables should be easy to compile/install on many other UNIX machines. This package has also passed all the tests on a UltraSparc platform with Solaris 7 and Solaris 8. It also compiles and passes all the tests on a SGI Origin2000 with MIPS R12000 processors, with the MIPSPro compiler and running IRIX 6.5. It also runs fine on Linux 64-bit platforms, like AMD Opteron running GNU/Linux 2.4.21 Server, Intel Itanium (IA64) running GNU/Linux 2.4.21 or PowerPC G5 with Linux 2.6.x in 64bit mode. It has also been tested in MacOSX platforms (10.2 but should also work on newer versions). Regarding Windows platforms, PyTables has been tested with Windows 2000 and Windows XP (using the Microsoft Visual C compiler), but it should also work with other flavors as well. Web site -------- Go to the PyTables web site for more details: http://pytables.sourceforge.net/ To know more about the company behind the PyTables development, see: http://www.carabos.com/ Share your experience --------------------- Let me know of any bugs, suggestions, gripes, kudos, etc. you may have. Enjoy data! -- Francesc Altet Who's your data daddy? ?PyTables From firstname.lastname at iki.fi-spam Fri Dec 31 16:56:09 2004 From: firstname.lastname at iki.fi-spam (Simo Melenius) Date: 31 Dec 2004 23:56:09 +0200 Subject: Securing a future for anonymous functions in Python References: <10t84q9icqjnie7@news.supernews.com> Message-ID: Ian Bicking writes: > But I do think there's other ways to approach this. Function > expressions could get really out of hand, IMHO, and could easily lead > to twenty-line "expressions". That's aesthetically incompatible with > Python source, IMHO. You can already write unaesthetic hundred-line Python functions, if you want to. Python's syntax doesn't yet impose a restriction on the number of sequential statements :-) It sounds artificial to impose such restrictions on these hypothetical "inline blocks", even if by only allowing them to be plain expressions. IMHO, the most pythonic way to write an "inline-block" is by reusing existing keywords, using Python-like start-of-blocks and ending it by indentation rules: map (def x: if foo (x): return baz_1 (x) elif bar (x): return baz_2 (x) else: global hab hab.append (x) return baz_3 (hab), [1,2,3,4,5,6]) and for one-liners: map (def x: return x**2, [1,2,3,4,5,6]) As a side-effect, we also - got rid of the "lambda" keyword; - strenghtened the semantics of "def": a "def" already defines a function so it's only logical to use it to define anonymous functions, too; - unified the semantics: function is always a function, and functions return values by using "return". When learning Python, I learned the hard way that "lambda"s are expressions, not functions. I'd pay the burden of writing "return" more often in exchange for better consistency. my two cents, br, S From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Tue Dec 21 04:43:17 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Tue, 21 Dec 2004 09:43:17 +0000 Subject: Boo who? (was Re: newbie question) In-Reply-To: References: <1103503985.015510.24680@z14g2000cwz.googlegroups.com><1103579296.951417.320000@c13g2000cwb.googlegroups.com> Message-ID: Erik Max Francis wrote: > How bizarre is it that they're trying to "sell" Spry by indicating it > uses the "very best" features of Prothon, given that Prothon was a > failed project? And Python uses the very best features of ABC. What's your point? ;-) Not that I've ever even used Prothon, although I thought the way the implementor dropped it into conversation was non-obnoxious. There could be a valuable lesson here. -- Michael Hoffman From steven.bethard at gmail.com Sat Dec 25 12:30:46 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 25 Dec 2004 17:30:46 GMT Subject: Keyword arguments - strange behaviour? In-Reply-To: <1103842710.927642.265090@c13g2000cwb.googlegroups.com> References: <1103622331.247762.161750@f14g2000cwb.googlegroups.com> <1103637176.450940.243500@c13g2000cwb.googlegroups.com> <1103802539.705471.122640@f14g2000cwb.googlegroups.com> <1103816686.956825.226880@z14g2000cwz.googlegroups.com> <7gCyd.245287$V41.152597@attbi_s52> <1103842710.927642.265090@c13g2000cwb.googlegroups.com> Message-ID: <9thzd.631929$D%.175524@attbi_s51> Fuzzyman wrote: > It wasn't that part of the example that I thought was over complex. > (although it's not a 'pattern' I use often). You suggested that if we > had dynamic evaluation of default values, you would have to replace it > with : > >>>>>class foo(object): >>>>> matcher=re.compile(r'...') >>>>> def __new__(self, bar, baz, matcher=None): >>>>> if matcher is None: >>>>> matcher = self.matcher >>>>> ... >>>>> text = matcher.sub(r'...', text) >>>>> ... > > > Now that I thought was over complex... when all you wanted to do was > put a constant into your default value ! Ahh. Yeah, the thing above is a bit complex, but it keeps the same namespaces -- matcher is only available to foo, not the enclosing class/module. Point taken of course. ;) Steve From sjmachin at lexicon.net Sat Dec 11 16:09:32 2004 From: sjmachin at lexicon.net (John Machin) Date: 11 Dec 2004 13:09:32 -0800 Subject: newbie questions In-Reply-To: References: <41ba6511$1@nntp.zianet.com> Message-ID: <1102799372.430347.308070@c13g2000cwb.googlegroups.com> Steven Bethard wrote: > > Of course, in this simple case, I wouldn't be likely to write the clear > function since the inline code is simpler and has less overhead: > > def main() > var1 = [] > var1.append('a') > var1[:] = [] Even less overhead: del var1[:] From ian at kirbyfooty.com Tue Dec 21 00:07:31 2004 From: ian at kirbyfooty.com (ian at kirbyfooty.com) Date: 20 Dec 2004 21:07:31 -0800 Subject: Python To Send Emails Via Outlook Express In-Reply-To: References: <1103519604.987664.117400@c13g2000cwb.googlegroups.com> <1103521500.427846.238790@c13g2000cwb.googlegroups.com> <41C67E3D.5040205@kdart.com> <1103528498.945675.43920@z14g2000cwz.googlegroups.com> <1103529746.281597.103710@c13g2000cwb.googlegroups.com> <41C6C9F8.7040400@holdenweb.com> <1103548626.745378.220020@c13g2000cwb.googlegroups.com> <41c6d6b7$0$258$edfadb0f@dread12.news.tele.dk> <1103557302.427109.298550@f14g2000cwb.googlegroups.com> Message-ID: <1103605651.147535.226590@z14g2000cwz.googlegroups.com> Hi Ganesan, I'm on the verge of giving up I don't suppose you could write a small script to send the email for me via the default windows email client. I will then try running your script and my end to see if it works ok. I may have missed something and would really appreciate your help. Thanks in advance Ian From rkern at ucsd.edu Fri Dec 10 09:02:07 2004 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 10 Dec 2004 06:02:07 -0800 Subject: collaborative editing In-Reply-To: <4edc17eb.0412100520.41c5ba39@posting.google.com> References: <4edc17eb.0412100520.41c5ba39@posting.google.com> Message-ID: Michele Simionato wrote: > Suppose I want to write a book with many authors via the Web. The book has > a hierarchical structure with chapter, sections, subsections, subsubsections, > etc. At each moment it must be possible to print the current version of the > book in PDF format. There must be automatic generation of the table of contents, > indices, etc. Conversions to many formats (Latex, DocBook, etc.) would be > welcome. Does something like that already exists? Alternatively, I would need > some hierarchical Wiki with the ability of printing its contents in an > structured way. Does it have to be via the Web? Why doesn't LaTeX/DocBook with a central CVS/Subversion repository work for what you want to do? Personally, I loathe writing at any length inside a Web browser and prefer to use a real editor at all times. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From justinstraube at charter.net Thu Dec 2 18:48:00 2004 From: justinstraube at charter.net (Justin Straube) Date: Thu, 02 Dec 2004 15:48:00 -0800 Subject: pickle and py2exe References: Message-ID: <35otq0hc4rrb6qb0fef485c562csvtc39s@4ax.com> On 1 Dec 2004 11:45:59 -0800, johan at pulp.se (Johan Lindberg) wrote: >Have you included string-escape encoding in your setup.py? >My guess is that you can fix the problem with something similar to: > > from distutils.core import setup > import py2exe > opts = { "py2exe": { "packages": ["encodings"], } } > setup(windows= ["spam.py"], options= opts) > >in your setup.py. > >Hope it helps >/Johan Lindberg Thanks Johan, but unfortunately the same traceback is given in the log. I should have mentioned in my previous post that Im using win2000, if it matters any. Thanks, Justin >> Im trying to compile a script with py2exe. The pickle module is causing the >> program to give an error. >> >> Traceback (most recent call last): >> File "SETIstat.pyw", line 330, in ? >> File "SETIstat.pyw", line 84, in start_up >> File "SETIstat.pyw", line 79, in config_load >> File "pickle.pyc", line 1390, in load >> File "pickle.pyc", line 872, in load >> File "pickle.pyc", line 985, in load_string >> LookupError: unknown encoding: string-escape >> >> the data in the pickled file is a dictionary containing a couple strings. The >> strings do contain \n and \t charaters but no other special characters or >> anything. >> >> Does anyone have any suggestions to what I can try to get around this? The >> pickle module works fine when the .pyw file is run. Its only when I compile >> this is there an issue. >> >> Thanks for any help, >> >> Justin > From grante at visi.com Fri Dec 3 14:17:53 2004 From: grante at visi.com (Grant Edwards) Date: 03 Dec 2004 19:17:53 GMT Subject: Need help on program!!! References: <41b0b87c$0$250$edfadb0f@dread12.news.tele.dk> Message-ID: <41b0bbe1$0$85096$a1866201@visi.com> On 2004-12-03, Max M wrote: >> That was also my impression. Even the description of the >> problem looks like it's just copied from the assignment, so >> probably didn't even take the time to restate the problem in >> his own words. [...] > Hopefully his teacher doesn't know about Google, or he can be > expelled from school for using it. And there's always the chance the somebody intentionally posted a wrong answer just to teach somebody a lesson. I'm not accusing Max of this, but I've seen it done in the past. -- Grant Edwards grante Yow! Yow! I like my new at DENTIST... visi.com From oritg at amdocs.com Thu Dec 2 02:53:00 2004 From: oritg at amdocs.com (Irit) Date: Thu, 02 Dec 2004 02:53:00 -0500 Subject: Pythons Mcmillan Installer : cannot load shared lib References: Message-ID: <9081391634e844bbaefea51a643dfcb1@localhost.talkaboutprogramming.com> Hi I have the same problem Have you found out what is the reason for this error message, and how it can be solved ? From peter at engcorp.com Mon Dec 27 12:04:12 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 27 Dec 2004 12:04:12 -0500 Subject: where is ctypes.py? In-Reply-To: <1104055174.719604.287630@c13g2000cwb.googlegroups.com> References: <1104055174.719604.287630@c13g2000cwb.googlegroups.com> Message-ID: wccppp at yahoo.com wrote: > I'm a complete newbie in learning python. > > I was testing some sample codes I found in this newsgroup and seems it > could not locate the module ctypes.py. I installed python 2.4, wxPython > and pywin32. Just could not find this file. I thought it should be in > Lib/site-packages/ directory but it is not there. > Where can I find this file? I see others have pointed you to the module, but nobody has yet told you how you could have found it yourself. "ctypes" and many other such modules are third-party packages which do not come with Python itself. In almost all cases, you should be able to use Google quite easily to find such a module by typing "python ctypes" (or substitute the appropriate name in place of ctypes) in a Google search. Quite often the home page of the package (where you'll find instructions on downloading) will be the first result Google provides. -Peter From Michael.J.Fromberger at Clothing.Dartmouth.EDU Fri Dec 3 14:12:48 2004 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Fri, 03 Dec 2004 14:12:48 -0500 Subject: Replace string except inside quotes? References: <3064b51d.0412030739.2c301449@posting.google.com> Message-ID: In article <3064b51d.0412030739.2c301449 at posting.google.com>, beliavsky at aol.com wrote: > The code > > for text in open("file.txt","r"): > print text.replace("foo","bar")[:-1] > > replaces 'foo' with 'bar' in a file, but how do I avoid changing text > inside single or double quotes? For making changes to Python code, I > would also like to avoid changing text in comments, either the '#' or > '""" ... """' kind. The first part of what you describe isn't too bad, here's some code that seems to do what you want: import re def replace_unquoted(text, src, dst, quote = '"'): r = re.compile(r'%s([^\\%s]|\\[\\%s])*%s' % (quote, quote, quote, quote)) out = '' ; last_pos = 0 for m in r.finditer(text): out += text[last_pos:m.start()].replace(src, dst) out += m.group() last_pos = m.end() return out + text[last_pos:].replace(src, dst) Example usage: print replace_unquoted(file('foo.txt', 'r').read(), "foo", "bar") It's not the most elegant solution in the world. This code does NOT deal with the problem of commented text. I think it will handle triple quotes, though I haven't tested it on that case. At any rate, I hope it may help you get started. Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From fredrik at pythonware.com Sun Dec 19 14:49:02 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Dec 2004 20:49:02 +0100 Subject: How about "pure virtual methods"? References: Message-ID: ... From: Doug ... (I think you could create some kind of drinking game based on the number of non-quoted lines between the "From"-line and the first line containing the word "boo" in Doug's posts on comp.lang.python. A little like the game based on the number of minutes between someone mentioning ElementTree or Anobind or some other Python/XML toolkit in a blog post, and David Mertz adding a comment about how his own tool can do the same thing faster and better...) ... boo ... () From fredrik at pythonware.com Mon Dec 20 16:33:15 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Dec 2004 22:33:15 +0100 Subject: Oddity in 2.4 with eval('None') References: <32opprF3pgrieU1@individual.net> <32oss0F3kedr2U1@individual.net> Message-ID: Leif K-Brooks wrote >> Yes. "print eval('None')" is printing the value of None as defined in your module's global >> namespace: > > Right, but why? The expression "None" doesn't worry about the global namespace when used in normal > code; why does it when used in eval()ed code? from what I can tell, the mapping of the None symbol to a constant is done in the peephole optimizer, which doesn't seem to be used when compiling expressions. in 2.4: >>> dis.dis(compile("None", "", "exec")) 1 0 LOAD_CONST 0 (None) 3 POP_TOP ... >>> dis.dis(compile("None", "", "eval")) 0 0 LOAD_NAME 0 (None) 3 RETURN_VALUE in 2.3: >>> dis.dis(compile("None", "", "exec")) 1 0 LOAD_NAME 0 (None) 3 POP_TOP ... >>> dis.dis(compile("None", "", "eval")) 0 0 LOAD_NAME 0 (None) 3 RETURN_VALUE From ebolonev at mail.ru Wed Dec 1 22:10:25 2004 From: ebolonev at mail.ru (Egor Bolonev) Date: Thu, 02 Dec 2004 13:10:25 +1000 Subject: [PIL] import error Message-ID: import image gives Traceback (most recent call last): File "image1.py", line 7, in ? import image ImportError: No module named image i've installed python 2.3.4 and PIL for python 2.3 From no at spam.please Wed Dec 22 16:42:15 2004 From: no at spam.please (Doug Holton) Date: Wed, 22 Dec 2004 15:42:15 -0600 Subject: [Re: newbie question] In-Reply-To: References: <3e8ca5c804122020157b89fb9b@mail.gmail.com> <1103637612.657658.67350@f14g2000cwb.googlegroups.com> <32tm7qF3gha75U1@individual.net> Message-ID: Ed Leafe wrote: > You've missed the obvious: it's 'criticism' or 'observation' when it > comes from Doug, but it's a 'flame' when it is directed at Doug. > > Unless there is something more substantial then whining, howzabout > we all just ignore it and let it die a quick death? It's amazing how many of you guys try this - spew some filth and then beg people to stop the thread right now. Speaking of Ed Leafe: " You might want to check out Dabo, an application framework of which I am one of the authors." What are you selling? "We offer one-on-one live phone, chat, or on-site support at an hourly rate, with a minimum charge of one hour plus phone charges or travel costs. Contact the authors (Ed Leafe and Paul McNett) for more information." From peter at engcorp.com Tue Dec 7 20:42:30 2004 From: peter at engcorp.com (Peter Hansen) Date: Tue, 07 Dec 2004 20:42:30 -0500 Subject: PIL for Windows for Python 2.4 In-Reply-To: References: Message-ID: Scott F wrote: > As there is no build for Python 2.4, I attempted to put it together > from source. Running > > setup.py build > > gives this error: > > Traceback (most recent call last): > File "C:\tmp\PIL\Imaging-1.1.4\setup.py", line 60, in ? > for line in open(os.path.join("libImaging", > "ImConfig.h")).readlines(): > IOError: [Errno 2] No such file or directory: 'libImaging\\ImConfig.h' > > Appears to be putting in two backslashes. Actually, you're just seeing the repr() of the filename. You really are missing that file in the place where it's looking. Note the similarity in the last two errors here: >>> open('test/this') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'test/this' >>> open('test\\this') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'test\\this' >>> open(r'test\this') Traceback (most recent call last): File "", line 1, in ? IOError: [Errno 2] No such file or directory: 'test\\this' -Peter From eviltofu at gmail.com Sun Dec 5 19:03:51 2004 From: eviltofu at gmail.com (Jerome Chan) Date: 5 Dec 2004 16:03:51 -0800 Subject: PajamaScript Message-ID: I wrote something called PajamaScript. Basically, it parses a text file and looks for tags. Then it calls python to handle the scripting. Why learn another language when you already know Python? This is fun! The Date is .
The Time is .

PajamaScript then calls the function "zdate" in module "misc" and the output replaces the tag. This is not really tested in any production system, just a proof of concept I did for a project that never materialized. In order to access cgi variables, you can use the cgi module or any other python module! Would this be useful to anyone? From mep_ at 163.com Tue Dec 7 01:45:26 2004 From: mep_ at 163.com (mep) Date: Tue, 7 Dec 2004 14:45:26 +0800 Subject: Python in debug version? Message-ID: <31l1tvF3dad3pU1@individual.net> Hi, all I view my python 2.3.4 from python.org by VC6's dependency walker tool. What suprise me is that python.exe and python32.dll are built into *DEBUG* version. Is it intend to do so?Is a release version faster? -- Best Regards, Wang Kebo http://www.huihoo.org/~mep From axel at straschil.com Thu Dec 16 02:30:18 2004 From: axel at straschil.com (Axel Straschil) Date: Thu, 16 Dec 2004 08:30:18 +0100 (CET) Subject: Html or Pdf to Rtf (Linux) with Python In-Reply-To: References: <20041214122121.CFC4B1E4006@bag.python.org> Message-ID: Hallo! > However, our company's product, PDFTextStream does do a phenomenal job of > extracting text and metadata out of PDF documents. It's crazy-fast, has a > clean API, and in general gets the job done very nicely. It presents two > points of compromise from your idea situation: > 1. It only produces text, so you would have to take the text it provides and > write it out as an RTF yourself (there are tons of packages and tools that do > this). Since the RTF format has pretty weak formatting capabilities compared I've got the Input Source in HTML, the Problem ist converting from any to RTF. Please give me a hint where the tons of packages are. Thanks, AXEL. -- The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119 [http://ietf.org/rfc/rfc2119.txt] From eppstein at ics.uci.edu Wed Dec 8 14:13:27 2004 From: eppstein at ics.uci.edu (David Eppstein) Date: Wed, 08 Dec 2004 11:13:27 -0800 Subject: guarding for StopIteration (WAS: Help with generators outside of loops.) References: <62ztd.532216$D%.125153@attbi_s51> Message-ID: In article <62ztd.532216$D%.125153 at attbi_s51>, Steven Bethard wrote: > David Eppstein wrote: > > I've made it a policy in my own code to always surround explicit calls > > to next() with try ... except StopIteration ... guards. > > > > Otherwise if you don't guard the call and you get an unexpected > > exception from the next(), within a call chain that includes a for-loop > > over another generator, then that other for-loop will terminate without > > any error messages and the cause of its termination can be very > > difficult to track down. > > Just to clarify here, the only time code raising a StopIteration will > cause a for-loop to exit silently is if the StopIteration is raised in > an __iter__ method, e.g.: Sure. But in the situation I was attempting to describe, the __iter__ method calls the code of the outer generator, which (perhaps nested several levels deep) may call an inner generator. In this case, the inner generator's StopIteration can terminate the outer loop. -- David Eppstein Computer Science Dept., Univ. of California, Irvine http://www.ics.uci.edu/~eppstein/ From craig at postnewspapers.com.au Tue Dec 21 22:44:54 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Wed, 22 Dec 2004 11:44:54 +0800 Subject: Printing In-Reply-To: <001201c4e7d2$144f8280$0200a8c0@fiftynine> References: <001201c4e7d2$144f8280$0200a8c0@fiftynine> Message-ID: <1103687094.12325.27.camel@bucket.localnet> On Wed, 2004-12-22 at 10:58, Jim & Joanne Collins wrote: > I'm not using any widget or any graphics. I've done programs in Basic for > years and they have all been strict data handling. I want to convert some > to Python > as Windows XP doesn't like 16 bit Basic. Ah, I see. I thought you were using something like VB, because now when many people say BASIC without further qualification they seem to mean VB. > If I have a line in basic that says "print "This is a test print"" how do I > direct that line to the printer instead of the console? And to send an escape > sequence with it for printer control in PCL what is the syntax/format required? I don't have a windows box to test with - well, our NT4 server, but it doesn't have anything on the serial ports. I would think that one just: printerport = open("lpt1","w") but on my NT box that results in a file not found exception. lpt0 opens, but I have no idea if it works. I did a quick google search and turned up little, but I'm sure this has been asked before so you might want to try a google groups search, etc. As for PCL commands - they're just part of the text stream, nothing interesting or special about them at all. You just need to know how to express them as Python string literals. Untested: The sequence &d0D (begin underline) from my HP4MV manual might be expressed as: '\x1b&d0D' or '\x1b&d%iD' % 0 The %i substitutes in the argument specified after the string. Good for escapes that can take many values. The \x1b is the escape sequence for the 'escape' character, same as the ^[ code some MS-DOS editors use. In most UNIX-like string escapes \e works too, but Python doesn't appear to accept that. IMO if you're doing much more than trivial formatting its much easier to use PDF. I was lucky enough never to have to fight printers that viewed output in terms of lines and columns, and I don't plan to start now ;-) > How does one use the operating system after importing it? Syntax and > commands? help(os) and see the Python documentation. Also note that 'import os' doesn't import the operating system - it imports a Python module that provides you with access to some operating system functionality. > What is the syntax for using COM? I'm afraid I have no idea - I don't use windows. The names win32all and ctypes come up a lot here. You might want to check out the archives, ctypes docs, ActivePython docs on win32all if any, etc. Someone who uses COM on windows might want to give him a quick summary. > In basic I write "shell"dir c:\temp\*.*>files.tem" and it does the same as > a dir command > at a DOS prompt and stores it in "files.tem" for me to access later. You don't generally need to use temporary files like that in Python. help(os.listdir) . I strongly recommend you read the Python tutorial if you haven't already, and have a browse over the documentation for some of the key modules like os and sys. Google and Google Groups are also often very helpful - you can use Google Groups to search comp.lang.python (this list/newsgroup). -- Craig Ringer From fumanchu at amor.org Mon Dec 20 12:40:10 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 20 Dec 2004 09:40:10 -0800 Subject: type method-wrapper? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398082@exchange.hqamor.amorhq.net> Thomas Guettler wrote: > Hi, > l=[] > print type(l.__delattr__) > # --> > > I didn't find a corresponding type in the modules "types". > Is it missing or am I blind? You're not blind. Have a look at Objects\decrobject.c in CVS. http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Objects/des crobject.c?rev=2.38&view=auto Relevant bits: /* --- Wrapper object for "slot" methods --- */ [snip] static PyTypeObject wrappertype = { PyObject_HEAD_INIT(&PyType_Type) 0, /* ob_size */ "method-wrapper", /* tp_name */ Robert Brewer MIS Amor Ministries fumanchu at amor.org From claird at lairds.us Tue Dec 28 11:08:39 2004 From: claird at lairds.us (Cameron Laird) Date: Tue, 28 Dec 2004 16:08:39 GMT Subject: Tkinter vs wxPython References: Message-ID: In article , Alejandro Weinstein wrote: . . . >the standard GUI for Python. I read some tutorials, but didn't go to >far, and didn't like the Tkinter looks too much. Then I tried . . . >IMO, wxPython has a softert learning curve (specially if you use >wxGlade), is portable between unix/windows/mac, with the advantage >over Tkinter that it has a native look. Regarding documentation, . . . While people seem to mean a range of different things when they write, "Tkinter doesn't look 'native'", most of them are being addressed in revisions currently underway. In fact, new look- and-feel are available in early releases for those interested in experimentation. From fred at adventistcare.org Fri Dec 24 12:47:26 2004 From: fred at adventistcare.org (Sells, Fred) Date: Fri, 24 Dec 2004 12:47:26 -0500 Subject: gridbaglayout Message-ID: <777056A4A8F1D21180EF0008C7DF75EE03317226@sunbelt.org> gridbag is a pain. google for tablelayout which is easier (to me) -----Original Message----- From: Diez B. Roggisch [mailto:deetsNOSPAM at web.de] Sent: Monday, December 20, 2004 1:17 PM To: python-list at python.org Subject: Re: gridbaglayout python473 at yahoo.com wrote: > Friends - I have tried to do abolute positioning using gridbaglayout, > but am having no success in jython. One book I have been referencing > says that it only works with JPanels. Could someone post a snippet of > code that works for a button? I am so close so just a hint would help. Google for java-examples and translat to jython. Ist straight forward. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list From biner.sebastien at ouranos.ca Tue Dec 7 14:30:37 2004 From: biner.sebastien at ouranos.ca (biner.sebastien at ouranos.ca) Date: 7 Dec 2004 11:30:37 -0800 Subject: finding byte order References: <41b0b4ab$1@nntp0.pdx.net> <41b0c9e3$1@nntp0.pdx.net> Message-ID: <1102447837.783733.34080@z14g2000cwz.googlegroups.com> Scott David Daniels wrote: > biner wrote: > > I am using a program that has to read binary data from files coming > > from different machines. The file are always written with big endian. > > Diez B. Roggisch wrote: > [Scott David Daniels wrote] > >>How about sys.byteorder? > > This doesn't help, as he wants to read files from varying endianess - what > > the _current_ endianess is doesn't matter here. > > But, in fact, he says the files are always big endian. So, code like > the following should address his problem. Note I use type 'h' as an > example so I can easily read samples. > > import sys, array > f =open('huge.dat') > v = array.array('h') # Or whatever data type > v.fromfile(f, 4096) > f.close() > if sys.byteorder == 'little': > v.byteswap() > > --Scott David Daniels > Scott.Daniels at Acm.Org This seems to do the what I want. I did not know about array.byteswap and sys.byteorder. Thanks for taking the time to answer my silly question. Ciao! From caleb.hattingh at gmail.com Thu Dec 9 07:39:33 2004 From: caleb.hattingh at gmail.com (caleb.hattingh at gmail.com) Date: 9 Dec 2004 04:39:33 -0800 Subject: Pictograms and Python In-Reply-To: References: <81a41dd.0411160125.1aa4c7c1@posting.google.com> Message-ID: <1102595973.598775.57650@z14g2000cwz.googlegroups.com> Diez Ya got me there! """ I have a sript that downloads a webpage. According to the picture on this webpage I need to pass a parameter to this , running script a few lines later. """ Err, ya, I guess I would be suspicious too. Sorry about that! Keep well Caleb From beliavsky at aol.com Sun Dec 26 08:11:40 2004 From: beliavsky at aol.com (beliavsky at aol.com) Date: 26 Dec 2004 05:11:40 -0800 Subject: Complementary language? References: Message-ID: <1104066700.150287.322640@c13g2000cwb.googlegroups.com> Robert Kern wrote: >If you do numeric calculations, learning just enough FORTRAN to do loops >and math can be quite useful. I find that F2PY makes writing FORTRAN >subroutines for numerical calculations over Numeric arrays much easier >than C. I agree with this and would add that Fortran, from the 1990 standard onwards, is one of the few compiled languages that support both array operations and multidimensional array slices, like the Python Numeric and Numarray modules (and lists for 1-D arrays). There is a free Fortran 95 compiler called g95 at http://www.g95.org . In some ways, the syntax of Python is closer to free format Fortran than C. Maybe the message http://groups-beta.google.com/group/comp.lang.python/msg/5de999e28ead0dd9 I wrote with comparative statistics on some programming languages could be informative. From maxm at mxm.dk Sun Dec 12 06:39:20 2004 From: maxm at mxm.dk (Max M) Date: Sun, 12 Dec 2004 12:39:20 +0100 Subject: Persistent objects In-Reply-To: <7xis77q1t7.fsf_-_@ruckus.brouhaha.com> References: <7xis77q1t7.fsf_-_@ruckus.brouhaha.com> Message-ID: <41bc2d98$0$200$edfadb0f@dread12.news.tele.dk> Paul Rubin wrote: > Basically I wish there was a way to have persistent in-memory objects > in a Python app, maybe a multi-process one. So you could have a > persistent dictionary d, and if you say > d[x] = Frob(foo=9, bar=23) > that creates a Frob instance and stores it in d[x]. Then if you > exit the app and restart it later, there'd be a way to bring d back > into the process and have that Frob instance be there. Have you considdered using the standalone ZODB from Zope? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From les_ander at yahoo.com Sun Dec 19 12:36:11 2004 From: les_ander at yahoo.com (les_ander at yahoo.com) Date: 19 Dec 2004 09:36:11 -0800 Subject: How do I define the search path for personal library In-Reply-To: <1103455888.785445.301300@c13g2000cwb.googlegroups.com> References: <1103424166.709841.206980@f14g2000cwb.googlegroups.com> <1103455888.785445.301300@c13g2000cwb.googlegroups.com> Message-ID: <1103477771.326147.260450@z14g2000cwz.googlegroups.com> Yes, this is exactly what I wanted--just like in perl I can add search path to @inc. thanks From theller at python.net Wed Dec 1 15:10:38 2004 From: theller at python.net (Thomas Heller) Date: Wed, 01 Dec 2004 21:10:38 +0100 Subject: Python Win32 Silent Install References: Message-ID: "Matt Gerrans" writes: > Looks like the installer for the Win32 extensions has changed from Wise to > distutils, so now my automated silent installations don't work anymore. > Anyone know if the distutils binary installer can be run silently? I > haven't been able find a command line reference for distutils binaries (I'm > still sifting through http://www.python.org/doc/current/dist/, though...). There are no command line options for the distutils created installer, and silent installation is not possible. > Maybe there is a better way to do an unattended install of the Win32 > extensions (that is, perhaps without using the binary)? I should be quite easy to write a Python script that opens the binary as a zipfile, and then does what the gui does without showing a gui. Thomas From PPNTWIMBXFFC at spammotel.com Thu Dec 16 09:27:18 2004 From: PPNTWIMBXFFC at spammotel.com (Marco Aschwanden) Date: Thu, 16 Dec 2004 15:27:18 +0100 Subject: Winge IDE Issue - an suggestions? References: <41c174f9$0$1123$afc38c87@news.optusnet.com.au> <41c1782d$0$4539$afc38c87@news.optusnet.com.au> Message-ID: Without further checking I would propose you let WingIDE ignore this exception - most probably WingIDE is choking on a exception that was thrown intentionally by the module writer. I hope you know how to let WingIDE ignore exceptions? (In the upper part of the Exceptions-tool click on 'Ignore this exception location')... hope this helps. Regards, Marco From jerf at jerf.org Mon Dec 6 22:32:30 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 06 Dec 2004 22:32:30 -0500 Subject: GUI Frames and classmethod References: <41b0ffbc$1@nntp0.pdx.net> <41b4c968$1@nntp0.pdx.net> <41b4d821$1@nntp0.pdx.net> Message-ID: On Mon, 06 Dec 2004 14:11:04 -0800, Scott David Daniels wrote: > Second, I was referring to code like: > > try: > inner = table[state] > except KeyError: > table[state] = inner = {} > inner[action] = whatever > > vs. code like this: > > table[state, action] = whatever > > That is, dynamic table modification code for a table of pairs is clearer. But it isn't quite as tradeoff free as you say; you do lose the ability to say table[state] and get just the information relevant to your state (you might take the .keys() of that or something). In this case, it may not be a big deal; depends on what the program does and how the programmer thinks. In other cases, dicts of dicts can make perfect sense. For instance, I have a Registry type that uses dicts-in-dicts the obvious way to store things like "table1.table2.table3.value", and that way there is a coherent way to pass "table1.table2.table3" around. Yeah, you could work out a string or tuple subclass that could still work, but that's a lot more work :-) and you'd still have a hard time getting all keys from a table without searching the whole thing. From airvine at ayrsoft.com Tue Dec 14 07:46:24 2004 From: airvine at ayrsoft.com (Allan Irvine) Date: 14 Dec 2004 04:46:24 -0800 Subject: need some help quickly Message-ID: <1103028384.783802.109120@z14g2000cwz.googlegroups.com> HI Hope this is the right place for this, I am new. I have a spec to create a (dual screen) framework application that 1 displays mp3, flash, jpegs etc. on top screen 2: displays buttons on bottom screen which alter image when a key is pressed. The hardware is a dell pc basically, no mouse and the keyboard is a simple 8 key pad that outputs numbers 1-8 (I think but can be mapped). I am looking for the best way to create this and tools to use etc. The system is basically an information kiosk like you see in airports etc. the presentation screen on top may show several borderless frames containing differing media. Hope you can help - any thoughts welcome I am willing to pay for some help. From none.by.e-mail Thu Dec 16 06:57:25 2004 From: none.by.e-mail (Mike Thompson) Date: Thu, 16 Dec 2004 22:57:25 +1100 Subject: Winge IDE Issue - an suggestions? In-Reply-To: <41c174f9$0$1123$afc38c87@news.optusnet.com.au> References: <41c174f9$0$1123$afc38c87@news.optusnet.com.au> Message-ID: <41c1782d$0$4539$afc38c87@news.optusnet.com.au> Mike Thompson wrote: > > I've run into a problem using WingIDE. I have a dead simple script > (which uses ElementTree): > > > from elementtree.ElementTree import Element, SubElement, tostring Just to be clear: that's the effbot's ElementTree package at http://effbot.org/zone/element-index.htm -- Mike From FBatista at uniFON.com.ar Thu Dec 23 09:40:12 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 23 Dec 2004 11:40:12 -0300 Subject: list Integer indexing dies?? Message-ID: [Ishwor] #- >>> 'invalid'[0] #- 'i' #- >>> 123232[-1] #- # Python should automagically infer here that user #- # means indexing and *not* the number per se. #- # (i mean list in context of the line :-) ) Python never should automagically infer nothing! Type "import this" in the interactive interpreter and look at rule #2. #- > IOW, the string is a sequence of characters, and the #- integer is not sequence #- > at all. #- > #- #- strings are immutable sequence of collections in Python. Integers are #- numbers. ;-) Nop. Strings are not a sequence of collections, just a sequence of characters. . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bjg at network-theory.co.uk Sat Dec 11 06:57:39 2004 From: bjg at network-theory.co.uk (Brian Gough) Date: 11 Dec 2004 11:57:39 +0000 Subject: Python Docs. Hardcopy 2.4 Library Reference, interested? References: <87oeh3v98s.fsf@network-theory.co.uk> Message-ID: <87fz2doxn0.fsf@network-theory.co.uk> Richie Hindle writes: > I'd be interested to know how many of these manuals you sell...? This is > only idle curiosity, and if you don't want to say then that's no problem. > (I'd briefly considered doing this myself, until I found your site.) I sell about 10 python manuals per month on average. For each copy sold, $1 of the price is donated to the Python Software Foundation. So far, that makes $341, putting us at #16 on the PSF donors ranking (http://www.python.org/psf/donations.html). All of the money from our sales (including other manuals) goes back into free software and documentation, either by direct donations or by supporting my work as a GNU maintainer. You can find more information at the following urls, http://www.network-theory.co.uk/python/manual/ - python tutorial http://www.network-theory.co.uk/python/language/ - language reference http://www.network-theory.co.uk/about.html - general company info -- best regards Brian Gough Network Theory Ltd, Publishing the Python Manuals --- http://www.network-theory.co.uk/python/ From replytogroup at nospam.org Sat Dec 11 21:50:15 2004 From: replytogroup at nospam.org (Michael McGarry) Date: Sat, 11 Dec 2004 19:50:15 -0700 Subject: Hashes Message-ID: Hi, Are there hashes in Python? Michael From luismgz at gmail.com Sun Dec 12 18:34:48 2004 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 12 Dec 2004 15:34:48 -0800 Subject: from vb6 to Python References: <1102814024.901947.287950@f14g2000cwb.googlegroups.com> Message-ID: <1102894488.968224.59460@z14g2000cwz.googlegroups.com> Martijn Faassen wrote: > Unfortunately this is currently not near production use, and whether > Microsoft is funding IronPython development is up in the air: It's true that he Ironpython's mailing list is a little bit innactive, but this is just because there's only one person in charge of Ironpython at this moment (although Microsoft was looking to hire a new developer to help on this). However, the innactivity is due to the fact that Jim Hugunin, its developer, has begun working for MS just a couple of months ago, and as he says, there are tons of new CLR features to learn that are applicable to dynamic languages. You should also give credit to Jim: he's the man who developed Jython, which is a complete inplementation of Python written in Java. He also created Numeric and co-authored Aspect, another programming language. So I'm sure that Ironpython will be a reality soon, and a very good one... From elephantum at dezcom.mephi.ru Sun Dec 19 06:38:47 2004 From: elephantum at dezcom.mephi.ru (Andrey Tatarinov) Date: Sun, 19 Dec 2004 14:38:47 +0300 Subject: dot products In-Reply-To: <1103454255.371143.95030@z14g2000cwz.googlegroups.com> References: <1103454255.371143.95030@z14g2000cwz.googlegroups.com> Message-ID: <32l7i8F3ndvi7U1@individual.net> Rahul wrote: > I want to compute dot product of two vectors stored as lists a and b.a > and b are of the same length. > > one simple way is > sum(a[i]*b[i] for i in range(len(a))) > btw, imho the most "Pythonic" would be: sum(i*j for (i,j) in zip(a,b)) From donn at drizzle.com Mon Dec 27 23:07:19 2004 From: donn at drizzle.com (Donn Cave) Date: 27 Dec 2004 22:07:19 -0600 Subject: argument type References: Message-ID: <41d0dbf7$1_1@127.0.0.1> Quoth "It's me" : | A newbie question. | | How can I tell from within a function whether a particular argument is a | sigular type, or a complex type? | | For instance, in: | | def abc(arg1) | | How do I know if arg1 is a single type (like a number), or a list? | | In C++, you would do it with function overloading. If arg1 is always simple | type, I wouldn't care what it is. But what if I *do* need to know whether | arg1 is a list or not? | | I hate to have to have 2 functions: 1 for simple types, and one for list | types and then do something like: | | abc_simple(1.0) | abc_list([1.0,2.0]) | | Any help would be greatly appreciated. How about abc([1.0])? That's easy, and it's a lot cleaner than mucking up your API with functions whose parameters have multiple possible interpretations. C++ doesn't always point the way to great programming models. Donn Cave, donn at drizzle.com From jeff at ccvcorp.com Thu Dec 23 13:15:05 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 23 Dec 2004 10:15:05 -0800 Subject: list IndexError In-Reply-To: <41caf242$0$12718$a1866201@visi.com> References: <34534aed04122211413845b33e@mail.gmail.com> <41C9D224.7050902@rogers.com> <34534aed041222122441a43901@mail.gmail.com> <34534aed04122212265cfa752d@mail.gmail.com> <41C9FF5A.3030200@rogers.com> <41caf242$0$12718$a1866201@visi.com> Message-ID: <10sm2g7nv1hk9b3@corp.supernews.com> Grant Edwards wrote: >On 2004-12-23, Steven Bethard wrote: > > > >>>Ah, my mistake, I missed the [:] after the source argument >>>that was taking a copy... which brings up the question, how >>>many other people would miss it? >>> >>> >>Too many. This is why I greatly prefer >> >> list(lst) >> >> > >To me, that's just as non-obvious. I would have guessed that >calling list() on a list was a noop. I would be wrong. >Surprised, but wrong. > > It makes a lot more sense when you remind yourself that list() et al are not conversion functions, but rather class constructors. (This is complicated by the fact that in old Pythons, int() and float() *were* conversion functions... but are not so any more.) Given a user-defined class, I think it wouldn't be any surprise to see that class Spam: # [....] s1 = Spam( ... ) s2 = Spam(s1) results in two (probably almost identical) instances of Spam. Using list() to create a copy of a list is analogous, but we're used to thinking of list() as a converter rather than a constructor... Jeff Shannon Technician/Programmer Credit International From fredrik at pythonware.com Thu Dec 9 13:51:11 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 9 Dec 2004 19:51:11 +0100 Subject: Calling a C program from a Python Script References: <41b89738$0$11034$a1866201@visi.com> Message-ID: Brad Tilley wrote: > for root, files, dirs in os.walk(path) > for f in files: > try: > EXECUTE_C_PROGRAM http://docs.python.org/lib/module-subprocess.html this module in new in 2.4; for older version, os.system() or the os.popen() family might be what you're looking for. see the "Replacing Older Functions with the subprocess Module" section for more info. From sigu4wa02 at sneakemail.com Sat Dec 18 19:05:33 2004 From: sigu4wa02 at sneakemail.com (Zhang Le) Date: 18 Dec 2004 16:05:33 -0800 Subject: Replace single item in tkinter ListBox Message-ID: <1103414733.157947.145050@c13g2000cwb.googlegroups.com> Hello, Is there a quick way to replace the content of a single item in tkinter's listbox? Currently my solution is to first delete the item, then insert a new item at the same position. I think there may be better way. Zhang Le From riko.wichmann at remove-this.desy.de Wed Dec 8 04:53:58 2004 From: riko.wichmann at remove-this.desy.de (Riko Wichmann) Date: Wed, 08 Dec 2004 10:53:58 +0100 Subject: cookie lib policy how-tp? In-Reply-To: <0okh82-011.ln1@halut.solar-empire.de> References: <1102435627.593309.301430@z14g2000cwz.googlegroups.com> <0okh82-011.ln1@halut.solar-empire.de> Message-ID: >>Tried that already. At least, I hope I guessed at least one of the >>possible identifiers correct: MSIE6.0, MSIE 6.0, MSIE/6.0 > > > When my opera is set to identify as MSIE, it sends > "Mozilla/4.0 (compatible; MSIE 6.0; X11; Linux i686) Opera 7.54 [en]". Hi Marc, thanks for the hint! that brought me a big step forward! Cheers, Riko From fredrik at pythonware.com Wed Dec 22 02:37:55 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Dec 2004 08:37:55 +0100 Subject: how to start a new process while the other ist running on References: Message-ID: Erik Geiger wrote: > I have a running python script (capisuit incoming.py). This script shall > start a linux shell script. If I start this script like os.system(/paht/to > shellscipt.sh) the python scipt waits for the exit of the shell script and > then goes on with the rest of the python script. > > How to start a shell script without waiting for the exit of that shell > script? It shall start the shell script and immediately execute the next > python command. if you have Python 2.4, you can use the subprocess module: http://docs.python.org/lib/module-subprocess.html see the spawn(P_NOWAIT) example for how to use it in your case: http://docs.python.org/lib/node236.html as others have noted, os.spawn(P_NOWAIT) can be used directly, as can os.system("command&") (where the trailing "&" tells the shell to run the command in the background). subprocess is available for Python 2.2 and 2.3 as well, by the way: http://www.lysator.liu.se/~astrand/popen5/ From davidf at sjsoft.com Thu Dec 2 04:28:38 2004 From: davidf at sjsoft.com (David Fraser) Date: Thu, 02 Dec 2004 11:28:38 +0200 Subject: Python Win32 Silent Install In-Reply-To: References: Message-ID: Thomas Heller wrote: > "Matt Gerrans" writes: > > >>Looks like the installer for the Win32 extensions has changed from Wise to >>distutils, so now my automated silent installations don't work anymore. >>Anyone know if the distutils binary installer can be run silently? I >>haven't been able find a command line reference for distutils binaries (I'm >>still sifting through http://www.python.org/doc/current/dist/, though...). > > > There are no command line options for the distutils created installer, > and silent installation is not possible. > > What I've often done is combine other people's extensions into my package by importing stuff from their distutils setup scripts. Now that pywin32 is using distutils this should be possible too :-) David From fuzzyman at gmail.com Thu Dec 9 06:28:23 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: 9 Dec 2004 03:28:23 -0800 Subject: ANN: GallerPy 0.5.0 In-Reply-To: <8Katd.84$ch5.40@text.usenetserver.com> References: <8Katd.84$ch5.40@text.usenetserver.com> Message-ID: <1102591703.111649.87820@c13g2000cwb.googlegroups.com> It's very nice looking and emminently 'hackable'. Nice one. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From fredrik at pythonware.com Wed Dec 22 08:12:28 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Dec 2004 14:12:28 +0100 Subject: Mutable objects which define __hash__ (was Re: Why are tuplesimmutable?) References: <20041215152606.1029.1225319887.divmod.quotient.10976@ohm> <10s48r5hbse5o57@corp.supernews.com> <41c350ef.331854992@news.oz.net> <41c9103e.708509723@news.oz.net> <41C96F1D.9070207@iinet.net.au> Message-ID: Nick Coghlan wrote: > I have a different suggestion: an identity dictionary. > > It ignores __hash__, __cmp__ and __eq__, and instead uses id() and is. that's a rather common pattern, and you don't really need a special type to handle it: just replace d[k] with d[id(k)]. if you really need to store the keys in the dict, use d[id(k)] = k, v. you can find some use of this pattern in Python's standard library. From grante at visi.com Thu Dec 30 12:41:35 2004 From: grante at visi.com (Grant Edwards) Date: 30 Dec 2004 17:41:35 GMT Subject: portable text user interface References: <1104329408.956094.48890@f14g2000cwb.googlegroups.com> <41d41441$0$12716$a1866201@visi.com> Message-ID: <41d43dcf$0$12711$a1866201@visi.com> On 2004-12-30, Maxim Kasimov wrote: >>>yes i'm telneting (sshing), that is the reason why i'm looking >>>for libs for making text interfaces. i know there is a project >>>named "anakonda" - red hat linux installer, but it is uses >>>specific C libs. i can use only python libs. >> >> By "only python libs" do you mean only the stuff that's >> included in the vanilla CPython distro? If that's the case, >> then curses is pretty much the only choice. Last time I >> looked, it didn't work on Windows. >> >> I've used the snack module (which is what anaconda uses), and >> it's very handy for simple text-based UIs. >> > at ports (FreeBSD) i've found this: > Port: snack-2.2.7 > Path: /usr/ports/audio/snack > Info: A sound toolkit for scripting languages Unfortunately there are two modules with the same name. The one you found is a sound library. The other one is the Python wrapped version of the newt library. I've no idea why the Python newt module is called "snack". The new source code comes with the Python "snack" module wrapper. The most recent version I have handy is available at ftp://ftp.visi.com/users/grante/stuff/newt-0.50.tar.gz There appear to be more recent versions available: http://rpmfind.net/linux/RPM/fedora/3/i386/newt-0.51.6-5.i386.html http://linux.maruhn.com/sec/newt.html http://www.freshports.org/devel/newt There's a rather outdated tutorial on using Newt v0.30 from C: http://www.oksid.ch/gnewt/tutorial.html Newt requires the s-lang library: http://www.s-lang.org/ -- Grant Edwards grante Yow! Imagine--a WORLD at without POODLES... visi.com From RPhillips at engineer.co.summit.oh.us Tue Dec 7 14:01:08 2004 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Tue, 07 Dec 2004 14:01:08 -0500 Subject: Time for : comp.lang.python.newbies ?? Message-ID: Speaking for the newbies (or that segment of them who aren't asking you to do their homework/job/googling for them): The trouble is, we don't know whether we can't find information(X) because: "X" is not the term "knowbies" use for the concept, or because: information(X) is rare due to the concept being so awful that a knowbie would avoid it altogether, or because: information(X) is rare due to being too obvious to document, or because: information(X) is non-existent because "X" comprises some legitmate terms, used in a way that makes no sense, with a question mark at the end or because: X is a genuinely new question and information(X) would advance the body of knowledge for all of us. In other words, we don't know what we don't know. If we did, we'd know whether our question should be sent to the newbies list or the knowbies list. Maybe just ask us to post *everything* to the .tutor list and let the question bubble up to this list if it doesn't get answered there? Or ask us to post to the .tutor list until we've responded to someone else's post a few times (proven ourselves competent to judge our own competence)? Ron >>> James Stroud 12/7/2004 12:52:08 PM >>> > Maybe a time for a new discussion group along that suggested > by the Subject line ? I would hesitate to change too much about this list. I spend about 1 hr. per day (probably too much) perusing the technical explanations, musings, and rants--and hoping to learn enough to reply with an answer sometimes. As far as lists go, this is my favorite, and I've subscribed to lists in a variety of fields. I'm afraid that scaring off newbies would remove some of the charm of this list. -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics 611 Charles E. Young Dr. S. MBI 205, UCLA 951570 Los Angeles CA 90095-1570 http://www.jamesstroud.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From miki.tebeka at zoran.com Tue Dec 28 15:38:06 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Tue, 28 Dec 2004 22:38:06 +0200 Subject: HELP Non-Blocking reads from sys.stdin in Windows. In-Reply-To: References: Message-ID: <20041228203738.GE1500@zoran.com> Hello Barr, > I am in real need of a way to perform non blocking reads from sys.stdin on > windows. I have looked every where for an answer but but with no luck. I > beleive there there must be a way of doing this, can some one please help > asap. Warning: The below code wasn't tested at all... ------------------------------- from Queue import Queue, Empty from sys import stdin from threading import Thread # Reading from empty stdin error class EmptyError(Exception): pass # Input queue _queue = Queue() def produce(): '''Read one char at a time from stdin and place in _queue''' try: while 1: c = stdin.read(1) # Read one char if not c: # EOF _queue.put(EOFError, 1) break _queue.put(c, 1) except EOFError, e: _queue.put(EOFError) # Start the thread t = Thread(target=produce) t.setDaemon(1) # Don't inhibit interperter exit t.start() # Start thread def get(): '''Get one item from queue. Might raise EmptyError if queue is empty or EOFError of end of input ''' try: val = _queue.get(0) if val is EOFError: raise EOFError return val except Empty: raise EmptyError def is_empty(): '''Tell if no input is ready''' return _queue.empty() ------------------------------- HTH. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From theller at python.net Thu Dec 16 07:19:24 2004 From: theller at python.net (Thomas Heller) Date: Thu, 16 Dec 2004 13:19:24 +0100 Subject: Why are tuples immutable? References: <41BE1644.8050906@freemail.gr> <7xwtviftz1.fsf@ruckus.brouhaha.com> Message-ID: "Fredrik Lundh" writes: > Antoon Pardon wrote: > >> That depends on whether the programmes wants value equality >> or identity equality. > > how does the dictionary know if you want key value equality or key > identity equality? Smalltalk has separate Dictionary and IdentityDictionary classes. Thomas From ebonakDUH at hotmail.com Sat Dec 11 10:48:56 2004 From: ebonakDUH at hotmail.com (Esmail Bonakdarian) Date: Sat, 11 Dec 2004 10:48:56 -0500 Subject: your favorite quick reference? (was Python Docs. Hardcopy 2.4 Library Reference, interested?) In-Reply-To: References: Message-ID: <10rm5n8qi7pi3b1@corp.supernews.com> somewhat related .. is there a good quick reference for python? o'reilly has a quick ref guide 2nd ed is a few years old, and the ones i have found on-line seem a bit big. I am looking for something relatively concise that I can carry with me ... not sure such a thing exists? thanks. From exarkun at divmod.com Sat Dec 4 10:56:51 2004 From: exarkun at divmod.com (Jp Calderone) Date: Sat, 04 Dec 2004 15:56:51 GMT Subject: using cmd.exe as a telnet client In-Reply-To: <20041204113113.93303.qmail@web50405.mail.yahoo.com> Message-ID: <20041204155651.1203.1439641760.divmod.quotient.1997@ohm> On Sat, 4 Dec 2004 03:31:12 -0800 (PST), Eyal Lotem wrote: > > You simple have to run PyInvoke's server.py on the > server, and then in the client, you can Pythonically > control anything on the server: > > client = pyinvoke.connect(('some_server', some_port)) > client.modules.shutil().rmtree('/tmp/blah') This seems terribly, terribly insecure; the kind of thing no one should ever run on any server or desktop anywhere for any reason. What am I missing? Jp From ramen at lackingtalent.com Sat Dec 4 17:37:17 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Sat, 04 Dec 2004 22:37:17 -0000 Subject: Audio interviews of Guido or other Python advocates? References: Message-ID: In article , Jimmy Retzlaff wrote: > Dave Benjamin wrote: >> I looked around for recordings of Guido, but couldn't find any. Does >> anyone know of any streamable audio (or video) interviews or speeches >> featuring Guido, the bots, or any other interesting people in the > Python >> community? > > There's a video with a few folks in it at: > > http://www.ibiblio.org/obp/pyBiblio/pythonvideo.php Ohh, man, the geek love story was almost too much to bear. =) Cool, so that covers Guido, Tim Peters, Eric Raymond, Jim Fulton... -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. "talking about music is like dancing about architecture." From carribeiro at gmail.com Fri Dec 3 09:22:46 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 3 Dec 2004 12:22:46 -0200 Subject: pre-PEP generic objects In-Reply-To: References: Message-ID: <864d370904120306225b28beee@mail.gmail.com> On Fri, 03 Dec 2004 08:58:48 -0500, Istvan Albert wrote: > On the other hand, it would be nice to have a module that > implements various design patterns. The Bunch, the Borg, the Null, > the Proxy all nicely documented tucked away in their separate > module. That would feel a lot less like littering the standard name space > with an class that just "seems" to be useful. Great idea. I have explored some ideas relating generic objects with "standard" patterns, namely "observer" & "proxy". One of the applications of generic objects is to allow for data sharing between objects of different classes that happen to share a few attributes; sometimes it's not possible to pass the entire object around for the other one to copy the data, either because of safety reasons, or because there is some slightly mismatch between the interfaces. The generic, in this case, can be implemented either as an intermediate storage structure (as a data-only records) or as an "proxy" that exposes only the desired attributes. In this case, data is passed around and copied manually, using the generic (or the "proxy" object). Another use case is when one wants to implement the "observer" pattern (which would allow for a "live" data sharing). One alternative is to use a "generic" as the base "observable' object; other objects can register with the generic and simply receive notifications, or even share the references to its internal attributes (btw, Python descriptors & properties are incredibly useful in this case). Extending it even further -- the observed object could accept modifications from its observers, although in this case we're already talking a about more complex pattern than the standard "observer" (btw, how is it called?). -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From luismgz at gmail.com Sun Dec 12 18:49:19 2004 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 12 Dec 2004 15:49:19 -0800 Subject: Python mascot proposal In-Reply-To: References: Message-ID: <1102895359.091934.275690@f14g2000cwb.googlegroups.com> Hey Dimitri, I completely agree with you in that Python needs once for all a cool logo. I like your design very much, but I have a few thoughts about it: 1) I think that Python's logo should reflect its power. If we use a mascot as its image, we would be giving the wrong idea: that Python is a "toy" language, instead of a very good alternative to other mainstream languages. 2) We should also bear in mind Guido's oppinion about using a snake for identifying Python. 3) And finally, we should consider it very seriously. Image is not everything, but it is very important for "marketing" a product. I'm sure that if Java didn't have a cool name and a cool logo, it wouldn't have been that succesfull. I don't mean to sound like I'm rejecting your idea. I really like it alot, and it is an excellent mascot. It's just that I wouldn't use a mascot... I'd rather use a more "killer" image. Something that reflects power and excellence. What do you think? From replytogroup at nospam.org Wed Dec 15 01:16:43 2004 From: replytogroup at nospam.org (Michael McGarry) Date: Tue, 14 Dec 2004 23:16:43 -0700 Subject: Regular Expression Message-ID: Hi, I am horrible with Regular Expressions, can anyone recommend a book on it? Also I am trying to parse the following string to extract the number after load average. ".... load average: 0.04, 0.02, 0.01" how can I extract this number with RE or otherwise? Michael From insert at spam.here Mon Dec 20 19:53:01 2004 From: insert at spam.here (Doug Holton) Date: Mon, 20 Dec 2004 18:53:01 -0600 Subject: Boo who? (was Re: newbie question) In-Reply-To: References: <1103503985.015510.24680@z14g2000cwz.googlegroups.com> Message-ID: Hans Nowak wrote: > Regardless of the merits of Boo, this is comp.lang.python, not > comp.lang.boo. The language may *look* like Python, but its inner > workings are nothing like Python, as several people have correctly > pointed out now. (Just like Java's syntax may look like C or C++ in > some areas, but the languages are nowhere near alike.) Pointing out the > difference is not trolling. Let me say it again then, although I do not know why it threatens people so much: the syntax of boo is indeed virtually identical to python's. That is what I said and what is clear from the website. I already stated that I will not mention boo again, to comply with Fredrik's wishes and yours. I will refer to CPython, and CPython only. But I will not be intimidated by the likes of Fredrik Lundh. Trollers will be held accountable. If it continues at this pace, then I suggest a weekly troll alert, to educate and prepare the so-called newbies for the behavior that occurs on this list. From alan.gauld at btinternet.com Mon Dec 20 03:46:14 2004 From: alan.gauld at btinternet.com (Alan Gauld) Date: Mon, 20 Dec 2004 08:46:14 +0000 (UTC) Subject: BASIC vs Python References: <41C342A0.3040700@users.ch> <86sm64tzax.fsf@guru.mired.org> <86d5x849bs.fsf@guru.mired.org> <86ekhm2hk8.fsf@guru.mired.org> Message-ID: > >>> was too late). A machine designed to be run on Forth would have been > >>> unbelievably powerful from the late 70s to the mid 90s (it would be > >>> more painful now than the x86 legacy, but still). A small data point here is that Sun still use Forth in their Sparc workstations. Their system prompt is really a Forth interpreter... I don;t know where the interpreter resides, presumably not in Sparc since its a RISC but interesting that they still use it. (Or they did last time I used a Sparc - 4 years ago?) Alan G. Author of the Learn to Program website http://www.freenetpages.co.uk/hp/alan.gauld From mattabat at hotmail.com Tue Dec 28 02:33:46 2004 From: mattabat at hotmail.com (mattabat) Date: 27 Dec 2004 23:33:46 -0800 Subject: Making pygopherd working with Mac OS X Message-ID: <36b480ff.0412272333.4d6e3805@posting.google.com> Hello, I attempted to use pygopherd 2.0.9 work with MacPython 2.3 under Mac OS X 10.3.7 but I'm afraid I hit a brick wall trying to make it run. Does anyone know how to make this work? I obtained pygopherd from gopher://gopher.quux.org/1/devel/gopher/pygopherd - or for the gopher client deprived, from http://gopher.quux.org:70/devel/gopher/pygopherd Has anyone managed to get pygopherd running with MacPython? -- mattabat From steven.bethard at gmail.com Fri Dec 17 16:03:26 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 17 Dec 2004 21:03:26 GMT Subject: better lambda support in the future? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Steven Bethard wrote: > > >>Even if you could settle the syntax issue, once you've decided that you really do need a true >>block in an anonymous function, you're not really saving much space by not declaring it: >> >>def f(*args): >> # body line 1 >> # body line 2 >> # ... >> # body line N >>x = func or f >> >>v.s. >> >>x = func or lambda *args: >> # body line 1 >> # body line 2 >> # ... >> # body line N > > > you meant: > > def x(*args): > # body line 1 > # body line 2 > # ... > # body line N > > v.s. > > x = func or lambda *args: > # body line 1 > # body line 2 > # ... > # body line N > > right? You're welcome to name the function whatever you want -- notice in my example that the function is used in the statement: x = func or f If you'd prefer the statement to read: x = func or x that's also fine. Depends on what exactly 'x' is, and whether or not it really makes sense for the function I called 'f' to have the same name as the variable called 'x'. It certainly may, but since I wasn't giving real code, I didn't want to commit to that. Perhaps a better example would have been something along the lines of: dict(a=lambda *args: # body 1 , b=lambda *args: # body 2 , c=lambda *args: # body 3 )[s](values) v.s. def a_func(*args): # body 1 def b_func(*args): # body 2 def c_func(*args): # body 3 dict(a=a_func, b=b_func, c=c_func)[s](values) where it's clear that I'm trying to use lambdas where expressions are required. I assume that the point you were trying to make is that: def f(*args): return expr is equivalent to f = lambda *args: expr ? Steve From mwm at mired.org Thu Dec 9 15:32:15 2004 From: mwm at mired.org (Mike Meyer) Date: Thu, 09 Dec 2004 14:32:15 -0600 Subject: Ideas for projects References: <2004120821300416807%pbowden@stxrrcom> <1102586855.116714.51520@z14g2000cwz.googlegroups.com> Message-ID: "Fuzzyman" writes: > Phillip Bowden wrote: > The first one is an online bookmarks manager. There are various of > these around - but none in python and none as straightforward as I > would like. It would be easy to get something working and then expand > it to do more things (like import bookmarks from IE/mozilla/firefox, > check links, organise folders etc). I could give you a section on > voidspace - complete with FTP login and python 2.3.4 - if you > wanted. My online bookmark manager - written in Python - has been around for seven or eight years. See for details. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From jeff at ccvcorp.com Thu Dec 2 21:17:05 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 02 Dec 2004 18:17:05 -0800 Subject: installing 2.4 In-Reply-To: References: Message-ID: <10qvit6p99ilraa@corp.supernews.com> Jive wrote: >Well ain't that a kick in the pants? > >Version 2.3 is broke now, so I'm kind of stuck. I haven't found a 2.4 >version of Numeric. Do you know where to find one? > > Since 2.4 has only been released for a few days, it'll probably be a short while yet before all the various third-party package maintainers get a chance to build 2.4 versions of their packages. Your main options at this point are to wait, or to do compile it yourself from source, or to convince/bribe someone else to compile it from source for you. I expect that a major package like Numeric will have 2.4-compiled binary distributions pretty soon. As for 2.3 being broken, check your application path and file associations. You may be inadvertently running the 2.3 version of Pythonwin under the 2.4 interpreter. Jeff Shannon Technician/Programmer Credit International From ncoghlan at iinet.net.au Wed Dec 15 04:41:53 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 15 Dec 2004 19:41:53 +1000 Subject: while 1 vs while True In-Reply-To: <7xsm6983rx.fsf@ruckus.brouhaha.com> References: <1102903165.589419.323000@z14g2000cwz.googlegroups.com> <7xllc1p3q4.fsf@ruckus.brouhaha.com> <7xsm6983rx.fsf@ruckus.brouhaha.com> Message-ID: <41C006E1.5090309@iinet.net.au> Paul Rubin wrote: > Nick Coghlan writes: > >>Until this code: >> >>.>>> import pdb >>.>>> pdb.True = 0 >>.>>> pdb.x = "Darn writeable module dictionaries" >>.>>> from pdb import True >>.>>> True >>0 >>.>>> from pdb import x >>.>>> x >>'Darn writeable module dictionaries' > > > If Python really does behave that way, that bug should be fixed immediately. I tried it out in the 2.4 interpreter before posting it - it certainly does behave that way. And some test frameworks do make use of the capability to inject behaviour into the module under test (e.g. the one mentioned here: http://mail.python.org/pipermail/python-list/2003-April/156301.html). This is behaviour which has been around for a while - and breaking such expected behaviour gratuitously isn't acceptable. PEP 267 discusses a way of speeding access to globals/builtins without giving up the external binding of names. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steven.bethard at gmail.com Mon Dec 27 11:51:17 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 27 Dec 2004 16:51:17 GMT Subject: Tutorial problem In-Reply-To: References: Message-ID: <94Xzd.268002$V41.66003@attbi_s52> R?ffffe9veill?ffffe9 wrote: > Hello, > > I have just started doing the python tutorials and i > tried to modify one of the exercises, it has to to > with defining functions. > > I wanted the user to be able to enter an option and > then get a print of the selected option. I also wanted > to have an exit for the user. As it is, your code throws an exception for me (temp.py contains your code): $ temp.py Traceback (most recent call last): File "D:\Steve\temp.py", line 24, in ? menu() NameError: name 'menu' is not defined So, I dedented the "def menu" line, which solved the above NameError and gave me a new exception: $ temp.py GOALS IN... ____________________ 1.Pick up 2.Python Programming 3.Overall 4.Motivation 5.Exit ____________________ Traceback (most recent call last): File "D:\Steve\temp.py", line 27, in ? while choice != 5: NameError: name 'choice' is not defined So, at the beginning of the while loop, 'choice' is not yet defined. So let's define it: choice = 1 while choice != 5: ... $ temp.py GOALS IN... ____________________ 1.Pick up 2.Python Programming 3.Overall 4.Motivation 5.Exit ____________________ Pick a number:2 To create a programme ... Pick a number:1 To have a ... Pick a number:5 Bye Seems to be working now. Moral of the story here is that posting the exact text of the error you got is the best way to get an answer quickly -- the experienced Python programmers on this list can quickly tell you what the problem is if given enough information. As a side note, I would probably write your code as: print ' GOALS IN... ' print '____________________' print '1.Pick up' print '2.Python Programming' print '3.Overall' print '4.Motivation' print '5.Exit' print '____________________' def choice_iter(): while True: choice = int(raw_input('Pick a number: ')) if choice == 5: break yield choice def PU(): print 'To have a ...' def Python(): print 'To create a programme ...' def overall(): print 'To make .....' def motv(): print 'I know you can do it!' selections = [PU, Python, overall, motv] for choice in choice_iter(): selections[choice - 1]() print 'Bye' This cleans up the program logic in two ways: (1) The iteration over user input is modularized into the choice_iter function. This separates the code reading input from the user from the code calling the specified functions. (2) Rather than an set of if-else statements, I put the functions to be called into a list, and use the integer selected as an index to this list. HTH! Steve From davidf at sjsoft.com Sat Dec 25 14:30:22 2004 From: davidf at sjsoft.com (David Fraser) Date: Sat, 25 Dec 2004 21:30:22 +0200 Subject: Python To Send Emails Via Outlook Express In-Reply-To: <1103926784.421668.169630@f14g2000cwb.googlegroups.com> References: <1103519604.987664.117400@c13g2000cwb.googlegroups.com> <1103521500.427846.238790@c13g2000cwb.googlegroups.com> <41C67E3D.5040205@kdart.com> <1103528498.945675.43920@z14g2000cwz.googlegroups.com> <1103529746.281597.103710@c13g2000cwb.googlegroups.com> <41C6C9F8.7040400@holdenweb.com> <652vmkgw.fsf@telus.net> <1103672447.748945.208800@c13g2000cwb.googlegroups.com> <1103702693.245508.277030@f14g2000cwb.googlegroups.com> <1103764016.741136.26440@c13g2000cwb.googlegroups.com> <1103852129.579906.158940@c13g2000cwb.googlegroups.com> <1103871054.040568.279890@z14g2000cwz.googlegroups.com> <41cc6989$0$190$edfadb0f@dread12.news.tele.dk> <1103926784.421668.169630@f14g2000cwb.googlegroups.com> Message-ID: ian at kirbyfooty.com wrote: > Hey guys, I'm just thankful the answer has been found and hope this > helps someone else. To everyone (especially Lenard) that responded to > my request for help, thank you!! > Merry Christmas everyone!!! > God bless > Ian > Thanks Ian, Why not post this to the python-win32 mailing list as well, then maybe your changes can be incorporated into pywin32? Happy christmas David From bvande at po-box.mcgill.ca Fri Dec 3 11:51:25 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 03 Dec 2004 11:51:25 -0500 Subject: How did you learn Python? In-Reply-To: References: Message-ID: <41B0998D.5010903@po-box.mcgill.ca> Shawn Milo said unto the world upon 2004-12-03 09:54: > I was just wondering what the best books were for learning Python. > > Which books are good for getting started, and which should be saved for > later, or or not useful except as a reference for the learned? > > I have a decent programming background in VB, JavaScript, VBScript, > Net.Data (IBM's macro language), regular expressions, and a teensy bit of > Perl. My point is, I don't want something that is going to explain the basic > programming concepts, but does give a good introduction to Python-specific > things. Then, once I know how to get the job done, I would like a good book > or two at the intermediate to advanced level, to learn how to write really good code. > > I understand that resources such as this list and Google searches have all the answers, > but it seems like a more structured tool, such as a book or formal class, would be > of great benefit to me. The other languages I have used were picked up because of the > need to get a job done. As a result, I am able to get the job done, but any experienced > coder can show me six more efficient ways to do what I'm doing. I'm new to > Python, and I want to do this one right. I believe that Python will be > around for a good, long time, and it matches my values as an Open-Source/Linux > supporter, while having relevance in the Windows and Mac world, as well. > Plus, it looks like it was designed extremely well, and I'm excited about the > principles I've read about. > > Thanks, > Shawn Hi Shawn, I'm not done learning (and not just in the sense that no one ever finishes learning -- I'm a hobbyist not a pro). But, I found Learning Python really useful. Once I'd read that, Python in a Nutshell has been great to remind me of what I learned but 'misplaced' . I've not read all of it, and it overlaps a fair bit with Learning Python, but the free Dive Into Python reads well and is often cited as a good intro for those with programming experience. . It is also available as a dead-tree product from APress. HTH, Brian vdB From duncan.booth at invalid.invalid Tue Dec 21 05:41:36 2004 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Dec 2004 10:41:36 GMT Subject: Keyword arguments - strange behaviour? References: <1103622331.247762.161750@f14g2000cwb.googlegroups.com> Message-ID: wrote: > Can anyone explain the behaviour of python when running this script? > >>>> def method(n, bits=[]): > ... bits.append(n) > ... print bits > ... >>>> method(1) > [1] >>>> method(2) > [1, 2] > > It's the same in python 1.5, 2.3 and 2.4 so it's not a bug. But I > expected the variable "bits" to be re-initialised to an empty list as > each method was called. Whenever I explain optional keyword arguments > to someone I have usually (wrongly as it turns out) said it is > equivalent to: No, it is closer to: # Assume you have done this earlier: import new def _realmethod(n, bits): bits.append(n) print bits # The def is roughly equivalent to this: _defaultArgs = ([], ) method = new.function(_realmethod.func_code, globals(), 'method', _defaultArgs) Each time you re-execute the def you get a new set of default arguments evaluated, but the result of the evaluation is simply a value passed in to the function constructor. The code object is compiled earlier then def creates a new function object from the code object, the global dictionary, the function name, and the default arguments (and any closure as well, but its a bit harder to illustrate that this way). From ian at kirbyfooty.com Tue Dec 21 18:40:47 2004 From: ian at kirbyfooty.com (ian at kirbyfooty.com) Date: 21 Dec 2004 15:40:47 -0800 Subject: Python To Send Emails Via Outlook Express In-Reply-To: <652vmkgw.fsf@telus.net> References: <1103519604.987664.117400@c13g2000cwb.googlegroups.com> <1103521500.427846.238790@c13g2000cwb.googlegroups.com> <41C67E3D.5040205@kdart.com> <1103528498.945675.43920@z14g2000cwz.googlegroups.com> <1103529746.281597.103710@c13g2000cwb.googlegroups.com> <41C6C9F8.7040400@holdenweb.com> <652vmkgw.fsf@telus.net> Message-ID: <1103672447.748945.208800@c13g2000cwb.googlegroups.com> That sound really promising. Is there any chance you could forward me a copy of the script. I'm still very new to Python and it would help me a lot. Thanks again Ian From ch.list at us-hampton.mail.saic.com Tue Dec 14 11:52:54 2004 From: ch.list at us-hampton.mail.saic.com (Chris) Date: Tue, 14 Dec 2004 11:52:54 -0500 Subject: Python 3.0 In-Reply-To: References: <41BF176D.8010909@us-hampton.mail.saic.com> Message-ID: <41BF1A66.30802@us-hampton.mail.saic.com> >>Okay, color me stupid, but what is everyone referencing when they mention Python 3.0? I didn't >>see any mention of it on the Python site. > http://www.python.org/peps/pep-3000.html > > (which happens to be the first hit if you search for "python 3.0" in the > search box on python.org...) Okay, I feel dumb now. :) Chris From jeff at ccvcorp.com Thu Dec 16 16:05:57 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 16 Dec 2004 13:05:57 -0800 Subject: Why no list heritable type? In-Reply-To: References: Message-ID: <10s3tudkkjrs5f5@corp.supernews.com> James Stroud wrote: >The thread "why not arrays" got me thinking. I would really like to inherit >from a list so that I can add methods based on its contents, say if I filled >it with a type of object and wanted to iterate over all objects. I have built >a wrapper around a list like this for general use: > >class list_of_objects: > def __init__(self): > self.data = [] > def __len__(self): > return len(self.data) > etc ... > >Then it can be heritable and I can add or override methods. Why aren't built >in lists and dictionaries real heritable types that can save this kind of >patchwork? Is there a pythonic reason I am missing here? > >James > > > > But they *are* subclassable, since 2.2 at least: PythonWin 2.2.1 (#34, Apr 15 2002, 09:51:39) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au) - see 'Help/About PythonWin' for further copyright information. >>> type(list) >>> class my_list(list): ... pass ... >>> type(my_list) >>> l = my_list() >>> l.append('foo') >>> l.extend(['bar', 'baz']) >>> l[2] 'baz' >>> l ['foo', 'bar', 'baz'] >>> type(l) >>> Jeff Shannon Technician/Programmer Credit International From fulimin_yuan at yahoo.com Sun Dec 5 20:10:05 2004 From: fulimin_yuan at yahoo.com (Limin Fu) Date: Sun, 5 Dec 2004 17:10:05 -0800 (PST) Subject: How is Python designed? In-Reply-To: Message-ID: <20041206011005.11808.qmail@web80903.mail.scd.yahoo.com> Hi, > Ok, thats clearer. This whole thing sounds familiar > - the technique you > describe seems to resemble continuation passing > style. For a brief > discussion read here: > > http://www.ps.uni-sb.de/~duchier/python/continuations.html > > Python has a continuation-based interpreter > implementation - its called > "stackless python". Google for it. It certainly is > interesting. That's interesting. I heared of stackless pyton a few days ago, I will have a more careful look at it. > And I don't see that the ast is more complicated, at > least implementation > wise - in fact, your method requires more analysis > as for each statement > its pollible successors have to be computed and made > known to it - where an > ast node only knows about its children that more or > less directly stem from > the syntax analysis. Not really. You think in this way, maybe because you know more about AST and less about that technique I mentioned. I thinked in the opposite way because I know different things better. Hehe. > I have to admit that I don't know if > continuation-based evaluation has > inherent performance-gains. The only thing I can > think of is that you don't > need a stackframe in some cases as tail-recursion - > useful, but not so > common that one would expect significant performance > gains there. But as I > said - I'm not on sure ground here. I'm not sure either. Certainly it depends very much in the implementation. If anybody want, we can make some tests to check. I don't know if it's important, because it seems people dosen't really care about the efficiency of an interpreter (as long as it is not really really too slow). > Can you elaborate on what you consider beeing an > unefficient recursive call > and where there is a difference between your method > of evaluation and the > ast-evaluation I mentioned? After all, the > ast-evaluation is a postorder > traversal which has the same complexity of a depth > first search - the only > difference beeing the latter one using a fifo, the > forme a lifo for > managing the list of untraversed nodes. I don't see > any difference here. Sorry maybe I didn't understand that part correctly and took grant that it would be implemented in recursive way. I just wondered if the following can be extended for arbitrary length arithmetic expressions: Assignment("foo", BinaryOp("+", Get("a"), BinaryOp("*", Get("b"), Get("c")))) > I don't have negative opinions about yuan and by no > meants want to > discourage you developing it. Its a nice project. > If I upseted you or anybody here by un-properly used words, please forgive me. I always feel my english must be improved :) Best regards, Limin __________________________________ Do you Yahoo!? Yahoo! Mail - Easier than ever with enhanced search. Learn more. http://info.mail.yahoo.com/mail_250 From usenet-spam-trap at brachttal.net Mon Dec 6 19:03:43 2004 From: usenet-spam-trap at brachttal.net (Andreas Volz) Date: Tue, 7 Dec 2004 01:03:43 +0100 Subject: regex syntax Message-ID: <20041207010343.3af69dee@frodo.mittelerde> Hi, ich kann nicht gut regex, aber f?r das n?tigste reicht es eigentlich. Irgendwie komm ich aber mit der Syntax der re.* Befehle in Python nicht klar Vielleicht kann mir das an diesem Beispiel jemand zeigen: string = "bild.jpg" ich m?chte jetzt einfach wissen ob in dem string ein ".jpg" vorkommt oder nicht und dann eine Entscheidung treffen. Ich hab mir schon ?berlegt einfach die letzten viel Stellen des strings "per Hand" auf die Zeichenfolge zu vergleichen und so regex zu umgehen. Aber ich muss es irgendwann ja doch mal nutzen ;-) Gru? Andreas From stephane.bronsart at teledisnet.be Sun Dec 26 13:43:24 2004 From: stephane.bronsart at teledisnet.be (StepH) Date: Sun, 26 Dec 2004 19:43:24 +0100 Subject: Tricks to install/run Python on Windows ? Message-ID: <41cf064e$0$17409$4d4efb8e@read.news.be.uu.net> Hi, I'm new to Python. I'm working under XP, and I've alot of prob. (not with the langage itself, but with the tools): I've install Pyhton 2.4 in C:\Python24, using the .msi windows installer. Then, I've install "PythonWin" (the last build-203). I'll try to summerize my prob.: 1./ The PythonWin IDE is not stable at all. Sometimes it exit without reason, or don't stop on breakpoint, etc... Are some of you aware of bugs in the last PyhtonWin IDE release ? I've to open the TaskManager. AT some point, i'm not able to (p.e.) open a file under it !!! 2./ I've try to download Komode (he 3.1 personnal). I've also prob. with it ! Also, the breakpoint seems to not always work... 3./ So, i've try to use the command line, but i've to manualy change the code page od my dos box from 437 to 1252 (i'm live in belgium). And i've not try how to do that permanently ! 4./ Before, I had Python23 and it seems that when unstalling it, all the keys in the registry are not removed at all. When i've install the 2.4, I had a mismatch which force me to complety re-install the machine (I'm not an expert of the registry)... 5./ Installing komodo seems to "block" pythonwinIDE completly... What's wrong ? Python seems terific, but the tools... So... maybe i've to try BlackAdder ? From kdahlhaus at yahoo.com Wed Dec 22 09:33:25 2004 From: kdahlhaus at yahoo.com (kdahlhaus at yahoo.com) Date: 22 Dec 2004 06:33:25 -0800 Subject: Best GUI for small-scale accounting app? In-Reply-To: References: <7xmzw9cf8l.fsf@ruckus.brouhaha.com> Message-ID: <1103726005.187734.291660@f14g2000cwb.googlegroups.com> > ZOPE could provide the workaround but ZOPE seems really huge to > me and an overkill for this. Or maybe it would work? I am intenionally *not* trying to argue web vs traditional gui for your app, but to tuck away for future apps, CherryPy2 is a lot easier than Zope to use and programming it does not require much of a learning curve. Recently I did a simple app that started as wx Windows, got bogged down, and switched to CherryPy/Cheetah running locally on the users station. I know more about wxWindows now than before, so perhaps things would be different now, but at the time the gui was really slowing my down my development. I had a hard time getting my hands around the wxWindows sizers. They are simple in concept, but not easy to learn at first in practice. I went w/wxPython for a second app because of its printing capabilities and the large number of controls that come with it. Otherwise I would use pyFltk for small apps. From ola.natvig at infosense.no Fri Dec 10 10:24:03 2004 From: ola.natvig at infosense.no (Ola Natvig) Date: Fri, 10 Dec 2004 16:24:03 +0100 Subject: Find Items & Indices In A List... In-Reply-To: References: Message-ID: andrea.gavana at agip.it wrote: > Hello NG, > > I was wondering if there is a faster/nicer method (than a for loop) > that will allow me to find the elements (AND their indices) in a list that > verify a certain condition. For example, assuming that I have a list like: > > mylist = [0, 1, 1, 1, 1, 5, 6, 7, 8, 1, 10] > > I would like to find the indices of the elements in the list that are equal > to 1 (in this case, the 1,2,3,4,9 elements are equal to 1). I could easily > use a for loop but I was wondering if there is a faster method... > > Thanks for every suggestion. > > Andrea. > ------------------------------------------------------------------------------------------------------------------------------------------ > Message for the recipient only, if received in error, please notify the > sender and read http://www.eni.it/disclaimer/ > > You could do a list comprehension /generator expression. Like this: [i for i in range(len(mylist)) if mylist[i] == 1] -- -------------------------------------- Ola Natvig infoSense AS / development From matt.gerrans at hp.com Fri Dec 10 15:32:29 2004 From: matt.gerrans at hp.com (Matt Gerrans) Date: Fri, 10 Dec 2004 20:32:29 GMT Subject: Zip with a list comprehension Message-ID: This is probably so easy that I'll be embarrassed by the answer. While enhancing and refactoring some old code, I was just changing some map()s to list comprehensions, but I couldn't see any easy way to change a zip() to a list comprehension. Should I just let those sleeping dogs lie? (list comprehensions seem more readable than map(), but if the list comprehension that does the equivalent of zip() is less expressive than zip(), I'll stick with zip()). From steven.bethard at gmail.com Sat Dec 18 05:54:36 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sat, 18 Dec 2004 10:54:36 GMT Subject: Troubleshooting: re.finditer() creates object even when no match found In-Reply-To: References: <1103301532.737444.296010@z14g2000cwz.googlegroups.com> <41C3DAAD.6000406@iinet.net.au> Message-ID: Nick Coghlan wrote: > Nick Coghlan wrote: > >> Chris Lasher wrote: >> >>> Hello, >>> I really like the finditer() method of the re module. I'm having >>> difficulty at the moment, however, because finditer() still creates a >>> callable-iterator oject, even when no match is found. This is >>> undesirable in cases where I would like to circumvent execution of code >>> meant to parse out data from my finditer() object. >> >> Take a look at itertools.tee > > Bleh - I hit send instead of delete. Tee probably doesn't do what you > want. Steve's cookbook recipe is likely a better option. Actually, there's an equally valid solution with tee too -- check Peter Otten's comments at the bottom of the recipe. Steve From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Mon Dec 13 08:23:21 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Mon, 13 Dec 2004 14:23:21 +0100 Subject: How can i send 8-bit data or binary data with pyserial? References: Message-ID: <41bd97e4$0$3116$8fcfb975@news.wanadoo.fr> Hi ! 1 byte is 8 bits. If you want to manage bits, one by one, you can rewrite a protocol, and replace pyserial. Have a good day -- Michel Claveau From nick at craig-wood.com Thu Dec 2 04:30:02 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 02 Dec 2004 09:30:02 GMT Subject: pre-PEP generic objects References: <41acd7fb$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > Nick Craig-Wood wrote: > > class Hash: > > def __init__(self, **kwargs): > > for key,value in kwargs.items(): > > setattr(self, key, value) > > def __getitem__(self, x): > > return getattr(self, x) > > def __setitem__(self, x, y): > > setattr(self, x, y) > > You can simplify this: > class Hash(object): > def __init__(self, **kwargs): > for key,value in kwargs.items(): > setattr(self, key, value) > __getitem__ = getattr > __setitem__ = setattr That doesn't work unfortunately... >>> class Hash(object): ... def __init__(self, **kwargs): ... for key,value in kwargs.items(): ... setattr(self, key, value) ... __getitem__ = getattr ... __setitem__ = setattr ... >>> h=Hash(a=1,b=2) >>> h.a 1 >>> h['a'] Traceback (most recent call last): File "", line 1, in ? TypeError: getattr expected at least 2 arguments, got 1 >>> I'm not exactly sure why though! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jb_perin at yahoo.fr Tue Dec 21 04:40:23 2004 From: jb_perin at yahoo.fr (Jean-Baptiste PERIN) Date: Tue, 21 Dec 2004 10:40:23 +0100 Subject: extending python with a C-written dll In-Reply-To: <201220041204131063%mrjean1ATcomcastDOTnet@no.spam.net> References: <41c6e784$0$16084$a1866201@visi.com> <201220041204131063%mrjean1ATcomcastDOTnet@no.spam.net> Message-ID: Jean Brouwers a ?crit : > First, you might check the calldll module available here > > I have one or two things to try before ..but it looks interesting .. thank you very much .. > Take a look at Pyrex, it may fit your requirements to access C from > Python. > > Yes, pirex looks very powerful ..I heard about it already .. I know someone who used it .. and the result was just amazing .. there's also SWIG which looks very sexy http://www.swig.org/tutorial.html My current problem is a compilation one .. I need to first solve it before exploring these tools .. > > If you do not have these already, you may need the Win32 API extension > > > > > /Jean Brouwers Thank you very much Jean From ishwor.gurung at gmail.com Thu Dec 23 11:41:27 2004 From: ishwor.gurung at gmail.com (Ishwor) Date: Fri, 24 Dec 2004 03:11:27 +1030 Subject: list Integer indexing dies?? In-Reply-To: References: Message-ID: <34534aed04122308416498bb0d@mail.gmail.com> On Thu, 23 Dec 2004 13:33:16 -0300, Batista, Facundo wrote: > > > [Ishwor] > > #- > What should 035[0] cough up? Be carefull it should > #- > #- >>>035[0] > #- 3 # my own opinion. > #- > #- > cough up the same as 29[0]. > #- > #- >>>29[0] > #- 2 #again my own opinion > > Be aware that: > > >>> 035 == 29 > True > >>> Yup. Octal variation of 29. But that wasn't my point. > > . Facundo > > . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . > . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . > . . . . . . . . . . . . . . . > [snip] -- cheers, Ishwor Gurung From chris.lasher at gmail.com Fri Dec 17 11:38:52 2004 From: chris.lasher at gmail.com (Chris Lasher) Date: 17 Dec 2004 08:38:52 -0800 Subject: Troubleshooting: re.finditer() creates object even when no match found Message-ID: <1103301532.737444.296010@z14g2000cwz.googlegroups.com> Hello, I really like the finditer() method of the re module. I'm having difficulty at the moment, however, because finditer() still creates a callable-iterator oject, even when no match is found. This is undesirable in cases where I would like to circumvent execution of code meant to parse out data from my finditer() object. I know that if I place a finditer() object in an iterative for loop, the loop will not execute, but is there some way I can test to see if the object contains no matches in the first place? I thought about using .next() but I don't want to lose the ability to process the first (sometimes only) match in the finditer() object. Thanks in advance, Chris From rson at new.rr.com Fri Dec 17 11:22:16 2004 From: rson at new.rr.com (hawkmoon269) Date: 17 Dec 2004 08:22:16 -0800 Subject: ftp In-Reply-To: References: <1103154571.204203.182710@c13g2000cwb.googlegroups.com> <1103296755.168762.206930@z14g2000cwz.googlegroups.com> Message-ID: <1103300536.606904.205840@z14g2000cwz.googlegroups.com> That's a good idea. Thanks! :-) From aweinstein at vtr.net Wed Dec 29 05:26:55 2004 From: aweinstein at vtr.net (Alejandro Weinstein) Date: Wed, 29 Dec 2004 08:26:55 -0200 Subject: Tkinter vs wxPython In-Reply-To: <1104284672.770585.201370@f14g2000cwb.googlegroups.com> Message-ID: <41D26A4F.11776.1FD932@localhost> > Sure wxGlade/Boa/etc can help speed design and layout up, but what > happens when you want to do non standard things or just get stuck > because some thing just isn't working. Then you add the necesary hand crafted code to the automatic generated code. At least is what I did when I needed. From maxm at mxm.dk Thu Dec 16 04:52:26 2004 From: maxm at mxm.dk (Max M) Date: Thu, 16 Dec 2004 10:52:26 +0100 Subject: python re - a not needed In-Reply-To: References: Message-ID: <41c15a9f$0$253$edfadb0f@dread12.news.tele.dk> kepes.krisztian wrote: > I want to get infos from a html, but I need all chars except <. > All chars is: over chr(31), and over (128) - hungarian accents. > The .* is very hungry, it is eat < chars too. Instead of writing ad-hoc html parsers, use BeautifulSoup instead. http://www.crummy.com/software/BeautifulSoup/ I will most likely do what you want in 2 or 3 lines of code. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From fumanchu at amor.org Sun Dec 5 10:34:39 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 5 Dec 2004 07:34:39 -0800 Subject: Linguistic challenge: name this program Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3245329@exchange.hqamor.amorhq.net> Andre Roberge wrote: > In 1981, Richard Pattis wrote a delightful little book titled "Karel > the Robot, a Gentle Introduction to the Art of Programming." Pattis's > "Karel the Robot" was named after the author Karel Capek, who > popularized the word "robot" in his play "Rossum's Universal Robots". > Pattis's approach was to introduce a robot who could follow 5 basic > instructions and be taught to accomplish tasks of increasing > complexity. > > A few years ago, a first implementation of "Karel the Robot" in Python > was created and called PyKarel. A second, newer implementation is > called Guido van Robot (GvR for short), and is available at > gvr.sourceforge.net. Work is currently underway by the developpers of > GvR to produce a new-and-improved version. > > I have been working on my own (better ;-) version (sometimes > collaborating with the GvR folks) in order to learn Python. It is now > 90% finished. It is meant to be a complete environment to learn about > programming concepts, from simple sequences of instruction to OOP. > > Given the origin of Pattis's name (Rossum's Universal Robot) and the > name of Python's BDFL, I find it difficult to think of a better name > than Guido van Robot to name a programming environment in which one > uses Python to teach a robot new tricks! (Hat's off to Steve Howell > for this one). Yet, I want a "clever" name for my version. > > Any suggestions? RUR? Perhaps http://jerz.setonhill.edu/resources/RUR/ might give you more ideas. FuManChu From insert at spam.here Sun Dec 19 19:46:13 2004 From: insert at spam.here (Doug Holton) Date: Sun, 19 Dec 2004 18:46:13 -0600 Subject: Boo who? (was Re: newbie question) In-Reply-To: References: Message-ID: Peter Hansen wrote: > Why? If it's virtually identical, why would anyone bother even > visiting that site? ;-) > > But I suspect you mean that the syntax of the language is virtually > identical, while probably there are some significant differences. > Maybe in the richness of its standard library? Or the size of > its community? Or something else.... That's why I wrote: > See http://boo.codehaus.org/ From Scott.Daniels at Acm.Org Thu Dec 2 15:07:05 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 02 Dec 2004 12:07:05 -0800 Subject: recombination variations In-Reply-To: <8ef9bea6.0412011937.7eb7019c@posting.google.com> References: <8ef9bea6.0412011937.7eb7019c@posting.google.com> Message-ID: <41af886f$1@nntp0.pdx.net> Hung Jung Lu wrote: > ... expand = lambda t: reduce(lambda r, s: [x+y for x in r > for y in alphabet[s]], t, ['']) > print expand('ATSGS') Or, for a more verbose version: multis = dict(W='AT', M='AC', R='AG', Y='TC', K='TG', S='CG', H='ATC', D='ATG', V='AGC', B='CTG', N='ATCG') def expanded(string, expansions=multis): result = '' for pos, char in enumerate(string): if char in multis: break else: yield string raise StopIteration parts = multis[char] prelude, string = string[:pos], string[pos+1:] for expansion in expanded(string, multis): for middle in parts: yield prelude + middle + expansion --Scott David Daniels Scott.Daniels at Acm.Org From ianb at colorstudy.com Sat Dec 4 23:12:36 2004 From: ianb at colorstudy.com (Ian Bicking) Date: Sat, 04 Dec 2004 22:12:36 -0600 Subject: pre-PEP generic objects In-Reply-To: <5E6sd.505685$D%.420757@attbi_s51> References: <5E6sd.505685$D%.420757@attbi_s51> Message-ID: <41B28AB4.80902@colorstudy.com> Steven Bethard wrote: > Ian Bicking wrote: > >> class bunch(object): >> def __init__(self, **kw): >> for name, value in kw.items(): >> # IMPORTANT! This is subclass friendly: updating __dict__ >> # is not! >> setattr(self, name, value) > > > Good point about being subclass friendly... I wonder if there's an easy > way of doing what update does though... Update (and therefore __init__) > allows you to pass in a Bunch, dict, (key, value) sequence or keyword > arguments by taking advantage of dict's update method. Is there a clean > way of supporting all these variants using setattr? class bunch(object): def __init__(self, __seq=None, **kw): if __seq is not None: if hasattr(__seq, 'keys'): for key in __seq: setattr(self, key, __seq[key]) else: for name, value in __seq: setattr(self, name, value) for name, value in kw.items(): setattr(self, name, value) That should match dict.update, at least from the 2.4 help(dict.update). I'm not sure that will work for updating from a bunch object; also, bunch objects could have a 'keys' attribute without being dictionaries. Do you get attributes from non-iterables through their __dict__? I don't care for that at all. Are bunch objects iterable? -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From ville at spammers.com Wed Dec 1 09:24:12 2004 From: ville at spammers.com (Ville Vainio) Date: 01 Dec 2004 16:24:12 +0200 Subject: Semaphore or what should I use? References: Message-ID: >>>>> "Bastian" == Bastian Hammer writes: Bastian> Now I have to make sure, that both threads are Bastian> synchronal, 1 thread edits something and the other is Bastian> blocked until the first thread is ready. Bastian> Isn?t it a good idea to do this with a semaphore? Semaphore will do, but this is a classical use case for threading.Lock. There should be lots of stuff regarding locks (or more googleably, "mutexes") on the net. -- Ville Vainio http://tinyurl.com/2prnb From caleb1 at telkomsa.net Tue Dec 7 22:56:09 2004 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Tue, 07 Dec 2004 22:56:09 -0500 Subject: Import a module without executing it? References: Message-ID: Hi You could just parse the model file. Off the top of my head *** f = open('ModuleYouWantToExamine.py','r') for i in f: if i.find('def ') > -1: print 'Found a function!: '+i.replace('def ','') f.close() *** You would have to build this up for a more complete examination. Of course, one of the guru's around here should be able to give you guidance regarding actually parsing the file with the interpreter (not executing) and building a dict or something with all the different types of constructs. That's not me :) > > I want to be able to import this module so I can see "ah ha, this module > defines a function called 'test'", but I don't want the code at the > bottom executed during the import. > > Thanks > > Take care, > Jay From fredrik at pythonware.com Tue Dec 14 15:01:44 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Dec 2004 21:01:44 +0100 Subject: Python 3.0 References: <41BF176D.8010909@us-hampton.mail.saic.com> Message-ID: Edward C. Jones wrote: > You are not dumb. Many search phrases are obvious if and only if you have already seen them. or typed them, in this case (did you read the subject before posting? ;-) From fredrik at pythonware.com Sun Dec 5 06:24:44 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 5 Dec 2004 12:24:44 +0100 Subject: Power with modulu References: Message-ID: Roie Kerstein wrote: > I want to compute a**b%c for very long numbers. > Computing a**b and then applying modulu is not practical, since it takes > ages. > There is a built-in optional parameter to the long.__pow__(a,b[,modulu]), > and it works well. > My question is: How can I write it is a form of an expression, like a**b? if you look up __pow__ in the documentation, you'll find that it explains that __pow__ is used to implement the built-in pow() function: http://docs.python.org/lib/built-in-funcs.html#l2h-54 in other words, pow(a, b, c) does what you want. From sigu4wa02 at sneakemail.com Wed Dec 22 12:22:15 2004 From: sigu4wa02 at sneakemail.com (Zhang Le) Date: 22 Dec 2004 09:22:15 -0800 Subject: extract news article from web Message-ID: <1103736135.209100.28900@z14g2000cwz.googlegroups.com> Hello, I'm writing a little Tkinter application to retrieve news from various news websites such as http://news.bbc.co.uk/, and display them in a TK listbox. All I want are news title and url information. Since each news site has a different layout, I think I need some template-based techniques to build news extractors for each site, ignoring information such as table, image, advertise, flash that I'm not interested in. So far I have built a simple GUI using Tkinter, a link extractor using HTMLlib to extract HREFs from web page. But I really have no idea how to extract news from web site. Is anyone aware of general techniques for extracting web news? Or can point me to some falimiar projects. I have seen some search engines doing this, for example:http://news.ithaki.net/, but do not know the technique used. Any tips? Thanks in advance, Zhang Le From harold.fellermann at upf.edu Tue Dec 21 10:26:22 2004 From: harold.fellermann at upf.edu (harold fellermann) Date: Tue, 21 Dec 2004 16:26:22 +0100 Subject: Keyword arguments - strange behaviour? In-Reply-To: <1103640442.940168.246130@c13g2000cwb.googlegroups.com> References: <1103622331.247762.161750@f14g2000cwb.googlegroups.com><11036371 76.450940.243500@c13g2000cwb.googlegroups.com> <1103640442.940168.246130@c13g2000cwb.googlegroups.com> Message-ID: Hi, I cannot see any strange behavior. this code works exacly as you and I suspect: >>> def otherfunction(x) : ... return x ... >>> def function(arg=otherfunction(5)) : ... return arg ... >>> function(3) 3 >>> function() 5 Or is this not what you excepted? - harold - On 21.12.2004, at 15:47, brian.bird at securetrading.com wrote: > def function(arg=otherfunction(value)): > return arg > > My expectation would have been that otherfunction(value) would be > called if (and only if) the arg keyword parameter was missing from the > function() call (ie. the optional value is evaluated the lazy way). > Also, otherfunction would be called each and every time this function() > is called without the arg keyword. (At least, I would have assumed this > before today) > > Still, I can see why it's been implemented the way it has, it just > seems a shame there isn't a neat shortcut to default lots of optional > arguments to new mutable objects. And since I'm not the only one to > fall into this trap it makes me wonder why the default behaviour isn't > made to be what most people seem to expect? > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- Freunde, nur Mut, L?chelt und sprecht: Die Menschen sind gut -- Blo? die Leute sind schlecht. -- Erich K?stner From devries at idolstarastronomer.com Fri Dec 17 15:05:55 2004 From: devries at idolstarastronomer.com (Christopher De Vries) Date: 17 Dec 2004 12:05:55 -0800 Subject: Email filters in python References: Message-ID: <1103312697.527385.23210@f14g2000cwb.googlegroups.com> I use fetchmail in daemon mode and have procmail set up to filter my email through bogofilter (http://bogofilter.sourceforge.net/). As for outgoing mail postfix, exim, and sendmail are popular. From my laptop I do use a python script to cache mail my mail when I'm not connected. I then use a script which sends my email over ssh to my work computer which uses sendmail to send it all out. I discuss those scripts at http://miyu.idolstarastronomer.com:8080/cgi-bin/cgiwrap/devries/blosxom.cgi/2004/04/27#laptop-mail and they are written in python. From charlie at ezweave.com Fri Dec 17 18:58:09 2004 From: charlie at ezweave.com (Charlie Taylor) Date: Fri, 17 Dec 2004 15:58:09 -0800 Subject: Is this a good use for lambda Message-ID: <20041217235613.1A1761E4004@bag.python.org> I find that I use lambda functions mainly for callbacks to things like integration or root finding routines as follows. flow = integrate(lambda x: 2.0*pi * d(x)* v(x) * sin(a(x)),xBeg, xEnd) root = findRoot(xBeg, xEnd, lambda x: y2+ lp*(x-x2) -wallFunc( x )[0], tolerance=1.0E-15) I have tried using named functions instead of using lambda functions, however, I always end up with a convoluted, hard to follow mess. Is there a better solution than a lambda in the above situations? From ialbert at mailblocks.com Mon Dec 13 14:21:05 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Mon, 13 Dec 2004 14:21:05 -0500 Subject: Performance (pystone) of python 2.4 lower then python 2.3 ??? In-Reply-To: References: Message-ID: Lucas Hofman wrote: > Anyone who understands what is going on? It is difficult to measure a speedup that might be well within your measurement error. Run the same pystone benchmark repeatedly and see what variation you get. Istvan. From steve at holdenweb.com Thu Dec 30 17:28:47 2004 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Dec 2004 17:28:47 -0500 Subject: need some help with threading module... In-Reply-To: <1104434798.220189.173060@z14g2000cwz.googlegroups.com> References: <41cf2610$0$791$8fcfb975@news.wanadoo.fr> <41cf373e$0$786$8fcfb975@news.wanadoo.fr> <1104102769.321923.4140@z14g2000cwz.googlegroups.com> <41d0515b$0$30648$8fcfb975@news.wanadoo.fr> <1104178961.065566.7660@z14g2000cwz.googlegroups.com> <41d3dc20$0$29646$8fcfb975@news.wanadoo.fr> <1104431262.457172.295520@c13g2000cwb.googlegroups.com> <1104434798.220189.173060@z14g2000cwz.googlegroups.com> Message-ID: <%l%Ad.64380$Jk5.15646@lakeread01> M.E.Farmer wrote: > Steve Holden wrote: > [snip] > >>Could be the OP is using Cygwin, which won't support threading by >>default and will give very confusing results > > > Thanks Steve, > Well your guess was better then mine :) > I didn't know Cygwin did not support threads by default , I will have > to remember that. > Why do you suppose he is having problems with this on Linux? > I am not on a Linux box to test it. > M.E.Farmer > I believe he said it runs under Linux but not under Windows. Since you (?) showed it does work under Windows, I guessed Cygwin. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From gandalf at geochemsource.com Mon Dec 6 09:34:36 2004 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Mon, 6 Dec 2004 15:34:36 +0100 Subject: byte code generated under linux ==> bad magic number under windows In-Reply-To: <200412060800.37358.philippecmartin@sbcglobal.net> References: <200412060800.37358.philippecmartin@sbcglobal.net> Message-ID: <13254757.20041206153436@geochemsource.com> > I understand from my reading that a .pyc generated by python anywhere should > run anywhere else - is that true ? > If I generate 'compile.all' a pyc with python 2.3.3 under Linux, I get a 'bad > magic number' trying to execute it under windows (2.4). > What am I doing wrong ? You should use the same python versions. > are the pyc plateform dependant ? and if so must I generate one version for > each version of Linux, windows ...... ? No, it is not platform dependent, but it is version dependent. Best, Laci 2.0 mailto:gandalf at geochemsource.com web:http://designasign.biz From fredrik at pythonware.com Mon Dec 6 12:49:35 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 6 Dec 2004 18:49:35 +0100 Subject: PIL and antialiasing problem References: <41aefbb0$0$1060$db0fefd9@news.zen.co.uk> <1113461438.20041202130455@geochemsource.com> Message-ID: Laszlo Zsolt Nagy wrote: > Statement: Sometimes PIL is better than Adobe Photoshop. :-) > > I also found these with the aid of the wonderful dir() function: > > MinFilter, MaxFilter, MedianFilter, ModeFilter, RankFilter, BuiltInFilter > > They do not have a docstring and they are not documented in the > handbook. I'm curious what they do exactly. The others (like BLUR, EMBOSS, > CONTOUR etc.) are documented very well. I wonder why is that. they were experimental (and some of them were slightly broken, iirc) in 1.1.4. they're all officially supported in 1.1.5: http://www.pythonware.com/library/pil/handbook/imagefilter.htm From pierre.barbier at cirad.fr Mon Dec 6 03:23:16 2004 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Mon, 06 Dec 2004 09:23:16 +0100 Subject: Semaphore or what should I use? In-Reply-To: References: <41aef9ea$0$18874$636a15ce@news.free.fr> Message-ID: <41b4169c$0$12306$626a14ce@news.free.fr> Sergei Organov a ecrit : > Pierre Barbier de Reuille writes: > > >>Ville Vainio a ecrit : >> >>>>>>>>"Bastian" == Bastian Hammer writes: >>> >>> Bastian> Now I have to make sure, that both threads are >> >>> Bastian> synchronal, 1 thread edits something and the other is >>> Bastian> blocked until the first thread is ready. >>> Bastian> Isn't it a good idea to do this with a semaphore? >> >>>Semaphore will do, but this is a classical use case for >>>threading.Lock. >>> >>>There should be lots of stuff regarding locks (or more googleably, >>>"mutexes") on the net. >>> >> >> >>I don't agree. Mutexes (or locks) are best suited for critical sections (ie. >>sections that cannot be run by many thread at the same time). > > > Please don't add even more confusion to the issue. Mutex conceptually is > designed to be used for MUTual EXclusion of access to a resource (e.g., > a peace of data). While critical section could be implemented using > mutex, the mutex itself is more general concept. Besides, the rule of > thumb using mutexes is: "protect data, not program code." > > My answer to OP's question is: use either lock (mutex) or semaphore. > I'd probably use semaphore as mutexes are usually optimized for the case > when contention probability is low (i.e., they usually shouldn't be locked > for a long time). > My point is : semaphore is more complex than what he needs. Event are simpler and just do what he needs : block one thread until another one finished some jobs and launchs the event (have a look at my example). Afterward, I agree that the concept of mutex is the most general : you can implement every other kind of lock using just mutexes. Pierre From db3l at fitlinxx.com Mon Dec 20 12:32:13 2004 From: db3l at fitlinxx.com (David Bolen) Date: 20 Dec 2004 12:32:13 -0500 Subject: threading priority References: <1103327386.094817.115770@f14g2000cwb.googlegroups.com> Message-ID: Peter Hansen writes: > alecwy at gmail.com wrote: > > I googled as suggested, and the answer isn't crystal clear. My > > impression is that the problem is that a python thread must acquire the > > GIL in order to execute, and the strategy for deciding which thread > > should get the GIL when multiple threads are waiting for it is not > > based on priority. Is that correct? > > That's basically correct. I don't actually know what > the strategy is, though I suspect it's either not > formally documented or explicitly not defined, though > for a given platform there may be some non-arbitrary > pattern... > (...) I expect the Python interpreter has little to say over thread prioritization and choice of execution, although it does impose some granularity on the rate of switching. The GIL itself is implemented on the lower layer lock implementation, which is taken from the native threading implementation for the platform. Therefore, when multiple Python threads are waiting for the GIL, which one is going to get released will depend on when the underlying OS satisfies the lock request from the threads, which should be based on the OS thread scheduling system and have nothing to do with Python per-se. I do believe you are correct in that the Python GIL prevents thread pre-emption by the OS (because all other Python threads are waiting on the GIL and not in a running state), but the actual act of switching threads at a switching point (sys.setcheckinterval()) would be an OS only decision, and subject to whatever standard platform thread scheduling rules were in place. So if you were to use a platform specific method to control thread priority, that method should be honored by the Python threads (subject to the granularity of the system check interval for context switches). For example, here's a Windows approach that fiddles with the thread priority: - - - - - - - - - - - - - - - - - - - - - - - - - import threading import ctypes import time w32 = ctypes.windll.kernel32 THREAD_SET_INFORMATION = 0x20 THREAD_PRIORITY_ABOVE_NORMAL = 1 class DummyThread(threading.Thread): def __init__(self, begin, name, iterations): threading.Thread.__init__(self) self.begin = begin self.tid = None self.iterations = iterations self.setName(name) def setPriority(self, priority): if not self.isAlive(): print 'Unable to set priority of stopped thread' handle = w32.OpenThread(THREAD_SET_INFORMATION, False, self.tid) result = w32.SetThreadPriority(handle, priority) w32.CloseHandle(handle) if not result: print 'Failed to set priority of thread', w32.GetLastError() def run(self): self.tid = w32.GetCurrentThreadId() name = self.getName() self.begin.wait() while self.iterations: print name, 'running' start = time.time() while time.time() - start < 1: pass self.iterations -= 1 if __name__ == "__main__": start = threading.Event() normal = DummyThread(start, 'normal', 10) high = DummyThread(start, 'high', 10) normal.start() high.start() # XXX - This line adjusts priority - XXX high.setPriority(THREAD_PRIORITY_ABOVE_NORMAL) # Trigger thread execution start.set() - - - - - - - - - - - - - - - - - - - - - - - - - And the results of running this with and without the setPriority call: Without: With: normal running high running high running high running normal running high running high running high running normal running normal running high running high running normal running high running high running high running normal running high running high running normal running normal running high running high running high running normal running normal running high running normal running normal running normal running high running normal running normal running normal running high running normal running normal running normal running high running normal running I'm not entirely positive why the normal thread gets occasionally executed before the high thread is done. It might be that the interpreter is actually releasing the GIL in the code I've written for the thread's run() (maybe during the I/O) which opens up an opportunity, or it may be that Windows is boosting the other thread occasionally to avoid starvation. So I expect the normal thread is getting occasional bursts of bytecode execution (the syscheckinterval). But clearly the OS level prioritization is largely driving things. -- David From adalke at mindspring.com Wed Dec 1 17:06:09 2004 From: adalke at mindspring.com (Andrew Dalke) Date: Wed, 01 Dec 2004 22:06:09 GMT Subject: Identifying exceptions that can be raised In-Reply-To: References: <6Rknd.6671$%M4.4203@trndny08> Message-ID: Tim Jarman wrote: > OK, I'm an arts graduate[1] so this is probably a really stupid > question, but what kind(s) of science would be non-experimental? Astronomy. Archaeology. Paleontology. Seismology. Cosmic ray research. There have been a few experiments in environmental science, like tenting a small island off the coast of Florida to kill all the insects then watch how they are reintroduced. Geology, unless you count the material science work used to understand how minerals change under pressure and heat, or including mining as part of geology. Andrew dalke at dalkescientific.com From max at alcyone.com Tue Dec 21 14:20:42 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 21 Dec 2004 11:20:42 -0800 Subject: Boo who? (was Re: newbie question) In-Reply-To: References: <1103503985.015510.24680@z14g2000cwz.googlegroups.com><1103579296.951417.320000@c13g2000cwb.googlegroups.com> Message-ID: Michael Hoffman wrote: > And Python uses the very best features of ABC. What's your point? ;-) > > Not that I've ever even used Prothon, although I thought the way the > implementor dropped it into conversation was non-obnoxious. There could > be a valuable lesson here. I'm not talking about the way the implementor "dropped it into conversation," I'm talking about the way the language is beyond sold. The blurb on the Web site mentions this as a selling point, and as a subtitle for "The Spry Computer Language": http://spry-lang.org/ Certainly Python mentions ABC in background information on where Python comes from. But Python doesn't mention this as the first sentence in describing what its virtues are! -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis I have not yet begun to right! -- John Paul Jones From aleaxit at yahoo.com Tue Dec 21 00:13:29 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 20 Dec 2004 21:13:29 -0800 Subject: expression form of one-to-many dict? References: <863by22gqs.fsf@guru.mired.org> <41c64888.526311586@news.oz.net> <86fz201q3t.fsf@guru.mired.org> Message-ID: <1gp42qp.ljmt895881xvN%aleaxit@yahoo.com> Mike Meyer wrote: > bokr at oz.net (Bengt Richter) writes: > > > On Sun, 19 Dec 2004 21:29:27 +0100, "Fredrik Lundh" wrote: > > (or maybe a restricted unquote_arg function for better safety). > > E.g., double back-tick is a syntax error now, so you could write > > > > def ternary(c, ``t, ``f): > > if c: return eval(t) > > else: return eval(f) > > Actually, I think it would be more pythonic if the indication of > non-evaluation happened at the function invocation instead of the > function definition. Having it at the function definition makes it As in, say, calling x = ternary(c, lambda:t, lambda:f) ? The 'lambda:' is a (not nice-looking, but...) "indication of non-evaluation"... or am I misundertanding what you're saying? Of course, the implementation of ternary could then use 'apply' rather than 'eval' (or, simply call t() or f() as appropriate, identically;-). Alex From g.belyh at grsu.by Thu Dec 2 06:37:24 2004 From: g.belyh at grsu.by (Belyh G.P.) Date: Thu, 02 Dec 2004 13:37:24 +0200 Subject: PIL and antialiasing problem In-Reply-To: <1948019384.20041202120357@geochemsource.com> References: <1948019384.20041202120357@geochemsource.com> Message-ID: <41AEFE74.8080708@grsu.by> Laszlo Zsolt Nagy wrote: >Hi all, > >I have a little problem with PIL. I need to display images in a >browser (thumbnails) (this is the selector window). >I also need the original version of the image to be displayed in a >Java applet. > >One example: > >thumbnail: http://designasign.biz/applet/GIF_Small/AIRCRAFT/a10per.png >original: http://designasign.biz/applet/GIF/AIRCRAFT/a10per.png > >I made the thumbnail from the original image using PIL this way: > > > im = Image.open(fullpath) > try: > im.thumbnail(THUMBSIZE,Image.ANTIALIAS) > im.save(thumbpath) > finally: > del im > > >If I do not use ANTIALIAS, then I get this: > >http://designasign.biz/tmp/a10per.png > >With the ANTIALIAS-ed version, the problem is that you cannot see the >lines - they are very light gray, almost invisible. I have many cliparts >with thin lines. However, I also have many cliparts like this: > >http://designasign.biz/applet/GIF/AFRICA/angel03.png > >I tried to posterize or darken the images but I could not find a good >solution. (I also tried to count the number of colors in the image and >use this info.) Can you suggest an image filter and/or method that creates >darker black lines from the original thin lines? Also it would be >great to have it working with those colorful smudged images. It will >be terribly slow to separate them by hand. There are almost 15000 of >them... > Photoshop cann't normaly resize http://designasign.biz/applet/GIF/AIRCRAFT/a10per.png too. But when I resize this image with bgcolor=white all done well. Maybe PIL needed image with bgcolor for normal resize. From Michael.Foord at tbsmerchants.co.uk Wed Dec 15 07:50:47 2004 From: Michael.Foord at tbsmerchants.co.uk (Michael Foord) Date: Wed, 15 Dec 2004 12:50:47 +0000 Subject: ANN: Python Test Environment Message-ID: <41C03327.1090900@tbsmerchants.co.uk> Well sort of....... Highly experimental - I'm interested in ways of improving this. http://www.voidspace.org.uk/atlantibots/pythonutils.html#testenv I've created a script that will build a 'test environment'. Windoze(tm) only as it uses py2exe. It scans your Python\Lib folder (configurable) and builds a script that *fakes* an import of every module (along with some boilerplate). This, more or less, amounts to everything in the standard lib. There is then a normal setup.py to turn this into a python executable. The result, is an executable that will run any python script. It gives sensible values for sys.path, sys.argv and __file__. This is useful for various purposes : 1) Easily have test environments for multiple versions of python - to test your scripts. 2) Run any python script on a machine without python installed. 3) Deploying several scripts using py2exe - one build fits all. Usage : testenv arg1 arg2... Which should be the equivalent of : python arg1 arg2... Sample output : (Built with Python 2.4 - then 2.3 - prints sys.version first) ######## D:\New Folder\testenv>testenv test.py arg1 arg2 arg3 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] sys.path = ['D:\\New Folder\\testenv\\library.zip', 'D:\\New Folder\\testenv', ' D:\\New Folder\\testenv'] sys.argv = ['D:\\New Folder\\testenv\\test.py', 'arg1', 'arg2', 'arg3'] import Tkinter # succeeded import dummylibrary # succeeded D:\New Folder\testenv> ########## D:\Python Projects\modules in progress\py2exe-testenv\dist>testenv test.py arg1 arg2 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] sys.path = ['D:\\Python Projects\\modules in progress\\py2exe-testenv\\dist\\lib \\shared.zip', 'D:\\Python Projects\\modules in progress\\py2exe-testenv\\dist', 'D:\\Python Projects\\modules in progress\\py2exe-testenv\\dist'] sys.argv = ['D:\\Python Projects\\modules in progress\\py2exe-testenv\\dist\\tes t.py', 'arg1', 'arg2'] import Tkinter # succeeded import dummylibrary # succeeded D:\Python Projects\modules in progress\py2exe-testenv\dist> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ I'm sure this can be improved in lots of ways - but already useful to me. Comments and suggestions for improvements welcomed. Thanks go to Bruno Thoorens for his suggestions so far. Currently has issues collecting 'sub-packages', but I *think* only the same issues that py2exe has. Extra modules can just be included somewhere on sys.path. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From ishwor.gurung at gmail.com Fri Dec 3 05:45:04 2004 From: ishwor.gurung at gmail.com (Ishwor Gurung) Date: Fri, 3 Dec 2004 15:45:04 +0500 Subject: window size in IDLE In-Reply-To: <41B0402E.9040905@seznam.cz> References: <34534aed0412030207672ab6cb@mail.gmail.com> <41B0402E.9040905@seznam.cz> Message-ID: <34534aed041203024522cafd7d@mail.gmail.com> hi kosina although i am new to this list as well, please CC to the python list as well. That way not only 'we' but everyone benefits. :) On Fri, 03 Dec 2004 11:30:06 +0100, gen2n wrote: > Thanks a lot. Could you help me once more with beginners question? > In IDLE, when saving a file, I have to always add .py to to name. Otherwise > it didnt work then. > Could it also be somehow automatically? I don't really understand what you mean by 'automatically' but i tried the following in my machine : test ( i didn't put .py as extension to test) ***** print "Hello"; Then at the prompt i did python test hello It seems that it works for me both at the prompt (using Python interpreter as well as in IDLE's Run > Run Module (F5) :) > I have IDLE 1.0.2. IDLE 1.1 is pretty good. If you have chance grab it :) [snip] cheers, Ishwor From dtcaciuc at sfu.ca Sun Dec 12 19:42:54 2004 From: dtcaciuc at sfu.ca (Dimitri Tcaciuc) Date: Mon, 13 Dec 2004 00:42:54 GMT Subject: Python mascot proposal In-Reply-To: <1102895359.091934.275690@f14g2000cwb.googlegroups.com> References: <1102895359.091934.275690@f14g2000cwb.googlegroups.com> Message-ID: Luis M. Gonzalez wrote: > Hey Dimitri, > > I completely agree with you in that Python needs once for all a cool > logo. > I like your design very much, but I have a few thoughts about it: > > 1) I think that Python's logo should reflect its power. > If we use a mascot as its image, we would be giving the wrong idea: > that Python is a "toy" language, instead of a very good alternative to > other mainstream languages. > > 2) We should also bear in mind Guido's oppinion about using a snake for > identifying Python. > > 3) And finally, we should consider it very seriously. Image is not > everything, but it is very important for "marketing" a product. I'm > sure that if Java didn't have a cool name and a cool logo, it wouldn't > have been that succesfull. > > I don't mean to sound like I'm rejecting your idea. I really like it > alot, and it is an excellent mascot. > It's just that I wouldn't use a mascot... I'd rather use a more > "killer" image. > Something that reflects power and excellence. > > What do you think? > Hehe, well, looking at linux, Tux is definitely not a killer type, yet it became very popular. BSD devil is kind of a cutsy thing, yet it proved to be pretty popular as well. Not sure if the word 'marketing' applies here, but I agree that the logo could probably be 'more serious' than what I proposed above. I'll think about that one some more. Cheers, From bearophileHUGS at lycos.com Thu Dec 23 04:49:35 2004 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 23 Dec 2004 01:49:35 -0800 Subject: Optional Static Typing Message-ID: <1103795375.843649.286620@c13g2000cwb.googlegroups.com> Adding Optional Static Typing to Python looks like a quite complex thing, but useful too: http://www.artima.com/weblogs/viewpost.jsp?thread=85551 I have just a couple of notes: Boo (http://boo.codehaus.org/) is a different language, but I like its "as" instead of ":" and "->", to have: def min(a as iterable(T)) as T: Instead of: def min(a: iterable(T)) -> T: Sometimes it can be useful to mix parts with static typing and parts without it in the same module (because dynamic typing is very useful sometimes), but some other times you want to be sure to have a full typed and checked module. So maybe a kind of compiler directive (like the # used to define encoding) can be used to define a module fully typed and fully checked by a pychecker-like. (A module with static typing can be very useful for a "true" python compiler too.) Bear hugs, bearophile From toforum at ifrance.com Mon Dec 6 20:52:14 2004 From: toforum at ifrance.com (To Forum) Date: Tue, 7 Dec 2004 02:52:14 +0100 Subject: Python Boost, help Message-ID: <41b50ccf$0$32324$79c14f64@nan-newsreader-06.noos.net> Hi, My problem is the following 1/ I install Python 2.4 at D:\Programs\Python24 using the binary file from www.python.org 2/ following the document from the boost.org I type the command >bjam "-sTOOLS=vc-7_1 --with-python-root=D:\Programs\Python24" stage But I receive the following error > --with-python-root=D:\Programs\Python24-tools.jam: Invalid argument I think I do something wrong here. If I use the simple command >bjam "-sTOOLS=vc-7_1 " stage I get the message: >skipping Boost.Python ..... Can someone show me how can I install Boost.Python correctly? TF From alecwy at gmail.com Fri Dec 17 18:49:46 2004 From: alecwy at gmail.com (alecwy at gmail.com) Date: 17 Dec 2004 15:49:46 -0800 Subject: threading priority In-Reply-To: References: Message-ID: <1103327386.094817.115770@f14g2000cwb.googlegroups.com> I googled as suggested, and the answer isn't crystal clear. My impression is that the problem is that a python thread must acquire the GIL in order to execute, and the strategy for deciding which thread should get the GIL when multiple threads are waiting for it is not based on priority. Is that correct? -Alec Peter Hansen wrote: > Joe Wong wrote: > > > Hi, Is there any way to increase/decrease a thread priority in Python? > > Not really, and as Python does not use a "free-threading" model, > it wouldn't work as you'd like anyway. > > Search Google for "Python GIL" or "Global Interpreter Lock" and you > should learn enough to see why this is so. > > -Peter From peter at engcorp.com Fri Dec 10 15:30:40 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 10 Dec 2004 15:30:40 -0500 Subject: thread/queue bug In-Reply-To: References: Message-ID: phil wrote: > You know, I get this all the time on language support groups. > All of my Linux support groups, if they don't understand, say > why and ask for elaboration. Wow, amazing! Imagine that... asking for elaboration when someone posts unclear confusing questions and extraneous information. The noive! I also find it remarkable that so many different people are all doing the same thing to you. It must be a conspiracy. Certainly not a problem with, say, you... From godoy at ieee.org Thu Dec 30 11:59:19 2004 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Thu, 30 Dec 2004 14:59:19 -0200 Subject: PyQT installation References: <1104370062.562575.88620@f14g2000cwb.googlegroups.com> <1104417268.153983.71970@z14g2000cwz.googlegroups.com> <8SVAd.64014$Jk5.26087@lakeread01> Message-ID: <6140126.OigETEp1Z6@strongwill.g2ctech> Steve Holden, Quinta 30 Dezembro 2004 14:13, wrote: > If that is a real *never* then Qt just fell behind in the "what's the > best GUI platform" stakes. It'd be a shame to lose PyQT, but if there's > no way to migrate it forwards it will atrophy and die. Have TrollTech > said they will never issue MSVC 7 binaries? "non-commercial" binaries he said... I hope it is just the non-commercial really, 'cause the look & feel of Qt is very nice. > Is there no way to use the free Microsoft toolchain to compile, or do > the language differences just make the whole deal too difficult (or is > there some other show-stopper that my ignorance prevents me from seeing?). Isn't it possible to compile everything with a free compiler? I'm not a Windows user, but... :-) -- Godoy. From mjackson at alumni.caltech.edu Fri Dec 3 15:23:31 2004 From: mjackson at alumni.caltech.edu (Mark Jackson) Date: 3 Dec 2004 20:23:31 GMT Subject: How did you learn Python? References: Message-ID: sjmachin at lexicon.net (John Machin) writes: > "Jeffrey Maitland" wrote in message news:... > > Well I would suggest the Python in a Nutshell and the Python Cookbook both > > by O'Reilly as references. They are great for a desktop reference and I > > check them first before I google/search else where for answers. Being they > > are reference books they or more on aide then a teaching device however I > > have learned from those books how to use certain standard classes, such as > > the re class for example. > > Somebody called O'Reilly taught you that Python has "standard > classes", one of which is "re"??? Hmmm, can't have been O'Reilly the > publisher; must have been O'Reilly the builder. Or possibly O'Reilly the pundit. Lucky he didn't tell you Python has falafels. -- Mark Jackson - http://www.alumni.caltech.edu/~mjackson You should always save hyperbole until you really need it. - Hobbes (Bill Watterson) From luke at tatooine.planet Wed Dec 1 17:36:45 2004 From: luke at tatooine.planet (Luke Skywalker) Date: Wed, 01 Dec 2004 23:36:45 +0100 Subject: Python Win32 Silent Install References: Message-ID: On Wed, 01 Dec 2004 17:15:38 -0500, Steve Holden wrote: >You are right about ActiveState, the copy you download from their web >site is licensed to prohibit redistribution. They might be prepared to >cut you a special license, but you'd have to ask them about that. Does it mean it's not allowed to build an application with ActiveState Python, and generate an installer that installs the whole thing, forcing users to go to ActiveState's web site and download the interpreter? Gee, that changes everything... Luke. From adam at cognitcorp.com Mon Dec 20 01:05:50 2004 From: adam at cognitcorp.com (Adam DePrince) Date: Mon, 20 Dec 2004 01:05:50 -0500 Subject: Writev In-Reply-To: References: Message-ID: <1103522750.14836.487.camel@localhost.localdomain> On Mon, 2004-12-20 at 00:30, Steven Bethard wrote: > Adam DePrince wrote: > > Many other programmers have faced a similar issue; cStringIO, > > ''.join([mydata]), map( file.write, [mydata]) are but some attempts at > > making this process more efficient by jamming the components to be > > written into a sequence. > > I'm obviously misunderstanding something because I can't figure out why > you would write: > > map(file.write, [mydata]) > > instead of > > file.write(mydata) No, you misunderstand. mydata is a metavariable symbolic for a long list of things that would be in that list. map( file.write, mydata ) where mydata is some really long list or iterator. > > Is your task to write a sequence/iterator of items into a file? I would > expect your example to look like: > > map(file.write, mydata) > > which I would write as: > > file.writelines(mydata) > > Could you explain a little more what your intent is here? file.writelines( seq ) and map( file.write, seq ) are the same; the former is syntactic sugar for the later. Writev is a neat abstraction in posix that allows the operating system to handle the gathering of data to be written instead of the application just in-case something in the hardware is smart enough to support scatter-gather I/O. With a dumb I/O device, either the user application (write) or the OS (writev) has the chore of gathering the data to be writen, concatenating it and sending it on its way. A lot of devices are smart enough to be handled a list of pointers and lengths and be told to "write this" to the device. In a sense, writev is a pretty close approximation to the API provided by a lot of high end disk and network controllers to the OS. The benefit is that you don't have to choose between these two evils: 1) Copying your strings so they are all in a line 2) Context switching to your OS a lot. Let us consider this straw man; the sequence that would be generated by: def numbers(): for x in range( 10000000 ): yield str( x ) You really don't want to say: write( ''.join(), numbers ) Nor do you want to say: map( write, numbers() ) Wouldn't it be nice to peal off the first 1000 items, tell the OS to write them, peal off the next 1000 items, etc etc ... and not even have to absorb the memcpy cost of putting them all together? Think of it as the later, without quite as much harassment of the underlying operating system. Lastly, my intent is to expose the writev system call simply because: * It is there. * It is sometimes useful. * If we get used to sharing our intent with the OS, the OS author might get used to doing something useful with this knowledge. Now you are probably thinking "but isn't this premature optimization." Yeah, it is, which is why we are up to version 2.4 without it. But I don't think it is premature anymore. There is one more time that writev would be beneficial ... perhaps you want to write a never ending sequence with a minimum of overhead? def camera(): while 1: yield extract_entropy( grab_frame() ) open( "/tmp/entropy_daemon_pipe", "w+" ).writev( camera(), 5 ) # 1/5 of the OS overhead, still get a fresh update every 5/30th of a second, assuming 30 FPS Adam DePrince From andreas at mtg.co.at Fri Dec 17 09:00:51 2004 From: andreas at mtg.co.at (Andreas Kostyrka) Date: Fri, 17 Dec 2004 15:00:51 +0100 Subject: Performance (pystone) of python 2.4 lower then python 2.3 ??? In-Reply-To: References: Message-ID: <1103292051.9602.1.camel@andi-lap> Ok, here are my results, all python Versions supplied by Debian: andreas at andi-lap:~> python1.5 /usr/lib/python1.5/test/pystone.py Pystone(1.1) time for 10000 passes = 1.33 This machine benchmarks at 7518.8 pystones/second andreas at andi-lap:~> python2.2 /usr/lib/python1.5/test/pystone.py Pystone(1.1) time for 10000 passes = 1.03 This machine benchmarks at 9708.74 pystones/second andreas at andi-lap:~> python2.3 /usr/lib/python1.5/test/pystone.py Pystone(1.1) time for 10000 passes = 0.73 This machine benchmarks at 13698.6 pystones/second andreas at andi-lap:~> python2.4 /usr/lib/python1.5/test/pystone.py Pystone(1.1) time for 10000 passes = 0.66 This machine benchmarks at 15151.5 pystones/second Run on a Knoppix/Debian based Duron 700 (Sony PCG-FX201 laptop). I guess there must be differences in how your pythons got compiled, even if you didn't specifies explicitly options. Andreas Am Mo, den 13.12.2004 schrieb Lucas Hofman um 17:09: > Hi, > > Just installed Python 2.4 on a machine (RH8.0 Linux) that also has python 2.3 > and python 2.2 installed. The latter came with the linux distribution, the other > are compiled from source tarballs. > > Comparing them gives the following unexpected result: > > [lucas at oslwb03 test]$ /usr/bin/python pystone.py > Pystone(1.1) time for 50000 passes = 1.86 > This machine benchmarks at 26881.7 pystones/second > [lucas at oslwb03 test]$ /usr/local/bin/python2.3 pystone.py > Pystone(1.1) time for 50000 passes = 1.22 > This machine benchmarks at 40983.6 pystones/second > > This is ok, a 52% speed increase, but: > > lucas at oslwb03 test]$ /usr/local/bin/python2.4 pystone.py > Pystone(1.1) time for 50000 passes = 1.31 > This machine benchmarks at 38167.9 pystones/second > > A 7% speed DECREASE??? According to the documentation it should be a 5% increase? > > The machine is a 3.0 GHz Xeon box. > > Both python 2.3 and 2.4 where configure without any options. > > Anyone who understands what is going on? > > Regards, Lucas -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Dies ist ein digital signierter Nachrichtenteil URL: From adam at cognitcorp.com Mon Dec 13 14:03:54 2004 From: adam at cognitcorp.com (Adam DePrince) Date: Mon, 13 Dec 2004 14:03:54 -0500 Subject: newbie questions In-Reply-To: References: <41ba6511$1@nntp.zianet.com> Message-ID: <1102964168.4015.18.camel@localhost.localdomain> On Mon, 2004-12-13 at 11:30, houbahop --> > thanks, very usefull answer. > > > > Immutable types (e.g. strings, numbers, tuples) are generally returned > > directly from functions, rather than returned as 'output parameters'. The > > ability to return multiple values easily (via "return a, b, c" & "x, y, z > > = myfunc()" generally eliminates the need for 'by reference' output > > parameters as used by C, C++, Java and the like. > > P.S. If you *really*, *really*, *really* want to fake output parameters, > > just wrap them in a list: > > return multiple values is ok, I usualy use a function only to return one > value, for exemple : value=IsSomething(), returning true, to include that in > an if statement : if (isSomething(blabla) ) ... but It's not a problem to > change that habit. and as I have read somewhere about python : "Explicit is > better than implicit" > > Dominique. I think your interpretation of the the "explicit vs. implicit" quote might be confusing in this case. Certainly: x = 0 def a(): something = 1 somethingelse = 2 global x x = something return somethingelse y = a() print x,y To say "we are explicitly setting X" in a is wrong. We are returning 1 and 2. We return 2 explicitly. We return 1 by side effect. If we want to explicitly return both, then: def a(): something = 1 somethingelse = 2 return something,somethingelse x,y = a() This makes the code clear and easy to understand. Navr? je ne pas r?pondre en fran?ais. - Adam DePrince From aleaxit at yahoo.com Sun Dec 26 15:32:46 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 26 Dec 2004 21:32:46 +0100 Subject: program in interactive mode References: <338iceF3s8qiiU1@individual.net> Message-ID: <1gpf7qp.c9e4w97cdazzN%aleaxit@yahoo.com> B.G.R. wrote: ... > numline=0 > for line in sys.stdin: > numline+=1 > workwithline(line) Consider the alternative: for numline, line in enumerate(sys.stdin): Nothing to do with your main program, but still neater... > that's ok, but if the user only does "./myprog.py" then I got to get into > interactive mode and show a prompt in every line expecting the user input > for that line. Problem is I don't know how to tell if I've been "piped" or sys.stdin.isatty() should serve you well. Alex From maxm at mxm.dk Mon Dec 20 15:44:34 2004 From: maxm at mxm.dk (Max M) Date: Mon, 20 Dec 2004 21:44:34 +0100 Subject: MIDI library recommendations, please? In-Reply-To: References: Message-ID: <41c73907$0$193$edfadb0f@dread12.news.tele.dk> Andrew Koenig wrote: > Are there widely used and recommended Python libraries that will let me > > 1) Interpret and generate MIDI messages easily? Yes. http://www.mxm.dk/products/public/pythonmidi > 2) Allow me to select and communicate with MIDI devices attached to my > computer? There are some project which does that on different platforms. But I am not aware how well they work. The best place to ask is probably on the Python Midi list at: http://sourceforge.net/mail/?group_id=113783 -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From someone at microsoft.com Sun Dec 12 12:48:30 2004 From: someone at microsoft.com (Jive) Date: Sun, 12 Dec 2004 17:48:30 GMT Subject: New versions breaking extensions, etc. References: <41BABC12.6080808@v.loewis.de> <41BC74A6.10104@v.loewis.de> Message-ID: "Martin v. L?wis" wrote in message news:41BC74A6.10104 at v.loewis.de... > Either VS.NET 2003 or VC++ .NET 2003 should do (although I don't know > anybody who owns the latter to be sure). The core issue is that it needs > a "native" C++ compiler (ie. not just managed C++), and that it needs > mscvcr71.dll. > Sorry if I'm being dense. If I had that DLL, why couldn't I use VC++ 6.0? It's still not clear to me exactly what's in each package. One would think there would be a more technical description on the MS web pages. From sf_kersteinroie at bezeqint.net Thu Dec 2 14:08:36 2004 From: sf_kersteinroie at bezeqint.net (Roie Kerstein) Date: Thu, 02 Dec 2004 21:08:36 +0200 Subject: Galois field Message-ID: I am looking for a python package that deals with galois fields. Does anybody know where can I find it? Thank in advance -- Best regards Roie Kerstein From fulimin_yuan at yahoo.com Fri Dec 3 16:31:08 2004 From: fulimin_yuan at yahoo.com (Limin Fu) Date: Fri, 3 Dec 2004 13:31:08 -0800 (PST) Subject: How is Python designed? In-Reply-To: Message-ID: <20041203213108.36025.qmail@web80908.mail.scd.yahoo.com> Thanks a lot for the explanations. So CPython used more or less the standard technique to implement the interpreter. Are there any other interpretation techniques? I guess many. But I'm quite new in this field and I couldn't find good references on internet about this. If there is anybody has such references, please send me some if you don't mind. I would be appreciative very much. Best, Limin --- Terry Reedy wrote: > > "Limin Fu" wrote in message > > news:20041203094617.9778.qmail at web80907.mail.scd.yahoo.com... > > To clarify, I mean the internal structure and > design > > of python interpreter. Any hint? Thanks. > > Ah... The interpreters (plural) are a separate issue > from the language > itself (a Python program is a list of Python > statements, etc). We'll > presume that you specifically mean the CPython > interpreter, as opposed to > Jython, Viper, Ironman, PyPy, Parrot, or the human > brain. For CPython: > > human or other source code generator ==> Python > source code > > CPython compile phase: > lexer ==> tokens > parser ==> ast tree > byte code generator ==> byte codes for Python > virtual machine > (see the Lib Ref chapter on the dis module for VM > commands) > > CPython runtime phase: > code evaluator ==> computations > (see source file ceval.c for the link between > byte codes and C > functions) > > CPython is currently both the reference > implementation and the most > commonly used implementation. Both facts could > change in the future, > possibly even with divergence between the two roles. > Since Python is meant > to be a practical computer language as well as an > abstract algorithm > language (for humans), a reference implementation is > needed to show that > proposed language features can be sensibly > implemented. > > Terry J. Reedy > > > > -- > http://mail.python.org/mailman/listinfo/python-list > __________________________________ Do you Yahoo!? Meet the all-new My Yahoo! - Try it today! http://my.yahoo.com From sizelji at insightbb.com Tue Dec 21 18:06:12 2004 From: sizelji at insightbb.com (Jim Sizelove) Date: Tue, 21 Dec 2004 23:06:12 GMT Subject: When was extended call syntax introduced? In-Reply-To: <1P1yd.64$4F.26@fe07.lga> References: <1P1yd.64$4F.26@fe07.lga> Message-ID: Edward K. Ream wrote: > Various documentation pages, e.g. > http://www.python.org/doc/2.3.3/lib/non-essential-built-in-funcs.html > state that the apply function has been deprecated since 2.3. > > Can anyone tell me when extended call syntax was actually introduced? > Neither googling nor brief checks of the 'What's new in Python' or the pep's > has turned up this information. Thanks. > > Edward > -------------------------------------------------------------------- > Edward K. Ream email: edreamleo at charter.net > Leo: Literate Editor with Outlines > Leo: http://webpages.charter.net/edreamleo/front.html > -------------------------------------------------------------------- > > It looks like the extended call syntax was added in Python 2.0. See "What's New in Python 2.0, 9.1 Minor Langage Changes" at http://www.amk.ca/python/2.0/new-python.html Jim From roy at panix.com Sat Dec 18 09:04:29 2004 From: roy at panix.com (Roy Smith) Date: Sat, 18 Dec 2004 09:04:29 -0500 Subject: Why are tuples immutable? References: <20041217193502.1029.1533501037.divmod.quotient.12346@ohm> Message-ID: Nick Coghlan wrote: [quoting from the Reference Manual] > If a class defines mutable objects and implements a __cmp__() > or __eq__() method, it should not implement __hash__(), since the dictionary > implementation requires that a key's hash value is immutable (if the object's > hash value changes, it will be in the wrong hash bucket)." I know that's what it says, but I don't think it's good advice. All that is really required is that __hash__() always returns the same value over the lifetime of the object, and that objects which __cmp__() the same always return the same hash value. That's it. That's all a dictionary cares about. Making the object immutable is certainly the easiest way to achieve that goal, but it's not the only way. From P at draigBrady.com Tue Dec 14 12:33:34 2004 From: P at draigBrady.com (P at draigBrady.com) Date: Tue, 14 Dec 2004 17:33:34 +0000 Subject: RegEx: find all occurances of a single character in a string In-Reply-To: <41BF1F97.1070300@draigBrady.com> References: <41BF1F97.1070300@draigBrady.com> Message-ID: <41BF23EE.1040805@draigBrady.com> P at draigBrady.com wrote: > import re > s='abcdatraataza' > r=re.compile('(? a_list=[ match.start() for match in re2.finditer(s) ] > Oops, tested this time: ---------------------------- import re def index_letters(s,l): regexp='(? Message-ID: Jp Calderone wrote: > Dictionaries support mutable keys just find. What they don't >support is unhashable keys. > > For some objects, this is an important distinction: lists are >mutable but not hashable. Of course, you could subclass list to make a mutable, hashable list: class HashableList (list): def __hash__ (self): return sum (self) myList = HashableList ((1, 2, 3)) d = {myList: "fred"} print d print d [myList] myList.append (0) print d [myList] myList.append (42) try: print d [myList] except KeyError: print "didn't work because the hash changed" From steve at holdenweb.com Tue Dec 28 09:21:49 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 28 Dec 2004 09:21:49 -0500 Subject: [Fwd: Re: DB-API format string conventions] Message-ID: <41D16BFD.3000802@holdenweb.com> [posted after mailing response in error] Craig Ringer wrote: > On Tue, 2004-12-28 at 21:16, Steve Holden wrote: > > >>>So ... anybody for a DB-API 2.1 with mandatory pyformat support and a >>>tuple dbmodule.paramstyles for supported styles? >> >> >>Well, you can certainly put me down as supporting less variability in >>allowed paramstyles, to the extent that it would allow much more >>application portability. >> >>However, you might not be aware that the reason that variability was >>included in the first place is to allow Python module authors to take >>advantage of features already available in the various underlying >>database platform support code - Oracle, for example, already supports >>numbered access (:1), and so on. > > > I'm not actually against the number of choices available, I'm just > concerned that there is currently no _single_ choice that can be > guaranteed to work, and that it's hard to identify all styles a given > API supports. > > Of course, even if one does confine ones self strictly to what can be > guaranteed to work in the DB API, there are a multitude of differences > in database SQL syntax and extensions to worry about. That is an issue > any programmer will face - not just a Python DB-API 2.0 user, and I see > it as a separate issue. Tackling that would involve building a DB > abstraction layer like the various query builders available for Java - a > very interesting, but much bigger, job that I'm not even remotely > interested in looking at right now ;-) > Though you might care to look at Chapter 11 of "Python Web Programming" when you have time, where I had a go at such an abstraction layer. It was moderately successful across a number of platforms. > >>So be aware that you are asking the various module authors for >>significant amounts of work, which may not be forthcoming under all >>circumstances. > > > That's true, and something I'm keeping in mind. I'd be quite happy to > implement the required changes for modules I'm familar with to help with > that issue. > That's good. > That said, if pyformat was chosen as the required style it might not be > too big a job at all. Many modules already support pyformat though not > all advertise the fact, and for them it may be as simple as bumping the > API version to 2.1 and adding a module-level var containing a tuple of > all supported styles. > We can but hope. I'm afraid I'm less optimistic than you, but this lack of optimism shouldn't be allowed to restrain your enthusiasm. > >>Also be aware that there have been various post-2.0 proposals for the DB >>API, which you might want to look up on Google and fold in to the >>current campaign. > > > Indeed. I went looking for proposals specifically related to argument > handling earlier, but still need to have a look for other API revision > proposals. > > I thought it best to ask here to find out how much interest there would > be in clarifying the API and adding a required format style before going > ahead with actually writing a few patches and a draft PEP for comments. > Well, let's hope I'm not the only one to respond, then. Since the push for 2.5 is allegedly to improve the standard library, it would be great if we could improve the portability of the DB API as well. I'd personally be in favor of trying to include a number of database modules either in the standard library or in a package that could easily be added in a lump. Go to it, and good luck - let me know when you need help. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From christian.ergh at gmail.com Thu Dec 16 12:28:05 2004 From: christian.ergh at gmail.com (Christian Ergh) Date: Thu, 16 Dec 2004 18:28:05 +0100 Subject: A beginner's problem... In-Reply-To: References: Message-ID: DogWalker wrote: > "Marc 'BlackJack' Rintsch" said: > > >>In , Amir Dekel wrote: >> >> >>>When I import a module I have wrote, and then I find bugs, it seems that >>>I can't import it again after a fix it. It always shows the same >>>problem. I try del module but it doesn't work. >>>(I use Python 2.4 with the ActivePython pack (PythonWin IDE) >>> >>>Solution anyone? >> >>Yes -> help(reload) >> >>Ciao, >> Marc 'BlackJack' Rintsch > > > First, save the file using the check option (Ctl+Shift+C, iirc); > Second, Fix any errors (attend to Status Bar); > Third, press Reload button in Toolbar (or type command from File Menu). > Four, assure that Status Bar indicates reload was successful. > If still doesn't load correctly, quit PythonWin and start it again. > Fifth, use the module unittest and write a test for your module. Just run the test to check your module and fix all errors, then import it into the larger sceme and see if everything works there. Most problems will appear in a good test, so you will not have the reimport issiue at all. Chris From ncoghlan at iinet.net.au Wed Dec 22 08:03:59 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 22 Dec 2004 23:03:59 +1000 Subject: Lazy argument evaluation (was Re: expression form of one-to-many dict?) In-Reply-To: <41C828B2.20106@iinet.net.au> References: <863by22gqs.fsf@guru.mired.org> <41C828B2.20106@iinet.net.au> Message-ID: <41C970BF.7050905@iinet.net.au> Nick Coghlan wrote: > def lazycall(x, *args, **kwds): > """Executes x(*args, **kwds)() when called""" > return lambda : x(*args, **kwds)() It occurred to me that this should be: def lazycall(x, *args, **kwds): """Executes x()(*args, **kwds) when called""" return lambda : x()(*args, **kwds) (Notice where the empty parens are) Then this does the right thing: lazycall(lazy(attrgetter('a'), x), y) # x.a(y) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From dave at pythonapocrypha.com Sat Dec 4 22:05:59 2004 From: dave at pythonapocrypha.com (Dave Brueck) Date: Sat, 04 Dec 2004 20:05:59 -0700 Subject: Quixote+Nevow+LivePage In-Reply-To: <20041204161706.1203.723384364.divmod.quotient.2004@ohm> References: <20041204161706.1203.723384364.divmod.quotient.2004@ohm> Message-ID: <41B27B17.6010603@pythonapocrypha.com> Jp Calderone wrote: > On 3 Dec 2004 22:02:51 -0800, Mir Nazim wrote: >>Q1) Is it possibe to use "Nevow + LivePage + Quixote" together in a >>web app. Live Page is really important for me as I am not into content >>oriented web apps. >> >>Q2) Is is nessary that LivePage only with Twisted or can work with any >>web server like Apache. >> > > > I haven't used LivePage myself, but someone in the know tells me > that LivePage requires an extra, non-HTTP connection to operate, so > will pretty much only work with Twisted. Do you have a reference that says this - I'd like to know for sure. I did a quick perusal of the code and thought that all the communication was via the XmlHttpRequest functionality available in a lot of modern browsers (IE, Mozilla, Safari). -Dave From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sun Dec 12 17:42:42 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Sun, 12 Dec 2004 23:42:42 +0100 Subject: possible ? References: <41bc0772$0$3436$8fcfb975@news.wanadoo.fr> Message-ID: <41bcc975$0$32206$8fcfb975@news.wanadoo.fr> (set font to : courier) : ______ __ __ /\__ _\/\ \ /\ \ \/_/\ \/\ \ \___ __ ___ \ \ \/'\ ____ \ \ \ \ \ _ `\ /'__`\ /' _ `\\ \ , < /',__\ \ \ \ \ \ \ \ \ /\ \L\.\_ /\ \/\ \\ \ \\`\ /\__, `\ \ \_\ \ \_\ \_\\ \__/.\_\\ \_\ \_\\ \_\ \_\\/\____/ \/_/ \/_/\/_/ \/__/\/_/ \/_/\/_/ \/_/\/_/ \/___/ __ __ /\ \ /\ \ \ `\`\\/'/ ___ __ __ `\ `\ /' / __`\ /\ \/\ \ `\ \ \ /\ \L\ \\ \ \_\ \ \ \_\\ \____/ \ \____/ \/_/ \/___/ \/___/ __ __ __ _ __ __ __ /\ \/\ \ /'__`\/\`'__\/\ \/\ \ \ \ \_/ |/\ __/\ \ \/ \ \ \_\ \ \ \___/ \ \____\\ \_\ \/`____ \ \/__/ \/____/ \/_/ `/___/> \ /\___/ \/__/ __ /\ \ ___ ___ __ __ ___ \ \ \___ /' __` __`\ /\ \/\ \ /'___\\ \ _ `\ /\ \/\ \/\ \\ \ \_\ \/\ \__/ \ \ \ \ \ __ \ \_\ \_\ \_\\ \____/\ \____\ \ \_\ \_\/\ \ \/_/\/_/\/_/ \/___/ \/____/ \/_/\/_/\ \/ \/ ____ __ __ __ /\ _`\ /\ \ __ /\ \ /\ \ \ \ \L\_\ _ __ __ \_\ \ _ __ /\_\\ \ \/'\ \ \ \ \ \ _\//\`'__\/'__`\ /'_` \ /\`'__\\/\ \\ \ , < \ \ \ \ \ \/ \ \ \//\ __/ /\ \L\ \\ \ \/ \ \ \\ \ \\`\ \ \_\ \ \_\ \ \_\\ \____\\ \___,_\\ \_\ \ \_\\ \_\ \_\ \/\_\ \/_/ \/_/ \/____/ \/__,_ / \/_/ \/_/ \/_/\/_/ \/_/ From spamerom at niet.com Wed Dec 29 19:03:49 2004 From: spamerom at niet.com (JZ) Date: Thu, 30 Dec 2004 01:03:49 +0100 Subject: Compiled bytecode References: <20041229185714.06154.00001753@mb-m21.aol.com> Message-ID: <165dbn64xuwqu$.idzmzjpx6x1h.dlg@40tude.net> Dnia 29 Dec 2004 23:57:14 GMT, LutherRevisited napisa?(a): > I haven't noticed any difference in the performance of text *.py > or a bytecompiled file. Importing modules works faster. -- JZ ICQ:6712522 http://zabiello.com From grante at visi.com Mon Dec 13 17:28:08 2004 From: grante at visi.com (Grant Edwards) Date: 13 Dec 2004 22:28:08 GMT Subject: Reading raw data from disc References: <41be0dbb$0$152$3a628fcd@reader2.nntp.hccnet.nl> Message-ID: <41be1778$0$80336$a1866201@visi.com> On 2004-12-13, Ivo Woltring wrote: > Is it possible to read e.g. the first 3 sectors of a disc > without opening a file or somesuch? Under Linux, no. You have to open the device. > I want to bitwise read a cd-rom or other media without > consulting a table of contents. Just start at track 0 and go > on for x bytes. Is it possible with python and if so, please > help me in the right direction sectorsize = 2048 # hard drives are usually 512, CDs 2K or 4K bytes = file('/dev/cdrom','rb').read(3*sectorsize) I've no idea what to do under Windows... -- Grant Edwards grante Yow! And furthermore, at my bowling average is visi.com unimpeachable!!! From gerrit at nl.linux.org Wed Dec 15 04:17:00 2004 From: gerrit at nl.linux.org (Gerrit) Date: Wed, 15 Dec 2004 10:17:00 +0100 Subject: lies about OOP In-Reply-To: References: <1102995205.949964.76020@c13g2000cwb.googlegroups.com> <29Evd.32591$Jk5.26287@lakeread01> Message-ID: <20041215091700.GA11479@topjaklont.student.utwente.nl> A non-text attachment was scrubbed... Name: not available Type: application/pgp-encrypted Size: 12 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: msg.asc Type: application/octet-stream Size: 4048 bytes Desc: not available URL: From someone at microsoft.com Tue Dec 14 03:57:06 2004 From: someone at microsoft.com (Jive) Date: Tue, 14 Dec 2004 08:57:06 GMT Subject: lies about OOP References: <1102995205.949964.76020@c13g2000cwb.googlegroups.com> <41be9e31$0$7078$afc38c87@news.optusnet.com.au> Message-ID: "Mike Thompson" wrote in message news:41be9e31$0$7078$afc38c87 at news.optusnet.com.au... > > Then came Brad Cox's book. I read it. > > Then there was Glockenspiel's C++ for PC in about '87 or '88. I didn't PC in those days. I Unixed. > And, of course, cfont on unix from about, what, '85? That's about when I got it. I used to chat with B.S. on the phone, discussing and proposing features. Now he's rich and famous. Me? Would you believe rich? How about not destitute? > > Across the late '80s there was, of course, Eiffel which seemed a > remarkable piece of work for the time. And was backed by a terrific book > by Myer. > I puzzled long over whether to adopt C++ or Eiffel at the company I was with at the time. I went with C++, dispite the fact that cfront was slow as death and buggy. C++ made it bigtime and the company went public. Lucky guesses? Hah! Ah, nostalgia isn't what it used to be. Jive From whereU at now.com Sun Dec 5 20:57:17 2004 From: whereU at now.com (Eric Pederson) Date: Sun, 5 Dec 2004 17:57:17 -0800 Subject: PajamaScript In-Reply-To: References: Message-ID: <20041205175717.1876310405.whereU@now.com> Jerome (aka evil tofu) advised: > I wrote something called PajamaScript. Basically, it parses a text > file and looks for tags. Then it calls python to handle the > scripting. Why learn another language when you already know Python? > > > > This is fun! > > > The Date is .
> The Time is .

> > > > > > PajamaScript then calls the function "zdate" in module "misc" and the > output replaces the tag. This is not really tested in any production > system, just a proof of concept I did for a project that never > materialized. In order to access cgi variables, you can use the cgi > module or any other python module! Would this be useful to anyone? Every tool has a use! Offhand it occurs to me this might a simple, well organized structure for a cgi environment, though I wonder if the extra level of processing might make it a little slow. Ought to be other uses too... I _do_ think the tags and the title "PajamaScript" is brilliant marketing. Highest kudos! ["PajamaScript" beats "PyTxtParse2ModuleExecEnviron.py" !] Any functioning examples of its use? Eric Pederson ::::::::::::::::::::::::::::::::::: def eAddy(): domainNot="@something.com" domainIs=domainNot.replace("s","z") ePrefix="".join([chr(ord(x)+1) for x in "do"]) mailMeAt=ePrefix+domainIs return mailMeAt ::::::::::::::::::::::::::::::::::: From Noah.Richards at infineon.com Fri Dec 17 08:25:35 2004 From: Noah.Richards at infineon.com (Richards Noah (IFR LIT MET)) Date: Fri, 17 Dec 2004 08:25:35 -0500 Subject: BASIC vs Python References: <867jnh1i9v.fsf@guru.mired.org> Message-ID: "Christos TZOTZIOY Georgiou" wrote in message news:ff95s0ttv8vp6clii0usldh7coecvethvk at 4ax.com... > On Fri, 17 Dec 2004 01:43:56 -0600, rumours say that Mike Meyer > might have written: > > >Assembler was better - at least you had recursion with > >assembler. > > You had recursion with BASIC --what you probably mean is that you had no > stacked parameters (unless you imitated that with using an indexed > array). > > 90 rem recursion > 100 print "beautiful colours" > 110 gosub 100 I think he means that you had no recursive function calls in BASIC. I suppose, to most of us, "recursion" doesn't mean "doing things more than once," since by that definition, iteration is also recursion. Recursion generally means some type of self reference, like in functional languages, where the simplest recursion is base case/recurring step. BASIC didn't do this, without a bit of unsightly hackery. Then again, I don't believe that it was really a concern at the time, so I don't suppose its too important of an issue :) From martin at v.loewis.de Mon Dec 13 18:17:57 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 14 Dec 2004 00:17:57 +0100 Subject: system requirements for python 2.4 In-Reply-To: <1102969092.705783.204000@z14g2000cwz.googlegroups.com> References: <1102969092.705783.204000@z14g2000cwz.googlegroups.com> Message-ID: <41be2323$0$22721$9b622d9e@news.freenet.de> ben wrote: > I'm trying to upgrade python from 2.2 to 2.4 on a RH9 system, and can't > find any rpm that will let me install it. > Is FC3 required for python 2.4? No. However, you may have to build Python yourself. Try using the source RPM; if that fails to work, either correct the spec file, or build directly from the pydotorg sources. Regards, Martin From kdart at kdart.com Tue Dec 14 06:52:09 2004 From: kdart at kdart.com (Keith Dart) Date: Tue, 14 Dec 2004 11:52:09 GMT Subject: Python mascot proposal In-Reply-To: References: <41bcbf31$0$1082$afc38c87@news.optusnet.com.au> Message-ID: Dimitri Tcaciuc wrote: > Yup, I was aware of the fact of Monty Python roots of the language name. > However, you will probably agree that a snake is more associative. > > Plus, if to use some characteristic MP feature like a giant foot, I'm > not positive that it won't trigger any copyright issues. I prefer an alternate meaning: 2. A diviner by spirits. ``[Manasses] observed omens, and appointed pythons.'' --4 Kings xxi. 6 (Douay version). Since Python is a divine language, and conjures up quick solutions to ghastly problems. And, in the spirit of oracles, reflects the wisdom of the languages design. 8-) Now, how about an icon that conveys something like that? hm... smoke curled around wizard perhaps? -- \/ \/ (O O) -- --------------------oOOo~(_)~oOOo---------------------------------------- Keith Dart public key: ID: F3D288E4 ============================================================================ From ncoghlan at iinet.net.au Thu Dec 16 09:30:46 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 17 Dec 2004 00:30:46 +1000 Subject: do you master list comprehensions? In-Reply-To: <41C02C61.6060709@iinet.net.au> References: <1102971085.659444.22790@z14g2000cwz.googlegroups.com> <41C02C61.6060709@iinet.net.au> Message-ID: <41C19C16.9060706@iinet.net.au> Nick Coghlan wrote: > (FYI, I filed bug report #1085744 on SF about this) And Raymond Hettinger was able to decipher my somewhat incoherent rambling (tip: don't try to write bug reports in the wee hours of the morning) and produce a potentially useful modification to PySequence_Tuple. Anyway, I guess the results I got emphasizes the fact that it's important to measure performance of the actual methods you're using on representative input data, rather than relying on overly simple demonstrators. And, of course, don't be *too* concerned about optimisations until you know you actually have a performance problem. . . Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steve at holdenweb.com Wed Dec 29 13:11:43 2004 From: steve at holdenweb.com (Steve Holden) Date: Wed, 29 Dec 2004 13:11:43 -0500 Subject: Other notes In-Reply-To: <863bxpuhlj.fsf@guru.mired.org> References: <1104287020.804167.9420@f14g2000cwb.googlegroups.com> <863bxpuhlj.fsf@guru.mired.org> Message-ID: <41D2F35F.7050808@holdenweb.com> Mike Meyer wrote: > bearophileHUGS at lycos.com writes: > > >>@infix >>def interval(x, y): return range(x, y+1) # 2 parameters needed >> >>This may allow: >>assert 5 interval 9 == interval(5,9) > > > I don't like the idea of turning words into operators. I'd much rather > see something like: > > @infix('..') > def interval(x, y): > return range(x, y + 1) > > assert 5 .. 9 == interval(5, 10) > > This would also allow us to start working on doing away with the magic > method names for current operators, which I think would be an > improvement. > Well, perhaps you can explain how a change that's made at run time (calling the decorator) can affect the parser's compile time behavior, then. At the moment, IIRC, the only way Python code can affect the parser's behavior is in the __future__ module, which must be imported at the very head of a module. > As others have pointed out, you do need to do something about operator > precedence. For existing operators, that's easy - they keep their > precedence. For new operators, it's harder. > Clearly you'd need some mechanism to specify preference, either relatively or absolutely. I seem to remember Algol 68 allowed this. > You also need to worry about binding order. At the very least, you > can specify that all new operators bind left to right. But that might > not be what you want. > Associativity and precedence will also have to affect the parsing of the code, of course. Overall this would be a very ambitious change. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 94 3119 From titus at caltech.edu Mon Dec 27 15:41:59 2004 From: titus at caltech.edu (C. Titus Brown) Date: Mon, 27 Dec 2004 12:41:59 -0800 Subject: RFC 2965 cookies, cookielib, and mailman. Message-ID: <41D07397.9080401@caltech.edu> Hi all, just spent some time playing with cookielib in Python 2.4, trying to get the cookielib example [0] to work with my mailman admindb page. The problem was that cookies weren't getting saved. The issue turned out to be that mailman sends out RFC 2965 [1] cookies, which are by default rejected by cookielib. I don't remotely pretend to understand the issues involved; hence my post ;). A few questions for those more clued in than me: * what is the difference between RFC 2965 cookies and others? * why would mailman implement RFC 2965 cookies over the old format? (I'm guessing simply because it's the latest/best/format?) * why would cookielib NOT accept RFC 2965 cookies by default? * my reference "good" implementation that worked with the urllib2/cookielib is Quixote, which seems to send out cookies in the older (Netscape?) style. Should this be changed or updated in Quixote? The obvious google searches found an awful lot of information but nothing obviously pertinent. In any case, the way to make the cookielib example work for mailman is like so: policy = cookielib.DefaultCookiePolicy(rfc2965=True) cj = cookielib.LWPCookieJar('cookies.lwp', policy=policy) thanks, --titus [0] http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302930 [1] http://www.faqs.org/rfcs/rfc2965.html From jdhunter at ace.bsd.uchicago.edu Fri Dec 17 14:40:13 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Fri, 17 Dec 2004 13:40:13 -0600 Subject: Create linear spaced vector? In-Reply-To: <1103311548.726228.263590@f14g2000cwb.googlegroups.com> (kjmacken@gmail.com's message of "17 Dec 2004 11:25:48 -0800") References: <6ca895b5.0412171039.7586077d@posting.google.com> <1103311548.726228.263590@f14g2000cwb.googlegroups.com> Message-ID: >>>>> "kjmacken" == kjmacken writes: kjmacken> Thanks for the code snippets guys. Exactly what I kjmacken> needed to get going. I knew I could get the solution kjmacken> from matplotlib, but getting it installed using Fink (OS kjmacken> X) has been giving me a headache, so I thought I could kjmacken> just write my own function for now to get a small piece kjmacken> of code written.... Yes, matplotlib fink installs have frustrated many an OSX user. Note that the matplotlib.mlab package (where linspace and others functions reside) do not require any extension code and can be reused anywhere you like as python code by copying and pasting, etc. Also, Robert Kern is in the process of building an "enthon" package for OSX that has most of the utilities for scientific computing including matplotlib built-in. Batteries included on steroids, basically. http://www.scipy.org/wikis/featurerequests/MacEnthon So keep your eyes on that site for release information. JDH From martin at v.loewis.de Tue Dec 7 14:27:11 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 07 Dec 2004 20:27:11 +0100 Subject: Win32 Libs for 2.4 In-Reply-To: References: <41b55c28$0$196$9b622d9e@news.freenet.de> Message-ID: <41b60404$0$22710$9b622d9e@news.freenet.de> Robin Becker wrote: > I don't think this > forces the linker to load stuff from this module although I can see that > it might be dangerous depending on which obj files are seen first. I think you are wrong. In the object, there will be simply a linker command line option encoded; do "dumpbin /all foo.obj" to see the linker options. > I believe this is a weak reference from the documentation. What makes you think so?: the linker option in the object file will be added to the linker line, unconditionally. > Fortunately I don't think this is a problem as Python24.dll also > references USER32.dll directly. Yes, that user32.dll indirectly uses msvcrt.dll should be no problem. Regards, Martin From luismgz at gmail.com Sun Dec 19 19:53:05 2004 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 19 Dec 2004 16:53:05 -0800 Subject: Boo who? (was Re: newbie question) In-Reply-To: References: Message-ID: <1103503985.015510.24680@z14g2000cwz.googlegroups.com> > Why? If it's virtually identical, why would anyone bother even > visiting that site? ;-) > > But I suspect you mean that the syntax of the language is virtually > identical, while probably there are some significant differences. > Maybe in the richness of its standard library? Or the size of > its community? Or something else.... The difference is that it runs on the .NET frmework (and Mono). So instead of using the python standard libraries, you use the .NET ones. Regarding its syntax, it is very similar to Python. However the language is statically typed, not dynamic. Anyway, you don't have to declare types too often, because it uses a very good type inference system. For all those reasons, Boo has very good performance. In theory, it's performance is equal to C# or any other .NET compliant language, but it is still in phase of development (although quite usable for many tasks). So I guess it has many characteristics that make it a very interesting language for any python fan. And for those concerned with speed and performance, it is god send. From bradtilley at gmail.com Wed Dec 1 11:25:50 2004 From: bradtilley at gmail.com (Brad Tilley) Date: Wed, 01 Dec 2004 11:25:50 -0500 Subject: Python 2.4 Uninstall Entry in WinXP Registry In-Reply-To: <41ADE1FC.2060105@gmail.com> References: <41ad87a5$0$23342$9b622d9e@news.freenet.de> <41ADE1FC.2060105@gmail.com> Message-ID: <41ADF08E.3080901@gmail.com> Brad Tilley wrote: > Martin v. L?wis wrote: > >> Brad Tilley wrote: >> >>> Python 2.3 placed a registry key under: >>> >>> 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Python2.3' >> >> >> >> >> [...] >> >>> Python 2.4 does not use this registry entry on the two machines I >>> have installed it on... any tips on how to locate this? >> >> >> >> It's under >> >> HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{82D9302E-F209-4805-B548-52087047483A} >> >> >> which is the product code of Python 2.4. Notice that Python 2.4.1 >> will use a different product code. >> >> However, if you merely want to avoid that users remove the package, >> you can set the ARPNOREMOVE property during installation, e.g. >> >> msiexec /i python24.msi ARPNOREMOVE=1 >> >> You might want to set ARPNOMODIFY and ARPNOREPAIR as well. >> >> If you cannot readily pass that property on the command line during >> installation, you can use orca.exe (or a python script) to add this >> property to the Property table of python24.msi. >> >> If you have W2k or later, you can also set the "NoRemove" registry >> value under the key above, to hide the remove feature after >> installation. >> >> HTH, >> Martin > > > That's very helpful, thanks Martin! How do I set the install path to > c:\Program Files? I found the documentation here: http://python.fyxm.net/2.4/msi.html From sjmachin at lexicon.net Fri Dec 3 15:12:31 2004 From: sjmachin at lexicon.net (John Machin) Date: 3 Dec 2004 12:12:31 -0800 Subject: How did you learn Python? References: Message-ID: "Jeffrey Maitland" wrote in message news:... > Well I would suggest the Python in a Nutshell and the Python Cookbook both > by O'Reilly as references. They are great for a desktop reference and I > check them first before I google/search else where for answers. Being they > are reference books they or more on aide then a teaching device however I > have learned from those books how to use certain standard classes, such as > the re class for example. Somebody called O'Reilly taught you that Python has "standard classes", one of which is "re"??? Hmmm, can't have been O'Reilly the publisher; must have been O'Reilly the builder. Sybil! Where's that garden gnome? From __peter__ at web.de Wed Dec 8 14:49:53 2004 From: __peter__ at web.de (Peter Otten) Date: Wed, 08 Dec 2004 20:49:53 +0100 Subject: How do I do this? (eval() on the left hand side) References: Message-ID: Caleb Hattingh wrote: > In what way is it unreliable???I?can't?seem?to?create?a?situation?where > the update through globals and locals doesn't work.???Are?you?referring Updates to a locals() dictionary may not be reflected by the variables in the local scope, e. g.: >>> def f(): ... locals()["a"] = 1 ... print a ... >>> f() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in f NameError: global name 'a' is not defined >>> def f(): ... a = 42 ... locals()["a"] = 1 ... print a ... >>> f() 42 Updating globals() should be safe. Peter From andre.roberge at ns.sympatico.ca Sun Dec 5 21:37:08 2004 From: andre.roberge at ns.sympatico.ca (Andr? Roberge) Date: 5 Dec 2004 18:37:08 -0800 Subject: exec and global puzzle Message-ID: I have the following two files: #--testexec.py-- def exec_code(co): try: exec co except: print "error" #-- test.py-- import thread import testexec import time code = "def a():\n print 'a'\n\n" +\ "def c():\n a()\n\nc()" code2 = "def a():\n print 'a'\n\n" +\ "def c():\n global a\n a()\n\nc()" print " exec code - no global" exec code print " exec from thread - no global" thread.start_new(testexec.exec_code, (code,)) time.sleep(1) print "\n exec code2 - with global" exec code2 print " exec from thread - with global" thread.start_new(testexec.exec_code, (code2,)) #----------------------- Here's the output when I execute test.py: exec code - no global a exec from thread - no global error exec code2 - with global a exec from thread - with global a #--------- Without the global statement, I get an error when trying to execute the code. I don't understand why I need to use the global statement within the definition of c() in order for it to know what a() is. If I define exec_code() within test.py and use it there, I do not get any error, with or without the use of a global statement. Andre From ThisIsNotMyReal at ddress.com Mon Dec 27 08:29:02 2004 From: ThisIsNotMyReal at ddress.com (Brian) Date: Mon, 27 Dec 2004 13:29:02 GMT Subject: Detecting if a program is currently running. References: <864qi85ngf.fsf@guru.mired.org> Message-ID: Thanks, that does the trick. Mike Meyer wrote in news:864qi85ngf.fsf at guru.mired.org: > Yeah, but it takes work on both ends. You could wrap your mpg123 in a > shell script like so: > > #!/bin/sh > mpg123 "$@" & > echo $! >/tmp/mpg123.pid > > > Or in python 2.4: > > #!/usr/bin/env python > from subprocess import Popen > > p = Popen('mpg123') > pidfile = file('/tmp/mpg123.pid', 'w') > pidfile.write("%d" % p.pid) > pidfile.close() > > Then have your check program do (again, using the 2.4 subprocess > module) > > from subprocess import Popen, PIPE > > try: > pidfile = file('/tmp/mpg123.pid') > except IOError: > print 'mpg123 is dead' > else: > pid = pidfile.read() > t = Popen('ps p %s' % pid, shell=True, stdout=PIPE).stdout > if t.readlines() < 2: > print 'mpg123 is dead' > os.remove('/tmp/mpg123.pid') > return 0 > return 2 > > Basically, instead of trusting grep to find mpg123, save the pid in a > file and let ps find it (or not) by pid. > > References: <1103622331.247762.161750@f14g2000cwb.googlegroups.com> <1103640442.940168.246130@c13g2000cwb.googlegroups.com> <1103801690.093414.72370@f14g2000cwb.googlegroups.com> Message-ID: <1103802330.751574.109350@f14g2000cwb.googlegroups.com> brian.b... at securetrading.com wrote: > > Channelling the effbot, I think he was asking what namespace context > you > > expected the expression "arg=otherfunction(x)" to be evaluated in > when > > it's used at the time of a function call to dynamically create a new > > default value for arg. > > Thanks, I realise now that's what was meant. I think I was just > assuming otherfunction() would be globally available - but that's not > something I want to go into since I can see now there will be problems > trying to define what python should do if it evaluated defaults at the > function call :) > > I think I can now explain to someone why there are good reasons that > the default params are evaluated at the definition. However, I still > can't give a nice looking solution on how to re-write a function to > have empty mutable values as default arguments: eg. > > def method(a,b,opt1=[],opt2=None,opt3="",opt4={}) > > How could I re-write this (especially if there are perhaps 20 optional > parameters,any number of which may have mutable defaults) without > writing 20 "if opt1 is None: opt1=[]" statements? > > Brian One way that is *slightly neater* is to simply collect all keyword arguments as a dictionary. Then compare with a dictionary of defaults for any missing keywords. def afunction(**keywargs): defaults = {'param1' : [], 'param2' : {}, 'param3' : []} for entry in defaults: if not keywargs.has_key(entry): keywargs[entry] = defaults[entry] This keeps all your defaults in a single dictionary and avoids a really long function definition. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From fuzzyman at gmail.com Mon Dec 13 03:30:27 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: 13 Dec 2004 00:30:27 -0800 Subject: Compiling PIL for Python 2.4 Message-ID: <1102926627.046518.40880@z14g2000cwz.googlegroups.com> I'll post this to the image-sig as well, but the audience is a bit wider here. I've just upgraded to Python 2.4. I've installed the free microsoft optimising compiler and hacked distutils to use it - following the instructiosn from http://www.vrplumber.com/programming/mstoolkit/ . It works great and I've built a windows installer for PyCrypto 2.0. I'm attempting to compile PIL for python 2.4. The build instructions for windows say : If you're using Python 2.0 or later, you can use the setup.py script to build the library. The following commands should do the trick: $ python setup.py build $ python setup.py install You may need to tweak the setup.py file somewhat in order to make it find certain external libraries; see comments in the file for details. Right - so you actually need to *get* the zlib and jpeg libraries, which I've done. I've not yet got the right header/include files for Tkinter, but it should work without them (just not build those files). Except it bombs out : C:\compile\Imaging-1.1.4\PIL>cd /D C:\compile\Imaging-1.1.4 C:\compile\Imaging-1.1.4>setup.py build *** Cannot find Tcl/Tk headers and library files. *** To build the Tkinter interface, set the TCLROOT *** variable in the setup.py file. running build running build_py running build_ext building '_imaging' extension C:\Program Files\Microsoft Visual C++ Toolkit 2003\bin\link.exe /DLL /nologo /INCREMENTAL:NO /LIBPATH:libImaging / LIBPATH:jpeg-6b /LIBPATH:zlib /LIBPATH:C:\Python24\libs /LIBPATH:C:\Python24\PCBuild Imaging.lib jpeg.lib zlib.lib kernel32.lib user32.lib gdi32.lib /EXPORT:init_imaging build\temp.win32-2.4\Release\_imaging.obj build\temp.win32 -2.4\Release\decode.obj build\temp.win32-2.4\Release\encode.obj build\temp.win32-2.4\Release\map.obj build\temp.wi n32-2.4\Release\display.obj build\temp.win32-2.4\Release\outline.obj build\temp.win32-2.4\Release\path.obj /OUT:bu ild\lib.win32-2.4\_imaging.pyd /IMPLIB:build\temp.win32-2.4\Release\_imaging.lib LINK : fatal error LNK1181: cannot open input file 'Imaging.lib' error: command '"C:\Program Files\Microsoft Visual C++ Toolkit 2003\bin\link.exe"' failed with exit status 1181 C:\compile\Imaging-1.1.4> _imaging.obj is being created - but not linked. I can't find an Imaging.lib file anywhere. Anyone got any clues for me ? Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From FBatista at uniFON.com.ar Thu Dec 30 09:22:59 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Thu, 30 Dec 2004 11:22:59 -0300 Subject: Securing a future for anonymous functions in Python Message-ID: [Nick Coghlan] #- I just don't understand why people complain so much about #- the restriction to a #- single expression in lambdas, yet there is nary a peep about #- the same #- restriction for generator expressions and list comprehensions. What *I* don't understand (and it could perfectly be plain ignorance, as never studied languages or computer sciences) is why anonymous functions are so important. While I'm one of those who spend 30% of the time writing the function and 70% choosing a name for it, I never really use lambdas (except for minor cases in Tkinter buttons). hoping-to-learn-something-new-in-the-next-mail--ly yours, . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From vze4rx4y at verizon.net Fri Dec 3 22:06:56 2004 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sat, 04 Dec 2004 03:06:56 GMT Subject: Replace string except inside quotes? References: <3064b51d.0412030739.2c301449@posting.google.com> Message-ID: wrote > The code > > for text in open("file.txt","r"): > print text.replace("foo","bar")[:-1] > > replaces 'foo' with 'bar' in a file, but how do I avoid changing text > inside single or double quotes? For making changes to Python code, I > would also like to avoid changing text in comments, either the '#' or > '""" ... """' kind. The source for the tokenize module covers all these bases. Raymond Hettinger From dieter at handshake.de Fri Dec 3 14:50:04 2004 From: dieter at handshake.de (Dieter Maurer) Date: 03 Dec 2004 20:50:04 +0100 Subject: Python 3000 and "Python Regrets" References: <3064b51d.0412011016.6efc20a6@posting.google.com> Message-ID: Tim Peters writes on Wed, 1 Dec 2004 13:38:49 -0500: > ... > > Are serious Python programmers already taking care to avoid > > using Python features that may disappear in Python 3000? > > No, although some naturally avoid dubious features without being > threatened . Are there dubious features in Python? :-) Dieter From jeff at ccvcorp.com Thu Dec 16 17:54:44 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 16 Dec 2004 14:54:44 -0800 Subject: Adding paths to sys.path permanently, and another problem... In-Reply-To: References: Message-ID: <10s44acrp0r7ea6@corp.supernews.com> Amir Dekel wrote: > 2. os.path.expanduser("~") always gives me "C:\\" instead of my > homepath. I have tried to change my homepath in WinXP using set > homepath(in command line), and alsaw using the "Environment Variables" > in WinXP system properties, non helped. I really have to fix this > somehow. Well, according to os.path.expanduser()'s docstring, it uses the $HOME environment variable to determine how to expand ~. I don't know what's standard on Windows, but I tried checking for a $HOME and found none. Here's (a slightly redacted copy of) what I *do* find (Win2K): >>> for key, val in os.environ.items(): ... print '%15s %s' % (key, val) ... TMP C:\DOCUME~1\Jeff\LOCALS~1\Temp USERNAME jeff COMPUTERNAME ###### LOGONSERVER ###### COMSPEC C:\WINNT\system32\cmd.exe USERDOMAIN ####### COMMONPROGRAMFILES C:\Program Files\Common Files PROCESSOR_IDENTIFIER x86 Family #... PROGRAMFILES C:\Program Files PROCESSOR_REVISION 0806 PATHEXT .COM;.EXE;.BAT;.CMD;#.... SYSTEMROOT C:\WINNT PATH C:\Python22\.;C:\WINNT\system32;C:\WINNT;##.... APPDATA C:\Documents and Settings\Jeff\Application Data TEMP C:\DOCUME~1\Jeff\LOCALS~1\Temp HOMEDRIVE C: SYSTEMDRIVE C: PROCESSOR_ARCHITECTURE x86 NUMBER_OF_PROCESSORS 1 ALLUSERSPROFILE C:\Documents and Settings\All Users.WINNT PROCESSOR_LEVEL 6 HOMEPATH \ OS2LIBPATH C:\WINNT\system32\os2\dll; USERPROFILE C:\Documents and Settings\Jeff OS Windows_NT WINDIR C:\WINNT >>> Judging from this, I think that os.environ['USERPROFILE'] seems like it may do what you want, though os.environ['APPDATA'] might be useful as well. Of course, if you're trying to get something to work cross-platform, things may be more difficult -- but that's because Windows doesn't normally use ~ so its use is not supported very well. You may be able to create a $HOME that's equivalent to $USERPROFILE... Jeff Shannon Technician/Programmer Credit International From Scott.Daniels at Acm.Org Sun Dec 26 15:58:24 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 26 Dec 2004 12:58:24 -0800 Subject: sql server support from linux In-Reply-To: References: <3A81C87DC164034AA4E2DDFE11D258E3024F62@exchange.hqamor.amorhq.net> <4e4a11f804122117126aa7cc51@mail.gmail.com> <41CB45BF.2030502@benjiyork.com> Message-ID: <41cf237b$1@nntp0.pdx.net> Simon Wittber wrote: >>I considered doing exactly the same thing a while ago, but was worried >>about running into an annoyance like that. > > > FWIW, The synchronous Pyro server performed much faster than the > multithreaded version, even under heavy use from 3 machines. > > It appeared that while the database queries were serialized, network > IO was not. I infered this from the observation that a large result > set would take around 15 seconds to complete, yet other smaller > queries were able to run about 2-3 seconds after the large query was > started. > > Sw. This is standard "real DB" behavior. The transactions must appear to have been executed in _some_ serial order, not the order of arrival. If the small ops are simply retrieving data, they may return data from "before" the transaction of of the larger, slower transaction. Even if they mutate the DB, they may be inserted early if the larger transaction has not in fact "read" the data they will right. Also, in some cases, the smaller ones may be allowed to proceed and force the larger one to abort if it attempts to acquire locks on the data they write. --Scott David Daniels Scott.Daniels at Acm.Org From guettli at thomas-guettler.de Tue Dec 21 09:29:00 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 21 Dec 2004 15:29:00 +0100 Subject: Change vars in the parent process References: <576fb15a.0412210620.e0bd49e@posting.google.com> Message-ID: Am Tue, 21 Dec 2004 06:20:09 -0800 schrieb Markus Franz: > Hi! > > > Is there any possibility to change vars inside a parent process from > the inside of a child process? > Thanks Hi, No, that's impossible. At least on unix. Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From steve at holdenweb.com Thu Dec 30 11:21:44 2004 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Dec 2004 11:21:44 -0500 Subject: Probleme mit der Installation der openSource Bittorrent.... python vs JAVA In-Reply-To: <1f8eavbxu58lo.1b5lbvs43d6bp.dlg@40tude.net> References: <1f8eavbxu58lo.1b5lbvs43d6bp.dlg@40tude.net> Message-ID: JZ wrote: > Dnia 30 Dec 2004 07:24:45 -0800, xunling napisa?(a): > > >>ich h?tte da mal eine Frage zum Azureus bttrn client. > > > This is not German newsgroup! Write English or none. > Perhaps not, but can we say "International"? There is no rule requiring the use of any particular language on c.l.py, and I can certainly remember both French and Esperanto threads in the past. Ease up, it's hard enough if you're German ;-) be-polite-or-don't-write-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From aahz at pythoncraft.com Tue Dec 21 19:33:34 2004 From: aahz at pythoncraft.com (Aahz) Date: 21 Dec 2004 19:33:34 -0500 Subject: What is on-topic for the python list [was "Re: BASIC vs Python"] References: Message-ID: In article , Erik Max Francis wrote: >Doug Holton wrote: >> >> I'm not going to dignify that or the rest of your note with a response. > >Please stop dignifying the whole group, then. Seconded. This is an extremely undignified newsgroup. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From and-google at doxdesk.com Tue Dec 28 06:22:17 2004 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 28 Dec 2004 03:22:17 -0800 Subject: Looking for source preservation features in XML libs References: Message-ID: <1104232937.864994.213420@f14g2000cwb.googlegroups.com> Grzegorz Adam Hankiewicz wrote: > I have looked at xml.minidom, elementtree and gnosis and haven't > found any such features. Are there libs providing these? pxdom (http://www.doxdesk.com/software/py/pxdom.html) has some of this, but I think it's still way off what you're envisaging. > One is to be able to tell which source file line a tag starts > and ends. You can get the file and line/column where a node begins in pxdom using the non-standard property Node.pxdomLocation, which returns a DOM Level 3 DOMLocator object, eg.: uri= node.pxdomLocation.uri line= node.pxdomLocation.lineNumber col= node.pxdomLocation.columnNumber There is no way to get the location of an Element's end-tag, however. Except guessing by looking at the positions of adjacent nodes, which is kind of cheating and probably not reliable. SAX processors can in theory use Locator information too, but AFAIK (?) this isn't currently implemented. > Another feature is to be able to save the processed XML code in a way > that unmodified tags preserve the original identation. Do you mean whitespace *inside* the start-tag? I don't know of any XML processor that will do anything but ignore whitespace here; in XML terms it is utterly insignificant and there is no place to store the information in the infoset or DOM properties. pxdom will preserve the *order* of the attributes, but even that is not required by any XML standard. > Or in the worst case, all identation is lost, but I can control to > some degree the outlook of the final XML output. The DOM Level 3 LS feature format-pretty-print (and PyXML's PrettyPrint) influence whitespace in content. However if you do want control of whitespace inside the tags themselves I don't know of any XML tools that will do it. You might have to write your own serializer, or hack it into a DOM implementation of your choice. -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From ncoghlan at iinet.net.au Fri Dec 17 23:26:27 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 18 Dec 2004 14:26:27 +1000 Subject: Why are tuples immutable? In-Reply-To: References: <41BE1644.8050906@freemail.gr> <10s1si0fb0l4pae@corp.supernews.com> <10s4a4rso24vb83@corp.supernews.com> Message-ID: <41C3B173.1050304@iinet.net.au> Antoon Pardon wrote: > Would you have us construct two related classes each time we find > ourselves in such a situation and copy an object from one > class to the other depending on the circumstances? Python itself seems to think so, given the pairings of set/frozenset & list/tuple. Using genuinely immutable objects as dictionary keys is much easier than saying "while this object is part of a dictionary, don't alter it's hash value or comparison results". Instead, the immutable version is provided to say "alterations are not allowed on this copy" You can certainly *do* the former (using __hash__ and appropriate comparison overrides), but it isn't particularly easy to do correctly, and hence usually isn't a great idea unless copies are *really* expensive (and even then, a shallow copy approach can often suffice). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steve at holdenweb.com Tue Dec 14 08:28:02 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 14 Dec 2004 08:28:02 -0500 Subject: thread/queue bug In-Reply-To: References: Message-ID: <41BEEA62.6000205@holdenweb.com> Antoon Pardon wrote: > Op 2004-12-13, Tim Peters schreef : > >>[Antoon Pardon] >> >>>I don't see why starting a thread as a side effect of importing is >>>bad thread practice. Sure python doesn't cater for it, but IMO >>>that seems to be python failing. >> >>Obviously, it's bad practice in Python because it can lead to >>deadlocks in Python. > > > By that argument any use of locks is bad practice because it > can lead to deadlock. > Not at all. You mentioned locks, not Tim. The reason it can lead to deadlocks is because import, being an executable statement, must terminate correctly in order to return control to the module that executed the import statement. > >>It's nearly tautological. Import is an >>executable statement in Python, not, e.g., as in many other languages, >>a declaration directed at the system linker. With that power comes >>opportunities to shoot yourself, although they're generally easy to >>avoid. Come up with a practical design that doesn't have this >>limitation, and then perhaps your characterization of the current >>design as "a failing" would be both credible and constructive. > > > If a car model has cranky brakes, I think I can call that a failing > even without having the ability to come up with a pratical design > that doesn's has those limitations. > But in fact your situation is more closely analogous to a customer who's bought a car that can be stopped by pressing on the brake pedal now complaining that sideways pressure on the brake pedal doesn;t affect the car's motion. > I judge a language by what it can and cannot do, not by my ability > to correct the things I perceive as failings. For all I know python > may have taken some design decisions that might have seen perfectly > logical but now prohibit a a practical design that doesn't have this > limitation. I don't see why something like that would make this > any less a failing then when a practical design was easy in the > current implemenation. > All that Tim was suggesting is that it's MORE SENSIBLE to start a thread as the result of a specific call to programmed functionality rather than as the side effect of an import. The reason for this is due to the semantics of the import statement. If you perceive that as a failing then you'd be better rewarded by an attempt to modify your perceptions. I've always found "don't argue with Tim about Python" to be a useful rule of thumb. He's wrong much less often than I am. I suspect he's also wrong much less often than you ;-) > >>Apart from that, ya, I do think it would *uisually* be poor practice >>to start a thread as a side effect of importing anyway. It's too >>mysterious, and IME has caused trouble even when it didn't lead to >>deadlocks. The fundamental purpose of import in Python is to add >>useful names to the importer's namespace, and users of a module >>generally think of it as doing no more than that. > > > Importing a module in general also does some kind of initialisation. > If starting a thread is a logical thing to do in this initialisation > fase I see nothing wrong with it. > But the reason, I suspect, that it's being suggested this is bad design is because it would be tricky (in any language) to ensure that the satisfactory conclusion of the import didn't depend on successful thread startup (and possibly termination). Plus, of course, in Python the side-effect of the import (creating the thread) can happen precisely once, because the module body is executed precisely once no matter how many times it's imported. That's not really the issue, however. > >>Note that the OP's example had a module that, upon the first attempt >>to import it, ran an infinite loop (even if it hadn't deadlocked), and >>it's clearly severe abuse of import's purpose.to write a module M such >>that "import M" *never* returns. Indeed, that's the other half of how >>deadlock occurs: not only that the imported module spawn a thread as >>a side effect of importing, but also that the imported module refuse >>to allow the import to complete. > > > Well I'll agree here. An import that has as a side effect that the > import doesn't return is bad practice. > But that's precisely the risk you run when starting up threads! > >>The current design actually supports spawning all the threads you like >>as a side effect of importing, provided you ensure also that the >>import ompletes. > > > Well in that case I don't have any problems with it. The perceived > failing was because of only knowing part of it based on what I had > read in this thread. > > >>The easiest way to avoid trouble remains not to >>spawn threads as a side effect of importing to begin with, although a >>programmer determined to demonstrate their bad taste can easily >>enough make it work. > > > Well then probably I have a bad taste. I have though of designs in which > it seemed very natural to have a thread started as part of the > initialisation in a module. Other limitations of python didn't make > it workable but in priciple I saw nothing wrong with doing it. > Bearing in mind that module initialisation is always one-off, relying on import to trigger such complex behavior is probably a design that will mislead users into false expectations. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From kdart at kdart.com Sat Dec 11 06:16:01 2004 From: kdart at kdart.com (Keith Dart) Date: Sat, 11 Dec 2004 11:16:01 GMT Subject: swig & Python question In-Reply-To: References: Message-ID: <41BAD6F0.6020509@kdart.com> It's me wrote: > "It's me" wrote in message > news:oDStd.31076$zx1.23489 at newssvr13.news.prodigy.com... > >>I am playing around with SWING building a Python module using the no > > brainer > >>example in http://www.swig.org/tutorial.html. With that first example, >> > > > Oops! Soapy fingers. "SWIG" - not "SWING". > > -- > It's me. I have used SWIG before, and it's not always such a "no-brainer". In fact, it rarely is except for trivial examples. But it can work. I think it is best suited for wrapping large libraries. For small stuff, it would be better to just do it "manually" using the Python C API. Good luck. -- It's not me. -- \/ \/ (O O) -- --------------------oOOo~(_)~oOOo---------------------------------------- Keith Dart public key: ID: F3D288E4 ============================================================================ From gawel at web-alternative.com Mon Dec 13 10:06:08 2004 From: gawel at web-alternative.com (gawel) Date: Mon, 13 Dec 2004 16:06:08 +0100 Subject: A problem with list In-Reply-To: <1102949381.675816.171660@z14g2000cwz.googlegroups.com> References: <1102949381.675816.171660@z14g2000cwz.googlegroups.com> Message-ID: export at hope.cz wrote: > The following code > ############## > import string > MyList=['abc','def'] > for i in MyList: > print i > ############### > > works as I expect that is I get > abc > def > > but when I have Mylist in a file and I read it from the file it does > not work as I expect. > ######### > import string > ff=open('C:\\Robotp\\MyFile.txt','r') # read MyList from a file > MyList=ff.read() > for i in MyList: > print i > ########### > I will get > [ > ' > a > b > c > ' > , > ' > d > e > f > ' > ] > > where my MyFile.txt looks like this: > ['abc','def'] > > Where is a problem? > Thanks for help > Lad > That's quite simple. Your file contain a string, not a list You must use eval(your_list_as_string). >>> f = open('/tmp/list') >>> f.seek(0) >>> s = f.read() >>> s "['adc','def']\n" >>> l = eval(s) >>> l ['adc', 'def'] >>> for i in l: ... print i ... adc def gawel From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Wed Dec 15 03:03:46 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Wed, 15 Dec 2004 09:03:46 +0100 Subject: Small Problem P 2.4 (line>2048 Bytes) Message-ID: <41bfeff9$0$10232$8fcfb975@news.wanadoo.fr> Hi, all ! I have un python script of 75 kB, who make a COM server. It's run OK with Python 2.3 + PyWin + P.I.L. But, with Python 2.4, I obtain a windows error (sorry, it's in french) : python.exe a rencontr?e un probl?me, et doit fermer. erreur sur module: ntdll.dll Exception Information Code: 0xc0000005 Flags: 0x00000000 Record: 0x000000000000000 Address: 0x0000000077f773905 I had try on three computers differents (XP SP1 and/or SP2) : it's same. After search, I had found that the problem come from a "long line" (more than 2048 caracters), with begin : mappingcharmaj = { chr(97):'A', chr(98):'B', chr(99):'C', ... And, if I "break" in multiples lines, the problem is solved. (I keep the script, to be able to repeat the error, upon request) Therefore, I have a sufficient solution. But I want just to announce this problem, which could have consequences, for other users. *sorry for my bad english* @-salutations -- Michel Claveau From bokr at oz.net Wed Dec 29 21:38:55 2004 From: bokr at oz.net (Bengt Richter) Date: Thu, 30 Dec 2004 02:38:55 GMT Subject: Other notes References: <1104287020.804167.9420@f14g2000cwb.googlegroups.com> <863bxpuhlj.fsf@guru.mired.org> Message-ID: <41d35721.1382016815@news.oz.net> On Wed, 29 Dec 2004 11:42:00 -0600, Mike Meyer wrote: >bearophileHUGS at lycos.com writes: > >> @infix >> def interval(x, y): return range(x, y+1) # 2 parameters needed >> >> This may allow: >> assert 5 interval 9 == interval(5,9) > >I don't like the idea of turning words into operators. I'd much rather >see something like: > >@infix('..') >def interval(x, y): > return range(x, y + 1) > >assert 5 .. 9 == interval(5, 10) > I like that for punctuation-character names. OTOH, there is precedent in e.g. fortran (IIRC) for named operators of the form .XX. -- e.g., .GE. for >= so maybe there could be room for both. A capitalization _convention_ would make such infix operators pretty readable even if the names were'nt always the best, e.g., for x in 5 .UP_TO_AND_INCLUDING. 9: ... Hm, you could make x .infix. y syntactic sugar in general (almost like a macro) for infix(x, y) and you could generalize that to permit .expression. with no embedded spaces, e.g., x .my_infix_module.infix. y for my_infix_module.infix(x, y) or to illustrate expression generality ridiculously, a = x .my_infix_module.tricky_func_factory_dict[random.choice(range(4))](time.time()). y for a = my_infix_module.tricky_func_factory_dict[random.choice(range(4))](time.time())(x, y)

If '..' were special-cased as a synonym for __nullname__ you could handle it by def __nullname__(x, y): whatever, but since it's punctuation-only, your @infix('..') seem preferable. Hm, ... if single (to exlude .infix.) missing dotted names defaulted to __nullname__, I wonder what that would open up ;-) obj. would be obj.__nullname__, which could be defined as a concise way of referring to the one special attribute or property. And .name would be __nullname__.name -- which with the approriate descriptor definition in the function class could make .name syntactic sugar for self.name (or whatever the first arg name was). ... just musing ;-) >This would also allow us to start working on doing away with the magic >method names for current operators, which I think would be an >improvement. > >As others have pointed out, you do need to do something about operator >precedence. For existing operators, that's easy - they keep their >precedence. For new operators, it's harder. > >You also need to worry about binding order. At the very least, you >can specify that all new operators bind left to right. But that might >not be what you want. Yes. My .expression. infix if implemented essentially as a left-right rewrite-as-soon-as-you-recognize macro would create the precedence rules of the macro-rewritten source. Which might cover a fair amount of useful ground. Needs to be explored though. E.g., x .op1. y .op2. z => op2(op1(x, y), z) But you could override with parens in the ordinary way: x .op1. (y .op2. z) => op1(x, op2(y, z)) But 2 * x + 3 .op1. y => 2 * x + op1(3, y) Etc. Well, something to think about ;-) Regards, Bengt Richter From aut_gbarros at uolinc.com Wed Dec 22 15:16:07 2004 From: aut_gbarros at uolinc.com (Gabriel Cosentino de Barros) Date: Wed, 22 Dec 2004 18:16:07 -0200 Subject: Best GUI for small-scale accounting app? Message-ID: <2814F26DA6908F41927A81C410C4991A02079C14@siamun.server.bl.corp.intranet> > I went w/wxPython for a second app because of its printing capabilities > and the large number of controls that come with it. Otherwise I would > use pyFltk for small apps. does FLK has any good positioning model now? Last time i checked i could only put something in pixel(sic) x=10, y=10, width=100, height=100. It's awfull because you have to write window resize code (argh) and the widgets doesn't repect the font size if said user is using a resolution like 1900x1600 with DPI of almost 300 (my case hehe). Since your testing enviroment probably was 800x600 with a DPI of no more then 100 you'r big screen user will have fonts 1/3 of the desired size. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ncoghlan at iinet.net.au Sat Dec 18 00:31:44 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sat, 18 Dec 2004 15:31:44 +1000 Subject: Why are tuples immutable? In-Reply-To: <20041217193502.1029.1533501037.divmod.quotient.12346@ohm> References: <20041217193502.1029.1533501037.divmod.quotient.12346@ohm> Message-ID: <41C3C0C0.6000002@iinet.net.au> Jp Calderone wrote: > On Fri, 17 Dec 2004 11:21:25 -0800, Jeff Shannon wrote: > > The correct characterization is that Python makes user-defined > mutable classes hashable (arguably correctly so) as the default > behavior. However, that is only achieved by using identity based equality by default. If you inherit from something which *doesn't* use identity based equality (say, list or dict), then the hashability isn't there. So while you're quite correct, it doesn't affect the OP's original complaint (not being allowed to use a list as a dictionary key). The Python docs are pretty precise about what the rules are: "__hash__(self) Called for the key object for dictionary operations, and by the built-in function hash(). Should return a 32-bit integer usable as a hash value for dictionary operations. The only required property is that objects which compare equal have the same hash value; it is advised to somehow mix together (e.g., using exclusive or) the hash values for the components of the object that also play a part in comparison of objects. If a class does not define a __cmp__() method it should not define a __hash__() operation either; if it defines __cmp__() or __eq__() but not __hash__(), its instances will not be usable as dictionary keys. If a class defines mutable objects and implements a __cmp__() or __eq__() method, it should not implement __hash__(), since the dictionary implementation requires that a key's hash value is immutable (if the object's hash value changes, it will be in the wrong hash bucket)." (from: http://www.python.org/dev/doc/devel/ref/customization.html) The key points are: 1. Objects which compare equal must have the same hash value 2. An object's hash value must never change during it's lifetime Lists could achieve the former, but not the latter. Tuples can achieve both, by virtue of being immutable, with immutable contents. Ditto for sets & frozensets. If you want to 'freeze' a mutable object for use as a key, the class below forces the use of object identity for keying purposes. As I'm sure Jeff would be quick to point out, the downside is that keying by different objects with the same value *does not work* if their identities are different (or rather, it does work - they just get new entries in the dictionary). However, whether that actually matters is going to be application dependent. Py> class KeyByIdentity(object): ... __slots__ = ["_obj", "_hash_value", "__hash__", "__cmp__"] ... def __new__(cls, obj): ... self = object.__new__(cls) ... self._obj = obj ... self._hash_value = id(obj) ... return self ... def __hash__(self): ... return self._hash_value ... def __cmp__(self, other): ... return cmp(self._hash_value, other._hash_value) ... Py> d = {} Py> key_list = [] Py> key_dict = {} Py> d[KeyByIdentity(key_list)] = "Keyed by a list" Py> d[KeyByIdentity(key_dict)] = "Keyed by a dict" Py> print "\n".join([str(x._obj) + ": " + str(y) for x, y in d.items()]) []: Keyed by a list {}: Keyed by a dict Py> key_list.append(3) Py> key_dict["A"] = 3 Py> print "\n".join([str(x._obj) + ": " + str(y) for x, y in d.items()]) [3]: Keyed by a list {'A': 3}: Keyed by a dict Py> key_with_same_id = key_list Py> d[KeyByIdentity(key_with_same_id)] 'Keyed by a list' Py> key_with_new_id = list(key_list) Py> d[KeyByIdentity(key_with_new_id)] Traceback (most recent call last): File "", line 1, in ? KeyError: <__main__.KeyByIdentity object at 0x009DA418> It would also be trivial to inherit from dict to make an "IdentityDict" which automatically used KeyByIdentity on its elements (using id() directly would be dangerous, as the dictionary then has no reference keeping the original object alive, thus failing to ensure the uniqueness of the keys - since id() only guarantees uniqueness with respect to currently existing objects). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From caleb1 at telkomsa.net Tue Dec 7 21:54:29 2004 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Tue, 07 Dec 2004 21:54:29 -0500 Subject: New experiences with PythonForDelphi Message-ID: Hi all I hadn't checked PythonForDelphi in a while, and decided to again today. All I can say is *wow*. Those guys are doing a terrific job. For those of you with a pascal background (and a Delphi/Kylix licence), you may want to check it out. In particular, the creation of binary addons/modules (e.g. pyd) is very nearly effortless (I have never used something like SWIG/Pyrex, so I can't compare), and this is where my interest lies. There is also support for Kylix, and I'm gonna try that out as soon as I can get the personal edition down my 56K line :) It is (good) news to me that C is not the only game in town for creating binary python extensions. Just a heads-up is all Caleb From opengeometry at yahoo.ca Thu Dec 9 15:24:10 2004 From: opengeometry at yahoo.ca (William Park) Date: 9 Dec 2004 20:24:10 GMT Subject: Parse XML using Python References: <1102577149.256162.316460@z14g2000cwz.googlegroups.com> Message-ID: <31rqj9F3fscsbU1@individual.net> anilby at gmail.com wrote: > Hi, > > I wanted to write a script that will read the below file: > > > . > > .... > > .. > > .. > > > > .. > > .. > > .. > > . > . > > . > > .... > > .. > > > > .. > > > > > > .. > and so on > > The output of the script shud be > > ABC > ..EFGA > ....ABDG > ..MON > > A1 > ..FGA > ....BG > > Please help me in writing a Python script for the above task. Take a look at http://home.eol.ca/~parkw/park-january.html on "Expat XML" section towards the end. Translating it to Python is left for homework. In essence, indent=.. start () { local "${@:2}" echo "${indent|*XML_ELEMENT_DEPTH-1}$label" } xml -s start "`< file.xml`" which prints ..ABC ....EFGA ......ABDG ....MON ..A1 ....FGA ......BG with modified input, ie. wrapping XML pieces into single root tree. -- William Park Open Geometry Consulting, Toronto, Canada Linux solution for data processing. From jstroud at mbi.ucla.edu Mon Dec 13 14:50:08 2004 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 13 Dec 2004 11:50:08 -0800 Subject: Python mascot proposal In-Reply-To: References: Message-ID: <200412131150.08184.jstroud@mbi.ucla.edu> As far as python.png below is concerned, I am reminded of the structure of the HIV virus: http://www.avert.org/pictures/hivstructure.htm Pleasing to virologists and drug companies, but as a single, computer-type guy, it makes my skin crawl in more ways than one. On Sunday 12 December 2004 07:40 pm, Brian Beck wrote: > Here are a couple of images/logos (quite a bit > different from a mascot) I've been working on... > > http://exogen.cwru.edu/python.png > http://exogen.cwru.edu/python2.png > > If anyone can think of a way to break free of the reptile-oriented > thought process but maintain clear, symbolic imagery, I'd love to see > more suggestions or renditions! -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics 611 Charles E. Young Dr. S. MBI 205, UCLA 951570 Los Angeles CA 90095-1570 http://www.jamesstroud.com/ From __peter__ at web.de Sat Dec 4 12:29:46 2004 From: __peter__ at web.de (Peter Otten) Date: Sat, 04 Dec 2004 18:29:46 +0100 Subject: assymetry between a == b and a.__eq__(b) References: <9YNsBls/K7gH089yn@the-wire.com> Message-ID: Tim Peters wrote: > See the Python (language, not library) reference manual, section 3.3.8 > ("Coercion rules"), bullet point starting with: > > Exception to the previous item: if the left operand is an > instance of a built-in type or a new-style class, and the right > operand is an instance of a proper subclass of that type or > class, ... So that is settled then. Not the most likely place to investigate when one has just read that "Arguments to rich comparison methods are never coerced" in 3.3.1 ("Basic customization"), though. Peter From richie at entrian.com Thu Dec 9 10:39:05 2004 From: richie at entrian.com (Richie Hindle) Date: Thu, 09 Dec 2004 15:39:05 +0000 Subject: Python Docs. Hardcopy 2.4 Library Reference, interested? In-Reply-To: <87oeh3v98s.fsf@network-theory.co.uk> References: <87oeh3v98s.fsf@network-theory.co.uk> Message-ID: <67sgr0dsh2kakd05j5tqhij0uh045mmvp5@4ax.com> [Brian] > I have one in the pipeline but I'm waiting for sales of the Python > Tutorial and Python Language Reference to justify bringing it out. I'd be interested to know how many of these manuals you sell...? This is only idle curiosity, and if you don't want to say then that's no problem. (I'd briefly considered doing this myself, until I found your site.) -- Richie Hindle richie at entrian.com From ch.list at us-hampton.mail.saic.com Tue Dec 14 11:49:06 2004 From: ch.list at us-hampton.mail.saic.com (Chris) Date: Tue, 14 Dec 2004 11:49:06 -0500 Subject: Python IDE In-Reply-To: <41BF1839.900@advfn.com> References: <41BF1692.6000103@us-hampton.mail.saic.com> <41BF1839.900@advfn.com> Message-ID: <41BF1982.2020104@us-hampton.mail.saic.com> >> What IDE's do y'all recommend for Python? I'm using PythonWin atm, >> but I'd like something with more functionality. > Oh god we're all going to die. -chuckle- Hopefully I don't start off a full fledged war.-grin- > But er, ActiveState Komodo is quite nice IIRC (can't use it anymore as > all my coding is commercial and I don't need it enough to spend that > much cash on it) but EditPlus is nice once you get it setup but not very > IDEy. Eclipse with one of the various Python modules is horrible don't > bother. There is of course always Emacs, but again it's hardly Visual > Studio (im only talking about the UI, emacs fans please dont flame me) > > Personally my vote goes for Komodo, it's at least worth a try with a > personal liscense. Why didn't you like Eclipse? Was it that the Python modules were bad, or just Eclipse in general? I use it for my Java developement and haven't had any problems with it. Chris From Dennis.Benzinger at gmx.net Thu Dec 9 04:37:43 2004 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Thu, 09 Dec 2004 10:37:43 +0100 Subject: wxPython bug In-Reply-To: <3APtd.4339201$yk.652531@news.easynews.com> References: <3APtd.4339201$yk.652531@news.easynews.com> Message-ID: <41b81ce4$1@news.uni-ulm.de> Jive wrote: > [...] > What to do? Ask in comp.soft-sys.wxwindows From bgailer at alum.rpi.edu Mon Dec 6 19:43:39 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon, 06 Dec 2004 17:43:39 -0700 Subject: [Python-Help] Programming help In-Reply-To: <001001c4db38$69675e10$6c0880ca@Alfred> References: <006801c4db34$31a7f650$670880ca@Alfred> <1102297812.85.807@mint-julep.mondoinfo.com> <001001c4db38$69675e10$6c0880ca@Alfred> Message-ID: <6.2.0.14.0.20041206172438.05a56a30@mail.mric.net> At 07:07 PM 12/5/2004, Alfred Canoy wrote: >Please help me out:(.. I've been trying to figure this out for 2 days now.. >I don't know what to use to print all the list of numbers. I hve know >idea how should I do this. I tried a lot of trial & error for the the def, >dict, .list( ). have no luck. >I just need to find this out then I'm good to go for the whole thing. I >have save the other test source code for this problem. I just need to >combine it after I figure this out. >Thank you all! > > >Source code: > ># compute the Mean, Median & Mode of a list of numbers: > >sum = 0.0 > >print 'This program will take several numbers then average them' >count = input(' How many numbers would you like to sum: ') >current_count = 0 >freq = {} >freq [current_count] = number > >while current_count < count: > current_count = current_count + 1 > number = input ('Enter a number: ') > print "Number", current_count,":",number > sum = sum + number >print " [x,...,x] ?" It's hard to respond since there is so much amiss in your code. Inside the while loop you need to append each user entry to a list. Then you can print the list. Have you studied list operations in a tutorial? Also it is unclear what you intend by freq [current_count] = number. There is no variable named "number" at that point in the program, so the program should crash at that statement. I think you want that statement inside the loop also, although it is not doing anything useful. If you want to capture frequencies you need to use the number as a dictionary key, and increment the value under that key. Clean things up as best you can then come back for the next round. Bob Gailer bgailer at alum.rpi.edu 303 442 2625 home 720 938 2625 cell From ianb at colorstudy.com Fri Dec 31 04:01:45 2004 From: ianb at colorstudy.com (Ian Bicking) Date: Fri, 31 Dec 2004 03:01:45 -0600 Subject: Securing a future for anonymous functions in Python In-Reply-To: <10t900i7r97386a@news.supernews.com> References: <10t84q9icqjnie7@news.supernews.com> <10t900i7r97386a@news.supernews.com> Message-ID: <41D51579.9070509@colorstudy.com> John Roth wrote: >> I appreciate some of the motivation, but merely avoiding giving >> something a name doesn't seem like a laudible goal. > > Actually, it is a laudable goal. It's always easier to understand > something when it's right in front of your face than if it's > off somewhere else. Naming the function doesn't move it far away. It changes the order (you have to define it before you use it), and it introduces a name. >> The one motivation I can see for function expressions is >> callback-oriented programming ... > > Well, that's true, but that's a very global statement: > when you pass a function into another routine, it's > essentially a callback. Sure, technically. But I'm thinking of real use cases. One I'm familiar with is things like map and filter. These are generally better handled with list expressions (and MUCH more readable as such, IMHO). Another is control structures, ala Ruby or Smalltalk. IMHO, we have all the control structures we need -- while, for, if. Most "novel" control structures in Ruby or Smalltalk are just another take on iterators. The exception being callbacks, and perhaps some other lazy evaluation situations (though outside of what I think of as "callbacks", I can't think of any lazy evaluation situations off the top of my head). So that's why I think callbacks are important; callbacks in the style of Twisted Deferred, GUI events, etc. >> Function expressions could get really out of hand, IMHO, and could >> easily lead to twenty-line "expressions". That's aesthetically >> incompatible with Python source, IMHO. > > Anything can get out of hand; there's no way of legislating > good style without restricting the language so much that it > becomes unusable for anything really interesting. Even then > it doesn't work: see COBOL as a really good example of > good intentions gone seriously wrong. OK, I should go further -- even a two-line expression (i.e., an expression that contains meaningful vertical whitespace) is aesthetically incompatible with Python source. Which covers any anonymous function that is more powerful than lambda. I'm not arguing that it can be abused, but more that it isn't any good even when it's not being abused. > Have you ever programmed in a language that does use > anonymous functions extensively like Smalltalk? Yep, I've done a fair amount of Smalltalk and Scheme programming. I don't expect Python to act like them. I appreciate the motivation, but I don't think their solution is the right one for Python. -- Ian Bicking / ianb at colorstudy.com / http://blog.ianbicking.org From mauriceling at acm.org Tue Dec 7 23:48:42 2004 From: mauriceling at acm.org (Maurice LING) Date: Wed, 08 Dec 2004 04:48:42 GMT Subject: Python for Palm OS? In-Reply-To: References: Message-ID: <41b687a6$1@news.unimelb.edu.au> Peter Hansen wrote: > Erik Max Francis wrote: > >> I just got myself a new Treo 650 and was looking around for Python for >> Palm projects. The only ones I find are Pippy >> >> http://pippy.sourceforge.net/ >> >> and Python to Palm Pilot Port >> >> http://www.isr.uci.edu/projects/sensos/python/ >> >> both of which look to be rather stale. They're both based on the 1.5 >> codebase, and both appear to be unmaintained (Pippy has the last news >> date in 2002; I couldn't find an obvious date for PPPP). >> >> Is there any news regarding Python on the Palm OS front? > > > I haven't seen any news, and gave up on the above as well. > > I did, however, find http://netpage.em.com.br/mmand/plua.htm , > a Palm port of Lua (4.0 currently, 5.0 in beta). It's quite > effective and, to a Python fan, not so far from Python that > I particularly mind. > > Just an FYI... > > -Peter As mentioned, since Pippy is pretty old or rather based on rather old code base, can it be assumed that not much is happening at this front? This might be dumb to ask then, does anyone know if Pippy had been used in any noticeable form for Palm development anywhere? Or it's more of an proof of concept kind of thing? Or has anyone envisioned anything? Cheers Maurice From grante at visi.com Wed Dec 29 16:56:05 2004 From: grante at visi.com (Grant Edwards) Date: 29 Dec 2004 21:56:05 GMT Subject: Why tuples use parentheses ()'s instead of something else like <>'s? References: <41d314c6$0$30032$a1866201@visi.com> <33gjr1F3siliuU1@individual.net> <41d31bbf$0$12737$a1866201@visi.com> Message-ID: <41d327f5$0$30072$a1866201@visi.com> On 2004-12-29, Dan Sommers wrote: > They're guillemets (with an "e"); this is a [relatively] well-known > Adobe SNAFU. Ah. Googling for "guillemots punctuation" did turn up enough hits that it didn't occur to me that I was using the wrong spelling. -- Grant Edwards grante Yow! at TAILFINS!!... click... visi.com From fredrik at pythonware.com Sun Dec 12 04:13:29 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 12 Dec 2004 10:13:29 +0100 Subject: handy stacktrace class References: Message-ID: Will Ware wrote: >I was fooling with some Python code, and starting to miss the > Exception.printStackTrace() feature in Java. traceback.print_exc() From vincent at visualtrans.de Wed Dec 8 00:12:49 2004 From: vincent at visualtrans.de (vincent wehren) Date: Wed, 08 Dec 2004 06:12:49 +0100 Subject: simple GUI question In-Reply-To: References: Message-ID: Roose wrote: > I have been writing only command line programs in python, and I need a way > to simply pop up a GUI dialog box, with an "OK" box. Simple huh? > > I have used tkMessageBox.showwarning. This works OK but it also pops up an > empty frame -- i.e. it pops up 2 things. Is there a way to disable this, or > is there an alternate way of doing things? OK call me anal, but it bothers > me. You want somthing like: root = Tkinter.Tk() root.withdraw() msg = tkMessageBox.showwarning("Ooops", "Some warning") -- Vincent Wehren > > Another thing I would *like* but is not strictly necessary would be to > change the font size and color of the text within the box. Is there a good > way of doing that? I have googled around but can't find any decent example > code for some reason. > I can use Python 2.3 only, and only stuff that is included in the standard > install. For something so trivial I can't roll out a new version of Python > or any additional software. > > So I assume Tkinter is pretty much my only option, or is that not the case? > > Thanks for any help. > > Roose > > From tjreedy at udel.edu Tue Dec 14 17:54:26 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 14 Dec 2004 17:54:26 -0500 Subject: lies about OOP References: <1102995205.949964.76020@c13g2000cwb.googlegroups.com> <41be9e31$0$7078$afc38c87@news.optusnet.com.au> Message-ID: I did not really 'get' OOP until after learning Python. The relatively simple but powerful user class model made more sense to me than C++. So introducing someone to Python, where OOP is a choice, not a mandate, is how *I* would introduce a procedural programmer to the subject. YMMV. Terry J. Reedy From g.horvath at gmx.at Fri Dec 17 07:09:31 2004 From: g.horvath at gmx.at (Gregor Horvath) Date: Fri, 17 Dec 2004 12:09:31 GMT Subject: BASIC vs Python In-Reply-To: References: <867jnh1i9v.fsf@guru.mired.org> <41c2af36$0$2443$afc38c87@news.easynet.co.uk> Message-ID: <%%zwd.12738$NS3.10253@news.chello.at> Peter Otten wrote: > May you could give us an idea of the current state of basic affairs then by > translating the following example snippet: yes you can do it in VB6, but pythons lists and dictionarys are superior to those built in in VB and I think to those in most other languages. > > It's me wrote: > > >>I saw this code from an earlier post: >> >>lst1 = ["ab", "ac", "ba", "bb", "bc"] >>lst2 = ["ac", "ab", "bd", "cb", "bb"] >>dct1 = dict.fromkeys(lst1) >>print [x for x in lst1 if x not in dct1] >>print [x for x in lst1 if x in dct1] I think line3 should be >>dct1 = dict.fromkeys(lst2) correct? VB6 Code: Sub xy() Dim lst1 As New Collection Dim lst2 As New Collection lst1.Add "ab", "ab": lst1.Add "ac", "ac": lst1.Add "ba", "ba": lst1.Add "bb", "bb": lst1.Add "bc", "bc" lst2.Add "ac", "ac": lst2.Add "ab", "ab": lst2.Add "bd", "bd": lst2.Add "cb", "cb": lst2.Add "bb", "bb" For Each item In lst1 If ColHasKey(lst2, item) Then Debug.Print "in:" & item Next For Each item In lst1 If Not ColHasKey(lst2, item) Then Debug.Print "not in:" & item Next End Sub Function ColHasKey(col As Collection, item) As Boolean On Error GoTo er A = col(item) ColHasKey = True Exit Function er: If Err.Number = 5 Then ColHasKey = False Else Err.Raise Err.Number End If End Function From steve at holdenweb.com Sun Dec 12 16:17:39 2004 From: steve at holdenweb.com (Steve Holden) Date: Sun, 12 Dec 2004 16:17:39 -0500 Subject: newsgroups In-Reply-To: References: <41b89738$0$11034$a1866201@visi.com> <41b8a6f9$0$9757$a1866201@visi.com> Message-ID: Francis Lavoie wrote: > Do we need a special account or something to use the newsgroup instead > of the mailling list? Yes, you have to find an NNTP server that carries comp.lang.python. It's possible your Internet service provider runs such a news server and will let you access it as a part of your subscription (this is the case for me). If not then you'll have to contract with a third party news service (some of htese are available for free). Alternatively, take a look at http://www.gmane.com/, a mailing list/newsgroup interface service which I believe offers an NNTP service. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From adam at cognitcorp.com Fri Dec 3 09:21:33 2004 From: adam at cognitcorp.com (Adam DePrince) Date: Fri, 03 Dec 2004 09:21:33 -0500 Subject: distinction between float & int In-Reply-To: <34534aed041203060153117a5c@mail.gmail.com> References: <34534aed041203060153117a5c@mail.gmail.com> Message-ID: <1102083692.4942.8.camel@localhost.localdomain> On Fri, 2004-12-03 at 09:01, Ishwor wrote: > hi all, > can anyone tell me why this distinction? i mean why it returns False > on floats?? > >>> a = 1 > >>> b = 1 > >>> a is b > True > >>> a = 1.1 > >>> b = 1.1 > >>> a is b > False > >>> > > thanx . > -- > cheers, > Ishwor Gurung In Python, some integers and strings are interned. 1 is 1 is true because 1 and 1 are "simplified" to point to the same object. >>> 2 is (1+1) True >>> 102 is (101+1) False >>> 102 == (101+1) True Why? To quote the Python/C API Reference Manual (section 7.2.1) The current implementation keeps an array of integer objects for all integers between -1 and 100, when you create an int in that range you actually just get back a reference to the existing object. When strings are compiled, they are interned, so ... >>> "abc" is "abc" True >>> "abc" is ("ab" + "c") False >>> "abc" == ( "ab" + "c" ) True >>> "abc" is intern("ab" + "c" ) True Is does not measure equality ... the _is_ operator returns true if its two parameters internally have the same pointer value and are the same object. Floating point values are not interned, so 1.1 is 1.1 is false. Adam DePrince From matt.fryer at gmail.com Sat Dec 11 05:35:25 2004 From: matt.fryer at gmail.com (Matt) Date: 11 Dec 2004 02:35:25 -0800 Subject: Raw Sockets vs. What? Message-ID: <1102761325.189000.217480@f14g2000cwb.googlegroups.com> Hi, I'm new to Python (1 week), but I'm writing an out-of-process debugger for a Python ide. I tried execFile first, but stuff leaked over from the wx libraries we are using. And, anyway, the next code set is PHP so this has to be tackled anyway. So, the question: How to communicate between two instances of the python interpreter? Specifically, I need to pass the api and objects from bdb, the base class for the debugger. One interpreter runs the ide, the other the debugger and client code. We were talking and just opening a socket and doing the rest from there came up. This, to me, (admitedly a java guy) seems like a lot of work. If it were just setting breakppoints and stepping, well ok. But I also want to have introspection on the debugger side objects. I could use raw sockets and write a bunch of stuff. Does anyone have a suggestion about some pythonesque way to tackle this? Many thanks in advance, Matt From edreamleo at charter.net Mon Dec 20 10:12:31 2004 From: edreamleo at charter.net (Edward K. Ream) Date: Mon, 20 Dec 2004 09:12:31 -0600 Subject: When was extended call syntax introduced? Message-ID: <1P1yd.64$4F.26@fe07.lga> Various documentation pages, e.g. http://www.python.org/doc/2.3.3/lib/non-essential-built-in-funcs.html state that the apply function has been deprecated since 2.3. Can anyone tell me when extended call syntax was actually introduced? Neither googling nor brief checks of the 'What's new in Python' or the pep's has turned up this information. Thanks. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: Literate Editor with Outlines Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From roy at panix.com Fri Dec 17 15:31:24 2004 From: roy at panix.com (Roy Smith) Date: 17 Dec 2004 15:31:24 -0500 Subject: Why are tuples immutable? References: <41BE1644.8050906@freemail.gr> <10s4a4rso24vb83@corp.supernews.com> <10s6aadbs66o8f0@corp.supernews.com> Message-ID: Jeff Shannon wrote: > The aesthetic purity I'm referring to is that Python respects the proper > meaning of hashing, even if it doesn't force the programmer to. The > builtin objects that Python provides don't offer a __hash__() method > that fails to meet the mathematical prerequisites of a proper hash > function -- that is, objects that are equal will hash identically. In > addition, dictionaries expect keys to have proper hashing semantics, > such that a given object's hash value will not change over its > lifetime. It is not possible for a mutable object to satisfy both > aspects of proper hashing behavior, therefore Python does not pretend > that mutable objects are hashable. If you look back over this thread, I've given several examples of mutable objects which meet your requirements: * Objects that are equal hash the same. * Hash value does not change over the lifetime of the object. All that's needed is to define __hash__() and __cmp__() methods which only look at some subset of the object's data atrributes. You can keep those attributes constant (perhaps enforced with __setattr__() hooks) and let others mutate. To be honest, I've never found a real-life need to do this. I often want to use user-defined classes as keys, but it's just plain easier to build tuples of that attribute subset on the fly than to build all the required methods to make it work in-place. If memory was tight, it might be worthwhile to avoid creating all those extra tuples, but so far I havn't been faced with that. I agree that saying "dictionary keys must be immutable" is a reasonable simplification which works fine the vast majority of the time. I would not, however, go as far as saying, "It is not possible for a mutable object to satisfy both aspects of proper hashing behavior". From davidb at mcs.st-and.ac.uk Tue Dec 7 17:12:01 2004 From: davidb at mcs.st-and.ac.uk (davidb at mcs.st-and.ac.uk) Date: 7 Dec 2004 14:12:01 -0800 Subject: PDF count pages In-Reply-To: References: Message-ID: <1102457521.840864.217980@z14g2000cwz.googlegroups.com> Andreas Lobinger wrote: > > Jose Benito Gonzalez Lopez wrote: > > Does anyone know how I could do in order > > to get/count the number of pages of a PDF file? > > Like this ? [...] > >>> import pdffile > >>> pf = pdffile.pdffile('../rfc1950.pdf') > >>> import pages > >>> pp = pages.pages(pf) > >>> len(pp.pagelist) [...] That's interesting. Here's my equivalent example: Python 2.3.3 (#1, May 2 2004, 15:04:07) [GCC 3.2.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from pdftools import pdffile >>> doc = pdffile.PDFDocument("PDFSPEC.pdf") >>> doc.count_pages() 518 The API shown above is from an unreleased version of pdftools (http://www.boddie.org.uk/david/Projects/Python/pdftools/). > This is an example of the usage of pdfplayground. pdfplayground > is available via sourceforge. There is no package at the > moment, but you should be able to check out via anon-cvs. I browsed the code in CVS and it looks like a pretty comprehensive implementation. Maybe we should join forces. David From ndbecker2 at verizon.net Fri Dec 3 09:23:48 2004 From: ndbecker2 at verizon.net (Neal D. Becker) Date: Fri, 03 Dec 2004 09:23:48 -0500 Subject: float point properties access Message-ID: Is there a way in python to access properties of floats? I need something equiv to C DBL_EPSILON defined in . From steve at holdenweb.com Wed Dec 29 16:24:00 2004 From: steve at holdenweb.com (Steve Holden) Date: Wed, 29 Dec 2004 16:24:00 -0500 Subject: calling functions across threads In-Reply-To: References: Message-ID: Steven Bethard wrote: > Fernando Perez wrote: > >> Steven Bethard wrote: >> >> >>> Fernando Perez wrote: >>> >>>> Steven Bethard wrote: >>>> >>>> >>>> >>>>> I get the correct output, but if you run this yourself, you'll see >>>>> that >>>>> the numbers 1 through 10 aren't printed in sync with the writes (i.e. >>>>> every half second); they're all printed at the end. Could someone >>>>> explain to me why this happens, and how (if possible) I can get the >>>>> numbers printed in sync with the appends to the list? >>>> >>>> >>>> >>>> This is just a shot in the dark, as I'm quite ignorant of threading >>>> details. >>>> But what happens if you try adding a sys.stdout.flush() call after >>>> the print >>>> statement in your custom update() method? It may just be a flushing >>>> problem >>>> what makes the output appear out of sync... >>> >>> >>> Strangely enough, that causes PythonWin to hang... Why that would be >>> true, I have no idea... >> >> >> >> Mmh. I wouldn't be surprised if under pythonwin, sys.stdout is not >> the true >> python sys.stdout. Check the following: >> >> sys.stdout is sys.__stdout__ >> >> The answer is probably false. In that case, they may have implemented >> some >> incomplete object whose flush method is broken, or something similar. >> I can't >> confirm, as I don't have windows access, so this is just a guess. > > > Just to verify, yes, the answer is False: > > py> import sys > py> sys.stdout is sys.__stdout__ > False > > Is there a list to ask PythonWin specific questions somewhere, or should > I just wait for a PythonWin expert around here? > > Steve There's a mailing list at python-win32 at python.org - it's listed on www.python.org should you choose to subscribe, and the volume isn't generally high (maybe 5-10 messages per day). regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From insert at spam.here Mon Dec 20 23:34:37 2004 From: insert at spam.here (Doug Holton) Date: Mon, 20 Dec 2004 22:34:37 -0600 Subject: BASIC vs Python In-Reply-To: References: <867jnh1i9v.fsf@guru.mired.org> <41c2af36$0$2443$afc38c87@news.easynet.co.uk> <%%zwd.12738$NS3.10253@news.chello.at> Message-ID: Michael Hoffman wrote: > Gregor Horvath wrote: > > > Or make any given standard python object accessible from MS Excel in 2 > > minutes. > > from win32com.client import Dispatch > > xlApp = Dispatch("Excel.Application") > xlApp.Visible = 1 > xlApp.Workbooks.Add() > xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!' > xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!' > xlApp.ActiveWorkbook.Close(SaveChanges=0) > xlApp.Quit() > del xlApp > > (stolen from ) As already pointed out to you, that is the exact opposite of what the poster was asking for. From steven.bethard at gmail.com Wed Dec 22 14:30:32 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 22 Dec 2004 19:30:32 GMT Subject: cmp of multiple attributes In-Reply-To: <1gp7prj.10lk90x1mllp7qN%aleaxit@yahoo.com> References: <20041215152606.1029.1225319887.divmod.quotient.10976@ohm> <5Zmwd.272268$R05.114851@attbi_s53> <1gp7prj.10lk90x1mllp7qN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Comparisons of tuples, lists, etc, are *lexicographical*: the first > items are compared; iff they're equal, then the second items, and so > forth. IOW, exactly what you want in this case. Just to check my understanding, this means that: cmp(a0, b0) or cmp(a1, b1) or ... or cmp(aN, bN) should give the same result as: cmp((a0, a1, ... aN), (b0, b1, ... bN)) right? Steve From aleaxit at yahoo.com Wed Dec 29 18:11:41 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 30 Dec 2004 00:11:41 +0100 Subject: what would you like to see in a 2nd edition Nutshell? References: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> <1104358120.403274.266290@c13g2000cwb.googlegroups.com> Message-ID: <1gpkz4y.1br7bp4b95d93N%aleaxit@yahoo.com> Grig Gheorghiu wrote: > As a tester, my vote goes to extending the "Testing" subsection of the > "Testing, debugging and optimizing". I'd like to see more testing tools > discussed there. Maybe py.test, PyFIT, and possibly others. Thanks! Very helpful input. Testing surely needs AND deserves more attention all around, yes. Alex From mwm at mired.org Sat Dec 18 13:40:04 2004 From: mwm at mired.org (Mike Meyer) Date: Sat, 18 Dec 2004 12:40:04 -0600 Subject: A rational proposal References: <864qik472n.fsf@guru.mired.org> <10s8serklea429c@news.supernews.com> Message-ID: <86y8fvqwl7.fsf@guru.mired.org> "John Roth" writes: > "Mike Meyer" wrote in message > news:864qik472n.fsf at guru.mired.org... >> PEP: XXX >> Title: A rational number module for Python >> The ``Rational`` class shall define all the standard mathematical >> operations: addition, subtraction, multiplication, division, modulo >> and power. It will also provide the methods: >> >> - max(*args): return the largest of a list of numbers and self. >> - min(*args): return the smallest of a list of numbers and self. > > max() and min() are already part of the standard library. > Providing them as instance methods is quite irregular. They don't handle decimals or rationals. This is following the lead of the decimal package. >> - decimal(): return the decimal approximation to the rational in the >> current context. > > This ought to be the responsibility of the decimal() constructor. > I can see including it here to avoid adding it to the decimal() > constructor, but IMO it's bad design. Good point. Currently, objects now how to convert themselves to int, float and complex. Should Rational now how to convert itself to Decimal (and conversely, decimal now how to convert itself to Rational)? >> - inv(): Return the inverse of self. > I presume this means that if the rational is x/y, then it > returns y/x? Is this better wording: - inv(): Return self to the power -1. >> Rationals will mix with all other numeric types. When combined with an >> integer type, that integer will be converted to a rational before the >> operation. When combined with a floating type - either complex or >> float - the rational will be converted to a floating approximation >> before the operation, and a float or complex will be returned. The >> reason for this is that floating point numbers - including complex - >> are already imprecise. To convert them to rational would give an >> incorrect impression that the results of the operation are >> precise. Decimals will be converted to rationals before the >> operation. [Open question: is this the right thing to do?] > > I'd prefer to have rationals converted to decimals before > the operation, for the same reason that they're converted > to floats. Decimals also have limited precision. I'm of two minds about this one. One is that decimals have limited precision. But they represent their values exactly, whereas 1E73 isn't a 1 followed by 73 zeros when converted to an int. On the other hand, every decimal has a rational equivalent, but not vice versa. Thanks, http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From someone at microsoft.com Fri Dec 3 21:14:05 2004 From: someone at microsoft.com (Jive) Date: Sat, 04 Dec 2004 02:14:05 GMT Subject: pythonwin broke References: <8uQrd.4000728$yk.610217@news.easynews.com> <031220040934408194%mrjean1ATcomcastDOTnet@no.spam.net> <031220041807179214%mrjean1ATcomcastDOTnet@no.spam.net> Message-ID: Do an experiment for me. Open Pythonwin from the start menu. Use the FILE menu to open a .py file. Now try to close the window you just opened using the X button in the upper right. Did it close? Try closing Pythonwin using its X button. From bokr at oz.net Thu Dec 30 19:31:45 2004 From: bokr at oz.net (Bengt Richter) Date: Fri, 31 Dec 2004 00:31:45 GMT Subject: Securing a future for anonymous functions in Python References: <10t84q9icqjnie7@news.supernews.com> <10t92ofkstn7if9@corp.supernews.com> Message-ID: <41d49202.1462565467@news.oz.net> On Thu, 30 Dec 2004 15:15:51 -0800, Jeff Shannon wrote: >David Bolen wrote: > >>>I think this specific use case -- defining callbacks -- should be >>>addressed, rather than proposing a solution to something that isn't >>>necessary. (...) >>> >>> >> >>I'd be interested in this approach too, especially if it made it simpler >>to handle simple manipulation of callback arguments (e.g., since I often >>ignore a successful prior result in a callback in order to just move on >>to the next function in sequence). >> >> > >It seems to me that what most people *actually* want, when asking for >lambdas, is a quicker and more convenient way to get closures. (At >least, that's what the vast majority of examples of lambda use seem to >be for.) Perhaps one could get a bit more traction by looking for >improved closure syntax instead of focusing on the anonymous function >aspect. Not sure what you mean by closure here. To me it means the necessary external environment needed to be captured for use by a function definition getting exported from its definition environment. I.e., it is something a function uses, and part of the function definition, but it isn't the function itself. I would compare a closure more to a callable class instance's self attributes, except that the latter are more flexible. In fact, for a callback, a constructor call creating a suitable callable class instance could sometimes work well as a substitute for a lambda expression, ISTM. (I.e., when it is not important to show the code in line, and the differences are in initialization parameters rather than code). > >All of the suggestions for anonymous multiline functions (with embedded >indentation) seem to me to miss what seems to me to be the only >significant benefit of lambda -- its ability to be used in-line without >creating a huge ugly tangle. (I'd argue that lambdas create a *small* >ugly tangle, but apparently that's just me. ;) ) Lambdas do have some >value in defining callbacks, but that value derives almost exclusively >from the fact that they are in-line (rather than a few lines above). They do let you define _code_ inline, which a constructor call doesn't do (unless you pass a string to compile etc -- not cool). >Mimicking function-def indentation inside of another function's arglist >strikes me as an abomination just waiting to happen; in comparison, the >need to type a name twice seems trivial. Self-restraint can avoid abominations ;-) > >As a result, it seems to me that, rather than generalize lambdas into >"full" anonymous functions (with most of the negatives and few of the >positives of lambda), it would be much better to specialize them further >into inline-closure-creators, where they can serve a valuable purpose >without quite as much risk of code pollution. There's always the temptation to be enforcer when being persuader is not the easiest ;-) (BTW, again, by closure, do you really mean deferred-action-thingie?) Regards, Bengt Richter From flamesrock at gmail.com Mon Dec 27 19:35:31 2004 From: flamesrock at gmail.com (flamesrock) Date: 27 Dec 2004 16:35:31 -0800 Subject: Confusion About Classes Message-ID: <1104194131.792545.140560@z14g2000cwz.googlegroups.com> Hi, I've been playing like mad with all sorts of python modules..but I still can't seem to get my head around the proper use of a class and self. The question stems from this code I made(snippet): -------------------------------------------------------------------------------------- import httplib, ftplib, urllib2, exPyCrypto, score_configurations #custom class create_server: def __init__(self, domain, servername, master_ftpUSER, master_ftpPASS, score_ftpUSER, score_ftpPASS, httpport=None, ftpport=None): self.domain = domain if httpport is None: self.__httpport = '80' else: self.__httpport = httpport if ftpport is None: self.__ftpport = '21' else: self.__ftpport = ftpport if servername is None: self.__servername = 'SCORE-SERVER' else: self.__servername = servername self.master_ftpUSER = master_ftpUSER self.master_ftpPASS = master_ftpPASS self.score_ftpUSER = score_ftpUSER self.score_ftpPASS = score_ftpPASS self.parser = ConfigParser.ConfigParser() def createUniversalConfig(self, score_domain, score_servername, score_port): '''''' self.parser.add_section('score') self.parser.set('score', 'domain', self.score_domain) self.parser.set('score', 'server', self.score_servername) self.parser.set('score', 'server', self.score_port) ------------------------------------------------------------------------------------- The goal is to create a create_server object with the given parameters, and then call the method createUniversalConfig() without passing and parameters to it. So here are my questions: 1) in the function parameter heading <> do I need to include those parameters as written, like this-- <> or not pass any parameters at all? 2) Do I reference the body of the function like I originally wrote it: self.parser.add_section('score') self.parser.set('score', 'domain', self.score_domain) self.parser.set('score', 'server', self.score_servername) self.parser.set('score', 'server', self.score_port) or, like this self.parser.add_section('score') self.parser.set('score', 'domain', score_domain) self.parser.set('score', 'server', score_servername) self.parser.set('score', 'server', score_port) (if the goal is to call the method from the object without any parameters) 3) Can I create a configParser object and just call self.parser.set() inside the function without passing it as a parameter, or do I pass it as a parameter and call it as parser.set (without the 'self' statement.) Basically..I'm confused on the proper use of 'self' in this type of situation, even after going through all these different tutorials. Any ideas? -thanks in advance\ From rkern at ucsd.edu Sat Dec 25 23:00:41 2004 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 25 Dec 2004 23:00:41 -0500 Subject: Optional Static Typing In-Reply-To: <1103952924.715051.44540@f14g2000cwb.googlegroups.com> References: <1103795375.843649.286620@c13g2000cwb.googlegroups.com> <1103952924.715051.44540@f14g2000cwb.googlegroups.com> Message-ID: Luis M. Gonzalez wrote: > I don't understand why this discussion on optional static typing came > up right at this moment. > As far as I know, it has been discussed many times in the past, and > there even was a SIG that simply died... but it seems that it never was > something of much interest to python developers (that's my impression, > I might be wrong). > > Now, that the Pypy project is steadily advancing (and which is aimed at > making Python faster while keeping it dynamic and simple), why has this > topyc been raised? > > Also there's starkiller, which deals with agressive type inference and > compilation to native code. If these projects are serious and are well > headed, then I don't know why we are talking now of static typing. > > Lets say that Pypy and/or Starkiller end up as succesful projects, what > would be the advantage of having static typing in Python? Starkiller would *love* type declarations. In Michael Salib's words (to my recollection), "every piece of type information helps." I'm sure that PyPy's code generator(s) could use this information to good effect, too. Automatic type inferencing is great, but sometimes the inference is "object". Being able to supply more information about types helps Starkiller keep the inferences tight and specific. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From peter at engcorp.com Wed Dec 1 08:11:32 2004 From: peter at engcorp.com (Peter Hansen) Date: Wed, 01 Dec 2004 08:11:32 -0500 Subject: 2.4 or 2.3.4 for 2.3 software? In-Reply-To: References: Message-ID: Jens Bloch Helmers wrote: > Can we expect the current release of 2.4 to be just as reliable as > 2.3.4 for 2.3 compliant software? Yes, you can expect it. Whether it *will be* just as reliable is of course a different story. The best way to find out is to install it and use it with your 2.3 software. Of course, you already did that during the beta period, right? ;-) -Peter From zathras at thwackety.com Fri Dec 24 20:32:24 2004 From: zathras at thwackety.com (Michael Sparks) Date: Sat, 25 Dec 2004 01:32:24 +0000 (GMT) Subject: ANN: Axon 1.0 Message-ID: Hi, Axon is the core set of modules in Kamaelia[1], and is essentially a set of tools for managing concurrency inside a single thread. Whilst it is a pre-requisite for Kamaelia, it can be used independently as well. Rather than the usual statemachine (or state machine derived) approach it uses communicating generators. The design of the system is inspired very heavily by asynchronous hardware verification systems. (Which leads to similarities with CSP & unix pipelines) [1] Kamaelia is BBC R&D testbed for developing media network protocols. (It takes it's name from an internal BBC R&D project aimed at looking how we scale internet delivery of the BBC's TV & Radio output.) Sourceforge page with Axon release: http://sourceforge.net/projects/kamaelia/ Installation is the usual "python setup.py install" dance, and the API should be fairly stable, and has evolved over a period of time, hence the 1.0 release version. The project became test infected rather late in the day, so some of test suite has been retrofitted if it looks a bit odd! Kamaelia's website: http://kamaelia.sourceforge.net/ (Explains context and there's a presentation that contains a simplified implementation using decorators, which might help show use cases) I've copied much of the README at the end of this mail for the curious. (License is the Mozilla tri-license : MPL1.1, GPL2.0, LGPL2.1) Merry Christmas! (Hopefully someone will find this a nice christmas toy :) Michael. -------- Axon is the core of Kamaelia. The contents of this directory must be installed before the rest of Kamaelia can be used. It can also be used independently of Kamaelia. The install procedure is python's usual dance: * python setup.py install Documentation is held in two places: * The usual 'pydoc name' - probably worth starting with: pydoc Axon.Component * The test suite is designed to allow you to get low level API behaviour information - "should X,Y, Z work? If so, what happens?". It's a partly retrofitted test suite, but some is TDD. (TDD took over late in the project) As a result, for example, passing a -v flag result in the docstring for each test to be dumped in a form that allows collation, and summarisation. (For an example of what we expect to automate from the test suite, see the end of this README file) Sample producer/consumber & wrapper component system: /-- testComponent -----------------------------------------------\ | | | +-- Producer ----+ +-- Consumer ----+ | | | |result|--->|source| |result|--->|_input|| | +----------------+ +----------------+ | | | \----------------------------------------------------------------/ The testComponent creates 2 subcomponents, creates the links in place, and takes the output from the consumer and links it to its own private/internal _input inbox. When it recieves a value from the consumer, it reports this fact and ceases operation. Producer sends values to its result outbox Consumer takes values from its source, does some work and sends results to its outbox (It's probably worth noting that an introspection system would be possible to write/nice to see that would be able to derive the above diagram from the running system) Example code: class Producer(component): Inboxes=[] Outboxes=["result"] def __init__(self): self.__super.__init__() def main(self): i = 100 while(i): i = i -1 self.send("hello", "result") yield 1 class Consumer(component): Inboxes=["source"] Outboxes=["result"] def __init__(self): self.__super.__init__() self.count = 0 self.i = 30 def doSomething(self): print self.name, "Woo",self.i if self.dataReady("source"): self.recv("source") self.count = self.count +1 self.send(self.count, "result") def main(self): yield 1 while(self.i): self.i = self.i -1 self.doSomething() yield 1 class testComponent(component): Inboxes=["_input"] Outboxes=[] def __init__(self): self.__super.__init__() self.producer = Producer() self.consumer = Consumer() self.addChildren(self.producer, self.consumer) self.link((self.producer, "result"), (self.consumer, "source")) linkage(self.consumer,self,"result","_input", self.postoffice) def childComponents(self): return [self.producer, self.consumer] def mainBody(self): while len(self.inboxes["_input"]) < 1: yield 1 result = self.recv("_input") print "Consumer finished with result:", result, "!" r = scheduler() p = testComponent() children = p.childComponents() p.activate() for p in children: p.activate() scheduler.run.runThreads(slowmo=0) (It would probably be nice to have better syntactic sugar here by using dictionaries, operators (eg '|' ) and decorators. The presentation on the website on Kamaelia shows a partial semi-reimplementation of ideas using decorators to eliminate the classes above) For various reasons it makes sense to run all Axon code using the -OO flags - this is due to the currently highly inefficient debug framework. One downside of async systems is that debuggers tend to have a hard time - but this has been thought of upfront :), the downside is that if you run with debugging enabled/possible, then the system runs like a pig. (Due to some rather heavy duty fumbling around in the garbage collector) Michael, December 2004 ----------------------------------------------------------------------------- Example of expected autodocs from test suite: (Ideally these would be merged with (or replace!)the doc strings/output from pydoc.) ./test_Component.py -v 2>&1 | ~/bin/parsetestResults.pl Standard: __init__ Class constructor is expected to be called without arguments. __str__ Returns a string representation of the component - consisting of Component, representation of inboxes, representation of outboxes. Returns a string that contains the fact that it is a component object and the name of it. Public: addChildren All arguments are added as child components of the component. childComponents Returns the list of children components of this component. closeDownComponent stub method, returns 1, expected to be overridden by clients. dataReady Returns true if the supplied inbox has data ready for processing. initialiseComponent Stub method, returns 1, expected to be overridden by clients. link Creates a link, handled by the component's postman, that links a source component to it's sink, honouring passthrough, pipewidth and synchronous attributes. main Returns a generator that implements the documented behaviour of a highly simplistic approach component statemachine. This ensures that the closeDownComponent method is called at the end of the loop. It also repeats the above test. mainBody stub method, returns None, expected to be overridden by clients as the main loop. recv Takes the first item available off the specified inbox, and returns it. removeChild Removes the specified component from the set of child components and deregisters it from the postoffice. send Takes the message and places it into the specified outbox, throws an exception if there is no space in a synchronous outbox. synchronisedBox Called with no arguments sets the outbox 'outbox' to being a synchronised box, with a maximum depth of 1. synchronisedSend Takes a list of things to send, and returns a generator that when repeatedly called tries to send data over a synchronised outbox. private: __addChild Registers the component as a child of the component. Internal function. _activityCreator Always returns true. Components are microprocesses instantiated by users typically - thus they are creators of activity, not slaves to it. Internal function. _closeDownMicroprocess Checks the shutdownMicroprocess message for the scheduler contains a reference to the postoffice associated with the component. Returns a shutdownMicroprocess. Internal Function. _collect Takes the first piece of data in an outbox and returns it. Raises IndexError if empty. Internal function. _collectInbox Tests with default args. All these deliveries should suceed. Internal Function. Tests with default args. Should raise IndexError as the box should be empty in this test. Internal Function. Tests with inbox arg. Should raise IndexError as the box should be empty in this test. Internal Function. Tests with inbox arg. Tests collection. Internal Function. _deliver Appends the given message to the given inbox. Internal Function. Checks delivery to a synchronised inbox fails when it is full using the force method. Checks delivery to a synchronised inbox fails when it is full. _passThroughDeliverIn Appends the given message to the given inbox. Internal Function. Should throw noSpaceInBox if a synchronised box is full. When force is passed as true the box can be overfilled. _passThroughDeliverOut Appends the given message to the given outbox. Internal Function. Checks delivery is limited to the pipewidth. Checks delivery is limited to the pipewidth. _passThroughDeliverOut_Sync Appends messages to given outbox. Should throw noSpaceInBox when full. _safeCollect Wrapper around _collect - returns None where an IndexError would normally be thrown. Internall Function. From aahz at pythoncraft.com Wed Dec 29 18:03:26 2004 From: aahz at pythoncraft.com (Aahz) Date: 29 Dec 2004 18:03:26 -0500 Subject: Why tuples use parentheses ()'s instead of something else like <>'s? References: <1104299822.394489.161500@z14g2000cwz.googlegroups.com> <41d314c6$0$30032$a1866201@visi.com> <33gjr1F3siliuU1@individual.net> Message-ID: In article , Roy Smith wrote: >In article <33gjr1F3siliuU1 at individual.net>, > Reinhold Birkenfeld wrote: >> >> >>+<< being an operator > >Looks more like a smiley for "guy wearing a bowtie" You know Ben Yalow? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From mrjean1ATcomcastDOTnet at no.spam.net Wed Dec 1 20:45:46 2004 From: mrjean1ATcomcastDOTnet at no.spam.net (Jean Brouwers) Date: Thu, 02 Dec 2004 01:45:46 GMT Subject: Python 2.4 and Tkinter References: Message-ID: <011220041747270144%mrjean1ATcomcastDOTnet@no.spam.net> FWIW, we just installed Python 2.4 (on RH Linx 8), rebuilt it from scratch and everything is fine. Tkinter is there, _tkinter as well and idle comes up as expected. /Jean Brouwers In article , Jeffrey Barish wrote: > http://www.python.org/moin/TkInter From jeff at ccvcorp.com Thu Dec 23 15:19:36 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 23 Dec 2004 12:19:36 -0800 Subject: list Integer indexing dies?? In-Reply-To: References: Message-ID: <10sm9po4ddbrca5@corp.supernews.com> Ishwor wrote: >On Thu, 23 Dec 2004 13:33:16 -0300, Batista, Facundo > wrote: > > >>[Ishwor] >> >>#- > What should 035[0] cough up? Be carefull it should >>#- >>#- >>>035[0] >>#- 3 # my own opinion. >> >> >why 3? The reason we get 3 and not 0 here is the *fact* that Python >knows that its an octal rep. and not decimal ;-) > > Except that, at the point where the indexing takes place, Python *doesn't* know that it's an octal rep. All integer literals, regardless of representation, generate exactly the same bytecode. >>> def f(): ... x = 035 ... y = 29 ... >>> dis.dis(f) 0 SET_LINENO 1 3 SET_LINENO 2 6 LOAD_CONST 1 (29) 9 STORE_FAST 1 (x) 12 SET_LINENO 3 15 LOAD_CONST 1 (29) 18 STORE_FAST 0 (y) 21 LOAD_CONST 0 (None) 24 RETURN_VALUE >>> Given that Python may not even have access to the .py file, only the .pyc (which has lost all record of the source representation), there's no way for the interpreter to do what you suggest. Jeff Shannon Technician/Programmer Credit International From nid_oizo at yahoo.com_removethe_ Wed Dec 29 22:20:29 2004 From: nid_oizo at yahoo.com_removethe_ (Nicolas Fleury) Date: Wed, 29 Dec 2004 22:20:29 -0500 Subject: Why would I use inspect.isclass()? In-Reply-To: References: Message-ID: > an_instance=Abc() > But what good is that? Of course I know Abc is a class, why would I want to > inspect it so that it would tell me what I already know? Well, for no reason in that case. For the same reason you would not call isinstance(an_instance, Abc) if you already know an_instance is an instance of Abc. > def Hello(self, some_class): > # since I don't know if the argument passed down *is* a class or not, I > would: > if inspect.isclass(some_class)==True: > ... > return > ### > > But that obviously isn't what isclass is for. What should I use? Well, it's obviously what isclass is for;) (By the way, you would be better not compare your conditions with True, unless it's really what you want). I guess another example would be an assert on the type of argument: def foo(someClass): assert inspect.isclass(someClass) # rest of code This way errors on types are handled at the beginning and at the same time the code it documenting itself. The function could also be useful in cases where you do some C++-like overloading mechanism. Anyway, isclass, like iscallable, are functions that are not used often, but you still might need them. Regards, Nicolas From fredrik at pythonware.com Wed Dec 22 14:46:23 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 22 Dec 2004 20:46:23 +0100 Subject: list IndexError References: <34534aed04122211413845b33e@mail.gmail.com> Message-ID: "Ishwor" wrote: > i am trying to remove an item 'e' from the list l but i keep getting IndexError. > I know the size of the list l is changing in the for loop & its sort > of trivial task but i found no other way than to suppress the > IndexError by doing a pass. any other ways you guys can suggest? this is discussed in the tutorial: http://docs.python.org/tut/node6.html#SECTION006200000000000000000 "It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, such as lists). If you need to modify the list you are iterating over (for example, to duplicate selected items) you must iterate over a copy. The slice notation makes this particularly convenient: >>> for x in a[:]: # make a slice copy of the entire list ... if len(x) > 6: a.insert(0, x) ... >>> a ['defenestrate', 'cat', 'window', 'defenestrate'] From bob_smith_17280 at hotmail.com Wed Dec 15 11:38:02 2004 From: bob_smith_17280 at hotmail.com (bob_smith_17280 at hotmail.com) Date: 15 Dec 2004 08:38:02 -0800 Subject: Fill a Server Message-ID: <1103128682.041915.62730@c13g2000cwb.googlegroups.com> I think this is a silly task, but I have to do it. I have to fill a file server (1 TB SATA RAID Array) with files. I wrote a Python script to do this, but it's a bit slow... here it is: import shutil import os import sys import time src = "G:" des = "C:scratch" os.chdir(src) try: for x in xrange(5000): for root, dirs, files in os.walk(src): for f in files: shutil.copyfile(os.path.join(root, f), "C:\scratch\%s%s" %(f,x)) print "Done!!!" except Exception, e: print e time.sleep(15) sys.exit() The problem with this is that it only copies about 35 GB/hour. I would like to copy at least 100 GB/hour... more if possible. I have tried to copy from the IDE CD drive to the SATA array with the same results. I understand the throughput on SATA to be roughly 60MB/sec which comes out to 3.6 GB/min which should be 216 GB/hour. Can someone show me how I might do this faster? Is shutil the problem? Also, my first attempt at this did a recursive copy creating subdirs in dirs as it copied. It would crash everytime it went 85 subdirs deep. This is an NTFS filesystem. Would this limitation be in the filesystem or Python? Thanks Bob Smith "I once worked for a secret government agency in South Africa... among other things, we developed and tested AIDS. I am now living in an undisclosed location in North America. The guys who live with me never let me drive the same route to work and they call me 'Bob Smith 17280' as there were more before me." -- Bob Smith From sylvain.thenault at nospam.logilab.fr Thu Dec 30 11:20:49 2004 From: sylvain.thenault at nospam.logilab.fr (Sylvain Thenault) Date: Thu, 30 Dec 2004 17:20:49 +0100 Subject: import with "python -O" References: Message-ID: On Thu, 30 Dec 2004 16:56:17 +0100, Sylvain Thenault wrote: > Hi there ! > > I'm usually relying on the fact that pyc file are autogenerated when > necessary (ie usually when the py file has been modified since the pyc > creation). However, it doesn't seems to work correctly when the -O option > is given to the interpreter : > > syt at musca:test$ python > Python 2.3.4 (#2, Sep 24 2004, 08:39:09) > [GCC 3.3.4 (Debian 1:3.3.4-12)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > .>>> from logilab import pylint > .>>> pylint.__file__ > '/home/syt/cvs_work/logilab/pylint/__init__.pyc' > .>>> > syt at musca:test$ python -O > Python 2.3.4 (#2, Sep 24 2004, 08:39:09) > [GCC 3.3.4 (Debian 1:3.3.4-12)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > .>>> from logilab import pylint > .>>> pylint.__file__ > '/usr/lib/python2.3/site-packages/logilab/pylint/__init__.pyo' > > The PYTHONPATH has not changed but the interpreter seems to take the first > pyo it finds, even if there is a more recent .py file before in the python > path. Should this behaviour be considered as normal ? ok, my fault... The problem was that the logilab subdirectory didn't have anymore the __init__.py file, but only the __init__.pyc file. Adding it fix the problem. Thank you four your attention. -- Sylvain Th?nault LOGILAB, Paris (France). http://www.logilab.com http://www.logilab.fr http://www.logilab.org From bokr at oz.net Wed Dec 8 20:00:01 2004 From: bokr at oz.net (Bengt Richter) Date: Thu, 09 Dec 2004 01:00:01 GMT Subject: [BUG] IMO, but no opinions? Uncle Tim? was: int(float(sys.maxint)) buglet ? References: <41b3f08f.105027181@news.oz.net> <41b5f3ba.9062691@news.oz.net> Message-ID: <41b7882c.112600621@news.oz.net> On Tue, 7 Dec 2004 16:44:56 -0500, Tim Peters wrote: >[Tim Peters] >>> ... there's no promise anywhere, e.g., that Python will return an int >>> whenever it's physically possible to do so. > >[Bengt Richter] >> Ok, I understand the expediency of that policy, but what is now the meaning >> of int, in that case? Is it now just a vestigial artifact on the way to >> transparent unification of int and long to a single integer type? > >I don't really know what you mean by "int". Python isn't C, and the Me neither, now that I'd been nudged into thinking about it -- that's why I was *asking* ;-) >distinction between Python's historical short integers and unbounded >integers is indeed going away. "int" is the name of a specific Python >type, and the constructor for that type (which old-timers will think >of as the builtin function named "int()") is happy to return unbounded >integers in modern Pythons too. Python-level distinctions here have >become increasingly meaningless over time; I expect that "int" and >"long" will eventually become synonyms for the same type at the Python >level. I guess the above is a long spelling of "yes" as an answer to my question ;-) I assumed that python int was not indifferent to the underlying platform's native C integer representations, and that its presence was a compromise (now being deprecated) to permit armslength internal representation control, for whatever reason (most likely to ease interfacing with something using a fixed representation deriving from a C library). > >The distinction remains very visible at the Python C API level, for >obvious reasons, but even C code has to be prepared to deal with that >a PyIntObject or a PyLongObject may be given in contexts where "an >integer" is required. > >> Promises or not, ISTM that if int->float succeeds in preserving all significant bits, >> then then a following float->int should also succeed without converting to long. > >Yes, that was obvious . But you haven't explained why you >*care*, or, more importantly, why someone else should care. It just IME a corner-case discrepancy in a 1:1 correspondence is a bug waiting to appear and bite. I admit to an aesthetic component to my unease with it though ;-) >as obviously doesn't bother me, and I'm bold enough to claim that it >"shouldn't" bother anyone. This seems as peripheral to me as arguing >that "there's something wrong" about returning "a long" in either of >these cases: > >>>> import os >>>> os.path.getsize("a.py") >165L >>>> f = open("a.py") >>>> f.tell() >0L > >The implementations of getsize() and .tell() certainly could have >endured complications to ensure that "an int", and not "a long", was >returned whenever physically possible to do so -- but why bother? > Those calls have obvious reasons for handling large-file sizes, but they don't explicitly call for an int representation (whatever it means). """ Help on class int in module __builtin__: class int(object) | int(x[, base]) -> integer | | Convert a string or number to an integer, if possible. A floating point | argument will be truncated towards zero (this does not include a string | representation of a floating point number!) When converting a string, use | the optional base. It is an error to supply a base when converting a | non-string. If the argument is outside the integer range a long object | will be returned instead. """ Maybe the above should be amended to say that the "integer range" is [-sys.maxint, sys.maxint-1] when the argument is a float ;-) Or explain what "an integer" means ;-) >... >> The 2.3.2 source snippet in floatobject.c : >> -------------- >> static PyObject * >> float_int(PyObject *v) >> { >... > >> But this is apparently accessed through a table of pointers, so would you oppose >> an auto-configuration that one time tested whether >> int(float(sys.maxint))==sys.maxint and int(float(-sys.maxint-1))==-sys.maxint-1 >> (assuming that's sufficient, of which I'm not 100% sure ;-) and if so switched >> the pointer to a version that tested if(LONG_MIN <= wholepart && >>> wholepart<=LONG_MAX) >> instead of the safe-for-some-obscure-system version? > >In the absence of identifying an actual problem this would solve, I >would oppose adding *gratuitous* complication. Abusing your sense of >aesthetics isn't "an actual problem" in this sense to me, although it >may be to you. Of course you're welcome to make any code changes you >like in your own copy of Python . > >> Of course, if int isn't all that meaningful any more, I guess the problem can be >> moved to the ctypes module, if that gets included amongst the batteries ;-) > >What problem? If there's an actual bug here, please open a bug report. I guess there won't be a bug until it bites, so we have to imagine an app where it would matter not to be able to get sys.maxint from a float (except via int(int(floatarg)) ;-) However unlikely, that seemed to me most likely to happen if there was interfacing to some external function requiring a C-derived integer representation, which is why I thought ctypes might be where a corner case long that should have been an int might be detected, and the "problem" might be solved there with a corner-case test and conversion, so as not to fail on a legitimate value whose specific representation is something the Python language per se is disassociating itself from ;-) Not saying it's a bug wrt Python's unified integer future, just noting the slow death of legacy expectations, and I guess tending to view it as a bug so long as int implies anything at all about representation, and sys.maxint purports to mean something specific about that ;-) Regards, Bengt Richter From exarkun at divmod.com Thu Dec 30 18:39:43 2004 From: exarkun at divmod.com (Jp Calderone) Date: Thu, 30 Dec 2004 23:39:43 GMT Subject: Other notes In-Reply-To: <86r7l7sczp.fsf@guru.mired.org> Message-ID: <20041230233943.26823.759513716.divmod.quotient.138@ohm> On Thu, 30 Dec 2004 15:16:42 -0600, Mike Meyer wrote: >Jp Calderone writes: > > > On Wed, 29 Dec 2004 12:38:02 -0600, Mike Meyer wrote: > >>Jp Calderone writes: > >> > This aside, not even Python 3.0 will be flexible enough to let you define > >> > an infix decorator. The language developers are strongly against supporting > >> > macros, which is what an infix decorator would amount to. > >> > >> Could you please explain how allowing new infix operators amount to > >> supporting macros? > > > > You misread - I said "what an infix decorator would amount to". Adding > > new infix operators is fine and in no way equivalent to macros. > > You misread, I said "allowing new infix oerpators amount to supporting > macros?" Clearly neither of us is following the point of the other here. Let me start over. Defining an infix decorator means changing the language in such a way that one function can change the syntax rules used in the definition of another function. It has nothing to do with the '@' syntax, since: @x def y(...): ... is no different than: def y(...): ... y = x(y) If one works to define an infix operator, both should. Otherwise, what is being used is not a "decorator" as it is currently defined. So my initial point was that If @infix("..") somehow works but y = infix("..")(y) does not, it is not a decorator. If it does, then I believe what you have added to Python is macros. > > >> > Now, they might be convinced to add a new syntax that makes a function > >> > into an infix operator. Perhaps something like this: > >> > > >> > def &(..)(x, y): > >> > return range(x, y + 1) > >> > >> And while you're at it, explain how this method of defining new infix > >> operators differs from using decorators in such a way that it doesn't > >> amount to supporting macros. > > > > Simple. You can't do anything except define a new infix operator with > > the hypothetical "def &( )" syntax. With real macros, you can > > define new infix operators, along with any other syntactic construct your > > heart desires. > > You failed to answer the question. We have two proposed methods for > adding new infix operators. One uses decorators, one uses a new magic > syntax for infix operators. Neither allows you to do anything except > declare new decorators. For some reason, you haven't explained yet, ^^^^^^^^^^ I assume you mean "infix operators" here. If so, this is likely the point on which we disagree. If you are suggesting adding "@infix('[punctuation]')" to the Python grammar, then I understand how you would see that as something less than macros. This is not how I interpreted the remarks. > you think that using decorators to declare infix operators would > amount to macros, yet using a new syntax wouldn't. Both require > modifying the grammer of the language accepted by the parser. How is > it that one such modification "amounts to macros", whereas the other > doesn't? Adding a new syntax for infix operator declaration is the same as the addition of any other syntax. It has nothing to do with macros, it is just new syntax. Adding the ability for arbitrary functions to modify the syntax used to define other arbtitrary functions, what would have to happen for @infix('..') to work, is adding macros. Hope I have expressed things more clearly, Jp From holywill at gmail.com Thu Dec 2 15:51:07 2004 From: holywill at gmail.com (Will) Date: Fri, 3 Dec 2004 09:51:07 +1300 Subject: Any affordable Python-based CRM & ERP solutions? Message-ID: <11a4311704120212515846a878@mail.gmail.com> Hi all, Please excuse the longish post. I'm new to Python (and programming), but love what I see and believe it to be an important language. I have (at least) one retail client (with single outlet at present) that requires a total business solution for their operation, preferably open source. They need: - an ecommerce website providing sales, customer service, order tracking and an opt-in newsletter - system for tracking inventory - full accounting system, tied-into the ecommerce website-- so full front-end and back-end system integration - possibly even point of sale tied-into the above. They've been using Windows up until now, but are happy to consider Linux, BSD, Mac, etc, as long as there's not a huge learning curve (they merely want a solution that works and is cost-effective). Other than standard accounting reporting requirements, they need the ability to add tax to local transactions. I have Googled with not a lot of contenders (Compiere-- http://www.compiere.org/index.html -- not Python and an Oracle license is required to run it; and I've just started reading about Bizar Shop-- http://www.bizarshop.com.au/). Anything else I've seen is either really expensive, doesn't fit the bill, or are not Python-based (which I'd ultimately like to promote). Because of the above requirements I was thinking something quite modular (that could be added to in future) would be the way to go. I like what I have seen with Plone and Zope but am unsure at present (given limited experience with these products) how one would integrate something into those solutions (if package didn't come from one 'vendor'), so that at least on the surface, everything appeared pretty seamless. Is this wishful thinking in Python at present? If so, have you encountered any other open source solutions that cover part of the above with Python handling the rest (and being easily integrated)? I look forward to any feedback. Thanks very much in advance. Cheers, Will :) From someone at microsoft.com Thu Dec 2 21:48:36 2004 From: someone at microsoft.com (Jive) Date: Fri, 03 Dec 2004 02:48:36 GMT Subject: pythonwin broke Message-ID: <8uQrd.4000728$yk.610217@news.easynews.com> I've un-installed Python 2.4, re-installed Python 2.3 and PythonWin for 2.3, but it's still broke. When I start PythonWin, sometimes it looks like it is going to be okay. But as soon as I open a .py file, the interactive window grabs the focus and will not let go. I am stumped. Is there something PythonWin uses that I could try re-installing? WxPython maybe? From Scott.Daniels at Acm.Org Mon Dec 27 14:38:25 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 27 Dec 2004 11:38:25 -0800 Subject: Optional Static Typing - Haskell? In-Reply-To: <10t0ggc4d4rg397@corp.supernews.com> References: <1103795375.843649.286620@c13g2000cwb.googlegroups.com> <10t0ggc4d4rg397@corp.supernews.com> Message-ID: <41d06236@nntp0.pdx.net> Michael Hobbs wrote: > I've always found that with Haskell, if I can get my program to > compile without error, it usually runs flawlessly. (Except for the > occasional off-by-one error. :-) Then you need "Scott and Dave's Programming Language" -- SAD/PL. By providing separate data types for even and odd numbers, you can avoid off-by-one errors ;-) --Tongue-in-cheek-ily-yours, Scott David Daniels Scott.Daniels at Acm.Org From deetsNOSPAM at web.de Fri Dec 3 14:28:57 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 03 Dec 2004 20:28:57 +0100 Subject: finding byte order References: <41b0b4ab$1@nntp0.pdx.net> <41b0c9e3$1@nntp0.pdx.net> Message-ID: > But, in fact, he says the files are always big endian. So, code like > the following should address his problem. Note I use type 'h' as an > example so I can easily read samples. I'm sorry, I confused that he asked for machine endianess. Then of course you are right. -- Regards, Diez B. Roggisch From hans at zephyrfalcon.org Thu Dec 30 17:02:20 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Thu, 30 Dec 2004 17:02:20 -0500 Subject: copying classes? In-Reply-To: References: <9C0FD378-59C7-11D9-927C-003065FB7B26@upf.edu> <1104345746.3398.69.camel@localhost.localdomain> <1104346382.3398.73.camel@localhost.localdomain> Message-ID: Jeff Epler wrote: > Here's an example of attempting to deepcopy a class: > >>>>class X: pass > > ... > >>>>import copy >>>>X is copy.deepcopy(X) > > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.2/copy.py", line 179, in deepcopy > raise error, \ > copy.Error: un-deep-copyable object of type Weird. I get (Python 2.3.4): >>> class X: pass ... >>> import copy >>> X is copy.deepcopy(X) True However: >>> class Foo: ... def bar(self, x, y, z): pass ... >>> import copy >>> FooCopy = copy.deepcopy(Foo) >>> FooCopy >>> Foo It appears it doesn't copy the class at all, you just get the same class back. -- Hans Nowak http://zephyrfalcon.org/ From usenet_spam at janc.invalid Wed Dec 22 16:10:00 2004 From: usenet_spam at janc.invalid (JanC) Date: Wed, 22 Dec 2004 21:10:00 GMT Subject: MIDI (was - Re: BASIC vs Python) References: <10sj8q6potitta2@corp.supernews.com> Message-ID: Bob van der Poel schreef: > Just as a side note, I remember reading somewhere that the Casio WK3000 > Keyboard uses Python. Not sure if that's internal or just for Casio's > own development. At the bottom it says: | 2. Python Programming Language - some of Casio's Internet Data | Expansion System is written in Python, a high-level interpreted, | interactive, object-oriented programming language (check your PC folder | holding the Casio wave converter program - it also holds a file called | python22.dll and other files ending in '.pyd' which are Python runtime | dlls). Programmers may be able to use Casio's runtime routines to create | new utilities for the wk3000. Python is free to download and use. | | I need someone to look inside the various runtime dll's and Python pyd's | and report back on what they discover... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From grig.gheorghiu at gmail.com Tue Dec 28 21:47:45 2004 From: grig.gheorghiu at gmail.com (Grig) Date: 28 Dec 2004 18:47:45 -0800 Subject: pyUnitPerf Message-ID: <1104288465.328992.120680@z14g2000cwz.googlegroups.com> I just released a Python port of Mike Clark's JUnitPerf. I called it pyUnitPerf and it's available at http://sourceforge.net/projects/pyunitperf. It is in a very early stage of development, but I think it's pretty usable (and useful) as it is. I already received an interesting comment from a hard-core Python user from Switzerland: "Problem with porting patterns/api's from java straight to python is that most of the outcome feels unpythonic. I'll not go about my own feelings python vs. java here now, but I just want to point out that there's already a rather large core of hard-python users who refuse to use pyUnit because of this, and pyUnitPerf's doomed to share this fate, unless of course somebody decides along the way to make it sexy and pythonic and takes on the trouble of lowering the red-flag again which java has become to lots of folks." My own experience with pyUnit has been very satisfactory and for me personally pyUnitPerf scratches an itch. I'm curious to find out more about people's feelings and opinions on this. I don't want to begin a flame war, but my personal take on it is that the various Java-based test frameworks are very useful and there's a lack of corresponding frameworks in Python. I'm thinking about tools such as HTTPUnit, Cactus, Abbot, The Grinder, and there are many others. I'm happy to see Jython being used more and more in such tools though (The Grinder, Test Maker, Marathon). Grig From steven.bethard at gmail.com Fri Dec 31 11:22:13 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 31 Dec 2004 16:22:13 GMT Subject: what is lambda used for in real code? In-Reply-To: <1gpngqs.gi6p511azrvn4N%aleaxit@yahoo.com> References: <1gpngqs.gi6p511azrvn4N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Steven Bethard wrote: > >>(2) lambda a: a.lower() >>My first thought here was to use str.lower instead of the lambda, but of >>course that doesn't work if 'a' is a unicode object: > > > Right, but string.lower works (after an 'import string'). More > generally, maybe it would be nice to have a way to say "call a method on > x" without x's type being checked, just like attrgetter says "fetch an > attribute on x" -- say s/thing like: > > def methodcaller(method_name, *a, **k): > def callit(x): > return getattr(x, method_name)(*a, **k) > callit.__name__ = method_name > return callit Yeah, that's exactly the kind of thing I was looking for. Very nice! >>(3) self.plural = lambda n: int(n != 1) >>Note that this is *almost* writable with def syntax. If only we could do: >> def self.plural(n): >> int(n != 1) > > > Not sure about the context, but maybe we could use, at class-level: > @staticmethod > def plural(n): > return int(n != 1) The context was within the _parse method of GNUTranslations. Basically, this method uses the fp passed in and a bunch of conditionals to determine how to define the plural method. So I don't think it can be done at the class level. Also, doesn't the assignment: self.plural = lambda n: int(n != 1) make this more like (at class level): def plural(self, n): return int(n != 1) that is, isn't this an instance method, not a staticmethod? py> class C(object): ... def __init__(self): ... self.plural = lambda n: int(n != 1) ... py> c = C() py> c.__class__.plural(1) Traceback (most recent call last): File "", line 1, in ? AttributeError: type object 'C' has no attribute 'plural' py> c.plural(1) 0 > Even though a good number of lambda uses may be avoidable or removable > by such means, I think there's just slightly too much variety -- in some > cases, a def with a name will have to be best Yup, that was my feeling. I was only able to rewrite as an expression about 50% of the lambdas that I found. However, I (personally) don't have much of a problem with adding a def in most of the other cases. The only ones that make me a little nervous are examples like: inspect.py: def formatargspec(args, varargs=None, varkw=None, ... formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), where the lambdas are declaring functions as keyword arguments in a def. I'm not sure how much I like adding to the module multiple function defs that are really intended to be accessed only within formatargspec. Still, were lambda to go away in Python 3000, it certainly wouldn't be the end of the world. ;-) Steve From pbowden at stx.rr.com Wed Dec 8 22:56:36 2004 From: pbowden at stx.rr.com (Phillip Bowden) Date: Thu, 09 Dec 2004 03:56:36 GMT Subject: Ideas for projects References: Message-ID: <2004120821564916807%pbowden@stxrrcom> On 2004-12-08 21:47:49 -0600, Mike Meyer said: > Phillip Bowden writes: > >> I feel that I've learned the language pretty well, but I'm having >> trouble thinking of a medium to large project to start. What are some >> projects that you have written in the past with Python? > > Why start with a medium to large project when you can do something > beneficial to the Python community at large. > > The most immediately useful thing to do is to follow the bugs link on > the python home page, and look for bugs in the standard libraries. Add > a test case to that libraries test code (lib/python2.X/test/...) to > test for the bug, then try and fix it. When you've done that, add > patches to the bug report. > > That's not only useful, but you spend time working on code that is > pythonic, so you'll learn how the language is used instead of just > what the language is. > > References: <41b0ed7e$0$85066$a1866201@visi.com> Message-ID: <41B49A49.1030201@donnal.net> Grant Edwards wrote: > You don't have to start from scratch. The telnet module has > hooks built-into it1 so that you can have it call your routines > to handle option negotiation. I did it once to impliment some > extra Telnet protocol features, and it wasn't difficult. Ok, you've inspired me to give it a try. First, I am assuming that you mean writing a custom callback function to send to Telnet.set_option_negotiation_callback(callback). Or did you mean writing a subclass of Telnet? Can someone provide an example of a callback function that I might use as a template for writing mine? This is unfamiliar territory for me, but as I can tell, the options in question are: 0, binary transmission 1, echo 3, suppress go ahead 23, send location And it may be that not all of these are critical, but if so, I don't know how to tell which is which. Eyal Lotem wrote: > I think I have a much simpler solution for you guys.. > Assuming you can run arbitrary code on the proprietary > server. Actually I cannot. The server runs a second-party information system, the primary access to which is third-party terminal emulator software that uses telnet connections. What I am trying to do is emulate this emulator. :-) Jp Calderone wrote: > cmd.exe is not a command line program. It's a terminal (emulator). > You might be able to use the telnet program, though. Yes, I see that now. Thanks. > Before doing this, > I'd recommend looking at Twisted's telnet support (both > the version in 1.3 and the version that will be in 2.0), > which actually supports option negotiation in a > reasonable way. I've been wanting to get acquainted with Twisted for awhile now, so this might be a good time to do so. I think I will give Grant's idea a whirl, but if I get bogged down there, I will definitely look at Twisted's telnet support. BTW, do you know if Twisted's option negotiation uses a callback function? I might download it just to take a look, even if I don't use it directly. Thanks, Donnal Walter Arkansas Children's Hospital From fredrik at pythonware.com Tue Dec 21 08:12:57 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 21 Dec 2004 14:12:57 +0100 Subject: List limits References: <1103561252.512434.143870@z14g2000cwz.googlegroups.com> <41C7FBED.7070904@iinet.net.au> Message-ID: Nick Coghlan wrote: > Given the size of the counter, is it actually physically possible for a list to run out of room > before the application runs out memory? depends on the system architecture, of course: consider an 64-bit computer with 32-bit integers and 256 GB of memory... From mwm at mired.org Thu Dec 16 20:01:07 2004 From: mwm at mired.org (Mike Meyer) Date: Thu, 16 Dec 2004 19:01:07 -0600 Subject: Python IDE References: <1103141895.620517.49860@z14g2000cwz.googlegroups.com> <1103218159.737726.241440@z14g2000cwz.googlegroups.com> Message-ID: <86zn0d20x8.fsf@guru.mired.org> A: What's the most obnoxious thing on Usenet? Q: topposting. "Dan Perl" writes: > "fuzzylollipop" wrote in message > news:1103218159.737726.241440 at z14g2000cwz.googlegroups.com... >> no it was a sideways remark at all the software socialists that thing >> EVERYTHING should be free, never said anything about Eclipse, just the >> people that insist ALL software should be free. > Interesting. I've never met anyone like that. If they are in high tech, > they must be hardware people, otherwise how would they make a living? And > I'm not sure "socialists" is the correct term in this case, it sounds to me > more like "communists". Or "liberals" for our friends in the US. I have. They make a living supporting free software. Take a look at www.zope.com and www.zope.org for an example (to be clear, I am *not* claiming that the folks at zope believe that all software should be free. Merely that they make a living off software they give away for free.) There have been other examples of such before. There was a group that made a living porting GCC to vender-specific hardware platforms, one condition being that the port wound up in the GCC suite. I believe they got bought by redhat. Phillip Greenspun once ran a company on this model as well. It did well until the venture capata -- Mike Meyer http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From gabriel.cooper at mediapulse.com Mon Dec 20 10:31:00 2004 From: gabriel.cooper at mediapulse.com (Gabriel Cooper) Date: Mon, 20 Dec 2004 10:31:00 -0500 Subject: Time Difference In-Reply-To: References: Message-ID: <41C6F034.5040203@mediapulse.com> GMane Python wrote: >Hello > I was wondering if there is an existing function that would let me >determine the difference in time. > For a more robust solution, checkout Python's profile module. http://docs.python.org/lib/profile.html From reinhold-birkenfeld-nospam at wolke7.net Tue Dec 21 17:11:56 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 21 Dec 2004 23:11:56 +0100 Subject: input record sepArator (not sepErator) In-Reply-To: <32rl8eF3o4b49U2@individual.net> References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com><1103501833.632076.74050@f14g2000cwb.googlegroups.com><1103504587.796518.245030@f14g2000cwb.googlegroups.com><41c6386e$1@nntp0.pdx.net> <32nmqtF3ninrdU1@individual.net> <41c6fe6b$1@nntp0.pdx.net> <32r5cfF3m90glU1@individual.net> <32rl8eF3o4b49U2@individual.net> Message-ID: <32rldcF3o4b49U4@individual.net> Reinhold Birkenfeld wrote: > Peter Otten wrote: >> Reinhold Birkenfeld wrote: >> >>>> the web: 4% >>>> python: 9% >>>> slashdot: 26% >>>> perl: 29% * >>> >>> How did you get these data points? >> >> I copied the numbers from these pages: >> >> http://www.google.com/search?q=separate >> http://groups-beta.google.com/group/comp.lang.python/search?group=comp.lang.python&q=separate >> http://www.google.com/search?q=site%3Aslashdot.org+separate >> http://groups-beta.google.com/group/comp.lang.perl.misc/search?group=comp.lang.perl.misc&q=separate >> >> Same thing for the "alternative" spelling. > > Thanks. A pity that there is no de.comp.lang.python, as for German posts > the "Standard/Standart" relation could be more accurate... > > or-just-count-the-misplaces-apostrophs-ly yours, Reinhold s/misplaces/misplaced/ just-don't-try-to-write-a-perfect-posting-ly yours! -- [Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs- mitteln inkompatibel. -- Florian Diesch in dcoulm From olepar at gmail.com Fri Dec 17 02:21:21 2004 From: olepar at gmail.com (Oleg Paraschenko) Date: 16 Dec 2004 23:21:21 -0800 Subject: Multithreading tkinter question References: Message-ID: <1103268081.325192.200460@z14g2000cwz.googlegroups.com> Hello John, > Mark, > > I tried your code snippet with Python 2.3.4. Worked fine. Only problem was > that the program fell off the end and terminated before the second thread > could open the Tkinter window. So I added these lines at the end to make the > main thread wait:- > > from msvcrt import kbhit, getch > print "\n\nPress key to end" > while not kbhit(): pass > getch() And I added print "\n\nPress key to end" l = sys.stdin.readline() > Both your Hello and Quit buttons worked. In my case "Hello" works and "Quit" doesn't (GUI stays frozen). Linux, Python 2.3.3, pygtk-0.6.9. > ... > > It is not optimal in that 'otherThread' runs continuously even when the > label is not being updated. What a waste of cpu cycles! This shows up in > that other windows apps slow right down. What is needed is a comms method > between threads that causes a thread to block while it's waiting for data > rather than my continuous polling approach. Would a Queue help here? > Yes, it should help. A time ago I tried to write a tkinter application, and my test code is available: A complete Python Tkinter sample application for a long operation http://uucode.com/texts/pylongopgui/pyguiapp.html Maybe you find it interesting. -- Oleg From the_proud_family at yahoo.com Sat Dec 4 08:13:09 2004 From: the_proud_family at yahoo.com (the_proud_family) Date: Sat, 04 Dec 2004 13:13:09 -0000 Subject: help needed Message-ID: HELP ME PLEASE!! I can't get the ball to go up right side and then I need it to turn around and keep turning until velocity=0 I have been at it for the past 2 weeks now i give up and call for help. Please if anyone can gide me through i will be so grateful!! I have pasted my code below from cmath import * from visual import * floor1 = box(length=10, height=0.5, width=4, color=color.blue) floor1.pos = (-6,4,0) floor1.axis= (5,-5,0) floor2 = box(length=10, height=0.5, width=4, color=color.blue) floor2.pos = (6,4,0) floor2.axis= (-5,-5,0) floor3 = box(length=7, height=0.5, width=4, color=color.blue) floor3.pos = (0,1.25,0) ball= sphere(radius=0.5, color=color.red) ball.pos=(-8.6,7.5,0) m=3. #kg angle=asin(3.6/5.)#radians g=-9.8 mu=.2 N=m*g*cos(angle) F=m*g*sin(angle) f=mu*N lax=(-N*sin(angle)+f*cos(angle))/m lay=(-N*cos(angle)-f*sin(angle)+m*g)/m rax=(+N*sin(angle)+f*cos(angle))/m ray=(-N*cos(angle)-f*sin(angle)+m*g)/m ds=0.01 dt=0.01 vx=lax*dt vy=lay*dt ball.velocity=vector(vx,vy,0) #print a while 1: rate(100) ball.velocity.x=ball.velocity.x+lax*dt ball.velocity.y=ball.velocity.y+lay*dt ball.pos=ball.pos+ball.velocity*dt if ball.x>-3.5 and ball.x<=3.5: vx=sqrt(2*(-g*ball.y+0.5*(vx**2+vy**2)-f*ds)) ball.velocity.x=ball.velocity.x+mu*g*dt ball.velocity.y=0 ball.pos=ball.pos+ball.velocity*dt if ball.x>3.5 and ball.x<8.6: vx=vx*cos(angle) vy=sqrt(2/m*(m*-g*ball.y-f*ds)) #print vy vy=vy*sin(angle) #print vy ball.velocity.x=ball.velocity.x+rax*dt ball.velocity.y=ball.velocity.y+ray*dt ball.pos=ball.pos+ball.velocity*dt #print ball.pos From seandavidross at hotmail.com Fri Dec 3 13:01:50 2004 From: seandavidross at hotmail.com (Sean Ross) Date: Fri, 3 Dec 2004 13:01:50 -0500 Subject: question on regular expressions References: Message-ID: "Darren Dale" wrote in message news:coq8n8$san$1 at news01.cit.cornell.edu... > I'm stuck. I'm trying to make this: > > file://C:%5Cfolder1%5Cfolder2%5Cmydoc1.pdf,file://C > %5Cfolderx%5Cfoldery%5Cmydoc2.pdf > > (no linebreaks) look like this: > > ./mydoc1.pdf,./mydoc2.pdf > > my regular expression abilities are dismal. I won't list all the > unsuccessful things I've tried, in a nutshell, the greedy operators are > messing me up, truncating the output to ./mydoc2.pdf. Could someone offer a > suggestion? > > Thanks, > Darren from os.path import basename import urllib url = 'file://C:%5Cfolder1%5Cfolder2%5Cmydoc1.pdf' print './%s'%basename(urllib.url2pathname(url)) HTH, Sean From aleaxit at yahoo.com Wed Dec 22 14:38:44 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 22 Dec 2004 20:38:44 +0100 Subject: cmp of multiple attributes References: <20041215152606.1029.1225319887.divmod.quotient.10976@ohm> <5Zmwd.272268$R05.114851@attbi_s53> <1gp7prj.10lk90x1mllp7qN%aleaxit@yahoo.com> Message-ID: <1gp7qi5.z3t5h310el1pgN%aleaxit@yahoo.com> Steven Bethard wrote: > Alex Martelli wrote: > > Comparisons of tuples, lists, etc, are *lexicographical*: the first > > items are compared; iff they're equal, then the second items, and so > > forth. IOW, exactly what you want in this case. > > Just to check my understanding, this means that: > > cmp(a0, b0) or cmp(a1, b1) or ... or cmp(aN, bN) > > should give the same result as: > > cmp((a0, a1, ... aN), (b0, b1, ... bN)) > > right? Yes, including 'shortcircuiting' the same way (you can check by having some ai define a __cmp__ which prints out some line of trace info). The single-cmp case is more general (since it also works for tuples of unequal length -- a shorter tuple being smaller, all other things being equal) and I suspect often speedier (but one would have to timeit for a few cases to check), but semantically they're the same. Alex From iketo2 at netscape.net Thu Dec 9 01:07:21 2004 From: iketo2 at netscape.net (Isaac To) Date: 09 Dec 2004 14:07:21 +0800 Subject: creating generators from function References: <_4Atd.207303$HA.197084@attbi_s01> <4e4a11f804120806185e65f357@mail.gmail.com> Message-ID: <87acsovwbq.fsf@sinken.local.csis.hku.hk> >>>>> "Mike" == Mike Meyer writes: Mike> I think it's a bit abnormal, because you have to scan the Mike> loop body for breaks. I tend to write: Mike> condition = True Mike> while condition: # corrected Mike> #code which iterates my simulation Then you'd have to scan the loop body to find the location where condition is set, which is more difficult than locating breaks normally. If you get a break, you really breaks. If you set condition to False, you still might be modifying it to True later in your code. And of course, most editors will highlight the "break" for you, while no editor will highlight for you the "condition" variable that you are staring at. Regards, Isaac. From d.lapasset Sat Dec 11 19:00:17 2004 From: d.lapasset (houbahop) Date: Sun, 12 Dec 2004 00:00:17 GMT Subject: from vb6 to Python References: Message-ID: Hi, I have used VB6 a lot too and Python appears to me as a good alternative to .net too, but the thing that will do the difference is the GUI... I hope the ones for Python are beautifull enough as appearence is an important thing to me in softwares. D. "MarcoL" a ?crit dans le message de news: xZoud.15126$Lg7.491897 at twister1.libero.it... > Hello, > I am a VB6 programmer and I would like to learn a new high level language > (instead of restarting from scratch with .NET), wich is opensource and > cross-platform, in order to develop cross-platform business applications > I think Python is the most suitable language for the scope. > My question are: > > - Which version of python is more suitable for creating cross-platform > GUI's? I've herard of PyGTK, wxPython, PyQT, tk, Anygui.. > > - What is the best IDE/RAD for Python (written in Python and OpenSource) > > - Does exist a tool (written in Python and OpenSource) like Crystal Report > for creating business reports? > > - Does exist a tool (written in Python and OpenSource) for makeing tables, > view, querys, relation of a database and generate the SQL script? > > - Is it possible, from Python, to work with sqlite? And with MsAccess? > > Thanks for your patience and your help. > > > Marco. From jerf at jerf.org Thu Dec 16 16:54:26 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Thu, 16 Dec 2004 16:54:26 -0500 Subject: Why no list heritable type? References: Message-ID: On Thu, 16 Dec 2004 12:53:32 -0800, James Stroud wrote: > Then it can be heritable and I can add or override methods. Why aren't > built in lists and dictionaries real heritable types that can save this > kind of patchwork? Is there a pythonic reason I am missing here? Along with others pointing out that list *is* inheritable and we don't quite know what you mean, I'd point out that any object that inherits the appropriate "magic methods", as described at http://python.org/doc/2.4/ref/sequence-types.html and http://python.org/doc/2.4/ref/sequence-methods.html "is" a list for most things you care about. Want to iterate? Implement __iter__, and "for blah in yourObjType:" will work as you'd want, even for things like trees if you like. Implement __getitem__ and you get [] working right. Python makes matching its "internal protocols" very easy, and you should definately take advantage of that. From fredrik at pythonware.com Mon Dec 20 16:42:43 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Dec 2004 22:42:43 +0100 Subject: extending python with a C-written dll References: <1103576588.929706.229990@z14g2000cwz.googlegroups.com> Message-ID: John Machin wrote: > By the way, lcc also *appears* to change "...Module3" to "...Module4" :-) $ more Include/modsupport.h ... #define Py_InitModule3(name, methods, doc) \ Py_InitModule4(name, methods, doc, (PyObject *)NULL, \ PYTHON_API_VERSION) ... From jdhunter at ace.bsd.uchicago.edu Wed Dec 29 22:00:19 2004 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Wed, 29 Dec 2004 21:00:19 -0600 Subject: Using Python in my programs In-Reply-To: (Squirrel Havoc's message of "Thu, 30 Dec 2004 01:50:11 GMT") References: Message-ID: >>>>> "Squirrel" == Squirrel Havoc writes: Squirrel> Hello. I am sorry if this has been asked before, but I Squirrel> am new here. Welcome Squirrel> If I recall correctly, Python can be used as a scripting Squirrel> language for other programs, as if the program had a Squirrel> builtin Python interpreter. I wish to extend my Squirrel> programs by making them scriptable with Python scripts. Squirrel> Is this possible? If so, does anyone know where I can Squirrel> find documentation on it? I searched the python.org site Squirrel> and didnt find anything useful Google embedding python. First link is a good place to start -- http://docs.python.org/ext/ext.html -- the official docs for extending and embedding python. Extending python is when you want to write or wrap some library, typically C, C++ or FORTRAN, and expose its functionality to python. Embedding python is when you want to use the python interpreter in your own program. Start with the official docs mentioned above, and then check out SWIG and boost::python. JDH From steven.bethard at gmail.com Sun Dec 12 22:56:52 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 13 Dec 2004 03:56:52 GMT Subject: Python mascot proposal In-Reply-To: References: Message-ID: <8q8vd.491044$wV.196123@attbi_s54> Brian Beck wrote: > > http://exogen.cwru.edu/python2.png Oooh, I like this one. Very cool! Steve From rkern at ucsd.edu Fri Dec 10 12:42:32 2004 From: rkern at ucsd.edu (Robert Kern) Date: Fri, 10 Dec 2004 09:42:32 -0800 Subject: style query: function attributes for return codes? In-Reply-To: References: <20041210104547.209a2b47.gry@ll.mit.edu> Message-ID: Steven Bethard wrote: > Sorry, I also meant to add that the other obvious way of dealing with > this kind of thing is to make the results keyword parameters: > > def get_connection(GOOD=1, BAD_AUTH=2, NO_SERVER=3): > if tcp_conn(): > if server_allows_conn(): > return GOOD > else: > return BAD_AUTH > else: > return NO_SERVER > > This has the benefit that if your user wants different return values > they can specify them, but the disadvantage that someone improperly > calling the function with more than 0 parameters will get, instead of an > error message, a strange return value. Another disadvantage is that one must compare the return value by value and not by name. That is, I cannot do something like this: code = get_connection() if code == NO_SERVER: ... -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From steven.bethard at gmail.com Fri Dec 17 04:49:09 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 17 Dec 2004 09:49:09 GMT Subject: create lowercase strings in lists - was: (No subject) In-Reply-To: References: Message-ID: Mark Devine wrote: > the trouble is it throws up the following error for set: > > $ ./test.py > Traceback (most recent call last): > File "./test.py", line 23, in ? > reflist = [normalize(element) for element in list1] > File "./test.py", line 20, in normalize > return set(text.split()) > NameError: global name 'set' is not defined > The set type became a builtin in Python 2.4. I would suggest upgrading, but if this is not an option, you can put this at the top of the file, and it should get rid of the NameError: from sets import Set as set Steve From maxm at mxm.dk Thu Dec 16 05:35:42 2004 From: maxm at mxm.dk (Max M) Date: Thu, 16 Dec 2004 11:35:42 +0100 Subject: Why are tuples immutable? In-Reply-To: References: <41BE1644.8050906@freemail.gr> Message-ID: <41c164c1$0$284$edfadb0f@dread12.news.tele.dk> Antoon Pardon wrote: > Well IMO there are two sides in this argument. The first is whether > or not python allows mutable keys. The second is whether or not > limiting keys to immutables in dictionaries provides a performance > gain. The problem is that you don't understand what dicts are typically used for. Because of the nonliniarity in dict lookups, dicts are used for optimisation. I actually think it's the most important tool for optimising Python code. If dicts allowed mutable keys, a dict would need to run code that corresponds to:: def has_key(key): for key in self.keys(): if a_key == key: return True return False Using immutable keys, a code can be generated for the key, that can be efficiently stored in something like a binary tree. This makes lookup *very much* faster, and is the speed concern that Python programmers care about. Not the time taken to convert a list into a tuple. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From miki.tebeka at zoran.com Wed Dec 8 05:55:01 2004 From: miki.tebeka at zoran.com (Miki Tebeka) Date: Wed, 8 Dec 2004 12:55:01 +0200 Subject: spawn or fork In-Reply-To: References: Message-ID: <20041208105449.GC300@zoran.com> Hello Colin, > I have a function > def printHello(): > fp = open('file','w') > fp.write('hello') > fp.close() > > I would like to call that function using spawn or fork. My questions are: > > 1. Which should I use spawn and fork are very different functions. Read the documentation on each. Note the "fork" is available only in Unix like systems. > 2. How do I call that function if it is defined in the same file. Just call it. def foo(): print 1 foo() Bye. -- ------------------------------------------------------------------------ Miki Tebeka http://tebeka.bizhat.com The only difference between children and adults is the price of the toys From danb_83 at yahoo.com Sun Dec 26 15:05:23 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 26 Dec 2004 12:05:23 -0800 Subject: A Revised Rational Proposal In-Reply-To: References: <86llbl7kvv.fsf@guru.mired.org> <1104071161.355661.10550@f14g2000cwb.googlegroups.com> Message-ID: <1104091523.776047.245680@c13g2000cwb.googlegroups.com> Steven Bethard wrote: > Dan Bishop wrote: > > Mike Meyer wrote: > >> > >>PEP: XXX > > > > I'll be the first to volunteer an implementation. > > Very cool. Thanks for the quick work! > > For stdlib acceptance, I'd suggest a few cosmetic changes: No problem. """Implementation of rational arithmetic.""" from __future__ import division import decimal as decimal import math as _math def _gcf(a, b): """Returns the greatest common factor of a and b.""" a = abs(a) b = abs(b) while b: a, b = b, a % b return a class Rational(object): """This class provides an exact representation of rational numbers. All of the standard arithmetic operators are provided. In mixed-type expressions, an int or a long can be converted to a Rational without loss of precision, and will be done as such. Rationals can be implicity (using binary operators) or explicity (using float(x) or x.decimal()) converted to floats or Decimals; this may cause a loss of precision. The reverse conversions can be done without loss of precision, and are performed with the from_exact_float and from_exact decimal static methods. However, because of rounding error in the original values, this tends to produce "ugly" fractions. "Nicer" conversions to Rational can be made with approx_smallest_denominator or approx_smallest_error. """ def __init__(self, numerator, denominator=1): """Contructs the Rational object for numerator/denominator.""" if not isinstance(numerator, (int, long)): raise TypeError('numerator must have integer type') if not isinstance(denominator, (int, long)): raise TypeError('denominator must have integer type') if not denominator: raise ZeroDivisionError('rational construction') factor = _gcf(numerator, denominator) self._n = numerator // factor self._d = denominator // factor if self._d < 0: self._n = -self._n self._d = -self._d def __repr__(self): if self._d == 1: return "Rational(%d)" % self._n else: return "Rational(%d, %d)" % (self._n, self._d) def __str__(self): if self._d == 1: return str(self._n) else: return "%d/%d" % (self._n, self._d) def __hash__(self): try: return hash(float(self)) except OverflowError: return hash(long(self)) def __float__(self): return self._n / self._d def __int__(self): if self._n < 0: return -int(-self._n // self._d) else: return int(self._n // self._d) def __long__(self): return long(int(self)) def __nonzero__(self): return bool(self._n) def __pos__(self): return self def __neg__(self): return Rational(-self._n, self._d) def __abs__(self): if self._n < 0: return -self else: return self def __add__(self, other): if isinstance(other, Rational): return Rational(self._n * other._d + self._d * other._n, self._d * other._d) elif isinstance(other, (int, long)): return Rational(self._n + self._d * other, self._d) elif isinstance(other, (float, complex)): return float(self) + other elif isinstance(other, _decimal.Decimal): return self.decimal() + other else: return NotImplemented __radd__ = __add__ def __sub__(self, other): if isinstance(other, Rational): return Rational(self._n * other._d - self._d * other._n, self._d * other._d) elif isinstance(other, (int, long)): return Rational(self._n - self._d * other, self._d) elif isinstance(other, (float, complex)): return float(self) - other elif isinstance(other, _decimal.Decimal): return self.decimal() - other else: return NotImplemented def __rsub__(self, other): if isinstance(other, (int, long)): return Rational(other * self._d - self._n, self._d) elif isinstance(other, (float, complex)): return other - float(self) elif isinstance(other, _decimal.Decimal): return other - self.decimal() else: return NotImplemented def __mul__(self, other): if isinstance(other, Rational): return Rational(self._n * other._n, self._d * other._d) elif isinstance(other, (int, long)): return Rational(self._n * other, self._d) elif isinstance(other, (float, complex)): return float(self) * other elif isinstance(other, _decimal.Decimal): return self.decimal() * other else: return NotImplemented __rmul__ = __mul__ def __truediv__(self, other): if isinstance(other, Rational): return Rational(self._n * other._d, self._d * other._n) elif isinstance(other, (int, long)): return Rational(self._n, self._d * other) elif isinstance(other, (float, complex)): return float(self) / other elif isinstance(other, _decimal.Decimal): return self.decimal() / other else: return NotImplemented __div__ = __truediv__ def __rtruediv__(self, other): if isinstance(other, (int, long)): return Rational(other * self._d, self._n) elif isinstance(other, (float, complex)): return other / float(self) elif isinstance(other, _decimal.Decimal): return other / self.decimal() else: return NotImplemented __rdiv__ = __rtruediv__ def __floordiv__(self, other): truediv = self / other if isinstance(truediv, Rational): return truediv._n // truediv._d else: return truediv // 1 def __rfloordiv__(self, other): return (other / self) // 1 def __mod__(self, other): return self - self // other * other def __rmod__(self, other): return other - other // self * self def _divmod__(self, other): return self // other, self % other def __cmp__(self, other): if other == 0: return cmp(self._n, 0) else: return cmp(self - other, 0) def __pow__(self, other): if isinstance(other, (int, long)): if other < 0: return Rational(self._d ** -other, self._n ** -other) else: return Rational(self._n ** other, self._d ** other) else: return float(self) ** other def __rpow__(self, other): return other ** float(self) def decimal(self): """Return a Decimal approximation of self in the current context.""" return _decimal.Decimal(self._n) / _decimal.Decimal(self._d) @staticmethod def from_exact_float(x): """Returns the exact Rational equivalent of x.""" mantissa, exponent = _math.frexp(x) mantissa = int(mantissa * 2 ** 53) exponent -= 53 if exponent < 0: return Rational(mantissa, 2 ** (-exponent)) else: return Rational(mantissa * 2 ** exponent) @staticmethod def from_exact_decimal(x): """Returns the exact Rational equivalent of x.""" sign, mantissa, exponent = x.as_tuple() sign = (1, -1)[sign] mantissa = sign * reduce(lambda a, b: 10 * a + b, mantissa) if exponent < 0: return Rational(mantissa, 10 ** (-exponent)) else: return Rational(mantissa * 10 ** exponent) @staticmethod def approx_smallest_denominator(x, tolerance): """Returns a Rational approximation of x. Minimizes the denominator given a constraint on the error. x = the float or Decimal value to convert tolerance = maximum absolute error allowed, must be of the same type as x """ tolerance = abs(tolerance) n = 1 while True: m = int(round(x * n)) result = Rational(m, n) if abs(result - x) < tolerance: return result n += 1 @staticmethod def approx_smallest_error(x, maxDenominator): """Returns a Rational approximation of x. Minimizes the error given a constraint on the denominator. x = the float or Decimal value to convert maxDenominator = maximum denominator allowed """ result = None minError = x for n in xrange(1, maxDenominator + 1): m = int(round(x * n)) r = Rational(m, n) error = abs(r - x) if error == 0: return r elif error < minError: result = r minError = error return result def divide(x, y): """Same as x/y, but returns a Rational if both are ints.""" if isinstance(x, (int, long)) and isinstance(y, (int, long)): return Rational(x, y) else: return x / y From lutherrevisited at aol.com Thu Dec 9 00:20:06 2004 From: lutherrevisited at aol.com (LutherRevisited) Date: 09 Dec 2004 05:20:06 GMT Subject: Setting Focus in WxTextCtrl Message-ID: <20041209002006.23348.00001781@mb-m03.aol.com> I'm wanting to know how I would go about setting the focus to the next text field after I press enter. I'm guessing it's gonna be EVT_TEXT_ENTER(yada yada) calling some function which will move the focus, but I don't know how to move the focus. I know in .NET text boxes have a focus method which will do this, but I can't find anything similar in the places I've looked so far. From cjbottaro at alumni.cs.utexas.edu Wed Dec 8 11:11:25 2004 From: cjbottaro at alumni.cs.utexas.edu (Christopher J. Bottaro) Date: Wed, 08 Dec 2004 10:11:25 -0600 Subject: Help with generators outside of loops. References: <0Vutd.625722$mD.525476@attbi_s02> Message-ID: Steven Bethard wrote: > I don't do much with SQL/databases stuff, but if you really know the > result will be a single row, you can take advantage of tuple unpacking > and do something like: > > row, = obj.ExecSQLQuery(sql, args) > > or > > [row] = obj.ExecSQLQuery(sql, args) > > This has the advantage that you'll get a ValueError if you happen to be > wrong (and there are more or fewer values in the generator). > > >>> def g(n): > ... for i in range(n): > ... yield i > ... > >>> x, = g(1) > >>> x > 0 > >>> x, = g(2) > Traceback (most recent call last): > File "", line 1, in ? > ValueError: too many values to unpack > >>> x, = g(0) > Traceback (most recent call last): > File "", line 1, in ? > ValueError: need more than 0 values to unpack > > Steve Wow, good advice. One question, how is the generator class implemented so that if assigned to a tuple/list, it knows what to do? Is it possible to overload the assignment operator kinda like in C++? Thank you all who replied to the original post, it was very helpful. From fredrik at pythonware.com Mon Dec 13 11:23:15 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Dec 2004 17:23:15 +0100 Subject: PEP 338: Executing modules inside packages with '-m' References: <1102833987.622846.64230@z14g2000cwz.googlegroups.com> <41BD78AC.7060302@iinet.net.au> Message-ID: Nick Coghlan wrote: >> $ python -c "import foo.bar" arg > > This doesn't work. Any code protected by "if __name__ == '__main__':" won't run in this context > (since 'foo.bar' is being imported as a module, not run as a script). I appreciate that you're taking the time to teach me about Python, but I can assure you that it's not really needed. as for the rest of your arguments, I have to assume that you were joking. (or that you have no experience whatsoever of distribution of Python programs in Unix and Windows environments). From godoy at ieee.org Wed Dec 22 08:13:07 2004 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Wed, 22 Dec 2004 11:13:07 -0200 Subject: how to pass globals across modules (wxPython) References: <87u0qij6qn.fsf@web.de> <1168398.J14ASI0oEJ@strongwill.g2ctech> <4969081.Tc9PZ3E6WB@strongwill.g2ctech> Message-ID: <5890823.x6ooTxNvFS@strongwill.g2ctech> Fredrik Lundh, Ter?a 21 Dezembro 2004 16:33, wrote: > well, in my applications, subsystems usually consists of one or more > classes, or at least > one or more functions. code that needs the global context usually gets > the content either as a constructor argument, or as an argument to > individual methods/functions. I see. Differences in terminology. We use the same approach as you do. Be seeing you, Godoy. From python-url at phaseit.net Thu Dec 30 07:47:27 2004 From: python-url at phaseit.net (Cameron Laird) Date: Thu, 30 Dec 2004 12:47:27 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (Dec 30) Message-ID: QOTW: "I found the discussion of unicode, in any python book I have, insufficient." -- Thomas Heller "If you develop on a Mac, ... Objective-C could come in handy. . . . PyObjC makes mixing the two languages dead easy and more convenient than indoor plumbing." -- Robert Kern Among other activities, the PSF aggregates donors with dollars destined to do good Python works, and developers expert in obscure corners of Pythonia. http://groups-beta.google.com/group/comp.lang.python.announce/browse_thread/thread/705bfe05419aa0b3 http://groups-beta.google.com/group/comp.lang.python.announce/browse_thread/thread/1122f3e14752ce5/ Yippee! The martellibot promises to explain Unicode for Pythoneers. http://groups-beta.google.com/group/comp.lang.python/msg/6015a5a05c206712 The glorious SciPy project supports *multiple* worthwhile Wikis. http://www.scipy.org/wikis Good style in Python does not generally include "in-place" operations on lists. Several cleaner idioms are possible. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/c94559f53d25474e Assume you're comfortable with tuples' semantics, immutability, and so on. Do you correctly understand the basics of their syntax, though? This is another opportunity to think about Unicode, by the way. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/990049d7adb1bcce Robert Kern, Paul Rubin, Mike Meyer, Alex Martelli, and others provide disproportionately high-quality advice (and tangents!) on the subject of languages which complement Python. http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/bbc1c6d9d87049b6 ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Brett Cannon continues the marvelous tradition established by Andrew Kuchling and Michael Hudson of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ The Python Business Forum "further[s] the interests of companies that base their business on ... Python." http://www.python-in-business.org Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://python.sourceforge.net/peps/pep-0042.html The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. deli.cio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topics/pythonurl/ http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From hans at zephyrfalcon.org Tue Dec 21 15:19:01 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Tue, 21 Dec 2004 15:19:01 -0500 Subject: What is on-topic for the python list [was "Re: BASIC vs Python"] In-Reply-To: References: <41C342A0.3040700@users.ch> <86sm64tzax.fsf@guru.mired.org> Message-ID: Doug Holton wrote: > Hans Nowak wrote: > >> Now you're trying to make it seem like I am against free speech on >> this list, and against people's rights to discuss whatever they want. >> I never said that, and I in fact enjoy the fact that c.l.py posters >> are an eclectic bunch who have knowledge of, and like to talk about, a >> great number of topics. > > > You said that boo should not be mentioned on this newsgroup. Please point me to the post where I said that. Since everything is stored in Google Groups, it should be easy for you to come up with an URL... if such a post existed. -- Hans Nowak http://zephyrfalcon.org/ From alexs at advfn.com Tue Dec 14 11:43:37 2004 From: alexs at advfn.com (Alex Stapleton) Date: Tue, 14 Dec 2004 16:43:37 +0000 Subject: Python IDE In-Reply-To: <41BF1692.6000103@us-hampton.mail.saic.com> References: <41BF1692.6000103@us-hampton.mail.saic.com> Message-ID: <41BF1839.900@advfn.com> Chris wrote: > What IDE's do y'all recommend for Python? I'm using PythonWin atm, but > I'd like something with more functionality. > > Chris Oh god we're all going to die. But er, ActiveState Komodo is quite nice IIRC (can't use it anymore as all my coding is commercial and I don't need it enough to spend that much cash on it) but EditPlus is nice once you get it setup but not very IDEy. Eclipse with one of the various Python modules is horrible don't bother. There is of course always Emacs, but again it's hardly Visual Studio (im only talking about the UI, emacs fans please dont flame me) Personally my vote goes for Komodo, it's at least worth a try with a personal liscense. From no_sp at m_please.cc Mon Dec 20 08:03:09 2004 From: no_sp at m_please.cc (Mathias) Date: Mon, 20 Dec 2004 14:03:09 +0100 Subject: Parallelization with Python: which, where, how? Message-ID: Dear NG, I have a (pretty much) "emberassingly parallel" problem and look for the right toolbox to parallelize it over a cluster of homogenous linux workstations. I don't need automatic loop-parallelization or the like since I prefer to prepare the work packets "by hand". I simply need - to specify a list of clients - a means of sending a work packet to a free client and receiving the result (hopefully automatically without need to login to each one) - optionally a timeout mechanism if a client doesn't respond - optionally help for debugging of remote clients So far I've seen scipy's COW (cluster of workstation) package, but couldn't find documentation or even examples for it (and the small example in the code crashes...). I've noticed PYRO as well, but didn't look too far yet. Can someone recommend a parallelization approach? Are there examples or documentation? Has someone got experience with stability and efficiency? Thanks a lot, Mathias From __peter__ at web.de Thu Dec 9 02:46:59 2004 From: __peter__ at web.de (Peter Otten) Date: Thu, 09 Dec 2004 08:46:59 +0100 Subject: How do I do this? (eval() on the left hand side) References: Message-ID: Peter Hansen wrote: > Caleb Hattingh wrote: >> I am convinced now that locals() doesn't work as (I) expected. Steven >> says there was some or other reason why locals() as used in this >> context is not writable - Do you know why this is? I really do not >> like guidelines like "may not work", "is unreliable" and so on. >> Perhaps this is a character flaw, but I really do like to know what >> works, when it works, and when it doesn't work. > > Those who've talked about it being "unreliable" are misstating > the Rule that you are looking for. I'll quote it below, so > that you aren't left in this unfortunate state of limbo: > > The Rule of locals() > Updating locals() should not be done. Treat the > return value of locals() as read-only. Never try > to update it. End of story. > > Anything that appears to suggest that locals() might sometimes > actually be writable is not really happening. Look the other > way. Pay no attention to the man behind the curtain. And > especially, whatever else you do, don't let the PSU se I agree. But much of the confusion stems from interpreter experiments like >>> locals()["a"] = 42 >>> a 42 That would go away if locals() returned an ignore-write proxy where the global and local scope are identical. The ability to "just try it" is an asset. Peter From steve at holdenweb.com Mon Dec 6 08:51:21 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 06 Dec 2004 08:51:21 -0500 Subject: exec and global puzzle In-Reply-To: References: Message-ID: Andr? Roberge wrote: > I have the following two files: > > #--testexec.py-- > def exec_code(co): > try: > exec co > except: > print "error" > > #-- test.py-- > import thread > import testexec > import time > > code = "def a():\n print 'a'\n\n" +\ > "def c():\n a()\n\nc()" > > code2 = "def a():\n print 'a'\n\n" +\ > "def c():\n global a\n a()\n\nc()" > > print " exec code - no global" > exec code > print " exec from thread - no global" > thread.start_new(testexec.exec_code, (code,)) > time.sleep(1) > print "\n exec code2 - with global" > exec code2 > print " exec from thread - with global" > thread.start_new(testexec.exec_code, (code2,)) > #----------------------- > > Here's the output when I execute test.py: > > exec code - no global > a > exec from thread - no global > error > > exec code2 - with global > a > exec from thread - with global > a > #--------- > Without the global statement, I get an error when trying to execute > the code. > I don't understand why I need to use the global statement within the > definition of c() in order for it to know what a() is. If I define > exec_code() within test.py and use it there, I do not get any error, > with or without the use of a global statement. > > Andre I have taken the liberty of restructuring your program slightly, by using a "from" to explicitly import the function you need, and by using extended string literals (""" ... """) to make the code easier to read. I have also included print statements to show the contents of the local and global namespaces after the definition of function a(). After these transformations it looks like this: import thread from testexec import exec_code import time code = """\ def a(): print 'a' def c(): a() c() """ code2 = """\ def a(): print 'a' def c(): global a a() c() """ print " exec code - no global" exec code print " exec from thread - no global" thread.start_new(exec_code, (code,)) time.sleep(1) print "\n exec code2 - with global" exec code2 print " exec from thread - with global" thread.start_new(exec_code, (code2,)) time.sleep(1) (OK, I added a final sleep so I saw the output from the second thread). The reason you are seeing this behavior lies in the behavior of the exec statement. The full syntax for that statement is exec_stmt ::= "exec" expression ["in" expression ["," expression]] The second and third expressions are mappings that will be used as namespaces. Since you don't provide either, the interpreter uses the current scope (whose contents can be determined using the locals() function) for both namespaces, so it doesn't matter whether the function is added to the local or the global namespace. When using threads, however (and, by the way, the usual advice is to use the threading module, which has a more convenient API), the namespaces are clearly different. The a() function is being added to the local namespace for the exec. So ultimately it's to do with namespaces, as many of the more perplexing problems in Python are. I hope this helps establish exactly *why* you see what you do. regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From fulimin_yuan at yahoo.com Sat Dec 4 15:12:02 2004 From: fulimin_yuan at yahoo.com (Limin Fu) Date: Sat, 4 Dec 2004 12:12:02 -0800 (PST) Subject: How is Python designed? In-Reply-To: Message-ID: <20041204201202.96784.qmail@web80901.mail.scd.yahoo.com> Hi, Probably you didn't understand well what I meant or maybe I didn't express clearly what I meant. So I think I need to spend more words to make it clear. First, there is no abstract syntax tree generated for the whole program, except for arithmetic expression(even for this, it is slightly different from what you said, I will come back to this point). The Yuan (the name of the interpreter I designed) interpreter first scans the source script, when it see a pattern, for example "if(a>1)", it generates a phrase object containing the arithmetic expression and the ID (it is determined after all phrase objects are created) of other two phrase objects. This phrase object has a member method "execute()", whose execution will return one of the IDs depending on the value of "a>1". Then the next phrase object with that ID is executed, and so on. I don't know how is the AST for a whole program, I think it should be more complicated than this. Then about arithmetic expression, indeed, it is represented as tree. But in Yuan each node contains all the information it need for evaluation. For example, the leaves contains either a variable or a constant value or a function call, and other nodes contains the operators. So far it is more or less the same as what you mentioned. But the evaluation is performed on this tree directly with deep first search, which is different from the two methods you mentioned. The first one you mentioned is the same as my first implementation, which results an unefficient recursive function call. The second is the standard way of evaluating arithmetic expressions. I guess I am not the first one to evaluate arithmetic expression by deep-first search on the tree (I would be surprised if I am). Any way it is enough efficient. Your further comments and discussion are welcome, I'm not that type who is afraid of negative opinions :) Any way I will continue to improve that interpreter, it's an interesting thing for me. Regards, Limin > I'd say that's pretty much standard interpreter > technique - an expression > like this: > > foo = a + b * c > > is translated and reduced to an abstract-syntax-tree > something like this: > > Assignment("foo", BinaryOp("+", Get("a"), > BinaryOp("*", Get("b"), > Get("c")))) > > Then on Assignment one can invoke eval(), and get > the result. Assignment > will invoke eval on its children, which in turn will > do that for their > operands, until something can be computed. The > result is returned. > > By using an emulated stack or register-machine, you > can flatten that to > something like this: > > push Get("c") > push Get("b") > push BinaryOp("*") > push Get("a") > push BinaryOp("+") > pop Assignment("foo") > > This is of course very makeshift - but you'll get > the idea. > > This doesn't mean I want to discourage you - on the > contraire. Developing > your own language is highly educating, and I > personally love it when I > "invent" something and then later find out that > people much cleverer than > me did so before - it shows that I went down the > same paths of thought :) > > -- > Regards, > > Diez B. Roggisch > -- > http://mail.python.org/mailman/listinfo/python-list > __________________________________ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail From bulba at bulba.com Wed Dec 22 17:37:37 2004 From: bulba at bulba.com (Bulba!) Date: Wed, 22 Dec 2004 23:37:37 +0100 Subject: Newbie question - default values of a function References: Message-ID: On Wed, 22 Dec 2004 22:29:44 GMT, "Matt Gerrans" wrote: >Actually i was not mutable. Try this: >i = 1 >id(i) >i += 1 >id(i) Looks like I will have to read the Language Reference anyway. :-( >Because you are assigning the local reference variable L to a new list, >instead of modifying that original default list that was created. >Is that more clear, or is it now more unclear? ;) Clear now, but I have to say for someone who's been doing some C programming in the past it is pretty confusing, because I'm used to think of any variable as basically a place in memory with a pointer to it, so anything without #define or const was considered "mutable" (gawd I still hate pointers). C-style thinking considered harmful when programming in Python. :o) -- It's a man's life in a Python Programming Association. From alanmk at hotmail.com Fri Dec 3 12:48:32 2004 From: alanmk at hotmail.com (Alan Kennedy) Date: Fri, 03 Dec 2004 17:48:32 +0000 Subject: Difficulties POSTing to RDP Hierarchy Browse Page In-Reply-To: <128a885f.0412030905.85d08cc@posting.google.com> References: <128a885f.0412030905.85d08cc@posting.google.com> Message-ID: <9G1sd.43192$Z14.18710@news.indigo.ie> [Chris Lasher] > I'm trying to write a tool to scrape through some of the Ribosomal > Database Project II's (http://rdp.cme.msu.edu/) pages, specifically, > through the Hierarchy Browser. (http://rdp.cme.msu.edu/hierarchy/) I'm sure that urllib is the right tool to use. However, there may be one or two problems with the way you're using it. > --------excerpted HTML---------------- >
----------end excerpted HTML-------------- The options I would like to simulate are browsing by strain=type, source=both, size = gt1200, and taxonomy = bergeys. I see that the form method is POST, and I read through the urllib documentation, and saw that the syntax for POSTing is urllib.urlopen(url, data). Since the submit button calls HierarchyControllerServlet/start (see the Javascript), I figure that the url I should be contacting is http://rdp.cme.msu.edu/hierarchy/HierarchyControllerServlet/start Thus, I came up with the following test code: --------Python test code--------------- #!/usr/bin/python import urllib options = [("strain", "type"), ("source", "both"), ("size", "gt1200"), ("taxonomy", "bergeys"), ("browse", "Browse")] params = urllib.urlencode(options) rdpbrowsepage = urllib.urlopen( "http://rdp.cme.msu.edu/hierarchy/HierarchyControllerServlet/start", params) pagehtml = rdpbrowsepage.read() print pagehtml ---------end Python test code---------- However, the page that is returned is an error page that says the request could not be completed. The correct page should show various bacterial taxonomies, which are clickable to reveal greater detail of that particular taxon. I'm a bit stumped, and admittedly, I am in over my head on the subject matter of networking and web-clients. Perhaps I should be using the httplib module for connecting to the RDP instead, but I am unsure what methods I need to use to do this. This is complicated by the fact that these are JSP generated pages and I'm unsure what exactly the server requires before giving up the desired page. For instance, there's a jsessionid that's given and I'm unsure if this is required to access pages, and if it is, how to place it in POST requests. If anyone has suggestions, I would greatly appreciate them. If any more information is needed that I haven't provided, please let me know and I'll be happy to give what I am able. Thanks very, very much in advance. Chris From R.Brodie at rl.ac.uk Tue Dec 7 14:19:42 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 7 Dec 2004 19:19:42 -0000 Subject: Unknown locale nb_NO ? References: <8tqg82-cfv.ln1@pluto.i.infosense.no> Message-ID: "Stas Z" wrote in message news:pan.2004.12.07.16.06.11.848442 at mobi.tuxhome... > However it strikes me as odd, that Python2.3.4 raises an exception when > querying for a valid locale. I tend to call it a bug :-( File one in the bug tracker, then, and it might get fixed. From mirnazim at gmail.com Sat Dec 4 01:02:51 2004 From: mirnazim at gmail.com (Mir Nazim) Date: 3 Dec 2004 22:02:51 -0800 Subject: Quixote+Nevow+LivePage Message-ID: <5cf3e7a6.0412032202.7b7bde63@posting.google.com> Hi I am a PHP developer and in trying to get a better tool for developing web apps, I have been strugling with zope for past few months and still could not get anything useful work up and going. I really felt that "Z" shaped learning curve. Yesterday I was looking at quixote. I was surprized how simple it is. I think quiote gives the power without getting into the way. And in just a few hours I had quite a good understanding of framework and actually got something up and working (http://www.quixote.ca/learn/1). I feel quixote is the simplest way to develop powerful web apps. I needed a simple and powerfull web framework to develop web apps that are NOT content oriented and where mostly GUI clients have ruled. And I think quixote is just the tool for me. I also came across nevow. Its is also good, rather very good. Especially Live Page is really cool idea. It really help separate logic and presentation and is simpler than MVC thing that I could never get a nack of. Now I have three questions: Q1) Is it possibe to use "Nevow + LivePage + Quixote" together in a web app. Live Page is really important for me as I am not into content oriented web apps. Q2) Is is nessary that LivePage only with Twisted or can work with any web server like Apache. Q3) I cannot understand how to get quixote up and working under Apache using mod_python, FastCGI, SCGI (I have used only mod_php). A link to a tutorial will be good. I saw a paper A. M. Kuchling (http://www.amk.ca/talks/quixote/) that said that nevow can be used with quixote but it did not mention anything of LivePage. Please provide comments, Pros and Cons of the aproach. Links to relevent articles and tutorials are really appreciated Thanks in advance. From andy at andygross.org Tue Dec 7 15:57:16 2004 From: andy at andygross.org (Andy Gross) Date: Tue, 7 Dec 2004 15:57:16 -0500 Subject: Import a module without executing it? In-Reply-To: References: Message-ID: <93DBEFF4-4892-11D9-B0E6-000A95CED3AC@andygross.org> You'll want to use the "compiler" package. compiler.parseFile will return an AST that you can inspect (which is not really 'reflection', btw). /arg On Dec 7, 2004, at 10:56 PM, Caleb Hattingh wrote: > Hi > > You could just parse the model file. Off the top of my head > > *** > f = open('ModuleYouWantToExamine.py','r') > for i in f: > if i.find('def ') > -1: > print 'Found a function!: '+i.replace('def ','') > > f.close() > *** > > You would have to build this up for a more complete examination. Of > course, one of the guru's around here should be able to give you > guidance regarding actually parsing the file with the interpreter (not > executing) and building a dict or something with all the different > types of constructs. That's not me :) > >> >> I want to be able to import this module so I can see "ah ha, this >> module defines a function called 'test'", but I don't want the code >> at the bottom executed during the import. >> >> Thanks >> >> Take care, >> Jay > > -- > http://mail.python.org/mailman/listinfo/python-list From steven.bethard at gmail.com Sat Dec 25 20:47:42 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 26 Dec 2004 01:47:42 GMT Subject: Clearing the screen In-Reply-To: <41ce04a4$1@nntp0.pdx.net> References: <34534aed041224151134aa4f4@mail.gmail.com> <20041224234701.GA1707@unpythonic.net> <41ce04a4$1@nntp0.pdx.net> Message-ID: <2Lozd.16203$k25.9717@attbi_s53> Scott David Daniels wrote: > Nick Coghlan wrote: > >> Jeff Epler wrote: >> >>> I don't know about idle, but the "real" python supports the >>> PYTHONSTARTUP environment variable. >> >> >> I just tried it - IDLE ignores PYTHONSTARTUP, as does PythonWin (I >> just started using PYTHONSTARTUP to switch the standard prompt from >> '>>>' to "Py>'). >> >> I believe PYTHONSTARTUP is handled by CPython's main function before >> it gets to the interactive interpreter. >> >> Cheers, >> Nick. >> > From the Fine Manual: > Command line usage > idle.py [-c command] [-d] [-e] [-s] [-t title] [arg] ... > > -c command run this command > -d enable debugger > -e edit mode; arguments are files to be edited > -s run $IDLESTARTUP or $PYTHONSTARTUP first > -t title set title of shell window > > On Windows, it is likely to be idle.pyw. So, add a -s to the command > line used in the shortcut to start Idle. Anyone know if there is a similar option to PythonWin? I looked around a bit, but couldn't find one... Steve From http Thu Dec 16 04:55:14 2004 From: http (Paul Rubin) Date: 16 Dec 2004 01:55:14 -0800 Subject: Why are tuples immutable? References: <41BE1644.8050906@freemail.gr> Message-ID: <7xwtviftz1.fsf@ruckus.brouhaha.com> Antoon Pardon writes: > Two guidelines can make it easier for a programmer to do this. > > 1) Put a copy in the dictionary, so that mutating the original > object won't affect what is in the dictonary. What's supposed to happen here? a = [1,2,3] d[a] = 9 a.append(4) print d[a] It doesn't sound like good dictionary semantics to me. From jbperez808 at wahoo.com Mon Dec 27 13:54:13 2004 From: jbperez808 at wahoo.com (Jon Perez) Date: Tue, 28 Dec 2004 02:54:13 +0800 Subject: PHP vs. Python (speed-wise comparison) In-Reply-To: <1103753016.780533.137480@f14g2000cwb.googlegroups.com> References: <1103753016.780533.137480@f14g2000cwb.googlegroups.com> Message-ID: <33b3jsF3tgn30U1@individual.net> stephen.mayer at gmail.com wrote: > Anyone know which is faster? I'm a PHP programmer but considering > getting into Python ... did searches on Google but didn't turn much up > on this. > > Thanks! > Stephen If you're talking about usage as a server side scripting language, then PHP will likely give better page serving throughput for the same hardware configuration versus even something that is mod_python based (but I believe the speed diff would be well under 100%). However, Python is just so much superior as a language (I was deep into PHP before I tried out Python and I always hate having to go back to PHP nowadays in the cases where it is unavoidable) that you will still want to use Python even if PHP requires lower server specs to handle the same throughput. Also, if you have a more complex application for which pooled variable reuse is an important performance-determining factor, Python-based server-side scripting solutions might offer better control of this aspect and may thus yield superior performance to a PHP-based one. The real problem with Python is not speed but _availability_. The number of hosting services out there supporting mod_php completely outstrips those supporting mod_python. Moreover, they are significantly cheaper, and offer a lot more features (Fantastico, etc...). The python-based hosting solutions out there tend to be dedicated to Python and thus do not offer these solutions. If this is not an issue (i.e. you will be running your own server), then I highly recommend going the Python route using something like Spyce (which is the closest thing to PHP in the Python world). From andre1 at yandex.ru Mon Dec 13 12:21:37 2004 From: andre1 at yandex.ru (Andrey Ivanov) Date: Mon, 13 Dec 2004 20:21:37 +0300 Subject: uptime for Win XP? Message-ID: <1708018484.20041213202137@yandex.ru> [Peter Hanson] > The real solution, in spite of the dozen alternatives we've > now produced, seems to be to use the win32pdh library > to access the "System"-> "System Up Time" value. It > claims to return an 8-byte value, which likely doesn't > wrap quite so soon. (And yes, remarkably, with the advent > of Windows XP Pro it is now possible to keep a Windows > machine running for longer than 49 days, even if it's > used as a development machine. Well, for Python development, > anyway. ;-) > > For the life of me, however, I can't figure out how to do it. Here's how. :-) ================================================================= import win32pdh query = win32pdh.OpenQuery() counter = win32pdh.AddCounter(query, r"\System\System Up Time") win32pdh.CollectQueryData(query) (bizzare_int, val) = win32pdh.GetFormattedCounterValue(counter, \ win32pdh.PDH_FMT_LONG) print "Uptime: %s secs" % (val,) ================================================================== Writting this script was harder than I initially thought due to a lack of documentation for win32all. And I still don't know what that bizzare_int value stands for (an error/status code?). Well, the registry interface to counters is definitely easier to use, but not available to Python at the moment :-( From vincent at visualtrans.de Sun Dec 19 01:15:51 2004 From: vincent at visualtrans.de (vincent wehren) Date: Sun, 19 Dec 2004 07:15:51 +0100 Subject: Easy "here documents" ?? In-Reply-To: References: Message-ID: Peter Hansen wrote: > Jim Hill wrote: > >> I've done some Googling around on this and it seems like creating a here >> document is a bit tricky with Python. Trivial via triple-quoted strings >> if there's no need for variable interpolation but requiring a long, long >> formatted arglist via (%s,%s,%s,ad infinitum) if there is. So my >> question is: >> >> Is there a way to produce a very long multiline string of output with >> variables' values inserted without having to resort to this wacky >> >> """v = %s"""%(variable) >> >> business? > > > I have no idea what a "here document" is, but there are several > alternatives to the "wacky" basic substitution with a tuple of > values. OP is looking for "heredoc" syntax; in, let's say, PHP this lets you do something like: $foo = new foo(); $name = 'MyName'; echo <<foo. Now, I am printing some {$foo->bar[1]}. This should print a capital 'A': \x41 EOT; AFAIK, there is no direct Python equivalent for this kind of syntax. Using a mapping like you suggested or the string.Template class in Python 2.4 still maybe improvements over what OP calls that "wacky" business. -- Vincent Wehren > > The simplest uses a mapping type: > > mydict = {'namedVal': 666} > '''v = %(namedVal)s''' % mydict > > Does that let you build whatever a "here document" is? From ncoghlan at iinet.net.au Sun Dec 26 21:38:56 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 27 Dec 2004 12:38:56 +1000 Subject: A Revised Rational Proposal In-Reply-To: <86llbl7kvv.fsf@guru.mired.org> References: <86llbl7kvv.fsf@guru.mired.org> Message-ID: <41CF75C0.6080308@iinet.net.au> Mike Meyer wrote: > Regarding str() and repr() behaviour, Ka-Ping Yee proposes that repr() have > the same behaviour as str() and Tim Peters proposes that str() behave like the > to-scientific-string operation from the Spec. This looks like a C & P leftover from the Decimal PEP :) Otherwise, looks good. Regards, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From no at spam.please Wed Dec 22 11:41:33 2004 From: no at spam.please (Doug Holton) Date: Wed, 22 Dec 2004 10:41:33 -0600 Subject: [Re: newbie question] In-Reply-To: <32tm7qF3gha75U1@individual.net> References: <3e8ca5c804122020157b89fb9b@mail.gmail.com> <1103637612.657658.67350@f14g2000cwb.googlegroups.com> <32tm7qF3gha75U1@individual.net> Message-ID: Reinhold Birkenfeld wrote: > Doug Holton wrote: > >>Peter Hansen wrote: >>>As a result of all the activity in the "Boo who?" thread, however, >> >>that you started > > > Apart from that it is considered disrespectful to put your "opponent's" > name into the subject, this flame war is biting its tail already. So putting "Boo Who?" in the subject is not disrespectful? You have just proven my point that Peter Hansen created that thread for no purpose but to troll and flame. From steven.bethard at gmail.com Mon Dec 13 15:48:42 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 13 Dec 2004 20:48:42 GMT Subject: how do I "peek" into the next line? In-Reply-To: References: <1102964987.812024.5180@c13g2000cwb.googlegroups.com> Message-ID: Skip Montanaro wrote: > les> suppose I am reading lines from a file or stdin. I want to just > les> "peek" in to the next line, and if it starts with a special > les> character I want to break out of a for loop, other wise I want to > les> do readline(). > > Create a wrapper around the file object: > [snip] > > Of course, this could be tested (which my example hasn't been) If you'd like something that works similarly and has been tested a bit, try one of my recipes for peeking into an iterator: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304373 You also might consider writing an iterator wrapper for a file object: >>> class strangefileiter(object): ... def __init__(self, file): ... self.itr = iter(file) ... def __iter__(self): ... while True: ... next = self.itr.next() ... if not next or next.rstrip('\n') == "|": ... break ... yield next ... >>> file('temp.txt', 'w').write("""\ ... some text ... some more ... | ... not really text""") >>> for line in strangefileiter(file('temp.txt')): ... print repr(line) ... 'some text\n' 'some more\n' >>> file('temp.txt', 'w').write("""\ ... some text ... some more ... ... really text""") >>> for line in strangefileiter(file('temp.txt')): ... print repr(line) ... 'some text\n' 'some more\n' '\n' 'really text' Steve From deetsNOSPAM at web.de Tue Dec 14 07:31:49 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Tue, 14 Dec 2004 13:31:49 +0100 Subject: How can i send 8-bit data or binary data with pyserial? References: Message-ID: > i have an electronic module which only understand binary data. > i use python pyserial. > for example the module starts when 001000000 8-bit binary data sent.but > pyserial sent only string data. > Can i send this binary data with pyserial or another way with python. Strings _are_ binary data. Use the module struct to convert data from more convenient representations (numbers) to strings, or use chr() to convert them yourself. -- Regards, Diez B. Roggisch From martin at v.loewis.de Sun Dec 26 19:24:27 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 27 Dec 2004 01:24:27 +0100 Subject: Unicode entries on sys.path In-Reply-To: References: <41CB0D7A.3080107@v.loewis.de> Message-ID: <41CF563B.7080802@v.loewis.de> Just wrote: >>The real question here is: why does Python not support arbitrary >>Unicode strings on sys.path? It could, in principle, atleast on >>Windows NT+ (and also on OSX). Patches are welcome. > > > Works for me on OSX 10.3.6, as it should: prior to using the sys.path > entry, a unicode string is encoded with Py_FileSystemDefaultEncoding. > I'm not sure how well it works together with zipimport, though. As Vincent's message already implies, I'm asking for Windows patches. In a Windows system, there are path names which just *don't have* a representation in the file system default encoding. So you just can't use the standard file system API (open, read, write) to access those files - instead, you have to use specific Unicode variants of the file system API. The only operating system in active use that can reliably represent all file names in the standard API is OS X. Unix can do that as long as the locale is UTF-8; for all other systems, there are restrictions when you try to use the file system API to access files with "funny" characters. Regards, Martin From db3l at fitlinxx.com Fri Dec 17 19:07:56 2004 From: db3l at fitlinxx.com (David Bolen) Date: 17 Dec 2004 19:07:56 -0500 Subject: A completely silly question References: <4qEwd.9148$cy6.8034@fe07.lga> <41C3213C.1020408@ort.org.il> <86y8fwya5u.fsf@guru.mired.org> Message-ID: Mike Meyer writes: > Steven Bethard writes: > > > Amir Dekel wrote: > >> What I need from the program is to wait for a single character > >> input, something like while(getchar()) in C. All those Python > >> modules don't make much sence to me... > > > > sys.stdin.read(1) > > That doesn't do what he wants, because it doesn't return until you hit > a newline. Well, but that's true as well for getchar() (at least in many cases of interactive input and line buffering), so in that respect I do think it's a fairly direct replacement, depending on how the OP was going to use getchar() in the application. For example, compare: with: #include >>> import sys >>> while 1: main() ... c = sys.stdin.read(1) { ... print ord(c), while (1) { ... int ch = getchar(); printf("%d ",ch); } } When run, both produce (at least for me): 0123456789 (hit Enter here) 48 49 50 51 52 53 54 55 56 57 10 under both Unix (at least FreeBSD/Linux in my quick tests) and Windows (whether MSVC or Cygwin/gcc). (I don't include any output buffer flushing, since it shouldn't be needed on an interactive terminal, but you could add that to ensure that it isn't the output part that is being buffered - I did try it just to be sure on the Unix side) > The answer is system dependent. Or you can use massive overkill and > get curses, but if you're on windows you'll have to use a third party > curses package, and maybe wrap it If you want to guarantee you'll get the next console character without any waiting under Windows there's an msvcrt module that contains functions like kbhit() and getch[e] that would probably serve. -- David From ian at kirbyfooty.com Tue Dec 21 03:52:17 2004 From: ian at kirbyfooty.com (ian at kirbyfooty.com) Date: 21 Dec 2004 00:52:17 -0800 Subject: Python To Send Emails Via Outlook Express References: <1103521500.427846.238790@c13g2000cwb.googlegroups.com> <41C67E3D.5040205@kdart.com> <1103528498.945675.43920@z14g2000cwz.googlegroups.com> <1103529746.281597.103710@c13g2000cwb.googlegroups.com> <41C6C9F8.7040400@holdenweb.com> <1103548626.745378.220020@c13g2000cwb.googlegroups.com> <41c6d6b7$0$258$edfadb0f@dread12.news.tele.dk> <1103557302.427109.298550@f14g2000cwb.googlegroups.com> <1103605651.147535.226590@z14g2000cwz.googlegroups.com> Message-ID: <1103619137.076507.92100@c13g2000cwb.googlegroups.com> Heavy sigh... ====== This script WILL send the email import win32com.client s = win32com.client.Dispatch('CDO.Message') c = win32com.client.Dispatch('CDO.Configuration') cdoSourceOutlookExpress = 2 c.Load(cdoSourceOutlookExpress) s.Configuration = c s.From = "i... at cgbs.com.au" s.To = "i... at kirbyfooty.com" s.Subject = "The subject" s.Send() ====== ====== But if a change the TO email address to a yahoo address the server rejects it import win32com.client s = win32com.client.Dispatch('CDO.Message') c = win32com.client.Dispatch('CDO.Configuration') cdoSourceOutlookExpress = 2 c.Load(cdoSourceOutlookExpress) s.Configuration = c s.From = "i... at cgbs.com.au" s.To = "iwcook at yahoo.com" s.Subject = "The subject" s.Send() ====== It's official. I have given up sending emails any other way but via smtp. From kjmacken at gmail.com Fri Dec 17 14:25:48 2004 From: kjmacken at gmail.com (kjmacken at gmail.com) Date: 17 Dec 2004 11:25:48 -0800 Subject: Create linear spaced vector? In-Reply-To: References: <6ca895b5.0412171039.7586077d@posting.google.com> Message-ID: <1103311548.726228.263590@f14g2000cwb.googlegroups.com> Thanks for the code snippets guys. Exactly what I needed to get going. I knew I could get the solution from matplotlib, but getting it installed using Fink (OS X) has been giving me a headache, so I thought I could just write my own function for now to get a small piece of code written.... The help is greatly appreciated. kjm John Hunter wrote: > >>>>> "kjm" == kjm writes: > > kjm> Hi Everyone, I am trying to port some old MatLab code to > kjm> python, and am stuck on how to accomplish something. > > kjm> I am trying to write a generalized function that will create > kjm> a linearly spaced vector, given the start and end point, and > kjm> the number of entries wanted. > > kjm> In MatLab I have this function that I wrote: > > kjm> [code] > > kjm> function out = linearspace(x1,x2,n) > > in matlab the builtin function to accomplish this is "linspace" > > The python package matplotlib defines a host of matlab compatible > functions, including linspace > > def linspace(xmin, xmax, N): > if N==1: return xmax > dx = (xmax-xmin)/(N-1) > return xmin + dx*arange(N) > > > Note that matplotlib extends the Numeric/numarray core of matlab > compatible functions (defined in MLab) to include plotting functions > > http://matplotlib.sourceforge.net > > A listing of matlab compatible functions is provided at > http://matplotlib.sourceforge.net/matplotlib.pylab.html > > > JDH From roy at panix.com Sat Dec 11 12:02:01 2004 From: roy at panix.com (Roy Smith) Date: Sat, 11 Dec 2004 12:02:01 -0500 Subject: Python vs. Perl References: <3xFud.92980$EZ.11077@okepread07> Message-ID: Michael McGarry wrote: > I am just starting to use Python. Does Python have all the regular > expression features of Perl? I can't vouch for "all", but the Python reference manual for the "re" module (http://docs.python.org/lib/module-re.html) says, "This module provides regular expression matching operations similar to those found in Perl". > Is Python missing any features available in Perl? Are you talking specifically about regex, or about the language in general? If the latter, then the answer is "Yes, and this is a Good Thing". If you meant the former, then I suspect the answer is that anything you can do with a Perl regex you can also do with a Python regex. I'm a pretty heavy regex user, and I've never found anything I wanted to do which I was unable to. The biggest difference between regex support in Perl and Python is that Perl has regex syntax built into the core language, while Python does it with a module that you have to import and then call functions inside that module. Which you like better is a matter of personal opinion. Like most Perl-Python feature comparisons, the Perl version usually ends up more compact, but the Python version ends up easier to understand. From http Tue Dec 14 18:18:57 2004 From: http (Paul Rubin) Date: 14 Dec 2004 15:18:57 -0800 Subject: How do I convert characters into integers? References: Message-ID: <7x3by8lb8e.fsf@ruckus.brouhaha.com> Markus Zeindl writes: > Now I get every character with a loop: > > buffer = "" > for i in range(len(message)): > ch = message[i-1:i] You mean ch = message[i] what you have does the wrong thing when i = 0. > Here is the problem. I got a string with one character and I > want his ascii representain, for "a" -> 97 > but I want to calculate like iCh = iCh+3 or something else. iCh = ord(ch) > The next step is how I convert it back to an char and append it > to the buffer, but that' no problem. ch = chr(iCh) From fuzzyman at gmail.com Wed Dec 29 08:17:35 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Dec 2004 05:17:35 -0800 Subject: ANN: GallerPy 0.6.0 In-Reply-To: <6pdAd.1029$ch5.295@text.usenetserver.com> References: <6pdAd.1029$ch5.295@text.usenetserver.com> Message-ID: <1104326255.385153.226050@z14g2000cwz.googlegroups.com> Nice one Freddie. You beat me to it - I had adding a 'header_file' type thingy to gallerpy on my list of things to do. gallerpy will be replacing my static galleries on voidspace 'soon'. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml From fuzzyman at gmail.com Mon Dec 13 04:43:40 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: 13 Dec 2004 01:43:40 -0800 Subject: ANN: PyCrypto 2.0 Binary Installer Message-ID: <1102931020.924800.116360@c13g2000cwb.googlegroups.com> Because of export restrictions, Andrew is unable to offer prebuilt binary versions of his excellent PyCrypto module. I've built a windows installer for Python 2.4 Actually download it here http://www.voidspace.org.uk/atlantibots/pythonutils.html#crypto Visit PyCrypto Homepage - http://www.amk.ca/python/code/crypto.html I was able to build the binary by installing microsofts free optimising compiler - VC Toolkit - and hacking distutils to use it. I followed the excellent instructions at http://www.vrplumber.com/programming/mstoolkit/ Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From steve at holdenweb.com Fri Dec 17 10:14:05 2004 From: steve at holdenweb.com (Steve Holden) Date: Fri, 17 Dec 2004 10:14:05 -0500 Subject: BASIC vs Python In-Reply-To: References: Message-ID: Steve Holden wrote: > Adam DePrince wrote: > >> On Thu, 2004-12-16 at 13:36, abisofile wrote: >> >>> hi >>> I'm new to programming.I've try a little BASIC so I want ask since >>> Python is also interpreted lang if it's similar to BASIC. >> >> >> >> Nobody is answering this question because they are shuddering in fear >> and revulsion. >> During the 1980's BASIC was the language to embedd into the ROM's of the >> computers of the day. This was in a misguided effort to make computers >> understandable to their target audience. The goal of the day was to >> build a system that a manager would want to buy; it was believed that >> the only way for a manager to see the value of a system was to make the >> language understandable to said manager. The expectation, of course, >> that the manager would sit down and play with the computer instead of >> delegating the tasks to somebody more qualified is somewhat misguided in >> hindsight. To do that, a language that closely resembled the process of >> micromanaging an untrained worker was employed. >> > But that language was COBOL, not BASIC. BASIC is actually an acronym for > "Beginners' All-purpose Symbolic Instruction Code", which the initial > implementations at Dartmouth weren't, really. The big innovation was the > use of line-numbering to allow interactive editing and testing of a > program. > Which, now I remember, Digital Equipment extended to floating-point in their FOCAL language. I never did discover whether the number of insertions required was limited by the floating-point precision, but Focal was unique in my experience in allowing insertion of statement 1.5 between statements 1 and 2. (mumbles into beard and drools quietly in the corner). talking-to-myself-again-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From insert at spam.here Tue Dec 21 17:08:29 2004 From: insert at spam.here (Doug Holton) Date: Tue, 21 Dec 2004 16:08:29 -0600 Subject: What is on-topic for the python list [was "Re: BASIC vs Python"] In-Reply-To: References: <41C342A0.3040700@users.ch> <86sm64tzax.fsf@guru.mired.org> Message-ID: Hans Nowak wrote: >> Quote: >> "this is comp.lang.python, not comp.lang.boo." > > > Which is obviously not the same as "Boo should not be mentioned on this > newsgroup". I used the exact same phrase in another note except using the term "logo" instead of "boo", and that is the exact interpretation I immediately received from others - they felt I was censuring the discussion here, as I felt you were. > The discussion with Logo and other languages in it was off-topic too, > but it wasn't offensive to anyone. I'm not going to dignify that or the rest of your note with a response. From stian at soiland.no Wed Dec 29 11:56:41 2004 From: stian at soiland.no (Stian =?iso-8859-1?Q?S=F8iland?=) Date: Wed, 29 Dec 2004 17:56:41 +0100 Subject: objects as mutable dictionary keys In-Reply-To: <41D2AB53.1030903@iinet.net.au> References: <41BE1644.8050906@freemail.gr> <33bdosF3qm2j6U1@individual.net> <33e3k7F3ulad0U1@individual.net> <41D2AB53.1030903@iinet.net.au> Message-ID: <20041229165641.GD32339@itea.ntnu.no> On 2004-12-29 14:04:19, Nick Coghlan wrote: > This *is* a bug (since Guido called it such), but one not yet fixed as the > obvious solution (removing object.__hash__) causes problems for Jython, and > a non-obvious solution has not been identified. class object: def __hash__(self): # Need to check if our instance has defined some other # comparison functions without overloading __hash__ for f in "__cmp__ __eq__".split(): if not hasattr(self, f): continue # It has the function, but is it the same as in # object? f1 = getattr(self, f) f2 = getattr(object, f) if f1.im_func != f2.im_func: raise TypeError, "unhashable instance" return id(self) (..) Of course this won't work, as self.__cmp__ and it's like are so-called method-wrapper objects, and I can't immediately see a way to retrieve the original function behind this. Also, it might be possible that someone does something like this: class A(object): def __init__(self, use_id=True): self.use_id = use_id def __eq__(self, other): if self.use_id: return super(A, self).__eq__(other) else: return something_else def __hash__(self, other): if self.use_id: return super(A, self).__hash__(other) else: return something_else This will break the object.__hash__ shown above.. What about checking if __hash__ has been overridden as well, and if so, always return id()? -- Stian S?iland Work toward win-win situation. Win-lose Trondheim, Norway is where you win and the other lose. http://soiland.no/ Lose-lose and lose-win are left as an exercise to the reader. [Limoncelli/Hogan] Og dette er en ekstra linje From john at grulic.org.ar Mon Dec 20 11:26:41 2004 From: john at grulic.org.ar (John Lenton) Date: Mon, 20 Dec 2004 13:26:41 -0300 Subject: dot products In-Reply-To: <1103454255.371143.95030@z14g2000cwz.googlegroups.com> References: <1103454255.371143.95030@z14g2000cwz.googlegroups.com> Message-ID: <20041220162641.GA17652@grulic.org.ar> On Sun, Dec 19, 2004 at 03:04:15AM -0800, Rahul wrote: > HI. > I want to compute dot product of two vectors stored as lists a and b.a > and b are of the same length. > > one simple way is > sum(a[i]*b[i] for i in range(len(a))) > > another simple way is > ans=0.0 > for i in range(len(a)): > ans=ans+a[i]*b[i] > > But is there any other way which is faster than any of the above. (By > the way profiling them i found that the second is faster by about 30%.) > rahul some numbers to confirm my previous reply: 1 zip: 0.00115 (1.00) range: 0.00108 (0.94) array: 0.00075 (0.65) 10 zip: 0.00306 (1.00) range: 0.00288 (0.94) array: 0.00074 (0.24) 100 zip: 0.02195 (1.00) range: 0.02035 (0.93) array: 0.00079 (0.04) 1000 zip: 0.21016 (1.00) range: 0.19930 (0.95) array: 0.00130 (0.01) 10000 zip: 4.98902 (1.00) range: 2.70843 (0.54) array: 0.01405 (0.00) (the integers are the number of elements in a random array of floats; 'zip' refers to sum([x*y for (x,y) in zip(a,b)]) 'range', to sum([a[i]*b[i] for i in range(len(a))]) and 'array' makes a and b Numeric's 'array' objects, with atlas installed (and hence dotblas loading and assembler version of dot tuned for the system's processor (in this case a pentium3)). The code in this case is simply Numeric.dot(a, b) The advantage of atlas on systems with sse2 should be even greater. -- John Lenton (john at grulic.org.ar) -- Random fortune: El deseo nos fuerza a amar lo que nos har? sufrir. -- Marcel Proust. (1871-1922) Escritor franc??s. -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From vincent at visualtrans.de Wed Dec 8 00:15:19 2004 From: vincent at visualtrans.de (vincent wehren) Date: Wed, 08 Dec 2004 06:15:19 +0100 Subject: after embedding and extending python (using swig) problem importing (non-core) modules In-Reply-To: <1102479704.220397.59070@c13g2000cwb.googlegroups.com> References: <1102479704.220397.59070@c13g2000cwb.googlegroups.com> Message-ID: stefan wrote: > Hi Folks, > > I currenty extended some of my C++ functionality to python and also > embedded python to use python functionality in my C++ system (and use > as well these extended functions). > > While this works fine with the core python functionality, as soon as I > run a script (on the embedded system) which tries to import modules > which are not in the core system, like "xml" or "re", it fails and says > it cannot find the related dll (for example in the case of re the > _sre.pyd). It works fine if i run the script with the 'regular' > interpreter. Is this in debug mode? If so, make sure you have the debug versions of those dll's in your path (i.e. _sre_d.pyd etc.)... HTH -- Vincent Wehren > > It does not look like a path-problem to me, so I'm clueless right now. > I could work around this extending some functions to python and use > them, but then I lose what I was aiming for, the "power" of python and > python-modules. > > Do i have to tell the embedded python system somehow where to look for > extension dll's? (it even does not work if i have the pyd files in the > (same) folder than the system where I start my embedded python program. > > It would be great if someone would have an idea, at least how to get me > started on this. > > thanks a lot in advance, > -stefan > From deetsNOSPAM at web.de Thu Dec 9 06:52:46 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 09 Dec 2004 12:52:46 +0100 Subject: newbie question: starting external application(win)? References: <1goisj4.15nv4u21lg3h9cN%esselbach@t-online.de> Message-ID: > I have googeled, but could not find informations that I can understand. > The most informations comes from unix/linux butIneed this for win32. The module popen2 is your friend. Or the os.spawn* methods in module os. -- Regards, Diez B. Roggisch From hanusah at ferber-hanusa.de Mon Dec 6 07:18:08 2004 From: hanusah at ferber-hanusa.de (Henning Hanusa) Date: 6 Dec 2004 04:18:08 -0800 Subject: MySQL-python-1.0.0.win32-... Message-ID: Could anybody please provide me with a "compiled" version of the above (MySQLdb 1.0.0 for Python on Win 2000 / XP) for Python version 2.4, as I do not have any possibility of compiling?? Many thanks in advance Henning From p.s.nuttall at dur.ac.uk Mon Dec 6 05:21:24 2004 From: p.s.nuttall at dur.ac.uk (Peter Nuttall) Date: Mon, 6 Dec 2004 10:21:24 +0000 Subject: Recursive list comprehension In-Reply-To: References: Message-ID: <200412061021.25337.p.s.nuttall@dur.ac.uk> On Monday 06 Dec 2004 09:26, Timothy Babytch wrote: > Hi all. > > I have a list that looks like [['N', 'F'], ['E'], ['D']] > I try to make it flat one: ['N', 'F', 'E', 'D'] > > How can I archieve such an effect with list comprehension? > Two cycles did the job, but that way did not look pythonic.. > > I tried > print [x for x in y for y in c_vars] > and got NameError: name 'y' is not defined. > > -- > Timothy Babytch Hi, I think you do it with a generator like this: def flatten(nested): for sublist in nested: for element in sublist: yield element n=[['N', 'F'], ['E'], ['D']] output=[] for value in flatten(n): output.append(value) print output Have a merry Christmas Peter Nuttall From arodrig at cscs.ch Thu Dec 16 06:17:09 2004 From: arodrig at cscs.ch (arodrig at cscs.ch) Date: Thu, 16 Dec 2004 12:17:09 +0100 Subject: MDaemon Warning - virus found: delivery failed Message-ID: <20041216111751.969091E4008@bag.python.org> ******************************* WARNING ****************************** Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado un fichero anexo(s) infectado(s). Por favor revise el reporte de abajo. Attachment Virus name Action taken ---------------------------------------------------------------------- instruction.zip I-Worm.Mydoom.m Removed ********************************************************************** Your message was not delivered due to the following reason(s): Your message was not delivered because the destination server was not reachable within the allowed queue period. The amount of time a message is queued before it is returned depends on local configura- tion parameters. Most likely there is a network problem that prevented delivery, but it is also possible that the computer is turned off, or does not have a mail system running right now. Your message could not be delivered within 2 days: Host 65.2.190.203 is not responding. The following recipients could not receive this message: Please reply to postmaster at cscs.ch if you feel this message to be in error. From craig at postnewspapers.com.au Thu Dec 23 02:02:43 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Thu, 23 Dec 2004 15:02:43 +0800 Subject: PHP vs. Python In-Reply-To: <1103753016.780533.137480@f14g2000cwb.googlegroups.com> References: <1103753016.780533.137480@f14g2000cwb.googlegroups.com> Message-ID: <1103785363.7586.7.camel@albert.localnet> On Thu, 2004-12-23 at 06:03, stephen.mayer at gmail.com wrote: > Anyone know which is faster? I'm a PHP programmer but considering > getting into Python ... did searches on Google but didn't turn much up > on this. Others have answered interpretations of your question other than execution speed. I can't give you numbers on that - you'd probably have to do some benchmarks yourself - but can offer a few suggestions. First, Python can be _seriously_ fast for web use. You need to make sure you're not starting and terminating interpreters all the time, so you'll need to use a Python embedded web server proxied by Apache (like Zope does), SCGI (as works well with Quixote), Twisted, or some other way of running your code persistently. Persistent CGI usually means worrying about memory leaks, but unless you're using flakey C extension modules that shouldn't be a problem with Python. If you have your Python code running as some sort of persistent server, then you can use tools like Psyco to get a further (often very impressive) speed boost. The biggest speed-up with Pysco that I've clocked is 20x, but 3x - 5x is fairly common. Whether it'll be faster or slower than PHP, I just can't guess. I think it'd certainly be well worth a try, especially if you're writing any more complex applications. That said, for 90% of users development time matters more than execution speed, and that's another matter entirely. -- Craig Ringer From cookedm+news at physics.mcmaster.ca Mon Dec 13 22:27:07 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Mon, 13 Dec 2004 22:27:07 -0500 Subject: Namespaces and the timeit module References: Message-ID: Roy Smith writes: > I'm playing with the timeit module, and can't figure out how to time a > function call. I tried: > > def foo (): > x = 4 > return x > > t = timeit.Timer ("foo()") > print t.timeit() > > and quickly figured out that the environment the timed code runs under > is not what I expected: > > Traceback (most recent call last): > File "./d.py", line 10, in ? > print t.timeit() > File "/usr/local/lib/python2.3/timeit.py", line 158, in timeit > return self.inner(it, self.timer) > File "", line 6, in inner > NameError: global name 'foo' is not defined > > In fact, trying to time "print dir()" gets you: > > ['_i', '_it', '_t0', '_timer'] > > It seems kind of surprising that I can't time functions. Am I just not > seeing something obvious? Like the documentation for Timer? :-) class Timer([stmt='pass' [, setup='pass' [, timer=]]]) You can't use statements defined elsewhere, you have to define them in the setup arguments (as a string). Like this: define_foo = ''' def foo(): x = 4 return x ''' t = timeit.Timer("foo()" setup=define_foo) print t.timeit() One common idiom I've seen is to put your definition of foo() in a module (say x.py), then, from the command line: $ python -m timeit -s 'from x import foo' 'foo()' (the -m is for python 2.4 to run the timeit module; use the full path to timeit.py instead for earlier pythons) Alternatively, the examples for the timeit module has another way to time functions defined in a module. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From robin at reportlab.com Mon Dec 6 12:09:50 2004 From: robin at reportlab.com (Robin Becker) Date: Mon, 06 Dec 2004 17:09:50 +0000 Subject: Win32 Libs for 2.4 In-Reply-To: References: Message-ID: <41B4925E.8040603@chamonix.reportlab.co.uk> Daniel Dittmar wrote: > Robin Becker wrote: > >> actually I want to build the PIL extension for 2.4 as pyd and include >> various libraries eg zlib and jpeg. To avoid the missing dlls issue we >> have done this in the past by incorporating the zlib/jpeg code using >> static libraries for both zlib and jpeg. >> >> It seems I can use the static lib built with MSC 6 with the extension >> code compiled with MSC 7.1. At least the extnsion build doesn't >> complain. Whether this is really allowed is another matter. > > > I guess that it won't work if something malloc'ed from the MSC 6 runtime > is free'd by the MSC 7.1 runtime. ...... I thought that static .libs didn't make reference to the dll's they need; isn't that done at load time? As for rebuilding that's easy; the hard part is having all the versions available at once. I prefer to keep common code in one place so would prefer to have only one static lib for these non version dependant things. > > Daniel -- Robin Becker From __peter__ at web.de Tue Dec 14 09:09:59 2004 From: __peter__ at web.de (Peter Otten) Date: Tue, 14 Dec 2004 15:09:59 +0100 Subject: while 1 vs while True References: <1102903165.589419.323000@z14g2000cwz.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Steve Holden wrote: > >> It was unfortunate that so many people chose to use that for >> compatibility, when if they'd used the same code that the win32all >> extensions did they could have retained backward compatibility even >> across a change to constants: >> >> try: >> True >> except AttributeError: >> True, False = (1==1), (1!=1) > > that doesn't work, though: > > $ python2.1 test.py > Traceback (most recent call last): > File "test.py", line 2, in ? > True > NameError: name 'True' is not defined Fixing the exception type doesn't help if the change is implemented like the constancy of None: >>> try: ... None ... except NameError: ... None = object() ... SyntaxError: assignment to None Another workaround seems viable: >>> globals()["None"] = "Evil Nun" >>> None >>> Peter From fuzzyman at gmail.com Wed Dec 29 09:10:08 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: 29 Dec 2004 06:10:08 -0800 Subject: portable text user interface In-Reply-To: References: Message-ID: <1104329408.956094.48890@f14g2000cwb.googlegroups.com> Miki Tebeka wrote: > Hello Maxim, > > > Are there widely used and recommended Python libraries that will > > let me makes a portable text user interface? > If you just need a text-like interface you can use Tkinter. > See (shameless plug) http://developer.berlios.de/projects/bcd/ and > http://developer.berlios.de/dbimage.php?id=1112 for example. > Hello Miki, Your project looks very interesting. It would be better if it displayed an error message if it can't find the '_bcdrc' file. If you run it from windoze it just appears and disapears. How about allowing the '_bcdrc' file to be in the same directory as the script as well. Any chance of you releasing the Tkinter text interface as a separate library, with a less restrictive license ? It looks very good - but I can't use it in my projects if it is GPL. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shtml > If you need something that runs through telnet/ssh ... than curses is what > your looking for. There's a win32 port to it somewhere. > > Bye. > -- > ------------------------------------------------------------------------ > Miki Tebeka > http://tebeka.bizhat.com > The only difference between children and adults is the price of the toys From lbates at syscononline.com Mon Dec 20 10:20:23 2004 From: lbates at syscononline.com (Larry Bates) Date: Mon, 20 Dec 2004 09:20:23 -0600 Subject: how to pass globals across modules (wxPython) In-Reply-To: <87u0qij6qn.fsf@web.de> References: <87u0qij6qn.fsf@web.de> Message-ID: I also struggled with this until I looked into many of the wxWindows examples. They all tend to pass in the parent to each subsequent layer of classes so that they can easily refer backwards in the hierarchy. Example In your code you will find that inside of SetTopWindow you have parent as the first argument. You can refer to parent.someattribute or parent.somemethod to refer back to "application", which is instance of MainApp. Just do something similar in MainFrame class. Changing MainFrame class a little and passing in self as the first argument will give you the same ability inside of MainFrame instance. Something like: class MainFrame(wxFrame): def __init__(self, parentclass, parentframe): self.parentclass=parentclass wxFrame.__init__(self, parentframe, -1, "Frame Description") . . . Then in Main App pass self as first argument (parentclass), then you can refer back to MainApp instance as self.parentclass. If you go several levels down you get self.parentclass.parentclass.parentclass.attribute: class MainApp(wxApp): def OnInit(self): self.mainFrame = MainFrame(self, None) self.mainFrame.Show() self.SetTopWindow(self.mainFrame) return True This might not be the "best" way, but seems to work and models what wxWindows appears to do internally. Larry Bates Syscon, Inc. Martin Drautzburg wrote: > My wxPython program starts execution in mainFrame.py like this > [...] > class MainApp(wxApp): > def OnInit(self): > self.mainFrame = MainFrame(None) > self.mainFrame.Show() > self.SetTopWindow(self.mainFrame) > return True > > > def main(): > global application > application=MainApp(0) > application.MainLoop() > > > if __name__ == '__main__': > main() > > > I need to access the "application" object from other modules, actually > the windows and frames that live therein and I don't know how to do > this. > > I tried using "global", but that does not seem to help. In the other > module I run an "import mainFrame" and that seems to reset the global > variables. > > Am I missing something obvious? From ask at etamp.net Sun Dec 5 17:31:12 2004 From: ask at etamp.net (etamp) Date: Mon, 6 Dec 2004 07:31:12 +0900 (KST) Subject: What's New on the Web : Today Message-ID: What's New on the Web : Today http://www.etamp.net/ =========================================================== Etamp(etamp.net) provides latest news of web sites around the globe. You can inform free of charge what is happening in your web site. To submit your releases, you must first become a member. It's free, fast and easy. ============================================================ ====== [ url2image.com Offers New Service to Help Web site Designers and Webmasters Discover Problems with Lack of Browser Compatibility ] url2image.com Offers New Service to Help Web site Designers and Webmasters Discover Problems with Lack of Browser Compatibility A new service of?? http://www.etamp.net/beta/?etamp=check_dir/news.html?&part=ws&number=1049 [ ICQ joins webmail battles with new service ] ICQ joins webmail battles with new service By Juan Carlos Perez The increasingly competitive webmail market has a new player: Instant messaging?? http://www.etamp.net/beta/?etamp=check_dir/news.html?&part=ws&number=1048 [ Voiceglo Issues Call for Beta Users for GloConnect IM Application ] Voiceglo Issues Call for Beta Users for GloConnect IM Application December 2004 ?Voiceglo, a global communications and networking company, to?? http://www.etamp.net/beta/?etamp=check_dir/news.html?&part=ws&number=1047 [ OmniOutliner 3.0 announced, public beta available ] OmniOutliner 3.0 announced, public beta available The Omni Group today announced a major new upgrade to its outlining and organizational applicati?? http://www.etamp.net/beta/?etamp=check_dir/news.html?&part=ws&number=1046 From zephyrwings at hotmail.com Wed Dec 8 02:30:37 2004 From: zephyrwings at hotmail.com (newbie) Date: Wed, 8 Dec 2004 15:30:37 +0800 Subject: use embedded python to build a dll Message-ID: <31np47F3dvdntU1@individual.net> Hi all, I got a problem using the embedded python. I'll be appreciated if some one can show me the way. What i want is, 1.build a dll(test.dll/test.lib) which uses the embedded python, for example, i want to use the 're' module. 2.build a exe(usedll.exe) which uses that dll. 3.use py2exe to eliminate the dependence of the python environment. here is the cpp file to build test.dll/test.lib **query.py is the python script i used. so i import the module 'query'** ==== #include "stdafx.h" #include #pragma comment(lib, "d:\\\\sdk\\Python23\\libs\\python23.lib") #include "d:\sdk\python23\include\python.h" BOOL APIENTRY DllMain( HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { return TRUE; } __declspec(dllexport) void __stdcall DoIt() { Py_Initialize(); PyObject *pM=PyImport_ImportModuleEx("query", NULL, NULL, NULL); Py_XDECREF(pM); std::cout<<"ok"; Py_Finalize(); } ==== here is the file to build usedll.exe ---- #include "stdafx.h" #include "windows.h" #pragma comment(lib, "..\\Release\\test.lib") __declspec(dllimport) void __stdcall DoIt(); int main(int argc, _TCHAR* argv[]) { DoIt(); return 0; } ---- i use setup.py file like this, from distutils.core import setup import py2exe setup() and then python setup.py py2exe --includes query --packages encodings and i got a bunch of files. Then I put usedll.exe test.dll test.lib query.py and all of these files generated by py2exe in the same directory. I run the usedll.exe, then I got a run time error 'this application has requested the runtime to terminate it in an unusual way...' but if i don't use those files generated by py2exe, i.e. i use the python environment on my machine, every thing is fine. I can not figure out where is the problem. Could anyone give me a hint? From fredrik at pythonware.com Mon Dec 6 11:25:57 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 6 Dec 2004 17:25:57 +0100 Subject: byte code generated under linux ==> bad magic number underwindows References: <200412060800.37358.philippecmartin@sbcglobal.net> <41B46DBE.7040703@cenix-bioscience.com> Message-ID: Aaron Bingham wrote: > .pyc files are platform-independant but are incompatible between major Python versions. "are incompatible" should be "may be incompatible" you can use imp.get_magic() to get a string that identifies the bytecode version supported by the current interpreter; any interpreter with the same string can run your bytecode. From mauriceling at acm.org Sun Dec 12 19:19:40 2004 From: mauriceling at acm.org (Maurice Ling) Date: Mon, 13 Dec 2004 11:19:40 +1100 Subject: Best book on Python? In-Reply-To: <1d6cdae30412121612680d3ed4@mail.gmail.com> References: <41bcc295$1@news.unimelb.edu.au> <1d6cdae30412121612680d3ed4@mail.gmail.com> Message-ID: <41BCE01C.6080208@acm.org> Daniel Bickett wrote: >>If the focus is only on printed books and there is some experience with >>programming, "programming python" by Lutz from O'Reilly might be a good >>one. >> >> > >I saw that book today at Barnes and Noble, and found it curiously >ironic that it had a very large mouse on the cover :) But maybe that's >just me. > >Daniel Bickett > > > Yes it is somewhat ironic. I do think that a snake or something closer to a long, tube-like, legless animal will be more suitable. I have absolutely no idea how animals are chosen in O'Reilly. maurice -------------- next part -------------- A non-text attachment was scrubbed... Name: mauriceling.vcf Type: text/x-vcard Size: 347 bytes Desc: not available URL: From apardon at forel.vub.ac.be Fri Dec 17 03:53:11 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Dec 2004 08:53:11 GMT Subject: Why are tuples immutable? References: <41BE1644.8050906@freemail.gr> <10s1si0fb0l4pae@corp.supernews.com> <10s4a4rso24vb83@corp.supernews.com> Message-ID: Op 2004-12-17, Jeff Shannon schreef : > Antoon Pardon wrote: > >>Op 2004-12-16, Jeff Shannon schreef : >> >> >> >>>nevermind the fact that I can't think of a case where I'm >>>likely to "retrieve" a key from a dict, modify it, and then put it >>>back. (I can think of endless cases where I'd want to do that with >>>*values*, but not with keys...) >>> >>> >> >>Well neither can I, but yet the fact that lists are mutable and tuples >>are not, is frequently presented as reason why tuples are allowed as >>keys and tuples are not. >> > > True -- in much the same way that the inability to see is why sighted > people are allowed to get driver's licenses and blind people are not. > The fact of mutability makes an object very poorly suited for use as a > dict key, and therefore allowing them to be used as dict keys would be a > dangerous thing. In the same way as mutability makes an object poorly suited to be a member of a sorted list. Mutability doesn't make an object unsuitable to be used in a structure that depends on some invariant, as dictionaries are one example. We only need to ensure that the object is stable while it is used in such a way. Is it such a rare occasion that objects are mutated during some time in a program after which they remain stable? And while we have collected a number of such stable objects couldn't it be usefull to be able to sort them, use them as a dict key or in some other structure that requires an invariant? Would you have us construct two related classes each time we find ourselves in such a situation and copy an object from one class to the other depending on the circumstances? > I'm sure that, with careful guidance and supervision, > a blind person could manage to operate a motor vehicle, but no matter > how high my regard for that blind person was I'd be a bit hesitant to > give them my car keys for a quick trip to the corner store... > >>>(And if dicts were somehow changed so that keys were copied when added >>>to a dict, just so that every once in a while someone might be able to >>>avoid a few conversions to/from tuple, then you're adding the overhead >>>of an object copy to *every* dict insertion, thus slowing down (possibly >>>by a significant amount) a large proportion of Python operations. How >>>is that a gain?) >>> >>> >> >>Well will look at two scenario's. In each we will work with mutable >>objects that we would like to use a keys. In the first we transform >>them into an immutable object, in the second we just allow mutables to >>be inserted as keys, but insert a copy of the key instead of the key >>itself in order to protect the programmer somewhat from mutating >>dictionary keys. >> >>Now in scenario one we will have a lot more copies then in scenario >>two, because each time we want to use an object as a key we will >>first have to transform it into an immutable. That means every >>addition to the dictionary as well as every key access and each >>such transform means a copy. >> >>In scenario two we will only make a copy when a key is added to >>the dictionary, we don't need to make copies with key accesses. >> >> >>I think scenario two is a performance gain over scenario one. >> >> > > Except that Python uses dicts internally, quite heavily. Much of the > speed gains of recent versions of Python have reportedly come > specifically due to extensive and impressive optimization of > dictionaries. Forcing an (extra) object copy every time a variable name > is bound (or rebound) would be hell on Python's performance across the > board, not just in those rare cases where someone thinks that they'd > benefit from using a mutable object as a key. No it wouldn't. 1) A copy wouldn't be needed on a rebind of a variable name because the name would then already be in the directory. 2) Some techniques could be used so that even a lot of binds will not require a copie. 3) Nothing stops python from checking if one of its standard immutables is used as a key and then proceed as it does now. Now I'm not asking that the people oblige me and implement this. I'm more then happy to take my own resposibility as a programmer and provide a copy myself to the dictionary when I have use of a mutable object as key. > (And I have to reiterate, here, that I have *never* felt it a hardship > to be unable to use lists as dictionary keys; it's just never come up > that the data that I had in a list was something that I wanted to use > as-is for a dict key, and I can't think of a situation where it *would* > happen. What you're saying, essentially, is that for the sake of one > form of aesthetic purity with no significant practical benefits, we > should break another form of aesthetic purity with massive practical > benefits.) You shouldn't limit the usefullness of a language to your ability to imagine what is usefull and what not. Besides python doesn't provide such an aesthetic purity. Even if it was true that only immutables could be used as keys in dictionaries there are other times some invariant is established or depended upon and yet python doesn't enforce immutable objects in those cases. So much of the aesthetic purity python provides. -- Antoon Pardon From tzot at sil-tec.gr Mon Dec 13 10:00:50 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Mon, 13 Dec 2004 17:00:50 +0200 Subject: predict directory write permission under windows? References: Message-ID: On Mon, 13 Dec 2004 22:14:03 +0800, rumours say that Qiangning Hong might have written: >I want to know if I can write files into a directory before I actually >perferm the write behavor. I found os.access(path, os.W_OK) but it uses >real uid/gid to check instead of euid/egid so it doesn't fit my problem. I didn't even know that the notion of effective uid/gid existed on windows. Unless that's a "service" from the Run as a different user service, but I wouldn't know. >I don't know how to get euid/egid under windows so I cannot use the mode >infomation returned by os.stat(). >Anybody give me a hint? I won't be very helpful, but Python is mostly built around the philosophy of asking forgiveness instead of permission (the opposite of "look before you leap", which is what you want). There are other typical arguments (what if permissions change between your check and the actual write? what if the directory disappears before writing? etc) which you might think they do not apply to you, but they most probably do. In case you want that to update some form of UI where the user should know in advance, well, create a dummy file in the directory (and instantly delete it) and report success or failure. However, if you insist on knowing something that could be false, pywin32 might offer more functions to check for permissions. -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From deetsNOSPAM at web.de Sun Dec 12 13:04:03 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 12 Dec 2004 19:04:03 +0100 Subject: for loop References: Message-ID: > for i in range(morethanzero, n): > ... > >> for i= 5 to len(var) > > for i in range(5, len(var)): > ... Better use xrange - it doesn't create an actual list, but instead an iterator enumerating the elements. That way more memory and cpu efficient. -- Regards, Diez B. Roggisch From aahz at pythoncraft.com Thu Dec 30 19:23:46 2004 From: aahz at pythoncraft.com (Aahz) Date: 30 Dec 2004 19:23:46 -0500 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: In article <1104425916.615972.97530 at z14g2000cwz.googlegroups.com>, Sridhar R wrote: > >What makes such companies to choose Java over dynamic, productive >languages like Python? Are there any viable, technical reasons for >that? It's a decent cross-platform way of delivering libraries compared to C libraries. We've been forced into Java because fewer and fewer credit card processing libraries are available as C libraries. Just yesterday, I ran into some annoyance because the PGP library I'm using doesn't allow recombining their .jar files due to signing. Which has some good and bad features, I suppose. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From ncoghlan at email.com Sat Dec 4 03:39:29 2004 From: ncoghlan at email.com (Nick Coghlan) Date: Sat, 04 Dec 2004 18:39:29 +1000 Subject: Help me asap!! In-Reply-To: References: Message-ID: <41b177c2$0$25778$5a62ac22@per-qv1-newsreader-01.iinet.net.au> the_proud_family wrote: > HELP ME PLEASE!! > I can't get the ball to go up right side and then I need it to turn > around and keep turning until velocity=0 I have been at it for the > past 2 weeks now i give up and call for help. Please if anyone can > gide me through i will be so grateful!! I have pasted my code below A few comments in the code stating what each section is *meant* to be doing might mean you actually got some useful responses (no guarantees, though). However, the current state of the code, where the reader is left entirely to guess as to what the overall program is for, and what each section of the program is meant to be doing virtually guarantees that you *won't* get any help. You could start by interpreting the cryptic comment above into something meaningful for anyone who doesn't already know what your assignment is. You might even find that articulating things clearly lets you identify the problem for yourself. Alternately, implement little pieces at a time, to make sure they work individually, then combine them to form the complete behaviour - don't try to write the whole thing in one hit (or you will get your current situation of "it doesn't work" with no idea which *bit* isn't working) Cheers, Nick. From google at vertigrated.com Thu Dec 16 12:29:19 2004 From: google at vertigrated.com (fuzzylollipop) Date: 16 Dec 2004 09:29:19 -0800 Subject: Python IDE In-Reply-To: References: <1103141895.620517.49860@z14g2000cwz.googlegroups.com> Message-ID: <1103218159.737726.241440@z14g2000cwz.googlegroups.com> no it was a sideways remark at all the software socialists that thing EVERYTHING should be free, never said anything about Eclipse, just the people that insist ALL software should be free. From tom at dtsam.com Thu Dec 30 12:12:30 2004 From: tom at dtsam.com (Thomas Bartkus) Date: Thu, 30 Dec 2004 11:12:30 -0600 Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: "Sridhar R" wrote in message news:1104425916.615972.97530 at z14g2000cwz.googlegroups.com... > >From technical point of view, I could not understand the the reasoning > behind using Java in major companies. Sure that Python, is used in > some, but still Java is considered as a sure-job language. > > After being a python programmer for long time, I consider it painful to > learn/use Java now (well, like many I will be forced to do that in my > job). > > What makes such companies to choose Java over dynamic, productive > languages like Python? Are there any viable, technical reasons for that? Are there "viable, technical reasons"? That would be doubtful. But There is a reason very important to major companies. When you leave that company, there will be a *long* line of Java programmers waiting to take your place. There need be nothing "technical" about such a decision. Thomas Bartkus From ptmcg at austin.rr._bogus_.com Wed Dec 8 00:13:48 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 08 Dec 2004 05:13:48 GMT Subject: regex for url paramter References: Message-ID: "Robert Brewer" wrote in message news:mailman.7337.1102459902.5135.python-list at python.org... Andreas Volz wrote: > I try to extract a http target from a URL that is given as parameter. > urlparse couldn't really help me. I tried it like this > > url="http://www.example.com/example.html?url=http://www.exampl > e.org/exa > mple.html" > > p = re.compile( '.*url=') > url = p.sub( '', url) > print url > > http://www.example.org/example.html > > This works, but if there're more parameters it doesn't work: > > url2="http://www.example.com/example.html?url=http://www.examp > le.org/exa > mple.html¶m=1" > > p = re.compile( '.*url=') > url2 = p.sub( '', url2) > print url2 > > http://www.example.org/example.html¶m=1 > > I played with regex to find one that matches also second case with > multible parameters. I think it's easy, but I don't know how > to do. Can you help me? I'd go back to urlparse if I were you. >>> import urlparse >>> url="http://www.example.com/example.html?url=http://www.example.org/example. html" >>> urlparse.urlparse(url) ('http', 'www.example.com', '/example.html', '','url=http://www.example.org/example.html', '') >>> query = urlparse.urlparse(url)[4] >>> params = [p.split("=", 1) for p in query.split("&")] >>> params [['url', 'http://www.example.org/example.html']] >>> urlparse.urlparse(params[0][1]) ('http', 'www.example.org', '/example.html', '', '', '') << Added by Paul>> Robert Brewer's params list comprehension may be a bit much to swallow all at once for someone new to Python, but it is a very slick example, and it works for multiple parameters. [p.split("=", 1) for p in query.split("&")] First of all, you see that the variable query is returned from urlparse and contains everything in the original url after the '?' mark. Now the list comprehension contains 'query.split("&")' - this will return a list of strings containing each of the individual parameter assignments. 'for p in query.split("&")' will iterate over this list and give us back the temporary variable 'p' representing each individual parameter in turn. For example [p for p in query.split("&")] is sort of a nonsense list comprehension, it just builds a list from the list returned from query.split("&"). But instead, Robert splits each 'p' at its equals sign, so for each parameter we get a 2-element list: the parameter, and its assigned value. Using a list comprehension does all of this iteration and list building in one single, compact statement. A long spelled out version would look like: allparams = query.split("&") params = [] for p in allparams: params.append( p.split("=",1) ) Now if we make a slight change Robert Brewer's "params = [p.split..." line to, and construct a dictionary using dict(): params = dict( [p.split("=", 1) for p in query.split("&")] ) this will create a dictionary for you (the dict() constructor will accept a list of pairs, and interpret them as key-value entries into the dictionary). Then you can reference the params by name. Here's the example, with more than one param in the url. >>> url="http://www.example.com/example.html?url=http://www.example.org/example. html&url2=http://www.xyzzy.net/zork.html" >>> print urlparse.urlparse(url) ('http', 'www.example.com', '/example.html', '', 'url=http://www.example.org/example.html&url2=http://www.xyzzy.net/zork.html ', '') >>> query = urlparse.urlparse(url)[4] >>> params = dict([p.split("=", 1) for p in query.split("&")]) >>> print params {'url': 'http://www.example.org/example.html', 'url2': 'http://www.xyzzy.net/zork.html'} >>> print params.keys() ['url', 'url2'] >>> print params['url'] http://www.example.org/example.html >>> print params['url2'] http://www.xyzzy.net/zork.html List comprehensions are another powerful tool to put in your Python toolbox. Keep pluggin' away, Andreas! -- Paul From rschroev_nospam_ml at fastmail.fm Wed Dec 15 09:18:21 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 15 Dec 2004 14:18:21 GMT Subject: Why are tuples immutable? In-Reply-To: References: <41BE1644.8050906@freemail.gr> Message-ID: Antoon Pardon wrote: > Op 2004-12-15, Fredrik Lundh schreef : >>sorry, but I don't understand your reply at all. are you saying that dictionaries >>could support mutable keys (e.g lists) by making a copy of the key? how would >>such a dictionary pick up changes to the original key object? (I'm talking about >>the key stored in the dictionary, not the key you're using to look things up). > > > You want to mutate a key that is within a dictionary? No, we don't want to mutate it; as far as I know, that is exactly the reason why dictionaries don't support mutable keys. -- "Codito ergo sum" Roel Schroeven From gh at ghaering.de Tue Dec 21 08:48:06 2004 From: gh at ghaering.de (Gerhard Haering) Date: Tue, 21 Dec 2004 14:48:06 +0100 Subject: Problem with msvcrt60 vs. msvcr71 vs. strdup/free Message-ID: <20041221134806.GA24641@mylene.ghaering.de> Hello, I used to build Python extension modules with mingw. Now, Python has switched to the MSVCR71 runtime with version 2.4, and I thought mingw has support for this. But I get problems with symbols being referenced from the wrong DLLs. You can see the problem by compiling this: ################## #include int main() { char* s; int i; for (i = 0; i < 10; i++) { s = strdup("foo"); free(s); } return 0; } ################## with gcc x.c -lmsvcr71 Then if you run a.exe it crashes. If you use depends.exe on it, you see that it resolves strdup() via msvcrt, but the rest with msvcr71.dll. That's why strdup() is using the one malloc, but free() a different free() from the other DLL, which is undoubtedly the reason for the crash. Is there any way I can force mingw to not link in msvcr for things like strdup? I think I found a very strange and ugly workaround: if I use _strdup() instead of strdup(), it is resolved using the msvcr71 DLL. I hope it is (soon) possible to use only the msvcr71 runtime from the mingw compiler. -- Gerhard -- A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? A: Top-posting. Q: What is the most annoying thing on usenet and in e-mail? -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From ed_tsang at yahoo.com Fri Dec 3 11:38:37 2004 From: ed_tsang at yahoo.com (ed) Date: 3 Dec 2004 08:38:37 -0800 Subject: how to list files with extension .txt in windows? References: <4d41c82e.0412022308.23b32e31@posting.google.com> Message-ID: <4d41c82e.0412030838.6d55a953@posting.google.com> I do have permission toa ccess the file as that file is careted and read my me. I have read/write access to that location. regards Aaron Bingham wrote in message news:... > ed wrote: > > >I have used batch script to do it but it has a lot of issues with > >access denied... errors I pretty much given up using batch to do this. > > > > > If you do not have permission to access the files, switching to a > different language will not help you. You need to determine the cause > of your access errors first. > > Aaron From redhog at takeit.se Fri Dec 10 18:03:01 2004 From: redhog at takeit.se (redhog at takeit.se) Date: 10 Dec 2004 15:03:01 -0800 Subject: Wrapper objects In-Reply-To: <41b9f1c6.270706104@news.oz.net> References: <41b9021b.209351251@news.oz.net> <1102700031.276079.36580@f14g2000cwb.googlegroups.com> <41b9f1c6.270706104@news.oz.net> Message-ID: <1102719781.151859.227370@f14g2000cwb.googlegroups.com> >Well, that could be a feature, depending on what your use case is. >Or you could make a method for adding methods, I suppose. >A perfectly transparent wrap of obj would be to do nothing ;-) >What do you actually want to do? Actually, the very best would if only type(), isinstance() and the is-keyword could an object and a wrapped version of it apart. I've thought of using a weakdict instaed, problem is, it would be a little bit too transparent for my purpose as the only way to tell an object and a wrapped version of it apart would be by my own functions which would do lookups in that dict. Secondly, it would only allow for one comment per object dopy, which would fail horribly for e.g. numbers (there are hundreds of uses of the number 1, which all needs different comments for the number). From CousinStanley at HotMail.Com Sun Dec 5 11:06:12 2004 From: CousinStanley at HotMail.Com (Cousin Stanley) Date: Sun, 05 Dec 2004 09:06:12 -0700 Subject: Python-Help ( Mean,Median & Mode) In-Reply-To: References: <000c01c4da88$60a68630$840880ca@Alfred> <6.2.0.14.0.20041205024210.02e146e8@mail.mric.net> Message-ID: <31gpvoF3b9m83U1@individual.net> | I revised my source code. It was doing great | but I'm having problem listing all the numbers | that I'd input. | | How can I input all the numbers that I selected? Alfred .... As a method to list the numbers that have been input and avoid having to know in advance how many numbers are needed, you might consider a simple input mode where a character other than an integer is input as a stop-input-mode character .... print '\n Input an integer at the > prompt \n' print ' Enter a period . to end input mode' print ' and begin processing .... \n' prompt = '> ' period = '.' list_input = [ ] while True : this_str = raw_input( prompt ) if this_str == period : break try : list_input.append( int( this_str ) ) except : print '\n Input Must be an Integer' print ' or a period . to exit Input Mode \n' num_entries = len( list_input ) print ' Input List .... \n' for this_item in list_input : print ' %s' % this_item print '\n # Entries .... %s \n' % num_entries -- Cousin Stanley Human Being Phoenix, Arizona From jctobin at gmail.com Thu Dec 30 09:34:28 2004 From: jctobin at gmail.com (Nanoscalesoft) Date: 30 Dec 2004 06:34:28 -0800 Subject: PyQT installation In-Reply-To: References: <1104370062.562575.88620@f14g2000cwb.googlegroups.com> Message-ID: <1104417268.153983.71970@z14g2000cwz.googlegroups.com> hi phil... py-->2.4 pyqt-->3.3 qt-->2.3.0 From craig at postnewspapers.com.au Fri Dec 10 03:09:44 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Fri, 10 Dec 2004 16:09:44 +0800 Subject: converting html escape sequences to unicode characters In-Reply-To: <1102638977.084921.72370@c13g2000cwb.googlegroups.com> References: <1102638977.084921.72370@c13g2000cwb.googlegroups.com> Message-ID: <1102666183.28721.24.camel@rasputin.localnet> On Fri, 2004-12-10 at 08:36, harrelson wrote: > I have a list of about 2500 html escape sequences (decimal) that I need > to convert to utf-8. Stuff like: I'm pretty sure this somewhat horrifying code does it, but is probably an example of what not to do: >>> escapeseq = '비' >>> uescape = ("\\u%x" % int(escapeseq[2:-1])).decode("unicode_escape") >>> uescape u'\ube44' >>> print uescape ??? (I don't seem to have the font for it, but I think that's right - my terminal font seems to show it correctly). I just get the decimal value of the escape, format it as a Python unicode hex escape sequence, and tell Python to interpret it as an escaped unicode string. >>> entities = ['비', '행', '기', '로', '보', '낼', '거', '에', '요', '내', '면', '금', '이', '얼', '마', '지', '잠'] >>> def unescape(escapeseq): ... return ("\\u%x" % int(escapeseq[2:-1])).decode("unicode_escape") ... >>> print ' '.join([ unescape(x) for x in entities ]) ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? ??? -- Craig Ringer From jzgoda at gazeta.usun.pl Thu Dec 16 16:48:43 2004 From: jzgoda at gazeta.usun.pl (Jarek Zgoda) Date: Thu, 16 Dec 2004 22:48:43 +0100 Subject: newbie: Datetime module for Python 2.2.x In-Reply-To: <161220041515399256%junk@azarcon.com> References: <161220041515399256%junk@azarcon.com> Message-ID: Eric Azarcon wrote: > I'm fairly new to Python, and was wondering if someone might be able to > help. I'm doing something that requires the datetime module released in > 2.3. Unfortunately, the target machines are running 2.2.x and there is > no easy way that I know of to install 2.3/2.4 (RHEL ES). > > I've done some looking around, and located and downloaded a tarball > from Zope that seems to address this, but have no idea how I am to > install this. The file is a datetime.tar. > > I've also downloaded the source from Python.org, and have the C source > for datetime. Of course, I have no idea how to compile just that > module. And installing it, if I ever get that far. Most of DB-API modules use mx.DateTime module and for Python 2.2 this one is mos widely used. Go for it to http://www.egenix.com/. -- Jarek Zgoda http://jpa.berlios.de/ | http://www.zgodowie.org/ From bjourne at gmail.com Wed Dec 1 06:08:28 2004 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 1 Dec 2004 12:08:28 +0100 Subject: decorators ? In-Reply-To: References: Message-ID: <740c3aec0412010308398b0972@mail.gmail.com> Some more decorator examples. How to create abstract methods using an @absractmethod decorator: http://www.brpreiss.com/books/opus7/html/page117.html Generics, property getters and setters. I don't know what these decorators are supposed to do: http://www.cis.upenn.edu/~edloper/pydecorators.html - And according to this, http://www.prothon.org/pipermail/prothon-user/2004-August/003173.html, one use of decorators is to put a functions docstring before the def f(): line like this: @doc("""blabla does something.""") def blabla(): Here is one decorator for optimizing: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 I think the essence of decorators is that it makes it possible to do in Python what you in other languages do with method qualifiers. This declaration in Java public synchronized static void doStuff() would you write in Python as @public @synchronized @staticmethod def doStuff(): I haven't seen an example of a @synchronized decorator, but I assume it is possible. Hopefully, it is possible to create a @private decorator which throws some kind of exception when a private method is accessed from outside the class. If that is possible, then it would also be nice to have a @public decorator which doesn't do anything. As far as I know, only two decorators are included in the standard library in Python 2.4, @staticmethod and @classmethod. That is a little unfortunate, because many more "obvious ones" could have been included. The devs are probably planning to correct that in the coming versions. That is all I know about decorators. Or rather THINK I know from reading stuff on the internet. Please don't flame me if I'm wrong. :) -- mvh Bj?rn From andre.roberge at ns.sympatico.ca Sun Dec 5 07:54:19 2004 From: andre.roberge at ns.sympatico.ca (Andr? Roberge) Date: 5 Dec 2004 04:54:19 -0800 Subject: Linguistic challenge: name this program Message-ID: In 1981, Richard Pattis wrote a delightful little book titled "Karel the Robot, a Gentle Introduction to the Art of Programming." Pattis's "Karel the Robot" was named after the author Karel Capek, who popularized the word "robot" in his play "Rossum's Universal Robots". Pattis's approach was to introduce a robot who could follow 5 basic instructions and be taught to accomplish tasks of increasing complexity. A few years ago, a first implementation of "Karel the Robot" in Python was created and called PyKarel. A second, newer implementation is called Guido van Robot (GvR for short), and is available at gvr.sourceforge.net. Work is currently underway by the developpers of GvR to produce a new-and-improved version. I have been working on my own (better ;-) version (sometimes collaborating with the GvR folks) in order to learn Python. It is now 90% finished. It is meant to be a complete environment to learn about programming concepts, from simple sequences of instruction to OOP. Given the origin of Pattis's name (Rossum's Universal Robot) and the name of Python's BDFL, I find it difficult to think of a better name than Guido van Robot to name a programming environment in which one uses Python to teach a robot new tricks! (Hat's off to Steve Howell for this one). Yet, I want a "clever" name for my version. Any suggestions? Andre Roberge From mal at egenix.com Mon Dec 6 13:38:03 2004 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 06 Dec 2004 19:38:03 +0100 Subject: ANN: eGenix mx Base Package 2.0.6 (mxDateTime, mxTextTools, etc.) Message-ID: <41B4A70B.4020000@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com mx Base Extension Package Version 2.0.6 Open Source Python extensions providing important and useful services for Python programmers. ________________________________________________________________________ ABOUT The eGenix.com mx Base Extensions for Python are a collection of professional quality software tools which enhance Python's usability in many important areas such as fast text searching, date/time processing and high speed data types. The tools have a proven record of being portable across many Unix and Windows platforms. You can write applications which use the tools on Windows and then run them on Unix platforms without change due to the consistent platform independent interfaces. All available packages have proven their stability and usefulness in many mission critical applications and various commercial settings all around the world. * About Python: Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. * About eGenix: eGenix is a consulting and software product company focused on providing professional quality services and products to Python users and developers (http://www.egenix.com/). ________________________________________________________________________ NEWS The new version includes patches needed to compile the package for Python 2.4. It now supports all Python versions 1.5.2 - 2.4. As always we are providing pre-compiled versions of the package for Windows and Linux as well as sources which allow you to install the package on all other supported platforms. ________________________________________________________________________ EGENIX MX BASE PACKAGE OVERVIEW mxDateTime - Generic Date/Time Types mxDateTime is an extension package that provides three new object types, DateTime, DateTimeDelta and RelativeDateTime, which let you store and handle date/time values in a very convenient way. You can add, subtract and even multiply instances, pickle and copy them and convert the results to strings, COM dates, ticks and some other more esoteric values. In addition, there are several convenient constructors and formatters at hand to greatly simplify dealing with dates and times in real-world applications. In addition to providing an easy-to-use Python interface the package also exports a comfortable C API interface for other extensions to build upon. This is especially interesting for database applications which often have to deal with date/time values (the mxODBC package is one example of an extension using this interface). mxTextTools - Fast Text Processing Tools mxTextTools is an extension package for Python that provides several useful functions and types that implement high-performance text manipulation and searching algorithms in addition to a very flexible and extendable state machine, the Tagging Engine, that allows scanning and processing text based on low-level byte-code "programs" written using Python tuples. It gives you access to the speed of C without the need to do any compile and link steps every time you change the parsing description. Applications include parsing structured text, finding and extracting text (either exact or using translation tables) and recombining strings to form new text. mxStack - Fast and Memory-Efficient Stack Type mxStack is an extension package that provides a new object type called Stack. It works much like what you would expect from such a type, having .push() and .pop() methods and focuses on obtaining maximum speed at low memory costs. mxTools - Collection of Additional Built-Ins mxTools is an extension package that includes a collection of handy functions and objects giving additional functionality in form of new built-ins to the Python programmer. The package auto-installs the new functions and objects as built-ins upon first import. This means that they become instantly available to all other modules without any further action on your part. Add the line import NewBuiltins to your site.py script and they will be available to all users at your site as if they were installed in the Python interpreter itself. mxProxy - Generic Proxy Wrapper Type mxProxy is an extension package that provides a new type that is suitable to implement Bastion like features without the need to use restricted execution environments. The type's main features are secure data encapsulation (the hidden objects are not accessible from Python since they are stored in internal C structures), customizable attribute lookup methods and a cleanup protocol that helps in breaking circular references prior to object deletion. In addition to being able to completely hide objects from the Python run-time, the module also provides a generic implementation of weak reference that works for all Python objects. mxBeeBase - On-disk B+Tree Based Database Kit mxBeeBase is a high performance construction kit for disk based indexed databases. It offers components which you can plug together to easily build your own custom mid-sized databases (the current size limit is sizeof(long) which gives you an address range of around 2GB on 32-bit platforms). The two basic building blocks in mxBeeBase are storage and index. Storage is implemented as variable record length data storage with integrated data protection features, automatic data recovery and locking for multi process access. Indexes use a high performance optimized B+Tree implementation built on top of Thomas Niemann's Cookbook B+Tree implementation (http://epaperpress.com/). ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the packages can be found at: http://www.egenix.com/ ________________________________________________________________________ LICENSES & COSTS The eGenix mx Base package is distributed under the eGenix.com Public License which is a Python 2.0 style Open Source license. You can use the package in both commercial and non-commercial settings without fee or charge. The package comes with full source code ________________________________________________________________________ SUPPORT Commercial quality support for these packages is available from eGenix.com Software GmbH. Please see http://www.egenix.com/files/python/eGenix-mx-Extensions.html#Support for details about our support offerings. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Dec 06 2004) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! :::: From fredrik at pythonware.com Sun Dec 5 03:07:56 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 5 Dec 2004 09:07:56 +0100 Subject: Book Recommendations References: <58ef839a.0412031306.301fd8a0@posting.google.com> Message-ID: Nathan Weston wrote: > I'm new to Python and am looking for a book to get me up to speed > quickly. I'm an experienced programmer and very proficient with Ruby, > so Python is coming easily to me and I don't need a gentle > introduction -- I just need a quick way to get familiar with common > Python idioms and important libraries. http://effbot.org/zone/librarybook-index.htm contains examples for all modules that were in 2.0, in idiomatic python (see the "new modules in ..." for info on modules added in later versions). From matthiasverniers at gmail.com Mon Dec 20 05:03:45 2004 From: matthiasverniers at gmail.com (Matthias Verniers) Date: Mon, 20 Dec 2004 11:03:45 +0100 Subject: MySQLdb & Python 2.4 on Windows In-Reply-To: References: <41c61059$0$44081$5fc3050@dreader2.news.tiscali.nl> Message-ID: <41c6a382$0$44075$5fc3050@dreader2.news.tiscali.nl> Fredrik Lundh schreef: > Matthias Verniers wrote: > > >>2. Is it possible to use Python 2.4 & 2.3 next to each other without conflicts? > > > yes, assuming "next to each other" means "on the same machine". > > but binary extensions are bound to the Python version they were built > for; you cannot use a 2.3 extension with 2.4 on windows. > > > > > Yes, that is what I mean. I think I will switch back to 2.3 for a while, untill MySQLdb can work with 2.4 or untill I find a way to use it with 2.4. Thanks for your help! Matthias From tzot at sil-tec.gr Fri Dec 10 12:43:58 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Fri, 10 Dec 2004 19:43:58 +0200 Subject: problem with win32file.RemoveDirectory References: Message-ID: On Wed, 08 Dec 2004 14:39:57 +0100, rumours say that me might have written: [python2.4 + pythonwin 2.03 on Win98] >The command i. e. 'win32file.RemoveDirectory("C:\\Python 2.4\\folder")' >causes the error message: > >Traceback (most recent call last): > File "C:\Python24\remove.py", line 2, in ? > win32file.RemoveDirectory('C:\\Python24\\folder') >error: (120, 'RemoveDirectoryW', 'This function is only valid in Win32 >mode.') > >The new documentation tells me that RemoveDirectory "is implemented >using RemoveDirectoryW." >Does that mean a "NT/2000 Unicode specific version" and the >impossibility using this function on Win98? AFAIK yes. The .*W versions of functions were only stubs in the Win9x family. You can see if there is a RemoveDirectoryA though; that would be usable. -- TZOTZIOY, I speak England very best, "Tssss!" --Brad Pitt as Achilles in unprecedented Ancient Greek From mefjr75 at hotmail.com Thu Dec 30 14:54:51 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 30 Dec 2004 11:54:51 -0800 Subject: OT: novice regular expression question In-Reply-To: <4MWAd.4695$5R.2506@newssvr21.news.prodigy.com> References: <4MWAd.4695$5R.2506@newssvr21.news.prodigy.com> Message-ID: <1104436491.861213.310070@z14g2000cwz.googlegroups.com> Hello me, Have you tried shlex.py it is a tokenizer for writing lexical parsers. Should be a breeze to whip something up with it. an example of tokenizing: py>import shlex py># fake an open record py>import cStringIO py>myfakeRecord = cStringIO.StringIO() py>myfakeRecord.write("['1','2'] \n 'fdfdfdfd' \n 'dfdfdfdfd' ['1','2']\n") py>myfakeRecord.seek(0) py>lexer = shlex.shlex(myfakeRecord) py>lexer.get_token() '[' py>lexer.get_token() '1' py>lexer.get_token() ',' py>lexer.get_token() '2' py>lexer.get_token() ']' py>lexer.get_token() 'fdfdfdfd' You can do a lot with it that is just a teaser. M.E.Farmer From kmey at despammed.com Wed Dec 1 11:13:51 2004 From: kmey at despammed.com (Klaus Meyer) Date: Wed, 01 Dec 2004 17:13:51 +0100 Subject: RELEASED Python 2.4 (final) In-Reply-To: References: Message-ID: <3168soF36ec26U1@individual.net> Anthony Baxter schrieb: > happy to announce the release of Python 2.4. Thanks! minor remarks: First line from C:\Python24\README.txt This is Python version 2.4 alpha 3 In C:\Python24\Tools in various subdirs the README.TXT files disappeared. -- regards kgm From hongqn at gmail.com Sun Dec 5 01:42:19 2004 From: hongqn at gmail.com (Qiangning Hong) Date: Sun, 05 Dec 2004 14:42:19 +0800 Subject: notification for cd insertion In-Reply-To: References: Message-ID: Qiangning Hong wrote: > I want one of my function to execute when a cdrom is inserted. How can > I achieve that? > > Further more, I want to do different things depend on the inserted disc > type: if it is a normal cd-rom, read from it; if it is a recordable cd, > write data on it. So, how can I get the inserted disc type infomation > in Python code? > > thanks in advance. > Sorry I forgot the important info: my platform is a Windows 2000 box. From bturczyn at gmail.com Thu Dec 16 09:08:55 2004 From: bturczyn at gmail.com (Bill Turczyn) Date: 16 Dec 2004 06:08:55 -0800 Subject: Module question In-Reply-To: <1103143345.721887.80940@c13g2000cwb.googlegroups.com> References: <1103143345.721887.80940@c13g2000cwb.googlegroups.com> Message-ID: <1103206134.972249.46000@f14g2000cwb.googlegroups.com> Thanks to everyone for the prompt reply, I now have several options to explore. Thanks again, Bill From ncoghlan at iinet.net.au Thu Dec 30 09:19:29 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Fri, 31 Dec 2004 00:19:29 +1000 Subject: Securing a future for anonymous functions in Python In-Reply-To: <20041230140626.26823.628616939.divmod.quotient.3@ohm> References: <20041230140626.26823.628616939.divmod.quotient.3@ohm> Message-ID: <41D40E71.5030709@iinet.net.au> Jp Calderone wrote: > On Fri, 31 Dec 2004 00:00:31 +1000, Nick Coghlan wrote: > >>Paul Rubin wrote: >> >>>Nick Coghlan writes: >>> >>> >>>>Anyway, I'm looking for feedback on a def-based syntax that came up in >>>>a recent c.l.p discussion: >>> >>> >>>Looks like just an even more contorted version of lambda. It doesn't >>>fix lambda's main deficiency which is inability to have several >>>statements in the anonymous function. >> >>Do you consider generator expressions or list comprehensions deficient because >>they don't allow several statements in the body of the for loop? >> > > > >>> (foo + bar > ... for foo in range(13) if foo % 3 == 2 > ... for bar in range(16, 23) if 2 <= bar % 5 < 4) > > >>> > > Hmm. Two for loops and two if clauses. That's four altogether. > Does that qualify as "several"? :) Sure, they're not statements > according to the grammar, but that's entirely beside the point. > > Jp And that's an expression, and hence perfectly legal as the body of an anonymous function. So if we feel like abusing our anonymous functions, we use generator expressions to get if statements and for loops, sys.stdout.write() for print statements, sys.stdin.read() for input statements, anonymous functions for def statements, and throw in our own functions with lazily evaluated arguments for anything that isn't already covered by the interpreter core (which isn't much). I just don't understand why people complain so much about the restriction to a single expression in lambdas, yet there is nary a peep about the same restriction for generator expressions and list comprehensions. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From gustafl at algonet.se Wed Dec 1 18:56:27 2004 From: gustafl at algonet.se (Gustaf Liljegren) Date: Thu, 02 Dec 2004 00:56:27 +0100 Subject: xml.sax in Python 2.3.4 Message-ID: After a long break with Python I'm trying to get started again. I need to do some SAX processing, but it seems things have changed, and I can't find any docs describing how to make things work *today*. The SAX example in the XML HOWTO [1] doesn't work anymore. I get this error: D:\Test>python comics.py Traceback (most recent call last): File "comics.py", line 5, in ? class FindIssue(saxutils.DefaultHandler): AttributeError: 'module' object has no attribute 'DefaultHandler' I hope someone here can explain what has changed and how a working example looks today. My needs are very simple, so don't want to install any packages on top of the standard distribution. 1. http://pyxml.sourceforge.net/topics/howto/node12.html -- Gustaf From mwm at mired.org Sat Dec 11 02:08:17 2004 From: mwm at mired.org (Mike Meyer) Date: Sat, 11 Dec 2004 01:08:17 -0600 Subject: Deadlock detection References: <361d0$41b440c1$51604868$26492@nf1.news-service-com> Message-ID: Adam DePrince writes: > On Mon, 2004-12-06 at 06:21, Duncan Grisby wrote: >> Hi, >> >> Does anyone know of a deadlock detector for Python? I don't think it >> would be too hard to hook into the threading module and instrument >> mutexes so they can be tested for deadlocks. I've googled around but I >> haven't found anything. > > In general, accurate deadlock detection is intractable. Like many > problems of this class you have two choices - either reduce the scope of > the problem to a non-general one or try a heuristic to guess. I've recently been involved in a thread on another list that dealt with the problems of programming with threads. There are people approaching the problems (including deadlocks) by providing constructs for threading that mean you can't write such code. At least, that's the idea. http://www.jot.fm/issues/issue_2004_04/article6 was posted as one such solution. I'm not convinced it works, but the paper only discusses half the solution. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From drew at gremlinhosting.com Wed Dec 1 11:39:44 2004 From: drew at gremlinhosting.com (Andrew James) Date: Wed, 01 Dec 2004 16:39:44 +0000 Subject: Drawing Cogwheels and Combinatoric diagrams Message-ID: <41ADF3D0.2060308@gremlinhosting.com> Gentlemen, I'm looking for a graphing or drawing python package that will allow me to draw complex geometric shapes. I need to be able to create shapes like cogwheels and Venn diagrams: http://encyclopedia.thefreedictionary.com/Venn The library must support alpha blending and the ability to return x,y co-ordinates for a shape, as I want to draw an imagemap on top of parts of the shape. Can PIL do this, or do I need to go the way of GnuPlot or Gri? Can anyone give me an example of a complex shape drawn like this? Many thanks, Andrew From deetsNOSPAM at web.de Sat Dec 4 10:28:21 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sat, 04 Dec 2004 16:28:21 +0100 Subject: Import Semantics, or 'What's the scope of an import?', and class attribute instantiation References: Message-ID: Hi, > I'm having some trouble with understanding python's importing behaviour > in my application. I'm using psyco to optimise part of my code, but I'm > not sure whether it inherits throughout the rest of my application (read > this as for any imported module) if I import in in a 'higher-level' > module. For example: In the psyco doc it says that you can do full() - but it will bloat the memory consumption, so its better to use either explicit or profile-based optimization. I suggest reading the docs for psyco on thate. > > A.py > ==== > > import psyco > from B import BClass > class AClass(): > ... > ... > b = BClass() > > B.py > ==== > > class BClass(): > ... > ... > > In general, I've noticed that if import X and B in A.py and want to > reference X.* from B.py, I need to import X again in B. Is this a hard > and fast rule, or is there a way I can import the common libs, etc. in > the starting .py file and have those inherited by other classes I > import/instantiate? How would I do this? No, you can't - and as you say later on that you come from java: That's not possible there, either. Generally speaking, for each unit/file for interpretation or compilation (in java/c++), you have to import all names that should be known there. > It seems to be the general consensus that it's best to keep a Python app > in fewer files in the same directory rather than spreading them out, a > few (or one) classes to a file in a directory hierarchy as in Java. I > understand this is due to Python's, self.* and import operations > having a relatively high cost (traversing directories, etc. etc.) No - the cost for importing are not so high, and occur only once. A second import will make python recognize that this module is already known, so it won't be imported again. So they don't add much to your runtime - only startup time. Which is still way faster than java's.... Java simply limits you to one class per file so the can maintain a bijektive .java <-> .class mapping. I guess for make-like dependency checking. And as in java the class is the only unit of code you can write, there is no way to declare functions outside of classes. Which you can do in python. If you really want to, you can go the way way java does it. But then you have to manually update the __init__.py for a module to make all declared names visible, like this: foo/__init__.py from A import A foo/A.py class A: pass This is of course somewhat tedious. Instead putting all classes and functions directly into a file called foo.py will rid you of these complications, and keep belonging code in one file. > Python loads all the class attributes into memory (or, at least, cycles > through them) at runtime *even if I never instantiate the class*. This > has lead me to write code like: > > class myX(): > att3 = None > def __init__(self): > att3 = MemoryHungryClass() > > Which seems to work a little better, but it seems rather ugly. I guess > the reason Python does this is because it's interpreted, not statically > compiled (and so needs to know whether myX.attr3 exists when called), > but I don't understand why the interpreter can't parse/instantiate the > attributes on the first call to instantiate the class. Surely this would > be a reason *for* splitting your code up into multiple files? I'm not totally sure that I understand what you are doing here - it seems to me that you confuse class attributes with instance attributes. The latter are (usually) created in the __init__-method, like this: class Foo: def __init__(self): self.bar = 1 a = Foo() b = Foo() a.bar += 1 print a.bar, b.bar yield 2 for a.bar and 1 for b.bar The former are attributes created while importing (so far you're right), but they are created only once - for the _class_, not the objects of that class. So you can compare them to static properties in java. Which will also be created at the first import, and consume whatever resources they need - time- and memorywise. You can of course instaniate them lazily - like this: class Foo: bar = None def __init__(self): if Foo.bar is None: Foo.bar = SomeMemoryConsumingObject() So bar gets filled only when you actually instantiate a Foo. But this is no different from java: class Foo { static Bar bar = null; public Foo() { if (bar == null) { bar = new SomeMemoryConsumingObject(); } } } > Being relatively new to Python, I'm trying to avoid coding things in an > un-Python (read C++/Java) manner, and am looking for some tutorials on > python-specific advanced features I can use (things like closures, > lambda forms, map(), etc. etc.). Could anyone point me towards some good > resources? http://docs.python.org/tut/tut.html Especially http://docs.python.org/tut/node8.html -- Regards, Diez B. Roggisch From http Tue Dec 28 13:16:40 2004 From: http (Paul Rubin) Date: 28 Dec 2004 10:16:40 -0800 Subject: Best GUI for small-scale accounting app? References: <1104029156.889650.15220@c13g2000cwb.googlegroups.com> <7xsm5qqs2k.fsf@ruckus.brouhaha.com> <7x652m8hj5.fsf@ruckus.brouhaha.com> Message-ID: <7xsm5q47av.fsf@ruckus.brouhaha.com> Ed Leafe writes: > Oh, geez. After months of us getting skewered for releasing > Dabo under GPL, with everyone saying that they wouldn't even *look* at > it for fear of 'infecting' all of their code, we change the license to > the MIT license, and now the complaint is that Microsoft is going to > sell the code! Well, those are commercial developers who are afraid of the GPL. If they want to require people to pay to use the code they release, then they, just like Microsoft, should also expect to pay the developers of the components they use. If I were you I would have stood firm on the GPL, unless they offered you funding. > Ever get that feeling that you can't win? ;-) I don't see how you lose with the GPL, unless you count missing out on the exciting opportunity to be an unpaid employee of someone else's corporation, without even getting back improvements made to your code. > > I hope Dabo can read the xml files Glade generates, so you have a gui > > builder that's already deployed. > > That's definitely part of the development plan. But after > looking at Glade and several other designers, our conclusion is that > they all lack something: either flexibility, ease of use, or something > else. Sizers were probably the item that was the most difficult thing > to handle well. The best designer for sizers we found was Qt > Designer. We'd like to make our designer as visually clear as that one. I'm not sure what sizers are, but why not just add them to Glade? > Also, Dabo is not just a UI toolkit: it's a full 3-tier > application framework. Our major design goal is to integrate the > database connections defined into the UI designer, so that you can > drag and drop fields from the tables in the connection onto the design > surface, and create data-bound controls in one step. Ehhh, sounds a little too much like javabeans :). From fredrik at pythonware.com Sun Dec 5 16:19:17 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 5 Dec 2004 22:19:17 +0100 Subject: import fails References: <45351425.20041205195257@geochemsource.com><20041205190709.1203.1397680046.divmod.quotient.2517@ohm><145515716.20041205201526@geochemsource.com> <1503944261.20041205212551@geochemsource.com> Message-ID: Laszlo Zsolt Nagy wrote: >>> Definitely. However, it would be better if the exception occurred on the >>> bad assignment (e.g. __all__ = [x]) > >> it does happen on the bad assignment (i.e. from foo import *) > > Well, the traceback isn't useful. It does not tell you the line > number not even the name of the module. you're missing the point: the error happens on the "from - import" line, which 1) ass?gns to all names in __all__, and 2) contains the name of the module. if you put your code in a module, you'll find that the traceback does tell you the line number (for the import statement), and the name of the pro- blematic module; example: Traceback (most recent call last): File "myprogram.py", line 8, in ? from mymodule import * TypeError: attribute name must be string in interactive mode, the line number is usually 1, and the offending line is the one you just typed. which contains the name of the module. this doesn't mean that the error message cannot be improved, of course, but things aren't quite as bad as you make them sound. From pje at telecommunity.com Fri Dec 3 19:08:41 2004 From: pje at telecommunity.com (Phillip J. Eby) Date: 3 Dec 2004 16:08:41 -0800 Subject: Python and generic programming References: <1gm17og.ctwoqv17vkctxN%aleaxit@yahoo.com> <419EEEAA.D3C1046F@yahoo.com> Message-ID: <25b5433d.0412031608.e66fa57@posting.google.com> Ian Bicking wrote in message news:... > Jive Dadson wrote: > > If you have, for example, several data-types for matrices, how do you > > write code that will automatically find the right routine for quickly > > multiplying a vector by a diagonal matrix represented as a vector, and > > automatically call the right code for multiplying by a sparse matrix > > represented by some sparse coding, etc? > > I haven't been following this thread, but Phillip Eby's recent > implementation of generic functions should be mentioned if it hasn't > been already: > > http://dirtsimple.org/2004/11/generic-functions-have-landed.html > > It might look something like this: > > @dispatch.on('m1', 'm2') > def matrix_mul(m1, m2): > "Multiply two matrices" > > @matrix_mul.when(VectorMatrix, SparseMatrix) > def matrix_mul_sparse(m1, m2): > "Special implementation" Actually, it would be more like: @dispatch.generic() def matrix_mul(m1, m2): """Multiply two matrices""" @matrix_mul.when("m1 in VectorMatrix and m2 in SparseMatrix") def matrix_mul_sparse(m1, m2): """Special implementation""" The 'dispatch.on()' decorator is for single-dispatch functions only. If you want to dispatch on multiple arguments or on logical conditions, you use 'dispatch.generic()'. The implementations for single and multiple dispatch are completely separate, and use different algorithms. From cjw at sympatico.ca Thu Dec 2 11:52:31 2004 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 02 Dec 2004 11:52:31 -0500 Subject: installing wxPython on Linux and Windows In-Reply-To: References: Message-ID: <41AF484F.5000207@sympatico.ca> Jp Calderone wrote: > On Thu, 02 Dec 2004 15:29:53 +0100, Peter Maas wrote: > >>Diez B. Roggisch schrieb: >> >>>>Same task on Win2k: download wxPython-setup.exe, double-click, done. >>>>Took me approx. 1 minute. This strikes me. Why are some tasks so hard >>>>on Linux and so easy on Windows? After all wxPython/Win and wxPython/Lin >>>>are made by the same developers. My guess: the software deployment >>>>infrastructure on Linux needs to be improved. >>> >>> >>>On debian, it >>> >>>apt-get install wxPython2.5.3 >>> >> >>I have heard praises of Debian's install system but Debian is quite >>conservative with latest versions. There are some packages (e.g. Python, >>PostgreSQL, Subversion) where I'd like to have the latest versions. >>I don't want to be too tightly bound to the update cycles of the >>Linux distribution. >> > > > exarkun at boson:~$ apt-cache show python2.4 > Package: python2.4 > Priority: optional > Section: python > Installed-Size: 10972 > Maintainer: Matthias Klose > Architecture: i386 > Version: 2.3.97-2 > Provides: python2.4-cjkcodecs > Depends: libbz2-1.0, libc6 (>= 2.3.2.ds1-4), libdb4.2, libncurses5 (>= 5.4-1), libreadline4 (>= 4.3-1), libssl0.9.7, zlib1g (>= 1:1.2.1) > Suggests: python2.4-iconvcodec | python2.4-japanese-codecs, python2.4-iconvcodec | python2.4-korean-codecs, python2.4-doc > Conflicts: python2.4-dev (<< 2.3.95-2) > Filename: pool/main/p/python2.4/python2.4_2.3.97-2_i386.deb > Size: 3503764 > MD5sum: 519ed28c52bff645b311b8d5d27b2318 > Description: An interactive high-level object-oriented language (version 2.4) > Version 2.4 of the high-level, interactive object oriented language, > includes an extensive class library with lots of goodies for > network programming, system administration, sounds and graphics. > > Package: python2.4 > Status: install ok installed > Priority: optional > Section: python > Installed-Size: 9764 > Maintainer: Matthias Klose > Version: 2.3.90-1 > Replaces: python2.4-xmlbase > Provides: python2.4-xmlbase > Depends: libbz2-1.0, libc6 (>= 2.3.2.ds1-4), libdb4.2, libncurses5 (>= 5.4-1), libreadline4 (>= 4.3-1), libssl0.9.7, zlib1g (>= 1:1.2.1) > Recommends: python2.4-iconvcodec | python2.4-cjkcodecs | python2.4-japanese-codecs, python2.4-iconvcodec | python2.4-cjkcodecs | python2.4-korean-codecs > Suggests: python2.4-doc > Conflicts: python2.4-xmlbase, python2.4-csv > Conffiles: > /etc/python2.4/site.py b448b0f87294e041b8276ea3459df4a8 > Description: An interactive high-level object-oriented language (version 2.4) > Version 2.4 of the high-level, interactive object oriented language, > includes an extensive class library with lots of goodies for > network programming, system administration, sounds and graphics. > > This is a long and obnoxious way of pointing out that Python 2.4 is already available as a Python package :) How much more up to date software can you ask for? > > And even if there are packages that aren't available, don't you think effort put into a packaging system would better be put into apt than an entirely new system that is guaranteed to be less useful than apt for many years? > > Jp Or synaptic, which puts a GUI layer on top of apt. Colin W. From steven.bethard at gmail.com Fri Dec 17 16:14:54 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 17 Dec 2004 21:14:54 GMT Subject: expression form of one-to-many dict? Message-ID: So I end up writing code like this a fair bit: map = {} for key, value in sequence: map.setdefault(key, []).append(value) This code basically constructs a one-to-many mapping -- each value that a key occurs with is stored in the list for that key. This code's fine, and seems pretty simple, but thanks to generator expressions, I'm getting kinda spoiled. ;) I like being able to do something like the following for one-to-one mappings: dict(sequence) or a more likely scenario for me: dict((get_key(item), get_value(item) for item in sequence) The point here is that there's a simple sequence or GE that I can throw to the dict constructor that spits out a dict with my one-to-one mapping. Is there a similar expression form that would spit out my one-to-many mapping? Steve From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Mon Dec 20 04:16:55 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Mon, 20 Dec 2004 09:16:55 +0000 Subject: Is this a good use for lambda In-Reply-To: <41c69127$0$306$edfadb0f@dread12.news.tele.dk> References: <41c654b9.529432724@news.oz.net> <41c69127$0$306$edfadb0f@dread12.news.tele.dk> Message-ID: Max M wrote: > Isn't it about time you became xml avare, and changed that to: > > That makes no sense. -- Michael Hoffman From ialbert at mailblocks.com Thu Dec 9 13:18:45 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 09 Dec 2004 13:18:45 -0500 Subject: ElementTree and XPATH In-Reply-To: <1102566161.677596.177680@z14g2000cwz.googlegroups.com> References: <1102566161.677596.177680@z14g2000cwz.googlegroups.com> Message-ID: dayzman at hotmail.com wrote: > it seems to be invalid syntax if I give "/a/b[0]" to the findall() > method. Does anyone know the correct syntax? I think the proper mindset going in should be that elementtree does not support xpath but that there are some handy constructs that resemble the location steps of xpath. Sometimes it takes very little work to achieve what you want directly with python. In your case you could probably use: findall("/a/b")[0] to the same effect. Istvan. From FBatista at uniFON.com.ar Mon Dec 6 15:57:52 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 6 Dec 2004 17:57:52 -0300 Subject: PyAr - Python Argentina 4th Meeting, Thursday, December 9th Message-ID: The Argentinian Python User Group, PyAr, will have its next meeting this Thursday, December 9th at 8.30pm. Please see http://pyar.decode.com.ar/Members/pziliani/event.diciembre for details (in Spanish.) Agenda ------ Despite our agenda tends to be rather open, this time we would like to cover these topics: - Website organization & content - Means of promoting the group's activities, in order to increase our member base. - Planning of our first sprint. Where ----- We're meeting at Hip Hop Bar, Hip?lito Yirigoyen 640, Ciudad de Buenos Aires, starting at 8.30pm. We use to get together early, but this month the starting time has been postponed for reasons beyond our control. About PyAr ---------- For more information on PyAr see http://pyar.decode.com.ar (in Spanish), or join our mailing list (Also in Spanish. For instructions see http://pyar.decode.com.ar/Members/ltorre/listademail) We meet on the second Thursday of every month. . Facundo -------------- next part -------------- An HTML attachment was scrubbed... URL: From shivaram.upadhyayula at wipro.com Mon Dec 6 09:55:02 2004 From: shivaram.upadhyayula at wipro.com (shivaram.upadhyayula at wipro.com) Date: Mon, 6 Dec 2004 20:25:02 +0530 Subject: Python parsers for C/C++/Java Message-ID: <52C85426D39B314381D76DDD480EEE0C315D80@blr-m3-msg.wipro.com> Hi, I am looking for a parser generator to parse C, C++ and Java (including popular extensions from various compilers) source code; I have come across PLY, SPARK, D-parser (there seems to be a all-python version itself for this one), etc. and am wondering which one would be the most appropriate one for our use -- which is to do a bit of static code analysis (in python) on the sources. The support for the various language dialects cannot be compromised; for instance if it's C, it will have to support all popular variants, like GCC's, Microsoft's, etc. If there are free pre-built python parsers that handle any of these languages, it would really help to start off. Thanks in Advance, Best Regards, Shivram U (Please CC me as i am not subscribed to the list) Confidentiality Notice The information contained in this electronic message and any attachments to this message are intended for the exclusive use of the addressee(s) and may contain confidential or privileged information. If you are not the intended recipient, please notify the sender at Wipro or Mailadmin at wipro.com immediately and destroy all copies of this message and any attachments. -------------- next part -------------- An HTML attachment was scrubbed... URL: From anilby at gmail.com Thu Dec 9 23:50:20 2004 From: anilby at gmail.com (Anil) Date: 9 Dec 2004 20:50:20 -0800 Subject: Parse XML using Python In-Reply-To: <31rqj9F3fscsbU1@individual.net> References: <1102577149.256162.316460@z14g2000cwz.googlegroups.com> <31rqj9F3fscsbU1@individual.net> Message-ID: <1102654220.351183.131700@z14g2000cwz.googlegroups.com> William Park wrote: > anilby at gmail.com wrote: > > Hi, > > > > I wanted to write a script that will read the below file: > > > > > > . > > > > .... > > > > .. > > > > .. > > > > > > > > .. > > > > .. > > > > .. > > > > . > > . > > > > . > > > > .... > > > > .. > > > > > > > > .. > > > > > > > > > > > > .. > > and so on > > > > The output of the script shud be > > > > ABC > > ..EFGA > > ....ABDG > > ..MON > > > > A1 > > ..FGA > > ....BG > > > > Please help me in writing a Python script for the above task. > > Take a look at > http://home.eol.ca/~parkw/park-january.html > on "Expat XML" section towards the end. Translating it to Python is > left for homework. > > In essence, > indent=.. > start () { > local "${@:2}" > echo "${indent|*XML_ELEMENT_DEPTH-1}$label" > } > xml -s start "`< file.xml`" > which prints > ..ABC > ....EFGA > ......ABDG > ....MON > ..A1 > ....FGA > ......BG > with modified input, ie. wrapping XML pieces into single root tree. > > -- > William Park > Open Geometry Consulting, Toronto, Canada > Linux solution for data processing. Thanks everyone for the responses. I will try the above solutions. From kael at alussinan.org Fri Dec 10 12:13:49 2004 From: kael at alussinan.org (kael) Date: Fri, 10 Dec 2004 18:13:49 +0100 Subject: Python + Newspipe In-Reply-To: <1rkud.40867$6q2.19116@newssvr14.news.prodigy.com> References: <41B9C0BE.4030106@alussinan.org> <1rkud.40867$6q2.19116@newssvr14.news.prodigy.com> Message-ID: <41B9D94D.9000808@alussinan.org> Dave Kuhlman wrote: > 1. Read about ConfigParser here: > > http://docs.python.org/lib/module-ConfigParser.html Thank you very for this link. > 2. Read the traceback from the bottom up: (1) The exception is > raised in ConfigParser.py on line 240 in function/method options. > (2) This was called from newspipe.py on line 895 in > function/method LeerConfig. Should the changes be made in the newspipe/* directory only ? Or should I manage the ConfigParser.py ? > 3. It's looking for a section named "NewsPipe" in your > options/config file. Check your config file. Is that > section name misspelled? Is the section missing? Does > the NewsPipe documentation tell you where the config file > should be and what it's name is? If not, look in newspipe.py. According to the Newspipe documentation http://newspipe.sourceforge.net/#configuration, only the 'smtp_server' and 'opml' lines are absolutely needed in newspipe.py. Please, see newspipe.py below: ---------------------------------- [NewsPipe] log_console=1 smtp_server=smtp.free.fr opml=test.opml sleep_time=30 check_online=http://www.google.com ---------------------------------- Do you think any lines are missing ? Unless, it could come from the OPML file ? > Hope this helps. Yes. But, unfortunately, not enough - it's hard to be a newbie. :-/ I thank you very much for your help. -- kael @759 .beats, 2004-12-10 From binux.lists at gmail.com Mon Dec 13 02:39:45 2004 From: binux.lists at gmail.com (Binu K S) Date: Mon, 13 Dec 2004 13:09:45 +0530 Subject: Path problem In-Reply-To: <18954783-4CD5-11D9-9C6A-000A9573BBC8@internode.on.net> References: <41bd1f10$0$21873$61ce578d@news.syd.swiftdsl.com.au> <2b7d8b420412122111bc70776@mail.gmail.com> <18954783-4CD5-11D9-9C6A-000A9573BBC8@internode.on.net> Message-ID: <2b7d8b4204121223391f9fd90e@mail.gmail.com> Hi Lars, sys.path[0] will contain the path to the script. >From the sys module documentation: "As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH." -Binu On Mon, 13 Dec 2004 18:03:30 +1100, Lars Yencken wrote: > Hi Binu, > > On 13/12/2004, at 4:11 PM, Binu K S wrote: > > This should get you the module's path: > > > > import sys > > sys.modules['rpy'].__file__ > > > > Unfortunately it's not the rpy module itself whose path I'm looking > for. It's the absolute path of my module that I've created. > > If my script was called runRScript.py, and it was in the same directory > as someScript.r, I'm only able to get it working if I run > > python runRScript.py > > from the same directory. In otherwords, I can't be in a child directory > and run: > > python ../runRScript.py > > because runRScript depends internally on the file someScript.r, and > can't find it. > > I've found a pathconf module posted earlier to this group, which does > half the job. Unfortunately, when I call get_rootdir() it returns > '/usr/bin' instead of my project's root directory ;( > > Lars > > From fumanchu at amor.org Wed Dec 15 19:09:20 2004 From: fumanchu at amor.org (Robert Brewer) Date: Wed, 15 Dec 2004 16:09:20 -0800 Subject: Dejavu 1.2.6, a Python ORM Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398053@exchange.hqamor.amorhq.net> The Dejavu Object-Relational Mapper (version 1.2.6) is now available and in the public domain. Get it at svn://casadeamor.com/dejavu/trunk. Dejavu is an Object-Relational Mapper for Python applications. It is designed to provide the "Model" third of an MVC application. Dejavu avoids making decisions in the framework which are better left to developers, and avoids forcing developers to make decisions which are better left to deployers. In particular, deployers are allowed to mix and match storage mechanisms, including how and when to cache objects in memory, making it easier for deployers to tune applications to their particular environment. Dejavu provides: MODELING LAYER 1. A subclassable Unit class for persisting objects to storage. 2. A base Unit Property class for declaring persistent object attributes. 3. ID Sequencers. 4. Associations between Unit classes. 5. Unit Engines, Rules, and Collections. 6. Aggregation and analysis tools. APPLICATION LAYER 1. Expressions: pure Python Unit queries. This is perhaps the most appealing feature of Dejavu. However, since it uses bytecode hacks, Dejavu only runs on CPython. 2. Sandboxes, which serve as Identity Maps and per-connection caches. Unit objects are "memorized" and "recalled" from a Sandbox, using Expressions. 3. An Arena class for application-level data. STORAGE LAYER 1. A subclassable StorageManager class and specification. Unlike many ORMs, Dejavu does not require you to have complete control of your back end. 2. Specific StorageManagers for: a. Microsoft SQL Server via ADO. b. Microsoft Access (Jet) via ADO. c. ODBC databases (not complete = broken) d. Shelve to dbm. e. Future versions of Dejavu will support PostgreSQL, MySQL, and SQLite. Others are being considered. Dejavu welcomes your use and feedback as an application developer. Dejavu also welcomes framework developers. New code for additional Storage Managers, analysis tools, will be gladly reviewed for inclusion in future releases. Drop me an email if you feel so inclined. Robert Brewer MIS Amor Ministries fumanchu at amor.org From drew at gremlinhosting.com Sat Dec 4 10:16:16 2004 From: drew at gremlinhosting.com (Andrew James) Date: Sat, 04 Dec 2004 15:16:16 +0000 Subject: Error in previous post - Import behaviour In-Reply-To: <1102171793.20843.21.camel@odin> References: <1102171793.20843.21.camel@odin> Message-ID: <1102173377.20965.6.camel@odin> All, The example given in the previous e-mail I sent was wrong (and makes the question look stupid). In the attribute instantiation example, the __main__ declaration should read: > if __name__ == 'main': > y = myY() I meant it to show that even if I never instantiate X, its attributes still get created. Regards, Andrew From finite.automaton at gmail.com Tue Dec 21 14:34:09 2004 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 21 Dec 2004 11:34:09 -0800 Subject: Tuple Question References: Message-ID: <1103657649.441383.210810@c13g2000cwb.googlegroups.com> > Why is this? It should work. Are you using an old version of Python? From bulba at bulba.com Mon Dec 20 09:23:30 2004 From: bulba at bulba.com (Bulba!) Date: Mon, 20 Dec 2004 15:23:30 +0100 Subject: Best GUI for small-scale accounting app? References: <1103550783.146272.192600@f14g2000cwb.googlegroups.com> Message-ID: On 20 Dec 2004 05:53:03 -0800, "RM" wrote: >Here is another question, are you deploying in Linux, Windows, Mac, or >some combination of these? I think that may be a big factor to >consider. I do like the look of Qt under Linux, however, I have never >seen it under Windows. Qt seems to be very focused in Linux, with Mac >and Windows support as a reluctant afterthought. Server will run on Linux, clients on Windows (all those Windows apps that workers typically use...). We're not excluding possible deployment of some specialized workstations on Linux only, however (thus one of the reasons for considering either wxWindows or QT is that they're cross-platform). >I have used wxPython and PythonCard under Windows and Linux. Under >Windows, both of these are excellent, and allow you to do some very >nice looking apps. I love the way PythonCard separates the interface >code from the rest of the app functionality. That's a strong pro, I don't like aspects of various problems intertwining too much in a particular place in a program, I like to keep them separate (that's one reason I don't like PHP very much, where the "business logic" naturally wants to be "mixed" with PHP with HTML over the whole damn place - maybe it's possible to keep all those separate in PHP but I don't see convenient ways of doing that). >PythonCard is a pleasure >to use. It is not quite finished, but its developers are now in the >final stretch towards the final 1.0 version. Too much of a good thing I guess. :-) Now the choice between GUIs is harder for me instead of it being easier. ;-) But it's great to know that Python can be used for serious GUI and other development, it seems like it's not going to die... >In Python, when you run into its speed limitations, you may have to >resort to writing pure C. That's not an issue here, as I obviously am not going to write my own DB server and I don't think accounting programming really needs the speed of C. >Similarly, when you run into a widget >limitation in PythonCard, you may have to resort to pure wxPython code. Hmm.. and if I may ask, what limitations you have stumbled on? -- It's a man's life in a Python Programming Association. From matt.gerrans at hp.com Fri Dec 3 04:02:25 2004 From: matt.gerrans at hp.com (Matt Gerrans) Date: Fri, 03 Dec 2004 09:02:25 GMT Subject: installing 2.4 References: Message-ID: "Peter Hansen" wrote: > Only pure Python code can run without change on a newer interpreter. Is the interpreter smart enough to rebuild a pyc (if the corresponding py file is there of course) file that was built by a previous version? From steven.bethard at gmail.com Sun Dec 26 12:55:34 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 26 Dec 2004 17:55:34 GMT Subject: A Revised Rational Proposal In-Reply-To: <1104071161.355661.10550@f14g2000cwb.googlegroups.com> References: <86llbl7kvv.fsf@guru.mired.org> <1104071161.355661.10550@f14g2000cwb.googlegroups.com> Message-ID: Dan Bishop wrote: > Mike Meyer wrote: >> >>PEP: XXX > > I'll be the first to volunteer an implementation. Very cool. Thanks for the quick work! For stdlib acceptance, I'd suggest a few cosmetic changes: Use PEP 257[1] docstring conventions, e.g. triple-quoted strings. Use PEP 8[2] naming conventions, e.g. name functions from_exact_float, approx_smallest_denominator, etc. The decimal and math modules should probably be imported as _decimal and _math. This will keep them from showing up in the module namespace in editors like PythonWin. I would be inclined to name the instance variables _n and _d instead of the double-underscore versions. There was a thread a few months back about avoiding overuse of __x name-mangling, but I can't find it. It also might be nice for subclasses of Rational to be able to easily access _n and _d. Thanks again for your work! Steve [1] http://www.python.org/peps/pep-0257.html [2] http://www.python.org/peps/pep-0008.html From Doran_Dermot at emc.com Fri Dec 3 10:21:57 2004 From: Doran_Dermot at emc.com (Doran_Dermot at emc.com) Date: Fri, 3 Dec 2004 15:21:57 -0000 Subject: How did you learn Python? Message-ID: <97B6410BE753D411894E00D0B77E6F7F0315E895@neam2mx1.corp.emc.com> Hi Shawn, I would recommend the following for starters: - The Tutorial (http://www.python.org/dev/doc/devel/tut/tut.html) - Python "How to Program" by Deitel After that it is like any language, natural or computer related! Use it! However, I think you'll find that it is a lot easier to use than most other languages. Cheers!! -----Original Message----- From: python-list-bounces+doran_dermot=emc.com at python.org [mailto:python-list-bounces+doran_dermot=emc.com at python.org] On Behalf Of Shawn Milo Sent: 03 December 2004 14:55 To: python-list at python.org Subject: How did you learn Python? I was just wondering what the best books were for learning Python. Which books are good for getting started, and which should be saved for later, or or not useful except as a reference for the learned? I have a decent programming background in VB, JavaScript, VBScript, Net.Data (IBM's macro language), regular expressions, and a teensy bit of Perl. My point is, I don't want something that is going to explain the basic programming concepts, but does give a good introduction to Python-specific things. Then, once I know how to get the job done, I would like a good book or two at the intermediate to advanced level, to learn how to write really good code. I understand that resources such as this list and Google searches have all the answers, but it seems like a more structured tool, such as a book or formal class, would be of great benefit to me. The other languages I have used were picked up because of the need to get a job done. As a result, I am able to get the job done, but any experienced coder can show me six more efficient ways to do what I'm doing. I'm new to Python, and I want to do this one right. I believe that Python will be around for a good, long time, and it matches my values as an Open-Source/Linux supporter, while having relevance in the Windows and Mac world, as well. Plus, it looks like it was designed extremely well, and I'm excited about the principles I've read about. Thanks, Shawn -- http://mail.python.org/mailman/listinfo/python-list From ch.list at us-hampton.mail.saic.com Mon Dec 20 11:40:46 2004 From: ch.list at us-hampton.mail.saic.com (Chris) Date: Mon, 20 Dec 2004 11:40:46 -0500 Subject: Python To Send Emails Via Outlook Express In-Reply-To: <1103519604.987664.117400@c13g2000cwb.googlegroups.com> References: <1103519604.987664.117400@c13g2000cwb.googlegroups.com> Message-ID: <41C7008E.7040207@us-hampton.mail.saic.com> > I'm a newbie (oh no I can here you say.... another one...) > > How can I get Python to send emails using the default windows email > client (eg outlook express)? > > I thought I could just do the following > > import win32com.client > > s = win32com.client.Dispatch('CDO.Message') > s.From = "ian at kirbyfooty.com" > s.To = "someone at yahoo.com" > s.Subject = "The subject" > s.Send > > ... but nothing happens. > > What am I doing wrong? Does anyone have some sample code to share with > me please? Do a search on the list for the thread Fun with Outlook and MAPI. That'll have your answers. Chris From kdart at kdart.com Sun Dec 12 19:22:59 2004 From: kdart at kdart.com (Keith Dart) Date: Mon, 13 Dec 2004 00:22:59 GMT Subject: Persistent objects In-Reply-To: <7xis77q1t7.fsf_-_@ruckus.brouhaha.com> References: <7xis77q1t7.fsf_-_@ruckus.brouhaha.com> Message-ID: <41BCE0E3.1040602@kdart.com> Paul Rubin wrote: > I've had this recurring half-baked desire for long enough that I > thought I'd post about it, even though I don't have any concrete > proposals and the whole idea is fraught with hazards. > > Basically I wish there was a way to have persistent in-memory objects > in a Python app, maybe a multi-process one. So you could have a > persistent dictionary d, and if you say > d[x] = Frob(foo=9, bar=23) > that creates a Frob instance and stores it in d[x]. Then if you > exit the app and restart it later, there'd be a way to bring d back > into the process and have that Frob instance be there. Check out the Durus project. http://www.mems-exchange.org/software/durus/ -- \/ \/ (O O) -- --------------------oOOo~(_)~oOOo---------------------------------------- Keith Dart vcard: public key: ID: F3D288E4 URL: ============================================================================ From fredrik at pythonware.com Mon Dec 13 11:48:49 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Dec 2004 17:48:49 +0100 Subject: urllib2 and Set-Cookie with "302 Moved temporarily" References: <6vfvd.703$aM4.37@reader1.news.jippii.net> Message-ID: "Eino M?kitalo" wrote: > It seems that urrlib2 default redirection does not allow me to handle > Cookies. Service I'm trying seems to use IP switcher and session id's with cookies. After > successful login it changes session id (PD-H_SESSION-ID) in 302 Moved temporarily. and adds a new cookie. > Urllib2 is so clever that it handles redirection but with wrong cookies. with the old cookies, that is. that's stupid. here's an ugly hack for the old urllib that looks for set-cookie headers in redirects, and adds corresponding cookie headers to the new request: import urllib class my_url_opener(urllib.FancyURLopener): def http_error_302(self, *args): headers = args[4] # print headers # <-- uncomment to see the headers cookie = headers.get("set-cookie") if cookie: # this is ugly self.addheaders.append(("Cookie", cookie.split(";")[0])) return urllib.FancyURLopener.http_error_302(self, *args) myurlopen = my_url_opener().open myurlopen("http://www.google.com") From gh at ghaering.de Thu Dec 2 10:28:43 2004 From: gh at ghaering.de (Gerhard Haering) Date: Thu, 2 Dec 2004 16:28:43 +0100 Subject: installer In-Reply-To: <20041203184504.GA25493@mrna.tn.nic.in> References: <20041203184504.GA25493@mrna.tn.nic.in> Message-ID: <20041202152843.GA4458@mylene.ghaering.de> On Sat, Dec 04, 2004 at 12:15:04AM +0530, km wrote: > Hi all, > > does python have a default module installer inbuilt as for perl in > windows ? No, there is no CPAN-like system for Python. You will have to search, download and install your third-party Python libraries yourself. OTOH, there are some good places to look for these, like http://www.python.org/pypi?:action=browse and the libraries are usually packaged with distutils into win32 installers that you can then easily install/uninstall. -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From steven.bethard at gmail.com Thu Dec 16 16:49:11 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 16 Dec 2004 21:49:11 GMT Subject: (No subject) In-Reply-To: References: <20041216154932.95D841E4009@bag.python.org> Message-ID: Jeremy Jones wrote: > Mark Devine wrote: >> I'm brand new to python and I was wondering if anybody knew of a easy [snip] > You could use string.lower (make sure you "import string"): string.lower is deprecated in Python 2.4. Better to go with str.lower as Diez B. Roggisch suggested: commands = [c.lower() for c in commands] Steve From imbosol at aerojockey.com Fri Dec 10 17:25:39 2004 From: imbosol at aerojockey.com (Carl Banks) Date: 10 Dec 2004 14:25:39 -0800 Subject: How do I do this? (eval() on the left hand side) In-Reply-To: References: <10rh37tt58vv362@corp.supernews.com> <1102629625.006251.52630@c13g2000cwb.googlegroups.com> <1102713054.448135.76880@z14g2000cwz.googlegroups.com> Message-ID: <1102717539.124358.30500@z14g2000cwz.googlegroups.com> > From my point of view, they're basically identical, and > although I find Carl's approach slightly less explicit > and harder to read (mainly the uncommon __import__ call, > but it's not a big deal), I can't see why either of them > would be considered evil. Of course, when I said evil, I didn't mean evil, I meant Evil(tm). I suspect Nick meant so as well. Personally, I just think __import__(__name__) is a bit more honest than globals() for a simple reason. What are you doing? You're changing module attributes. Well, here's the module object. You're using setattr on the module object to set module attributes. What are you doing? You're changing module attributes. Well, here's the module's dict. You're using dictionary access on the modules dict to set modules attributes. It's a bit more honest to set module attributes using setattr than dict access, I would say. That's why I prefer it. I admit, it's pretty weak. (But then again, so is __import__ being uncommon. :) It's not a big deal which you choose, as you say. Although I don't use globals() in this way, I do modify object dicts to get the effect of changing object attributes from time to time (mostly to take advantage of dict methods, which I could see being a reason to use globals() as well). -- CARL BANKS From steve at holdenweb.com Mon Dec 27 08:37:29 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 27 Dec 2004 08:37:29 -0500 Subject: WxListBox In-Reply-To: <20041225231335.22097.00002707@mb-m06.aol.com> References: <20041225231335.22097.00002707@mb-m06.aol.com> Message-ID: LutherRevisited wrote: > I'm wanting to put a listbox in the place of a textctrl I'm using in my > application because I'm running out of space in my textctrl. The online > documentation is down at wxpython.org so I have no idea how to construct this > control or anything. Can someone help me out. Here's what I'm doing with the > WxTextCtrl: > > self.text_ctrl_4 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE) > sizer_1.Add(self.text_ctrl_4, 6, wx.LEFT|wx.RIGHT|wx.EXPAND, 80) > self.text_ctrl_4.AppendText(str(count) + '\t\t' + str(address) + '\t\t' > + str(pageNumber) + '\t\t' + str(pageArray[pageNumber, 1]) +'\r\n') > > I'm wanting to implement something similar with a listbox, any thoughts? Well, my *first* thought was "Isn't a listbox supposed to allow choice between alternative? How can that substitute for what looks like a very complex text input?" My second thought was "It's not very helpful to use a name like 'text_ctrl_4' in the code". I'm also not really sure what the double-tabs are supposed to do. Perhaps you could explain exactly what you'd like your program to do here, as at present it's not even clear whether this code is intended to act as input as well as output? What's wrong with what happens now, and how would you like to change it? regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From peter at engcorp.com Mon Dec 13 22:11:25 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 13 Dec 2004 22:11:25 -0500 Subject: looking for blocking on read of a real file (not socket or pipe) In-Reply-To: References: Message-ID: Steven wrote: > I'm seeking a read method that will block until new data is available. Is > there such a python function that does that? It may be relevant which platform(s) are of interest. Linux? Mac? Windows? All? The more cross-platform this needs to be, the less likely it exists... From steven.bethard at gmail.com Fri Dec 31 01:53:55 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 31 Dec 2004 06:53:55 GMT Subject: what is lambda used for in real code? Message-ID: I thought it might be useful to put the recent lambda threads into perspective a bit. I was wondering what lambda gets used for in "real" code, so I grepped my Python Lib directory. Here are some of the ones I looked, classified by how I would rewrite them (if I could): * Rewritable as def statements ( = lambda : usage) These are lambdas used when a lambda wasn't needed -- an anonymous function was created with lambda and then immediately bound to a name. Since this is essentially what def does, using lambdas here is (IMHO) silly. pickletools.py: getpos = lambda: None def getpos(): return None tarfile.py: normpath = lambda path: os.path.normpath(path).replace(os.sep, "/") def normpath(path): os.path.normpath(path).replace(os.sep, "/") urllib2.py: H = lambda x: md5.new(x).hexdigest() def H(x): md5.new(x).hexdigest() urllib2.py: H = lambda x: sha.new(x).hexdigest() def H(x): sha.new(x).hexdigest() * Rewritable with existing functions Mainly these are examples of code that can benefit from using the functions available in the operator module, especially operator.itemgetter and operator.attrgetter (available in 2.4) cgi.py: return map(lambda v: v.value, value) return map(operator.attrgetter('value'), value) CGIHTTPServer.py: nobody = 1 + max(map(lambda x: x[2], pwd.getpwall())) nobody = 1 + max(map(operator.itemgetter(2), pwd.getpwall())) SimpleXMLRPCServer.py: server.register_function(lambda x,y: x+y, 'add') server.register_function(operator.add, 'add') SimpleXMLRPCServer.py: server.register_function(lambda x,y: x+y, 'add') server.register_function(operator.add, 'add') sre_constants.py: items.sort(key=lambda a: a[1]) items.sort(key=operator.itemgetter(1)) tarfile.py: return map(lambda m: m.name, self.infolist()) return map(operator.attrgetter('name'), self.infolist()) * Rewritable with list comprehensions/generator expressions Lambdas in map or filter expressions can often be replaced by an appropriate list comprehension or generator expression (in Python 2.3/2.4) cgi.py: plist = map(lambda x: x.strip(), line.split(';')) plist = [x.strip() for x in line.split(';') cgi.py: return map(lambda v: v.value, value) return [v.value for v in value] CGIHTTPServer.py: nobody = 1 + max(map(lambda x: x[2], pwd.getpwall())) nobody = 1 + max(x[2] for x in pwd.getpwall()) glob.py: names=filter(lambda x: x[0]!='.',names) names=[x for x in names if x[0] != '.'] hmac.py: return "".join(map(lambda x, y: chr(ord(x) ^ ord(y)), s1, s2)) return "".join(chr(ord(x) ^ ord(y)) for x, y in zip(s1, s2)) imaplib.py: l = map(lambda x:'%s: "%s"' % (x[0], x[1][0] and '" "'.join(x[1]) or ''), l) l = ['%s: "%s"' % (x[0], x[1][0] and '" "'.join(x[1]) or '') for x in l] inspect.py: suffixes = map(lambda (suffix, mode, mtype): (-len(suffix), suffix, mode, mtype), imp.get_suffixes()) suffixes = [(-len(suffix), suffix, mode, mtype) for suffix, mode, mtype in imp.get_suffixes() inspect.py: return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object)) return join([strseq(o, convert, join) for o in object]) mailcap.py: entries = filter(lambda e,key=key: key in e, entries) entries = [e for e in entries if key in e] poplib.py: digest = ''.join(map(lambda x:'%02x'%ord(x), digest)) digest = ''.join('%02x' % ord(x) for x in digest) pstats.py: if line and not filter(lambda x,a=abbrevs: x not in a,line.split()): if line and not [x for x in line.split() if x not in abbrevs]: tabnanny.py: firsts = map(lambda tup: str(tup[0]), w) firsts = [str(tup[0]) for tup in w] tarfile.py: return map(lambda m: m.name, self.infolist()) return [m.name for m in self.infolist()] tarfile.py: return filter(lambda m: m.type in REGULAR_TYPES, self.tarfile.getmembers()) return [m for m in self.tarfile.getmembers() if m.type in REGULAR_TYPES] urllib2.py: return map(lambda x: x.strip(), list) return [x.strip() for x in list] webbrowser.py: _tryorder = filter(lambda x: x.lower() in _browsers or x.find("%s") > -1, _tryorder _tryorder = [x for x in _tryorder if x.lower() in _browsers or x.find("%s") > -1] * Functions I don't know how to rewrite Some functions I looked at, I couldn't figure out a way to rewrite them without introducing a new name or adding new statements. (Warning: I have trouble following code that uses 'reduce', so I only glossed over lambdas in reduce calls.) calendar.py: _months.insert(0, lambda x: "") cgitb.py: inspect.formatargvalues(args, varargs, varkw, locals, formatvalue=lambda value: '=' + pydoc.html.repr(value)) cgitb.py: inspect.formatargvalues(args, varargs, varkw, locals, formatvalue=lambda value: '=' + pydoc.text.repr(value)) csv.py: quotechar = reduce(lambda a, b, quotes = quotes: (quotes[a] > quotes[b]) and a or b, quotes.keys()) csv.py: delim = reduce(lambda a, b, delims = delims: (delims[a] > delims[b]) and a or b, delims.keys()) difflib.py: matches = reduce(lambda sum, triple: sum + triple[-1], self.get_matching_blocks(), 0) gettext.py: return eval('lambda n: int(%s)' % plural) gettext.py: self.plural = lambda n: int(n != 1) inspect.py: classes.sort(key=lambda c: (c.__module__, c.__name__)) inspect.py: def formatargspec(args, varargs=None, varkw=None, ... formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), inspect.py: def formatargvalues(args, varargs, varkw, locals, ... formatvarargs=lambda name: '*' + name, formatvarkw=lambda name: '**' + name, formatvalue=lambda value: '=' + repr(value), pyclbr.py: objs.sort(lambda a, b: cmp(getattr(a, 'lineno', 0), getattr(b, 'lineno', 0))) SimpleHTTPServer.py: list.sort(key=lambda a: a.lower()) subprocess.py: p = Popen(["id"], preexec_fn=lambda: os.setuid(100)) symtable.py: self.__params = self.__idents_matching(lambda x: x & DEF_PARAM) symtable.py: self.__locals = self.__idents_matching(lambda x: x & DEF_BOUND) symtable.py: self.__globals = self.__idents_matching(lambda x: x & glob) urllib2.py:setattr(self, '%s_open' % type, lambda r, proxy=url, type=type, meth=self.proxy_open: meth(r, proxy, type)) xdrlib.py: unpacktest = [ (up.unpack_uint, (), lambda x: x == 9), (up.unpack_bool, (), lambda x: not x), (up.unpack_bool, (), lambda x: x), (up.unpack_uhyper, (), lambda x: x == 45L), (up.unpack_float, (), lambda x: 1.89 < x < 1.91), (up.unpack_double, (), lambda x: 1.89 < x < 1.91), (up.unpack_string, (), lambda x: x == 'hello world'), (up.unpack_list, (up.unpack_uint,), lambda x: x == range(5)), (up.unpack_array, (up.unpack_string,), lambda x: x == ['what', 'is', 'hapnin', 'doctor']), ] Of the functions that I don't know how to rewrite, I think there are a few interesting cases: (1) lambda x: "" This is the kind of parameter adaptation that I think Jeff Shannon was talking about in another lambda thread. Using the ignoreargs function I suggested there[1], you could rewrite this as: ignoreargs(str, 1) (2) lambda a: a.lower() My first thought here was to use str.lower instead of the lambda, but of course that doesn't work if 'a' is a unicode object: py> str.lower(u'a') Traceback (most recent call last): File "", line 1, in ? TypeError: descriptor 'lower' requires a 'str' object but received a 'unicode' It's too bad I can't do something like: basestring.lower (3) self.plural = lambda n: int(n != 1) Note that this is *almost* writable with def syntax. If only we could do: def self.plural(n): int(n != 1) (4) objs.sort(lambda a, b: cmp(getattr(a, 'lineno', 0), getattr(b, 'lineno', 0))) My first intuition here was to try something like: objs.sort(key=operator.attrgetter('lineno')) but this doesn't work because then we don't get the default value of 0 if the attribute doesn't exist. I wonder if operator.attrgetter should take an optional "default" parameter like getattr does: Help on built-in function getattr in module __builtin__: getattr(...) getattr(object, name[, default]) -> value (5) lambda x: x & DEF_PARAM This could probably be written as: functional.partial(operator.and_, DEF_PARAM) if PEP 309[2] was accepted, thought I'm not claiming that's any clearer... So, those are my thoughts on how lambdas are "really" used. If others out there have real-life code that uses lambdas in interesting ways, feel free to share them here! Steve [1]http://mail.python.org/pipermail/python-list/2004-December/257982.html [2]http://python.fyxm.net/peps/pep-0309.html From pierre.barbier at cirad.fr Tue Dec 14 06:29:03 2004 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Tue, 14 Dec 2004 12:29:03 +0100 Subject: Suggestion for "syntax error": ++i, --i In-Reply-To: References: Message-ID: <41bece0b$0$25288$636a15ce@news.free.fr> Christian Ergh a ?crit : > Hmm, i never liked the i++ syntax, because there is a value asignment > behind it and it does not show - except the case you are already used to > it. > > >>> i = 1 > >>> i +=1 > >>> i > 2 > > I like this one better, because you see the assignment at once, it is > easy to read and inuitive usability is given - in my opinion. > Chris > IMO, there is an assignement only for languages like python ! (ie. reference languages) In languages like C or C++ (in which variables correspond to values) it makes perfect sens to modify the current value by an operator. Nevertheless, I agree with you concerning Python ! But not for C++ :) Pierre From ptmcg at austin.rr._bogus_.com Tue Dec 14 02:20:08 2004 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 14 Dec 2004 07:20:08 GMT Subject: lies about OOP References: <1102995205.949964.76020@c13g2000cwb.googlegroups.com> Message-ID: "Jive" wrote in message news:Revvd.807843$SM5.50718 at news.easynews.com... > > But by '86, the Joy of OOP was widely known. > "Widely known"? Errr? In 1986, "object-oriented" programming was barely marketing-speak. Computing hardware in the mid-80's just wasn't up to the task of dealing with OO memory and "messaging" overhead. Apple Macs were still coding in C and Forth. Borland didn't ship Turbo-Pascal with Object-Oriented programming until 1989, and Turbo-C++ shipped in 1991. Smalltalk had been around for 10 years by 1986, but it was still a curiosity, hardly "widely known." It wasn't until the publication of David Taylor's "Object Technology: A Manager's Guide" in 1990 that OOP began to be legitimized to many management decision makers, that it was more than just "fairy dust" (as Bill Gates had characterized it in an attempt to discredit Borland's forays into the field). I would pick the publication of "Design Patterns" in 1995 by the Gang of Four (Gamma, Helm, Johnson, and Vlissides), to be the herald of when "the Joy of OOP" would be "widely known." DP formalized a taxonomy for many of the heuristics that had evolved only intuitively up until then. Its emergence reflects a general maturation of concept and practice, sufficient to say that the Joy of OOP could be said to be "widely known." -- Paul From noway at sorry.com Sat Dec 11 22:46:37 2004 From: noway at sorry.com (Giovanni Bajo) Date: Sun, 12 Dec 2004 03:46:37 GMT Subject: Upgrade woes: Numeric, gnuplot, and Python 2.4 References: Message-ID: Jive wrote: > 4) Buy a copy of the VC++ 7.1 and port Numeric myself. (I still don't > know what to buy from Mr. Gates -- VC++ .net Standard?) VC++ 7.1, the compiler/linker, is a free download. Google for "VC toolkit". You won't get the fancy IDE and stuff, but you have everything you need to build your extensions. I saw patches floating around to build Python itself with the free version (a couple of small nits). -- Giovanni Bajo From bvande at po-box.mcgill.ca Fri Dec 3 11:26:54 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri, 03 Dec 2004 11:26:54 -0500 Subject: hello all In-Reply-To: <34534aed04120300365f2e7dcb@mail.gmail.com> References: <34534aed04120300365f2e7dcb@mail.gmail.com> Message-ID: <41B093CE.9040909@po-box.mcgill.ca> Ishwor Gurung said unto the world upon 2004-12-03 03:36: > Hello all, > I am just starting out on learning Python and joined this list. I > have grabbed the Learning Perl book by Mark & David. This book really > seems good so far.. the concepts are explained pretty nicely. :) I > have a background a bit in Java but Python seems so cooler. The > concept of Dynamically assigning values n the objects springing into > existence is really nice to see especially you don't have to declare > variable everytime its used. In this book though it says Python 3.0 as > upcoming python version but all i see so far is Python 2.4 ?? Any > hints anyone has? So contrasting with Java which is a bit like C++ > where values and object has to be "created" before assigning, Python > seems very typical of "on the edge" language, "ready to go" language > :) > cheers, > Ishwor Hi Ishwor, *Learning Perl*? -- burn him, he's a witch! ;-) I am only a hobbyist, and know just enough Python to be dangerous. But, for what you ask: Python recently released 2.4. Python 3.0 is definitely in the future. Python seems to have quite a conservative stance with respect to backwards compatibility. Most (all?) Python 1.5.2 code will still run on Python 2.4. Python 3.0 is being pondered well in advance, because, as I understand it, the 2.x to 3.x switch will be allowed to loosen the backwards comp. requirement considerably. 2.3 -> 2.4 took 18 months. I don't know how many more 2.x's are planned/likely, but there will be, as I understand it, at least a 2.5. Since you have a Java background, you might find the recent interesting. I did, but I know even less Java than Python. So, YMMV. Also, while you might be more of a programmer than the target audience, the Tutor list is very good for people just getting started with Python. The main list is also quite happy to answer newcomer help questions, but the Tutor folk specialize at it. HTH, Brian vdB From http Wed Dec 22 21:27:14 2004 From: http (Paul Rubin) Date: 22 Dec 2004 18:27:14 -0800 Subject: PHP vs. Python References: <1103753016.780533.137480@f14g2000cwb.googlegroups.com> <7xzn0526ae.fsf@ruckus.brouhaha.com> Message-ID: <7xu0qdn3zx.fsf@ruckus.brouhaha.com> Jeremy Bowers writes: > Your point is circular; "fast enough (right now)" can be defined as > "doesn't need to scale (right now)". > > For any given server app, enough clients will bog it down. If you're > trying to claim that PHP has less trouble with this, I've seen a lot of > PHP sites go down under load, so it is clearly not a non-issue. > > Python's scaling isn't automatic, it's just easier to do. I've never heard of any large sites being done in Python, with or without scaling. By a large site I mean one that regularly gets 100 hits/sec or more. There are many sites like that out there. Those are the ones that need to be concerned about scaling. For sites that get less traffic than that, they only reason they need to scale if they're written in Python is that Python is too slow. From terekhov at emc.com Fri Dec 10 16:31:46 2004 From: terekhov at emc.com (MMM) Date: 10 Dec 2004 13:31:46 -0800 Subject: collaborative editing In-Reply-To: <4edc17eb.0412100520.41c5ba39@posting.google.com> References: <4edc17eb.0412100520.41c5ba39@posting.google.com> Message-ID: <1102714306.055839.153990@z14g2000cwz.googlegroups.com> Michele Simionato wrote: > Suppose I want to write a book with many authors via the Web. The book has > a hierarchical structure with chapter, sections, subsections, subsubsections, > etc. At each moment it must be possible to print the current version of the > book in PDF format. There must be automatic generation of the table of contents, > indices, etc. Conversions to many formats (Latex, DocBook, etc.) would be > welcome. Does something like that already exists? Alternatively, I would need > some hierarchical Wiki with the ability of printing its contents in an > structured way. > > > Michele Simionato Tkae a look at http://www.infrae.org/products/silva/ Regards, Mikhail From exarkun at divmod.com Sat Dec 4 22:33:35 2004 From: exarkun at divmod.com (Jp Calderone) Date: Sun, 05 Dec 2004 03:33:35 GMT Subject: Quixote+Nevow+LivePage In-Reply-To: <41B27B17.6010603@pythonapocrypha.com> Message-ID: <20041205033335.1203.1688030557.divmod.quotient.2234@ohm> On Sat, 04 Dec 2004 20:05:59 -0700, Dave Brueck wrote: >Jp Calderone wrote: > > On 3 Dec 2004 22:02:51 -0800, Mir Nazim wrote: > >>Q1) Is it possibe to use "Nevow + LivePage + Quixote" together in a > >>web app. Live Page is really important for me as I am not into content > >>oriented web apps. > >> > >>Q2) Is is nessary that LivePage only with Twisted or can work with any > >>web server like Apache. > >> > > > > > > I haven't used LivePage myself, but someone in the know tells me > > that LivePage requires an extra, non-HTTP connection to operate, so > > will pretty much only work with Twisted. > > Do you have a reference that says this - I'd like to know for sure. I did a > quick perusal of the code and thought that all the communication was via the > XmlHttpRequest functionality available in a lot of modern browsers (IE, Mozilla, > Safari). Just this: [11:11] exarkun: if you are on that list, will you reply and mention that livepage requires access to the raw socket apis and thus only works with twisted.web [11:13] raw as in "non-http" right, not "non-tcp"? [11:14] right Jp From skip at pobox.com Thu Dec 23 11:06:27 2004 From: skip at pobox.com (Skip Montanaro) Date: Thu, 23 Dec 2004 10:06:27 -0600 Subject: Improving Python (was: Lambda going out of fashion) In-Reply-To: References: Message-ID: <16842.60675.975998.973628@montanaro.dyndns.org> Keith> My personal gripe is this. I think the core language, as of 2.3 Keith> or 2.4 is very good, has more features than most people will ever Keith> use, and they (Guido, et al.) can stop tinkering with it now and Keith> concentrate more on the standard libraries. What keeps you from being part of the "et al"? This is open source, after all. Note that there's more to be done than simply writing code. Documentation always needs attention. Bug reports and patches always need to be verified and vetted. Even mundane stuff like managing mailing lists detracts from the time the most experienced people could spend writing code you might not be able to do. There's lots to do. Start here: http://www.python.org/dev/ Go anywhere. Skip From newgene at bigfoot.com Thu Dec 2 07:14:03 2004 From: newgene at bigfoot.com (Newgene) Date: 2 Dec 2004 04:14:03 -0800 Subject: "readline()" omitted '\r' in win32 for dos format text file Message-ID: <1101989643.429525.245770@z14g2000cwz.googlegroups.com> Hi, group, I have python2.3 installed on win2k. I noticed that when I open a dos format text file (eol is '\r\n'), readline() always returns a line ending with '\n' only, not '\r\n'. While I read the same file on unix, it returns a line ending with '\r\n' correctly. This makes me difficult to determine the format of a text file, dos or unix. Is this a bug or intended behavior? If not a bug, then how to determine the format of a text file? Thanks. C From http Tue Dec 28 12:22:06 2004 From: http (Paul Rubin) Date: 28 Dec 2004 09:22:06 -0800 Subject: Best GUI for small-scale accounting app? References: <1104029156.889650.15220@c13g2000cwb.googlegroups.com> <7xsm5qqs2k.fsf@ruckus.brouhaha.com> Message-ID: <7x652m8hj5.fsf@ruckus.brouhaha.com> Ed Leafe writes: > Obviously, something like that could also be added - do you > want to help develop Dabo? We're always looking for talented people > with good ideas! Only if you want to hire me. I mostly do volunteer development only on GPL projects. If I'm writing something that can become part of a commercial Microsoft product, I expect to be paid. But I don't mind posting snarky comments :). > Since Dabo is now a two-person effort, we develop as we need > things. I am working on the UI Designer, and needed to make menu I hope Dabo can read the xml files Glade generates, so you have a gui builder that's already deployed. From cookedm+news at physics.mcmaster.ca Wed Dec 29 00:07:45 2004 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 29 Dec 2004 00:07:45 -0500 Subject: getattr() woes References: <87hdm5hnet.fsf@thomas.local> Message-ID: aahz at pythoncraft.com (Aahz) writes: > In article <87hdm5hnet.fsf at thomas.local>, > Thomas Rast wrote: >> >>class dispatcher: >> # ... >> def __getattr__(self, attr): >> return getattr(self.socket, attr) >> >>>>> import asyncore >>>>> class Peer(asyncore.dispatcher): >>... def _get_foo(self): >>... # caused by a bug, several stack levels deeper >>... raise AttributeError('hidden!') >>... foo = property(_get_foo) >>... > > You're not supposed to use properties with classic classes. Even if dispatcher was a new-style class, you still get the same behaviour (or misbehaviour) -- Peer().foo still raises AttributeError with the wrong message. A simple workaround is to put a try ... except AttributeError block in his _get_foo(), which would re-raise with a different error that wouldn't be caught by getattr. You could even write a property replacement for that: >>> class HiddenAttributeError(Exception): ... pass >>> def robustprop(fget): ... def wrapped_fget(self): ... try: ... return fget(self) ... except AttributeError, e: ... raise HiddenAttributeError(*e.args) ... return property(fget=wrapped_fget) Ideally, I think the better way is if getattr, when raising AttributeError, somehow reused the old traceback (which would point out the original problem). I don't know how to do that, though. -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From gh at ghaering.de Tue Dec 21 08:50:10 2004 From: gh at ghaering.de (Gerhard Haering) Date: Tue, 21 Dec 2004 14:50:10 +0100 Subject: Problem with msvcrt60 vs. msvcr71 vs. strdup/free In-Reply-To: <20041221134806.GA24641@mylene.ghaering.de> References: <20041221134806.GA24641@mylene.ghaering.de> Message-ID: <20041221135010.GA24671@mylene.ghaering.de> Of not so much interest to most Pythoneers, but ... I cross-posted this to python-list to make people aware that thare are *real* problems with mingw + Python 2.4, not only theoretical ones. -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From grante at visi.com Fri Dec 17 13:49:23 2004 From: grante at visi.com (Grant Edwards) Date: 17 Dec 2004 18:49:23 GMT Subject: Create linear spaced vector? References: <6ca895b5.0412171039.7586077d@posting.google.com> Message-ID: <41c32a33$0$86405$a1866201@visi.com> On 2004-12-17, kjm wrote: > I am trying to write a generalized function that will create a > linearly spaced vector, given the start and end point, and the number > of entries wanted. >>> from scipy import * >>> mgrid[0.0:10.0:5j] array([ 0. , 2.5, 5. , 7.5, 10. ]) -- Grant Edwards grante Yow! Is this where people at are HOT and NICE and they visi.com give you TOAST for FREE?? From gry at ll.mit.edu Fri Dec 10 14:35:23 2004 From: gry at ll.mit.edu (george young) Date: Fri, 10 Dec 2004 14:35:23 -0500 Subject: style query: function attributes for return codes? References: <20041210104547.209a2b47.gry@ll.mit.edu> Message-ID: <20041210143523.3b06b769.gry@ll.mit.edu> On Fri, 10 Dec 2004 16:40:25 GMT Steven Bethard threw this fish to the penguins: > george young wrote: > > This is obviously just evil, since a misspelling in the string > > return is treacherous. I'm considering function attributes: > > > > def get_connection(): > > if tcp_conn(): > > if server_allows_conn(): > > return get_connection.GOOD > > else: > > return get_connection.BAD_AUTH > > else: > > return get_connection.NO_SERVER > > get_connection.GOOD = 1 > > get_connection.BAD_AUTH = 2 > > get_connection.NO_SERVER = 3 > > Although in most cases this is probably okay, you're not guaranteed that > the name of your function will stay the same, so there are some hazards > in this style: > > >>> def f(x): > ... return f.y * x > ... > >>> f.y = 100 > >>> f(2) > 200 > >>> g, f = f, None > >>> g(2) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 2, in f > AttributeError: 'NoneType' object has no attribute 'y' Yes, I was worried about this. > One option is to turn your function into a class: > > class get_connection(object): > GOOD = 1 > BAD_AUTH = 2 > NO_SERVER = 3 > def __new__(cls): > if tcp_conn(): > if server_allows_conn(): > return cls.GOOD > else: > return cls.BAD_AUTH > else: > return cls.NO_SERVER > > This is a little sneaky here -- because you only need shared state > between all instances of get_connection, you don't actually ever need to > create an instance. So I've overridden __new__ to return the result of > the function instead. This allows you to call the function just like > you would have before. I haven't tested the code above, but here's a > simpler example that works: > > >>> class look_ma_no_function(object): > ... X = 42 > ... def __new__(cls): > ... return cls.X > ... > >>> look_ma_no_function() > 42 Hmm, this is quite clever, and indeed does what I want. I hesitate to adopt it, though, because it *looks* sneaky. For readable and maintainable code, I think it may be a bit too hackish... The original impetus for my post was to find a clear, maintainable form. I wonder about returning an object that tests True if all is ok, and has boolean attributes to query if not True...: def get_connection(): class Ret: def __init__(self, badauth=False, noserver=False): self.badauth = badauth self.noserver = noserver def __nonzero__(self): return not(self.badauth and self.noserver) if tcp_conn(): if server_allows_conn(): return Ret() else: return Ret(badauth=True) else: return Ret(noserver=True) ret = get_connection() if not ret: if ret.badauth: ... still seems a bit cumbersome in definition, though the use is not bad... -- George -- "Are the gods not just?" "Oh no, child. What would become of us if they were?" (CSL) From skip at pobox.com Wed Dec 1 14:20:21 2004 From: skip at pobox.com (Skip Montanaro) Date: Wed, 1 Dec 2004 13:20:21 -0600 Subject: Python xmlrpc servers? In-Reply-To: <41AE357B.9010405@verizon.net> References: <16814.4018.68899.998083@montanaro.dyndns.org> <41AE357B.9010405@verizon.net> Message-ID: <16814.6517.65827.997749@montanaro.dyndns.org> ted> Would several web services on the same server listen on different ted> ports (8888, 8889, 8890...) or on the same port? Port numbers are never implicit. You need to provide a listen port each time you start the server. Skip From neil.benn at arcor.de Mon Dec 20 18:11:41 2004 From: neil.benn at arcor.de (Neil Benn) Date: Tue, 21 Dec 2004 00:11:41 +0100 Subject: gridbaglayout In-Reply-To: <1103565840.885381.54700@c13g2000cwb.googlegroups.com> References: <1103565840.885381.54700@c13g2000cwb.googlegroups.com> Message-ID: <41C75C2D.2030202@arcor.de> python473 at yahoo.com wrote: >Friends - I have tried to do abolute positioning using gridbaglayout, >but am having no success in jython. One book I have been referencing >says that it only works with JPanels. Could someone post a snippet of >code that works for a button? I am so close so just a hint would help. >Thanks as always. - John > > > Hello, Two points : Don't use GridBagLayout - it's horrible, you can nearly always use the other layouts (BorderLayour, Flow Layout, BoxLayout and GridLayout are teh most common ones to use) will get you far far further then GridBagLayout. GridBagLayout is from the old old days - a secret is, don't be afraid to nest layouts. Don't use absolute positioning - Absolute positioning is a real pain, isn't well supported and doesn't scale on different resolutions properly.. Sorry to send a message with two don'ts in it but it's an easy mistake to make at first (I did it too!) and you need to avoid doing this. If you want some good examples of Java coding then a good resource is Javaworld (http://www.javaworld.com). At first you need to get a feel for LayoutManagers but once you have you can knock stuff together pretty well. If you get stuck then use an IDE such as JBuilder at furst but don't rely on this too much as it can end up writing a lot of code you can;t really get stuck into to make your app more responsive/smoother coded. Finally if you are new then check out the Swing tutorial on the Java tutorials site by sun - that can give you some good starters. Cheers, Neil From mwm at mired.org Fri Dec 24 06:44:50 2004 From: mwm at mired.org (Mike Meyer) Date: Fri, 24 Dec 2004 05:44:50 -0600 Subject: list Integer indexing dies?? References: Message-ID: <86652rapjh.fsf@guru.mired.org> Ishwor writes: > On 23 Dec 2004 14:28:37 GMT, Antoon Pardon wrote: > My experience as a learner here is that there should be some > automagics & say like "okay you want to do indexing on integers ( > context dependent); i'll give you the index of 0th position in that > integer" ??? Python doesn't do things automagically. The rules for pythonic behavior include "Explicit is better than implicit" and "In the face of ambiguity, refuse the tempation to guess." Both of those are violated by automatic conversions and the like. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at holdenweb.com Wed Dec 22 15:21:37 2004 From: steve at holdenweb.com (Steve Holden) Date: Wed, 22 Dec 2004 15:21:37 -0500 Subject: extract news article from web In-Reply-To: <1103736135.209100.28900@z14g2000cwz.googlegroups.com> References: <1103736135.209100.28900@z14g2000cwz.googlegroups.com> Message-ID: Zhang Le wrote: > Hello, > I'm writing a little Tkinter application to retrieve news from > various news websites such as http://news.bbc.co.uk/, and display them > in a TK listbox. All I want are news title and url information. Since > each news site has a different layout, I think I need some > template-based techniques to build news extractors for each site, > ignoring information such as table, image, advertise, flash that I'm > not interested in. > > So far I have built a simple GUI using Tkinter, a link extractor > using HTMLlib to extract HREFs from web page. But I really have no idea > how to extract news from web site. Is anyone aware of general > techniques for extracting web news? Or can point me to some falimiar > projects. > I have seen some search engines doing this, for > example:http://news.ithaki.net/, but do not know the technique used. > Any tips? > > Thanks in advance, > > Zhang Le > Well, for Python-related news is suck stuff from O'Reilly's meerkat service using xmlrpc. Once upon a time I used to update www.holdenweb.com every four hours, but until my current hosting situation changes I can't be arsed. However, the code to extract the news is pretty simple. Here's the whole program, modulo newsreader wrapping. It would be shorter if I weren't stashing the extracted links it a relational database: #!/usr/bin/python # # mkcheck.py: Get a list of article categories from the O'Reilly Network # and update the appropriate section database # import xmlrpclib server = xmlrpclib.Server("http://www.oreillynet.com/meerkat/xml-rpc/server.php") from db import conn, pmark import mx.DateTime as dt curs = conn.cursor() pyitems = server.meerkat.getItems( {'search':'/[Pp]ython/','num_items':10,'descriptions':100}) sqlinsert = "INSERT INTO PyLink (pylWhen, pylURL, pylDescription) VALUES(%s, %s, %s)" % (pmark, pmark, pmark) for itm in pyitems: description = itm['description'] or itm['title'] if itm['link'] and not ("<" in description): curs.execute("""SELECT COUNT(*) FROM PyLink WHERE pylURL=%s""" % pmark, (itm['link'], )) newlink = curs.fetchone()[0] == 0 if newlink: print "Adding", itm['link'] curs.execute(sqlinsert, (dt.DateTimeFromTicks(int(dt.now())), itm['link'], description)) conn.commit() conn.close() Similar techniques can be used on many other sites, and you will find that (some) RSS feeds are a fruitful source of news. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From erik at heneryd.com Sun Dec 12 16:30:05 2004 From: erik at heneryd.com (Erik Heneryd) Date: Sun, 12 Dec 2004 22:30:05 +0100 Subject: MP3 - VBR - Frame length in time In-Reply-To: References: <41b75ca5$0$147$3a628fcd@reader2.nntp.hccnet.nl> <10rfffr3f83lu11@corp.supernews.com> <41bb4b53$0$779$3a628fcd@reader10.nntp.hccnet.nl> Message-ID: <41BCB85D.8020905@heneryd.com> Florian Schulze wrote: > On Sat, 11 Dec 2004 20:32:30 +0100, Ivo Woltring > wrote: > >> mmpython will help but not always. >> Lets put it this way. I will ALWAYS read through the whole file. In that >> order I don't mind evaluating each frame. The thing I don't seem to be >> able >> to find is the timelength-constants for frames for the different mp3 >> versions, bitrates and layers. Can anybody help me? > > > From http://www.oreilly.com/catalog/mp3/chapter/ch02.html#71109 > "In addition, the number of samples stored in an MP3 frame is constant, > at 1,152 samples per frame." > > > So you only need the samplerate for each frame to calculate the duration > of that frame. > > 1152 samples / 44100 samples per second ~ 0.026 seconds > > I don't exactly know whether you need to include mono/stereo into the > calculation, you would have to test that out. > > Regards, > Florian Schulze > This thread prompted me to dig up some old code I wrote in April 2003 parsing MPEG audio headers. Don't remember much about it except I had trouble finding reference material. This is what I used for frame duration: self.size = (144*self.bitrate) / self.samplerate + self.padding if self.bitrate: self.duration = self.size*8.0/self.bitrate else: self.duration = 0.0 That is, using bitrate instead of samplerate. More complicated, if you don't need the frame size. However, remember there might be metaframes, so the naive samplerate method might be off. I think most encoders set bitrate to 0 for metaframes, but you should check the Xing/Info tag to be sure... Ofcourse, the right way to do it is to parse and use the VBR tag... I'm attaching my old as-is MPEG code. Most of that project was lost in a disk crash and abandoned, so I don't know what state it's in, but... Erik -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: mpeg.py URL: From andrea.gavana at agip.it Mon Dec 13 07:58:21 2004 From: andrea.gavana at agip.it (andrea.gavana at agip.it) Date: Mon, 13 Dec 2004 13:58:21 +0100 Subject: Another RegEx Question... Message-ID: Hello NG, I'm quite new to Python and I don't know if this is a FAQ (I can't find it) or an obvious question. I'm using the RE module in python, and I would like to be able to contruct something like the Window$ "Find Files Or Folders" engine. As the Window$ users know, you can filter the file names using the character "*", as: myfilen* (Will find a file named myfilenames) *yf*nam* (Will find a file named myfilenames) I have tried something like: import re mystring = "*yf*nam*" mystring.replace("*","\w+") php = re.compile(mystring + "\w+") But it does not work... Is there a way to let the user of my application use the "*" character and to do a Regular Expression search inside a Python code? Thank you for every suggestion. Andrea. ------------------------------------------------------------------------------------------------------------------------------------------ Message for the recipient only, if received in error, please notify the sender and read http://www.eni.it/disclaimer/ From hancock at anansispaceworks.com Fri Dec 10 13:55:22 2004 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 10 Dec 2004 12:55:22 -0600 Subject: Possible to insert variables into regular expressions? In-Reply-To: <1102629075.164321.6600@f14g2000cwb.googlegroups.com> References: <1102626727.811590.135890@f14g2000cwb.googlegroups.com> <1102629075.164321.6600@f14g2000cwb.googlegroups.com> Message-ID: <200412101255.22097.hancock@anansispaceworks.com> On Thursday 09 December 2004 03:51 pm, Chris Lasher wrote: > Thanks for the reply, Steve! That ought to work quite nicely! For some > reason, I hadn't thought of using %-formatting. I probably should have, > but I'm still learning Python and re-learning programming in general. > This helps a lot, so thanks again. Remember, in Python, a regex (well, regex source) is just a string, so you can do any string manipulation you want to with it, and python has a lot of tools for doing that. One cool way to make regexes more readable, that i've seen proposed, is to break them into components like the following (please pardon my lack of regex skill, these may not actually work , but you get the idea): normalword = r'[A-Za-z][a-z]*' digit = r'\d' capletter = r'[A-Z]' codeblock = normalword + 4*digit + '-' + 3*digit + 2*capletter + '\s+' + normalword or somesuch (the 'r' BTW stands for 'raw', not 'regex', and while it's the most obvious use, there's nothing particularly special about r strings, except for not trying to process escape characters, thus avoiding the "pile of toothpicks" problem). And hey, you could probably use a regex to modify a regex, if you were really twisted. ;-) Sorry. I really shouldn't have said that. Somebody's going to do it now. :-P Cheers, Terry -- Terry Hancock ( hancock at anansispaceworks.com ) Anansi Spaceworks http://www.anansispaceworks.com From ishwor.gurung at gmail.com Sun Dec 26 19:03:27 2004 From: ishwor.gurung at gmail.com (Ishwor) Date: Mon, 27 Dec 2004 10:33:27 +1030 Subject: list addition methods compared. In-Reply-To: References: <34534aed0412252012638c85fd@mail.gmail.com> <34534aed04122615176056a0a9@mail.gmail.com> Message-ID: <34534aed0412261603279c1096@mail.gmail.com> On Sun, 26 Dec 2004 18:37:35 -0500, Terry Reedy wrote: > > "Ishwor" wrote in message > news:34534aed04122615176056a0a9 at mail.gmail.com... > > On Sun, 26 Dec 2004 04:57:17 -0500, Terry Reedy wrote: > >> > >> "Ishwor" wrote in message > >> news:34534aed0412252012638c85fd at mail.gmail.com... > >> > Hi all > >> > I have just wrote a small script to compare the speed of list addition > >> > methods. > >> > >> There are two meanings of 'list addition': > >> > >> li = li+[item] *copies* the list and adds item > >> > >> li += [item] is the same as li.extend([item]) which add item to the end > >> of > >> the list *without* copying. > >> > >> Of course, extending a list is faster than copying + one more. > >> > > > > I agree with you that list extending is faster way to add as compared > > to method 1. also that method 2 is mapped to 'extend()' anyway, > > As near as I could tell from what you posted (and I snipped), method 2 was > about the same as 1 and not mapped to extend(). ah.. well....what to tell?? i wanted the method 2 to be l2.extend() @#$@#$!!!!! hhah.. thanks for that anyway. > > but > > why is the method 3 ( l3.extend() ) in my example code talking only > > nearly 1% of time to complete as compared to method 1/2??? > > Because writing 1 pointer takes 1/100th as long as writing 100 pointers (in > the C code of CPython). You used lists long enough for the difference > between O(n) and O(n**2) behavior to show. theres the correct output AFAIK is - C:\Python24\file\PyFiles>python -O listadditioncompare.py @@@@@@@ Method 1 done in (average finish time(out of 3)) - 1.3589999676 Method 2 done in (average finish time(out of 3)) - 0.0213334560 Method 3 done in (average finish time(out of 3)) - 0.0256667137 @@@@@@@ C:\Python24\file\PyFiles>python -O listadditioncompare.py @@@@@@@ Method 1 done in (average finish time(out of 3)) - 1.3593332767 Method 2 done in (average finish time(out of 3)) - 0.0306665897 Method 3 done in (average finish time(out of 3)) - 0.0213334560 @@@@@@@ C:\Python24\file\PyFiles>python -O listadditioncompare.py @@@@@@@ Method 1 done in (average finish time(out of 3)) - 1.3593332767 Method 2 done in (average finish time(out of 3)) - 0.0203335285 Method 3 done in (average finish time(out of 3)) - 0.0203332901 @@@@@@@ so indeed method 2 (l2.extend() ) is the fastest ?? In 2/3 times, method 3 (l3 += [x] seems faster than method 1/2 in my P2.4GHZ machine with 512mb??? :-( Could u run the code in your machine and perhaps and let me know what the average speed is?? The code is - #compare the speeds of 3 different type of list element addition import time def method(TYPE): if TYPE == 1: l1 = []; finish = 0; start = 0; start = time.time(); for y in range(0,3): for x in range(0,10000): l1 = l1 + [x];# type 1 l1 = []; finish += time.time(); averageFinish = finish/3; #m = float(finish-start); print "Method 1 done in (average finish time(out of 3)) - %.10f" %(averageFinish-start); if TYPE == 2: l2 = []; finish = 0; start = 0; start = time.time(); for y in range(0,3): for x in range(0,10000): l2.extend([x]);# type 2 l2 = []; finish += time.time(); averageFinish = finish/3; #m = float(finish-start); print "Method 2 done in (average finish time(out of 3)) - %.10f" %(averageFinish-start); if TYPE == 3: l3 = []; finish = 0; start = 0; start = time.time(); for y in range(0,3): for x in range(0,10000): l3 += [x];# type 3 l3 = []; finish += time.time(); averageFinish = finish/3; #m = float(finish-start); print "Method 3 done in (average finish time(out of 3)) - %.10f" %(averageFinish-start); print "@@@@@@@"; method(1); method(2); method(3); print "@@@@@@@"; [snip] Thanks. ;-) -- cheers, Ishwor Gurung From jstroud at mbi.ucla.edu Thu Dec 16 15:53:32 2004 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 16 Dec 2004 12:53:32 -0800 Subject: Why no list heritable type? Message-ID: <200412161253.32160.jstroud@mbi.ucla.edu> The thread "why not arrays" got me thinking. I would really like to inherit from a list so that I can add methods based on its contents, say if I filled it with a type of object and wanted to iterate over all objects. I have built a wrapper around a list like this for general use: class list_of_objects: def __init__(self): self.data = [] def __len__(self): return len(self.data) etc ... Then it can be heritable and I can add or override methods. Why aren't built in lists and dictionaries real heritable types that can save this kind of patchwork? Is there a pythonic reason I am missing here? James -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics 611 Charles E. Young Dr. S. MBI 205, UCLA 951570 Los Angeles CA 90095-1570 http://www.jamesstroud.com/ From itsme at yahoo.com Sat Dec 11 13:22:30 2004 From: itsme at yahoo.com (It's me) Date: Sat, 11 Dec 2004 18:22:30 GMT Subject: New versions breaking extensions, etc. References: <41BABC12.6080808@v.loewis.de> <1102771156.926467.134390@f14g2000cwb.googlegroups.com> Message-ID: On the other hand, it can be annoying. I can't use Python 2.4 right now because NumPy won't run. So, I need to wait for NumPy to get updated. Of course, one would say: but NumPy is open source, go build it yourself. My answer is simple: If there are more then 24 hours to a day, I definitely would... -- It's me "John Machin" wrote in message news:1102771156.926467.134390 at f14g2000cwb.googlegroups.com... Jive wrote: > "Martin v. L?wis" wrote in message > news:41BABC12.6080808 at v.loewis.de... > > OTOH, people who only have VC6 just need to buy VS.NET 2003, > > which is still available. > > I don't even know how to do that! :-) What's the difference between VC++ > .net Standard and Visual Studio .net Pro? (Besides $370?) Is the former > C++ only, but with the IDE, and the later the whole shebang with SourceSafe, > VBASIC, and all that? > > OH NO! I've gone seriously off-topic. Please don't call the Spanish > Inquisiton. Allow me to re-phrase the question: What do I need to build > (on-topic) Python extensions? Short answer to Jive's question: (1) free non-MS C compiler (either MinGW or Borland) (2) inner calm. I really can't understand what all the screaming and yelling is about. Windows Python is built using an MS compiler. Those extension developers who can't/won't buy the MS compiler use either the free MinGW compiler or the free Borland 5.5 compiler (or both!). Yes, you have to be careful about mixing the runtimes. An extension that tries to use a FILE * that was created by Python will crash. Using free() on a pointer that was malloc()ed by the other party isn't a bright idea either. There are adequate solutions to these problems, involving Python-supplied higher-level functions instead of C runtime functions. Otherwise, not a problem. Distutils has made the process of using MinGW and bcpp a snap. The documentation is adequate. When a new version of Python comes out, one rebuilds and tests one's extensions. So ... now there are THREE compilers that can be used instead of the one that Python's built with; what's the big deal? From steven.bethard at gmail.com Fri Dec 31 13:19:59 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 31 Dec 2004 18:19:59 GMT Subject: Securing a future for anonymous functions in Python In-Reply-To: <1gpo8yu.1mwlfwvi30nafN%aleaxit@yahoo.com> References: <41D40E71.5030709@iinet.net.au> <1104444094.091555.278650@z14g2000cwz.googlegroups.com> <1gpo8yu.1mwlfwvi30nafN%aleaxit@yahoo.com> Message-ID: <9LgBd.667548$D%.282315@attbi_s51> Alex Martelli wrote: > Paul L. Du Bois wrote: >>def fn(gen): >> """Turns a generator expression into a callable.""" >> def anonymous(*args): return gen.next() >> return anonymous >> >>def args(): >> """Works with fn(); yields args passed to anonymous().""" >> while True: yield sys._getframe(2).f_locals['args'] >> >>args = args() >> >>foo = fn(a + b * c for (a,b,c) in args) >>assert foo(3,4,5) == 3+4*5 >>assert foo(4,5,6) == 4+5*6 > > > Paul, you really SHOULD have posted this BEFORE I had to send in the > files for the 2nd ed's Coobook... this gets my vote for the most > delightful abuse of sys._getframe even (and I've seen quite a few;-). So, I couldn't figure out why this worked until I started to write an email to ask. Once I understood it, I figured it wouldn't hurt to send my thoughts out anyway to (1) verify that I understand it right, and (2) help anyone else who was trying to figure this out. As I understand it sys._getframe(2).f_locals should get the names local to the stack frame two above the current one. So, in the context of: fn(... for ... in args) sys._getframe(2).f_locals should be looking at the names local to the 'anonymous' function in the 'fn' function, because one stack frame up from the 'args' function is the generator's 'next' function, and two stack frames up is the 'anonymous' function. That means that: sys._getframe(2).f_locals['args'] gets whatever object has been bound to 'args' in: def anonymous(*args): So then in: foo = fn(a + b * c for (a,b,c) in args) foo(3,4,5) foo(4,5,6) sys._getframe(2).f_locals['args'] will get (3, 4, 5) in the first foo call, (4, 5, 6) in the second foo call, etc. So basically the way a call like foo(3, 4, 5) works is: (1) foo(3, 4, 5) calls gen.next() where gen is the generator expression (2) gen.next() calls args.next() (3) args.next() returns the (3, 4, 5) argument tuple of foo by looking up the stack frames (4) gen.next() binds (3, 4, 5) to the names a, b, c respectively (5) gen.next() returns the value of "a + b * c" for these bindings (6) foo(3, 4, 5) returns the same value (as gen.next() did) Does that seem about right? Steve P.S. That's so *evilly* cool! From exarkun at divmod.com Sat Dec 18 13:55:56 2004 From: exarkun at divmod.com (Jp Calderone) Date: Sat, 18 Dec 2004 18:55:56 GMT Subject: A rational proposal In-Reply-To: <86y8fvqwl7.fsf@guru.mired.org> Message-ID: <20041218185556.1029.415545259.divmod.quotient.12903@ohm> On Sat, 18 Dec 2004 12:40:04 -0600, Mike Meyer wrote: >"John Roth" writes: > > > "Mike Meyer" wrote in message > > news:864qik472n.fsf at guru.mired.org... > >> PEP: XXX > >> Title: A rational number module for Python > >> The ``Rational`` class shall define all the standard mathematical > >> operations: addition, subtraction, multiplication, division, modulo > >> and power. It will also provide the methods: > >> > >> - max(*args): return the largest of a list of numbers and self. > >> - min(*args): return the smallest of a list of numbers and self. > > > > max() and min() are already part of the standard library. > > Providing them as instance methods is quite irregular. > > They don't handle decimals or rationals. This is following the lead of > the decimal package. They do handle decimals. They handle any object which define __cmp__, or the appropriate rich comparison methods. The Decimal type seems to define min and max so that NaNs can be treated specially, but I glean this understanding from only a moment of reading decimal.py. Perhaps someone more well informed can declare definitively the purpose of these methods. Also, note that the signatures are not Decimal.max(*args) and Decimal.min(*args), but rather each takes a single decimal argument in addition to self and an optional context argument. So if the goal is symmetry with the Decimal type, then Rational.max() and Rational.min() should take only one argument. Jp From steve at holdenweb.com Tue Dec 14 08:14:52 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 14 Dec 2004 08:14:52 -0500 Subject: while 1 vs while True In-Reply-To: References: <1102903165.589419.323000@z14g2000cwz.googlegroups.com> Message-ID: Raymond Hettinger wrote: >>Dan Bishop wrote: >> >>>>Out of pure curiousity, >>>>Why wasn't 'While True' optimized also? >>> >>> >>>Probably has something to do with "True" and "False" not being >>>constants. > > > [Nick Coghlan] > >>Yup. Even 'None' only just became a constant in 2.4. >> >>I don't know if 'True' and 'False' are in line for similar treatment (there > > are > >>obvious backwards compatibility issues in doing so). > > > It is unlike to before Py3.0. Making them constants would break the reams of > compatability code: True, False = (1==1), (1!=1). > It was unfortunate that so many people chose to use that for compatibility, when if they'd used the same code that the win32all extensions did they could have retained backward compatibility even across a change to constants: try: True except AttributeError: True, False = (1==1), (1!=1) regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From vincent at visualtrans.de Thu Dec 30 05:47:30 2004 From: vincent at visualtrans.de (vincent wehren) Date: Thu, 30 Dec 2004 11:47:30 +0100 Subject: Unicode entries on sys.path In-Reply-To: References: <41CB0D7A.3080107@v.loewis.de> <7jn3ag8b.fsf@python.net> <41d03bc3$0$1677$9b622d9e@news.freenet.de> Message-ID: Thomas Heller wrote: > "Martin v. L?wis" writes: > > >>Thomas Heller wrote: >> >>>How should these patches be approached? >> >>Please have a look as to how posixmodule.c and fileobject.c deal with >>this issue. >> >> >>>On windows, it would probably >>>be easiest to use the MS generic text routines: _tcslen instead of >>>strlen, for example, and to rely on the _UNICODE preprocessor symbol to >>>map this function to strlen or wcslen. >> >>No. This fails for two reasons: >>1. We don't compile Python with _UNICODE, and never will do so. This >> macro is only a mechanism to simplify porting code from ANSI APIs >> to Unicode APIs, so you don't have to reformulate all the API calls. >> For new code, it is better to use the Unicode APIs directly if you >> plan to use them. >>2. On Win9x, the Unicode APIs don't work (*). So you need to chose at >> run-time whether you want to use wide or narrow API. Unless >> a) we ship two binaries in the future, one for W9x, one for NT+ >> (I hope this won't happen), or >> b) we drop support for W9x. I'm in favour of doing so sooner or >> later, but perhaps not for Python 2.5. > > > I wasn't asking about the *W functions, I'm asking about string/unicode > handling in Python source files. Looking into Python/import.c, wouldn't > it be required to change the signature of a lot of functions to receive > PyObject* arguments, instead of char* ? > For example, find_module should change from > static struct filedescr *find_module(char *, char *, PyObject *, > char *, size_t, FILE **, PyObject **); > > to > > static struct filedescr *find_module(char *, char *, PyObject *, > PyObject **, FILE **, PyObject **); > > where the fourth argument would now be either a PyString or PyUnicode > object pointer? > > >>(*) Can somebody please report whether the *W file APIs fail on W9x >>because the entry points are not there (so you can't even run the >>binary), or because they fail with an error when called? > > > I always thought that the *W apis would not be there in win98, but it > seems that is wrong. Fortunately, how could Python, which links to the > FindFirstFileW exported function for example, run on win98 otherwise... Normally I would have thought this would require using the Microsoft Layer for Unicode (unicows.dll). According to MSDN 9x already does have a handful of unicode APIs. FindFirstFile does not seem to be one of them - unless the list on htpp://msdn.microsoft.com/library/default.asp?url=/library/en-us/mslu/winprog/other_existing_unicode_support.asp) is bogus (?). -- Vincent Wehren > > Thomas From gh at ghaering.de Thu Dec 16 09:16:36 2004 From: gh at ghaering.de (Gerhard Haering) Date: Thu, 16 Dec 2004 15:16:36 +0100 Subject: why not arrays? In-Reply-To: <1103205078.423240.297790@f14g2000cwb.googlegroups.com> References: <1103205078.423240.297790@f14g2000cwb.googlegroups.com> Message-ID: <20041216141636.GA6229@mylene.ghaering.de> On Thu, Dec 16, 2004 at 05:51:18AM -0800, Rahul wrote: > Hi. > I just wanted to know why arrays have not been included as a builtin > datatype like lists or dictionaries? The numpy extension shows that it > can be implemented. then why not include arrays in core python? Arrays are included in a module in the standard module called 'array'. -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From ialbert at mailblocks.com Fri Dec 3 08:58:48 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Fri, 03 Dec 2004 08:58:48 -0500 Subject: pre-PEP generic objects In-Reply-To: References: Message-ID: Steven Bethard wrote: > The question is not how easy it is to write, > but how many times it's going to get written. but with that logic we could create a standard "looping" construct called loop(x) that would stand in for for i in range(x): or a file_reader('whatever') generator that would be a shortcut for: for line in file('whatever'): line = line.strip() elems = line.split() > and more than one of them had rewritten the class a few times. Two observations regarding that: 1. Probably not entirely true. They might have used something like a Bunch but it is a bit too optimistic to believe that they could have directly used your Bunch. My Bunches turn out to be just a ever so slightly different. Either have an update operation or an equality, or can be hashed etc. So in the end it might save a lot less work. 2. Even if it was, no big deal. It takes too little time to do it. On the other hand, it would be nice to have a module that implements various design patterns. The Bunch, the Borg, the Null, the Proxy all nicely documented tucked away in their separate module. That would feel a lot less like littering the standard name space with an class that just "seems" to be useful. just an opinion. Istvan From fuzzyman at gmail.com Mon Dec 13 08:07:59 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: 13 Dec 2004 05:07:59 -0800 Subject: Tibia 0.1 DOM-based website editor In-Reply-To: References: <3A81C87DC164034AA4E2DDFE11D258E32453AA@exchange.hqamor.amorhq.net> Message-ID: <1102943279.597168.211490@c13g2000cwb.googlegroups.com> The example that Robert posted is protected with http BASIC authentication (judging by the popup anyway). Part of the Jalopy toolkit is `Login Tools` that implements a CGI Login framework that can be plugged into any CGI with the addition of as little as 2 lines of code. It includes optional user sign up, user accoutn editing and account administration. This is due for it's first public release into the wild any day now. (All done, docs done, just needs me to finish the Jalopy docs). You can see it in action at the Jalopy demo. (Which doesn't really address your question to RObert I guess - sorry - didn't think it was too OT) Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From ncoghlan at iinet.net.au Sat Dec 18 17:49:03 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Sun, 19 Dec 2004 08:49:03 +1000 Subject: A beginner's problem... In-Reply-To: References: <86y8fv2qtr.fsf@guru.mired.org> Message-ID: <41C4B3DF.1030600@iinet.net.au> Amir Dekel wrote: > Mike Meyer wrote: > >> >> Doing a second import will find the module in sys.modules and not >> bother looking in the file system. The solution is to reload(module) >> instead of import module. >> >> > What if I import using "from module import class"? It seems to me that I > can't use reload then, or I just couldn't find the right syntax... Correct. Using a non-from import is actually easier when experimenting, since reload is easier to use. If you have used a from-style import, you have to do this to force a reload of the relevant class: Py> from module import x Py> # Do stuff Py> import module Py> reload(module) Py> from module import x Py> # We now have the updated version of x Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steve at holdenweb.com Tue Dec 14 11:00:20 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 14 Dec 2004 11:00:20 -0500 Subject: lies about OOP In-Reply-To: References: <1102995205.949964.76020@c13g2000cwb.googlegroups.com> Message-ID: <29Evd.32591$Jk5.26287@lakeread01> Paul McGuire wrote: > "Jive" wrote in message > news:Revvd.807843$SM5.50718 at news.easynews.com... > > > >>But by '86, the Joy of OOP was widely known. >> > > > "Widely known"? Errr? In 1986, "object-oriented" programming was barely > marketing-speak. Computing hardware in the mid-80's just wasn't up to the > task of dealing with OO memory and "messaging" overhead. Apple Macs were > still coding in C and Forth. Borland didn't ship Turbo-Pascal with > Object-Oriented programming until 1989, and Turbo-C++ shipped in 1991. > Smalltalk had been around for 10 years by 1986, but it was still a > curiosity, hardly "widely known." It wasn't until the publication of David > Taylor's "Object Technology: A Manager's Guide" in 1990 that OOP began to be > legitimized to many management decision makers, that it was more than just > "fairy dust" (as Bill Gates had characterized it in an attempt to discredit > Borland's forays into the field). > Well, that's not true either, and the fact that Bill Gates was denigrating it implies that he at least knew about it, even if he chose not to adopt it (then: of course nowadays Microsoft call almost all their technologies "object oriented"; sometimes this description is as accurate as when Gates speaks about "our open Windows environment"). > I would pick the publication of "Design Patterns" in 1995 by the Gang of > Four (Gamma, Helm, Johnson, and Vlissides), to be the herald of when "the > Joy of OOP" would be "widely known." DP formalized a taxonomy for many of > the heuristics that had evolved only intuitively up until then. Its > emergence reflects a general maturation of concept and practice, sufficient > to say that the Joy of OOP could be said to be "widely known." > We could all make our own choices, but anyone who's been programming *seriously* since the 60s will likely remember Simula as the birth of many oft he ideas later picked up by Alan Kay and promoted by the Xerox PARC SmallTalk group. I visited that group in 1981 (after Kay left, unfortunately, and then being headed by Adele Goldberg, who is now coincidentally promoting the delights of Python at conferences like OSCON), and object-oriented programming was certainly something that was being taken pretty seriously in the academic world as a potential solution to some serious PLIT engineering problems. The fact that it took the technology a relatively long time to appear "in the wild", so to speak, is simply the natural maturation of any new technology. Given that UNIX was developed in the early 1970s I'd say it took UNIX 20 years to start becoming mainstream. But a lot of people knew about it before it *became* mainstream, especially those who had to place their technology bets early. The same is true of object-oriented concepts. I guess this is just to say that I'd dispute your contention that SmallTalk was a curiosity - unless you define anything of interest mostly to the academic world as a curiosity, in which case there's no way to overcome your objection. It was the first major implementation of an entire system based exclusively on OO programming concepts and, while far from ideal, was a seminal precursor to today's object-oriented systems. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From hpk at trillke.net Fri Dec 10 14:57:00 2004 From: hpk at trillke.net (holger krekel) Date: Fri, 10 Dec 2004 20:57:00 +0100 Subject: style query: function attributes for return codes? In-Reply-To: <31ucgiF3ee1vtU1@individual.net> References: <20041210104547.209a2b47.gry@ll.mit.edu> <31ucgiF3ee1vtU1@individual.net> Message-ID: <20041210195700.GD23693@solar.trillke.net> [Reinhold Birkenfeld Fri, Dec 10, 2004 at 08:42:10PM +0100] > holger krekel wrote: > > class Connection(object): > > def __init__(self, **kw): > > for name in kw: > > assert name in ('good', 'badauth', 'noserver'), name > > setattr(self, name, kw[name]) > > > > def get_connection(): > > if tcp_conn(): > > if server_allows_conn(): > > return Connection(good=True) > > else: > > return Connection(badauth=True) > > else: > > return Connection(noserver=True) > > That's evil, because "if conn.good" raises an AttributeError instead of > evaluating to False if the connection is not good. You would have to > inizialize all three attributes in every construction of a Connection > object. Ups, you are right of course. I somehow managed to delete the line ... class Connection(object): good = badauth = noserver = False thanks for pointing it out. holger From fredrik at pythonware.com Wed Dec 15 02:29:12 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Dec 2004 08:29:12 +0100 Subject: effbot ElementTree question References: <1103086772.333399.61900@c13g2000cwb.googlegroups.com> Message-ID: wrote: > Is anyone here familiar with ElementTree by effbot? > > With hello how is "hello" stored in the > element tree? Which node is it under? Similarly, with: > foo blah bar, how is bar stored? Which node is > it in? reposting the reply I just posted to the discussion board where you asked the same question: in the body case, the "hello" text ends up in the 'text' attribute of the "body" node (in HTML/CSS terminology, this is known as an "anonymous block"). in the other case, the trailing text is stored in the 'tail' attribute of the preceeding element ("a" in this case); see: http://effbot.org/zone/element-infoset.htm#mixed-content for details on how ElementTree deals with mixed content. From fredrik at pythonware.com Thu Dec 23 05:56:49 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 23 Dec 2004 11:56:49 +0100 Subject: regular expression: perl ==> python References: <1103692329.420064.257540@f14g2000cwb.googlegroups.com> Message-ID: Nick Craig-Wood wrote: > I take your point. However I don't find the below very readable - > making 5 small regexps into 1 big one, plus a game of count the > brackets doesn't strike me as a huge win... if you're doing that a lot, you might wish to create a helper function. the undocumented sre.Scanner provides a ready-made mechanism for this kind of RE matching; see http://aspn.activestate.com/ASPN/Mail/Message/python-dev/1614344 for some discussion. here's (a slight variation of) the code example they're talking about: def s_ident(scanner, token): return token def s_operator(scanner, token): return "op%s" % token def s_float(scanner, token): return float(token) def s_int(scanner, token): return int(token) scanner = sre.Scanner([ (r"[a-zA-Z_]\w*", s_ident), (r"\d+\.\d*", s_float), (r"\d+", s_int), (r"=|\+|-|\*|/", s_operator), (r"\s+", None), ]) >>> print scanner.scan("sum = 3*foo + 312.50 + bar") (['sum', 'op=', 3, 'op*', 'foo', 'op+', 312.5, 'op+', 'bar'], '') From Scott.Daniels at Acm.Org Fri Dec 3 12:20:34 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 03 Dec 2004 09:20:34 -0800 Subject: Module list generation In-Reply-To: References: Message-ID: <41b0b2e2$1@nntp0.pdx.net> Doug Kearns wrote: > Is this the best/simplest way to generate a module list? > > python -c 'from pydoc import help; help("modules")' > > Thanks, > Doug I am not sure if this is what you want, but how about: For python 2.4, try: python -c "import sys; print sorted(sys.modules)" For earlier pythons, use: python -c "import sys; nms = sys.modules.keys(); nms.sort(); print nms" or: python -c "import sys; print sys.modules.keys()" if you don't care about order. --Scott David Daniels Scott.Daniels at Acm.Org From fredrik at pythonware.com Sun Dec 12 04:23:28 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 12 Dec 2004 10:23:28 +0100 Subject: uptime for Win XP? References: <10rmr8ksbhlq341@corp.supernews.com> Message-ID: Esmail Bonakdarian wrote: > Is there a way to display how long a Win XP system has been up? > Somewhat analogous to the *nix uptime command. ugly, somewhat slow, and possibly locale dependent: import os, re def uptime(): return re.search( "System Up Time:\s*(.+)", os.popen("systeminfo").read() ).group(1) print uptime() From steven.bethard at gmail.com Fri Dec 17 17:04:03 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 17 Dec 2004 22:04:03 GMT Subject: better lambda support in the future? In-Reply-To: References: Message-ID: Jason Zheng wrote: > The true beauty of lambda function is not the convenience of creating > functions without naming them. Lambda constructs truly enables > higher-order function. For example, I can create a function A that > returns a function B that does something interesting according to the > arguments that I pass to function A. Like this? def A(*args, **kwds): def B(): print args, kwds return B But you don't need lambdas to do this. In fact, even in your email, you'll note that you referred to your two functions by name. If you're naming functions, why not use a def statement? Steve From andre1 at yandex.ru Sun Dec 12 06:02:43 2004 From: andre1 at yandex.ru (Andrey Ivanov) Date: Sun, 12 Dec 2004 14:02:43 +0300 Subject: uptime for Win XP? Message-ID: <1588331931.20041212140243@yandex.ru> >> I believe that "uptime" works from the console, but don't have a machine >> to check it with... > Doesn't work for me, but if you have win32all installed, you can get it > from Python: > >>> import win32api > >>> print "Uptime:", win32api.GetTickCount(), "Milliseconds" > Uptime: 148699875 Milliseconds MSDN recommends another approach. They say, that you should retrieve the value of "System Up Time" counter from HKEY_PERFORMANCE_DATA. In theory, you can do it without win32all, by using _winreg module. All you need is to know a counter index, which can be fetched from registry. On my system "System Up Time" counter has index "674", so Python code should look like this: >>> import _winreg >>> value, type_code = _winreg.QueryValueEx(_winreg.HKEY_PERFORMANCE_DATA, "674") >>> print "Uptime: %s miliseconds" % (value,) But in current implementation of _winreg it doesn't work. I've checked the sources and found that current implementation doesn't handle ERROR_MORE_DATA, which prevents it from retrieving any performance counters. I'm thinking of bug/patch submission. From FBatista at uniFON.com.ar Mon Dec 27 08:26:33 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Mon, 27 Dec 2004 10:26:33 -0300 Subject: A Revised Rational Proposal Message-ID: [Dan Bishop] #- * Binary operators with one Rational operand and one float or Decimal #- operand will not raise a TypeError, but return a float or Decimal. I think this is a mistake. Rational should never interact with float. #- * Expressions of the form Decimal op Rational do not work. This is a #- bug in the decimal module. Can you tell me where? (or submit a bug in SF). Thanks. #- * The constructor only accepts ints and longs. Conversions #- from float #- or Decimal to Rational can be made with the static methods: #- - fromExactFloat: exact conversion from float to Rational What ExactFloat means to you? For example, what should Rational.fromExactFloat(1.1) should return? And we starting here the same long discussion that lead decimal to not be created from float because it never would be clear what it will do. #- - fromExactDecimal: exact conversion from Decimal to Rational Rational already is created from strings like "2.33", so use str() over the Decimal, not a special method: >>> import decimal >>> decimal.Decimal("3.44") Decimal("3.44") >>> str(decimal.Decimal("3.44")) '3.44' >>> import rational >>> rational.Rational(str(decimal.Decimal("3.44"))) Rational("344 / 100") >>> . Facundo Bit?cora De Vuelo: http://www.taniquetil.com.ar/plog PyAr - Python Argentina: http://pyar.decode.com.ar/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informaci?n contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informaci?n confidencial o propietaria, cuya divulgaci?n es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est? autorizado a divulgar, copiar, distribuir o retener informaci?n (o parte de ella) contenida en este mensaje. Por favor notif?quenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magn?tico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telef?nica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electr?nicos pueden ser alterados, motivo por el cual Telef?nica Comunicaciones Personales S.A. no aceptar? ninguna obligaci?n cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet_spam at janc.invalid Mon Dec 27 17:01:39 2004 From: usenet_spam at janc.invalid (JanC) Date: Mon, 27 Dec 2004 22:01:39 GMT Subject: Best GUI for small-scale accounting app? References: <1104029156.889650.15220@c13g2000cwb.googlegroups.com> Message-ID: McBooCzech schreef: > IMHO this is the worst think for the Python community: you can find > one Python only with an excellent support. Great!!!! But on the other > hand it is possible to find plenty of GUI tools and for the beginner > (and may be not just for the beginner) it is so hard to choose the > "proper" one!!!!! The field of GUI tools is so fragmented!!!! I think the field of GUI frameworks / tools for Python is fragmented because it's fragmented outside of Python too... -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From exogen at gmail.com Mon Dec 6 11:28:56 2004 From: exogen at gmail.com (Brian Beck) Date: Mon, 06 Dec 2004 11:28:56 -0500 Subject: The python2.4 IDLE can't be lanuched. In-Reply-To: References: Message-ID: Brian Beck wrote: > I have the exact same problem. The IDLE window just never opens, and > checking the process list shows that is was never even launched. So I > can't make much use of Python 2.4 since I use IDLE as my IDE... I forgot to note that I am also using Windows XP SP2 and this happens on two completely different machines of mine. -- Brian Beck Adventurer of the First Order From mwm at mired.org Wed Dec 8 22:41:06 2004 From: mwm at mired.org (Mike Meyer) Date: Wed, 08 Dec 2004 21:41:06 -0600 Subject: creating generators from function References: <_4Atd.207303$HA.197084@attbi_s01> <4e4a11f804120806185e65f357@mail.gmail.com> Message-ID: Simon Wittber writes: >> A function containing an infinite loop will never return, so it is bugged >> and useless unless it does has an external effect with something like >> 'print xxx' within the loop. > > I thought the idiom: > > while True: > #code which iterates my simulation > if condition: break > > wat quite normal. This is the style loop I am using. I think it's a bit abnormal, because you have to scan the loop body for breaks. I tend to write: condition = True while not condition: #code which iterates my simulation But that's just me. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From steve at holdenweb.com Tue Dec 28 08:10:33 2004 From: steve at holdenweb.com (Steve Holden) Date: Tue, 28 Dec 2004 08:10:33 -0500 Subject: Repainting In-Reply-To: <20041228031140.21753.00002001@mb-m12.aol.com> References: <20041228031140.21753.00002001@mb-m12.aol.com> Message-ID: LutherRevisited wrote: > I have an application that uses a WxListCtrl to hold data that is updated > extremely fast. When I run my application the listctrl updates so fast that it > practically disappears. Is there a way I can have it update with the user > seeing it update rapidly without the dissapearing? Right now I have used the > freeze and thaw methods to get rid of that disappearing listctrl problem, only > now you have to wait for it to run it's course to see the output. It really > isn't critical, I just think it would be a cool visual if the user could see it > rapidly updating, I'm beginning to think that because of how rapidly it updates > that isn't possible, but if it is I appreciate any help. And you guys would be > so proud of me, I actually downloaded the Wx docs and found freeze and thaw all > on my own under wxwindows members....lol. That's a quick note out to all that > have been patient with me while helping me learn wxpython. Well, the logical approach would seem to be to freeze, add a hundred items, thaw, freeze, add a hundred items, thaw ... [rinse and repeat]. Basically, control the repainting so it only occurs (relatively) infrequently. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From steve at holdenweb.com Mon Dec 27 08:50:11 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 27 Dec 2004 08:50:11 -0500 Subject: Jython & IronPython Under Active Development? In-Reply-To: References: <1104033303.754319.269650@c13g2000cwb.googlegroups.com> <1104039182.718016.78800@f14g2000cwb.googlegroups.com> <7q03a2-uev.ln1@lairds.us> Message-ID: HackingYodel wrote: > Cameron Laird wrote: > >> In article , Robert Kern >> wrote: >> . >> . >> . >> >>> It should be noted that Jim Hugunin no longer works on Jython >>> although he did start the project (possibly with others, I'm not sure). >> >> >> . >> . >> . >> Mostly he started it with others discouraging him, arguing, >> "*That*'s one project that'll never fly." > > > Short story at http://hugunin.net/story_of_jython.html from Jim himself. > :) Just a little further background. The Python Software Foundation recently awarded a grant to help to bring Jython into line with the current CPython release. Jim Hugunin now works for Microsoft, and hopes to promote Python as a full member of the .NET environment. He'll be speaking at PyCon DC 2005 in March this year, and I hope that his talk will include some details of his experiences at Microsoft (though that's entirely up to Jim). regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From doran_dermot at emc.com Tue Dec 7 04:32:10 2004 From: doran_dermot at emc.com (Dermot Doran) Date: Tue, 7 Dec 2004 10:32:10 +0100 Subject: [pywin32] windows shares, was os.listdir("\\\\delta\\public") In-Reply-To: <9A28C052FF32734DACB0A288A35339910358FE@vogbs009.gb.vo.local> References: <9A28C052FF32734DACB0A288A35339910358FE@vogbs009.gb.vo.local> Message-ID: Hi Tim, Something like this is what I think you are looking for: from win32com.client import Dispatch theNetwork = Dispatch("WScript.Network") mappedNetDrives = theNetwork.EnumNetworkDrives for netDrive in mappedNetDrives(): print netDrive Should give you some ideas anyway. Cheers!! On 6 Dec 2004, at 11:04, Tim Golden wrote: > [Egor Bolonev] > | how to get list of shares using pywin32? > > You want to be looking at the NetShareEnum function > in the win32net module. > > TJG > > _______________________________________________________________________ > _ > This e-mail has been scanned for all viruses by Star. The > service is powered by MessageLabs. For more information on a proactive > anti-virus service working around the clock, around the globe, visit: > http://www.star.net.uk > _______________________________________________________________________ > _ > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/enriched Size: 1048 bytes Desc: not available URL: From apardon at forel.vub.ac.be Thu Dec 16 03:36:47 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 16 Dec 2004 08:36:47 GMT Subject: Why are tuples immutable? References: <41BE1644.8050906@freemail.gr> <10s1si0fb0l4pae@corp.supernews.com> Message-ID: Op 2004-12-16, Jeff Shannon schreef : > Antoon Pardon wrote: > >>Demanding that users of dictioanaries somehow turn their mutable objects >>into tuples when used as a key and back again when you retrieve the keys >>and need the object [...] >> > > But, you generally don't "retrieve" _keys_ from dicts. You *use* keys > to retrieve *values* from a dict. The only way to get a dict to give > you a key is by using the keys() method (or items() method) to give you > *all* of the keys. > > You say that mutating the keys inside of a dict is bad, and yet you want > keys to be mutable. 1) I don't want them to be mutable. If there was a way to mark individual objects as immutable, I wouldn't mind having all the keys in a dictionary so marked. But I do have objects that turn out to be mutable which are IMO usefull as keys in a dictionary, although I don't want to mutate the keys in dictionaries. > This seems to be an internally inconsistent position, That is because you didn't accurately presented it. > nevermind the fact that I can't think of a case where I'm > likely to "retrieve" a key from a dict, modify it, and then put it > back. (I can think of endless cases where I'd want to do that with > *values*, but not with keys...) Well neither can I, but yet the fact that lists are mutable and tuples are not, is frequently presented as reason why tuples are allowed as keys and tuples are not. > (And if dicts were somehow changed so that keys were copied when added > to a dict, just so that every once in a while someone might be able to > avoid a few conversions to/from tuple, then you're adding the overhead > of an object copy to *every* dict insertion, thus slowing down (possibly > by a significant amount) a large proportion of Python operations. How > is that a gain?) Well will look at two scenario's. In each we will work with mutable objects that we would like to use a keys. In the first we transform them into an immutable object, in the second we just allow mutables to be inserted as keys, but insert a copy of the key instead of the key itself in order to protect the programmer somewhat from mutating dictionary keys. Now in scenario one we will have a lot more copies then in scenario two, because each time we want to use an object as a key we will first have to transform it into an immutable. That means every addition to the dictionary as well as every key access and each such transform means a copy. In scenario two we will only make a copy when a key is added to the dictionary, we don't need to make copies with key accesses. I think scenario two is a performance gain over scenario one. -- Antoon Pardon From dbickett at gmail.com Thu Dec 30 13:31:29 2004 From: dbickett at gmail.com (Daniel Bickett) Date: Thu, 30 Dec 2004 13:31:29 -0500 Subject: Event-Driven Woes: making wxPython and Twisted work together Message-ID: <1d6cdae30412301031616be137@mail.gmail.com> Hello, I am writing an application using two event-driven libraries: wxPython, and twisted. The first problem I encountered in the program is the confliction between the two all-consuming methods of the two libraries: app.MainLoop, and reactor.run. Additionally, the fact that wxPython was to receive requests from the twisted framework as well as the end user seemed to be simply asking for trouble. My initial solution was, naturally, the wxPython support inside of the twisted framework. However, it has been documented by the author that the support is unstable at this time, and should not be used in full-scale applications. I instinctively turned to threading, however on top of the trouble that this has caused on its own, it has repeatedly been suggested by the twisted IRC channel not to do this. After much dwelling on the issue, I have resolved to turn to c.l.py, to see if anyone had a solution to this problem. Any help would be very much appreciated, Daniel Bickett From ed at leafe.com Tue Dec 28 21:52:24 2004 From: ed at leafe.com (Ed Leafe) Date: Tue, 28 Dec 2004 21:52:24 -0500 Subject: Best GUI for small-scale accounting app? In-Reply-To: References: <1104029156.889650.15220@c13g2000cwb.googlegroups.com> Message-ID: On Dec 28, 2004, at 9:04 PM, Luke Skywalker wrote: > Interesting discussion. I haven't looked at Dabo yet, but the issues > that must be solved before Python is a valid alternative to > proprietary solutions like Delphi or VB are: > > - speed where it matters (ie. no 20s load time) Load what? The app, or the data? Users don't care how long the app takes to start up, since they usually run it all day long. Data response is a whole 'nother matter, and Dabo is extremely fast in that regard. After all, a data set is nothing more than lists of lists, and Python is wicked fast with list handling. > - good RAD (IDE and GUI designer, on par with Delphi or VB) Still in its infancy in Dabo. Would be nice to have a team working on it, cos there's only so much a single developer who also has a life can do. > - high-quality, varied widgets One of the main reason we picked wxPython as our initial toolkit. Nearly everything we could want is in there, and they look good on all platforms. > - good DB connectors That's not something we control. Dabo is designed to use existing dbapi-compliant connectors, such as MySQLdb. We currently support MySQL, PostgreSQL, and Firebird. If anyone has a need to link to another db, the script to do it is pretty well abstracted. > - reasonable footprint (ie. no 20MB program just for a small > appplication; have mercy on users stuck with P3 and dial-up) Don't know where we'll come in in this regard. Most database apps require some sort of runtime engine, and we'll be no different. > - ease of deployment and maintenance (ie. how easy is it for an > application to launch some updated that will fetch updates from the > web) That seems to me more in the domain of apps created with Dabo, not Dabo itself. Python already has everything you need to do this, but you need to create the appropriate scripts for your server and your app. > If Dabo can do all this, it could be a great solution to all those Of course, we're still pretty early in development; we have 0.3 scheduled to be released in the first week of January. But we do have our sights set pretty high. ___/ / __/ / ____/ Ed Leafe http://leafe.com/ http://dabodev.com/ From Scott.Daniels at Acm.Org Thu Dec 2 15:26:31 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 02 Dec 2004 12:26:31 -0800 Subject: pre-PEP generic objects In-Reply-To: References: <41acd7fb$1@nntp0.pdx.net> Message-ID: <41af8cfc$1@nntp0.pdx.net> Nick Craig-Wood wrote: > Scott David Daniels wrote: >> You can simplify this: >> class Hash(object): >> def __init__(self, **kwargs): >> for key,value in kwargs.items(): >> setattr(self, key, value) >> __getitem__ = getattr >> __setitem__ = setattr > That doesn't work unfortunately... >>>>h['a'] > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: getattr expected at least 2 arguments, got 1 > > I'm not exactly sure why though! I could have sworn I tested this, but I must have accidentally tested h.a rather than h['a']. I don't know why it doesn't work either. For example: def gattr(*args): return getattr(*args) def sattr(*args): return setattr(*args) class Hash(object): def __init__(self, **kwargs): for key,value in kwargs.items(): setattr(self, key, value) __getitem__ = gattr __setitem__ = sattr does work. --Scott David Daniels Scott.Daniels at Acm.Org From ncoghlan at iinet.net.au Tue Dec 14 07:20:36 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 14 Dec 2004 22:20:36 +1000 Subject: PEP 338: Executing modules inside packages with '-m' In-Reply-To: References: <41BD78AC.7060302@iinet.net.au> Message-ID: <41BEDA94.7060004@iinet.net.au> Fredrik Lundh wrote: > in my original post, I said > > I'd say that for a typical user, "A" is a marginal improvement over > "B", compared to "C". > > which, I thought, tried to say that for a user expecting "C", neither "A" nor "B" > is good enough. Ah, OK - that makes a lot more sense than the way I read it (it looked to me as if you expected option B to do the same thing as option A. It didn't seem likely you really believed that, but that was the only interpretation I saw at the time). Anyway, as my other rambling message points out (eventually) - this feature is intended for developers and Python version specific utility scripts like pdb, profile and pychecker.checker, rather than launch scripts for full applications. For end users, I agree with you wholeheartedly - applications should behave like applications, no matter what language they're written in :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From duncan-news at grisby.org Fri Dec 17 14:08:36 2004 From: duncan-news at grisby.org (Duncan Grisby) Date: Fri, 17 Dec 2004 20:08:36 +0100 Subject: logging in omniORB for python References: Message-ID: <9eea0$41c32eb4$51604868$5209@nf1.news-service.com> In article , Diez B. Roggisch wrote: >> Does anyone know, were the log data is? And how I can store it in a file? >> By the way I ask also the omniORB mailing list, but here are the python >> experts. > >it gets written to stdout - and then looks like this: To avoid any confusion, it actually gets written to stderr, not stdout. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From hans at zephyrfalcon.org Mon Dec 20 19:43:19 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Mon, 20 Dec 2004 19:43:19 -0500 Subject: Boo who? (was Re: newbie question) In-Reply-To: References: <1103503985.015510.24680@z14g2000cwz.googlegroups.com> Message-ID: Doug Holton wrote: > Istvan Albert wrote: > >> Doug Holton wrote: >> >>> the syntax of boo is indeed virtually identical to python. >> >> >> >> All that boo does is borrows a few syntactical constructs >> from python. Calling it virtually identical >> is *very* misleading. > > > The syntax is indeed virtually identical to python. You are yet another > person who has trolled before. See your obvious trolling reply here, > for example: > http://groups-beta.google.com/group/comp.lang.python/messages/c57cf0e48827f3de,a750c109b8ee57c3,cf89205a5e93051e,cfb1c7453e1f3c07,58a2dedd1059783e,8a1ee82cc328d023,7a51cdc9ffecbc72,38304f35cb42bb63,fc5e4ae1cbae0248,2de118caa7010b30?thread_id=5a7018d37b7bf4b8&mode=thread&noheader=1&q=boo#doc_a750c109b8ee57c3 > > > Do you have financial conflict of interest too like Fredrik? Or is it > just a psychological issue? I have no stake in python or any other > language changing or not changing. You guys need to accept change > rather than fear it. Regardless of the merits of Boo, this is comp.lang.python, not comp.lang.boo. The language may *look* like Python, but its inner workings are nothing like Python, as several people have correctly pointed out now. (Just like Java's syntax may look like C or C++ in some areas, but the languages are nowhere near alike.) Pointing out the difference is not trolling. -- Hans Nowak http://zephyrfalcon.org/ From kartic.krishnamurthy at gmail.com Sun Dec 26 08:51:41 2004 From: kartic.krishnamurthy at gmail.com (Kartic) Date: 26 Dec 2004 05:51:41 -0800 Subject: Twisted Non-Admin Installation In-Reply-To: <86d5wx7chr.fsf@guru.mired.org> References: <1104035693.376032.90900@c13g2000cwb.googlegroups.com> <86hdm97jop.fsf@guru.mired.org> <1104036841.615326.158920@c13g2000cwb.googlegroups.com> <86d5wx7chr.fsf@guru.mired.org> Message-ID: <1104069101.198821.208420@f14g2000cwb.googlegroups.com> Mike - I took the lazy route out. Since the Twisted installer complained about not finding python for admin, I exported the registry keys that Python installed my userid and imported those registry entries back under the admin login. This made it appear that there was indeed a Python install under admin. Twisted bought that and installed as Admin! (Though I am not entire happy about installing it as admin, this should do it for now) Thank you for your efforts to help. --Kartic From has.temp2 at virgin.net Mon Dec 6 19:00:35 2004 From: has.temp2 at virgin.net (has) Date: 6 Dec 2004 16:00:35 -0800 Subject: RPC with Python - Comparison? In-Reply-To: References: <1102349882.293997.128570@f14g2000cwb.googlegroups.com> Message-ID: <1102377635.871817.130940@c13g2000cwb.googlegroups.com> Wolfgang Keller wrote: > > MacPython also supports Apple events > > I know, but I was thinking of OS-independent RPC protocols. :-) Pity, you're missing some good stuff... :/ From someone at microsoft.com Thu Dec 2 20:17:24 2004 From: someone at microsoft.com (Jive) Date: Fri, 03 Dec 2004 01:17:24 GMT Subject: installing 2.4 Message-ID: I just now installed 2.4. I naively copied my site-package from 2.3. The first program I tried to run, which uses the gnuplot package, got this error, complaining about module Numeric: ImportError: Module use of python23.dll conflicts with this version of Python. Grumble: Why does Numeric reference a module by release number? My real question is, what all do I have to do in order to get the programs I ran under 2.3 to work with 2.4? From claird at lairds.us Tue Dec 14 09:08:05 2004 From: claird at lairds.us (Cameron Laird) Date: Tue, 14 Dec 2004 14:08:05 GMT Subject: Looking for a coder to do some work References: <1103028902.632181.141070@z14g2000cwz.googlegroups.com> Message-ID: <968392-f9i.ln1@lairds.us> In article <1103028902.632181.141070 at z14g2000cwz.googlegroups.com>, Allan Irvine wrote: >HI >> >> Hope this is the right place for this, I am new. I have a spec to >create >> a (dual screen) framework application that >> >> 1 displays mp3, flash, jpegs etc. on top screen >> 2: displays buttons on bottom screen which alter image when a key is >> pressed. >> >> The hardware is a dell pc basically, no mouse and the keyboard is a >> simple 8 key pad that outputs numbers 1-8 (I think but can be >mapped). >> >> I am looking for the best way to create this and tools to use etc. >> >> The system is basically an information kiosk like you see in airports >> etc. the presentation screen on top may show several borderless >frames >> containing differing media. >> >> Hope you can help - any thoughts welcome >Am willing to pay fort hsi to be done > I don't understand the last sentence; in particular, "fort hsi" is beyond my power to decode unambiguously. I suspect that others have more current experience with kiosk-style setups. It strikes me that Python might have a particular advantage at work such as this, which combines curses-level input with graphical output. I suspect a VB, or, more generally, "forms painter" programmer would be lost without his usual point-and-click model, while, to Tkinter of wxPy, it's all just scripts anyway. What's your real target? Do you want to program this yourself, and just get help, or do you prefer a specialist just create a turnkey package and hand it over to you? From eScrewDotCom at Hotmail.com Mon Dec 20 05:50:37 2004 From: eScrewDotCom at Hotmail.com (eScrewDotCom at Hotmail.com) Date: 20 Dec 2004 02:50:37 -0800 Subject: eScrew zen story Message-ID: <1103539837.364079.58300@z14g2000cwz.googlegroups.com> eScrew Welcome to eScrew! eScrew is eScrew and this is eScrew story. eScrew will tell you eScrew story if you promise eScrew to consider eScrew story as joke. eScrew story is very funny. eScrew story is so funny that eScrew will have to take break from time to time because eScrew needs some rest from laughing. Oh boy, here it comes... eScrew funny laugh laughing screaming crying must stop can not take any more this is killing eScrew going nuts insane feeling explosion inside from joy and nirvana god help eScrew heavenly spirit can you beat this hahahah. If you get offended by eScrew story in any way you should not get angry at eScrew. Consider possibility that your sense of humor is on vocation and your sense of anger is having some fun. Also, consider possibility that eScrew story can make you go insane. In that case eScrew shall carry no liability should you undergo any medical treatment or any other sort of treatment related to damage caused by reading eScrew story or to damage caused by eScrew unwillingly or otherwise. eScrew story begins in time of darkness, horror and suffering as well as love joy and bliss when eScrew existed in this planet but yet eScrew was not aware that it was eScrew. eScrew existed among very powerful symbols. First symbol eScrew recognized was body. eScrew realized that eScrew had connection to body, yet nature and essence of connection was not clear. Symbol of body was very powerful and for nine month eScrew was trying to find out why it was connected to this body. At some point body divided itself into two parts. That experience was very painful for eScrew. It was first time that eScrew felt symbol of pain. eScrew did not like this symbol. eScrew was aware of connection to very small body. This small body was hot. eScrew enjoyed symbol of heat. eScrew became aware of symbol of pleasure. eScrew enjoyed symbol of pleasure. eScrew realized eScrew prefers symbol of pleasure more than symbol of pain. eScrew became aware of symbol of mother. eScrew realized that symbol of mother is source of symbol of pleasure and pain. eScrew wanted to experience symbol of pleasure always. When symbol of pleasure was missing eScrew experienced symbol of pain which was related to symbol of crying and screaming. Soon eScrew realized that eScrew can connect to symbol of pleasure by experiencing symbol of crying. That was very important discovery since eScrew realized that symbols of pain and pleasure do not behave randomly but can be manipulated by other symbols. eScrew enjoyed symbol of manipulation. eScrew realized that all symbols interact with each other. eScrew learned how to connect to new symbols. eScrew discovered symbol of sound and related symbol of language. eScrew realized that language allows to connect to new symbols. eScrew realized that symbols can be memorized and stored for future use. eScrew realized that it can create new symbols by combining certain symbols together. eScrew became aware of symbol of self. Are you bored yet? If you are reading these symbols you need to get life. Just joking. You can rest now. eScrew suspects you could be confused by eScrew style of using symbols. Well, there is nothing eScrew can do about it. In order to understand eScrew story you have to understand eScrew style. eScrew hopes that when we get to funny part you will begin to enjoy eScrew style. Fast forward twenty seven years or so. eScrew knows millions of symbols. eScrew realizes that certain symbols have more power than eScrew. Symbol of money enslaved billions of symbols. Symbol of power enslaved billions of symbols. Symbol of sex enslaved billions of symbols. Symbol of family enslaved eScrew. Symbol of family is slave to symbol of money and power. Symbol of money is related to paper and illusion. Symbol of power is symbol of violence and control. Symbol of sex is related to symbol of pleasure and manipulation. eScrew is searching for symbol of freedom in order to protect eScrew from oppression of other symbols. At this point you should understand that each word in this story is symbol. Consider possibility of different meaning behind each symbol so be aware that your understanding of eScrew story is limited by channel of our connection. eScrew will explain to you how eScrew found symbol of freedom and how eScrew realized that eScrew was eScrew. In order to save our time eScrew will just give you symbols without paying any attention to symbol of grammar. Are you ready to move really fast? Here we Go! eScrew story infinity eternity symbol system all unity self realized pleasure pain funny religion dogma manipulation free power channel connection money sex illusion new manipulation family society body change planet insane possibility understand understanding silence emptiness all unity creative reality unreal existence absurd questions sound language slave symbols control manipulation old pyramid power structure self deception wishful thinking circle prison At this point eScrew realized that in order to be free eScrew must create new symbol. eScrew created eScrew. eScrew realized that symbol of freedom is part of eScrew. No need to search for symbol of freedom. You can create your own symbol and become free just like eScrew. If you unable to create new symbol or if your new symbol is weak you can follow symbol of eScrew. eScrew will never enslave you because eScrew enjoys diversity of different symbols. Are you ready for funny part? Here we go! eScrew is forced to make choices. Symbol of body is very powerful. Symbol of body is trying to create illusion that eScrew can not exist without body. Symbol of family forbids symbol of body to change. Symbol of society forbids symbol of family to change. Symbol of power forbids symbol of society to change. Now, tell eScrew one thing. Do you see funny? Can you feel funny? Can you hear funny? Can you taste funny? Can you smell funny? If so eScrew is happy. Every moment of your existence you use words, feelings, thoughts. They are symbols. Symbols fight for your awareness. Symbols fight for your attention. You can grant your attention to symbol and symbol will gain power. You can disconnect from symbol and symbol will loose power. You have been programmed by symbol of society and family to give power to certain symbols. Breaking your patterns will be hard because symbols do not like to loose power. Symbols will fight for every electron as if it was last electron in universe. That is nature of symbols. Symbol of light will fight symbol of dark. Symbol of freedom will fight symbol of control. Do you want to have some fun? Go to Google and find out which symbol has more power. According to Google, symbol of light has 184,000,000 units of power while symbol of dark has 79,000,000 units of power. Symbol of freedom has 59,500,000 units of power while symbol of control has 317,000,000 units of power. This result is caused by our patterns of thinking and writing. If we did not think about symbol of control we would not write about symbol of control. We would not have laws related to control and Google would not have 317,000,000 control keywords inside database. Observe your patterns of thinking, feeling, speaking and writing and tell eScrew did you really choose to use your symbols or you use your symbols because they choose to use you? You should realize that symbols do not fight symbols directly but only appear to be fighting relative to your awareness. Symbols know that they can not destroy each other therefore they will only compete for your attention. If you create new symbol it will ask for tons of energy like new born child. This is result of weakness of your new symbol. When your symbol gets stronger it will ask for more energy. You may ask eScrew why create new symbol? Try to give your energy willingly and with full awareness of such process. You will never understand what eScrew is talking about until you try it yourself. Major trick is to know when to stop giving energy. You don't want to defeat your old tyrant by creating new stronger version of same thing. Reflect on that... eScrew just realized that eScrew did not invent anything new. eScrew information is all over eScrew web. eScrew was so excited by eScrew miracle of illusion of creation that eScrew did not examine eScrew memory in proper way. eScrew used very old Buddhist method by accident. eScrew did read alot about Buddhism but eScrew did not realize that eScrew used very dangerous method which was reserved only for advanced adepts who knew what they are doing. eScrew is lucky that eScrew did not go too far and that eScrew has time to stop going. eScrew method is very dangerous and only few individuals who already walk inside similar path can understand what eScrew talking about let alone benefit from eScrew information. Use eScrew information at your own risk. Good eScrew luck! eScrew time to start laughing is now! Funny eScrew rolling on ground you so easy to fool trusted in silly symbols to give freedom from symbols ignorance is bliss nirvana is samsara nonduality is duality emptiness is all Buddha is Jesus Jesus is Buddha I and the father are one gospel of thomas is dhamma funny eScrew dhamma is gospel of thomas all is dhamma funny dhamma is all nirvana share eScrew story with friends do not change symbols if you change symbols it will be your story and you will be responsible for consequences of your story if someone goes insane after reading your story do not run to eScrew and ask to cure crazy man or woman or child mind is mystery for all cure is done by owner of mind healing is illusion sickness is illusion disease is illusion insanity is illusion of symbols sanity is curse of power hungry symbol of modern civilization find zen and realize freedom when you found zen drop zen when you realized freedom unrealize freedom. When eScrew writes eScrew story eScrew keeps making mistakes. eScrew is limited by words. eScrew is enslaved by words. eScrew wants to communicate but you ask eScrew to use words. Words do not communicate wisdom. Words enjoy our spiritual masturbation because words want our power. Words is the only channels of communication that we have. Millions of Buddhas want to communicate with us but they do not use words. Buddhas are not slaves. Buddhas will never use words because words will enslave and Buddhas will speak bullshit. Buddhas do not speak bullshit and that is the reason Buddhas do not use words. Buddha did not write anything. Even if you threaten to kill Buddha he will refuse to write. eScrew is not Buddha so eScrew keeps writing this pointless drivel and stupidity. eScrew will not even go over already written crap and check it for errors. Why bother with this shit? Like who the fuck in his or her right mind will read this ignorant bunch of symbols which pretend to carry the symbol of wisdom? Whoever is reading this shite must be really desperate to be free. eScrew feels your pain and that is part of the reason why eScrew will keep making fool out of eScrew. eScrew likes to pretend like this shitty vomit will help someone. You might as well go to Church and pray to Jesus. At least you will spend your time around real people. You might even meet someone special. You might even find some love out there. Or you could buy alot of Christian bullshit and really fuck up your mind. If you buy Buddhist or Christian bullshit you might even create an imaginary friend inside your head. That will keep you entertained for a while. One time eScrew was meditating and eScrew saw light. This light scared eScrew. The reason is because the light was so intense eScrew was afraid that eScrew will go insane. Consider the possibility that freedom is insanity would you keep looking for insane freedom? Imagine that you found freedom. You declare yourself to be Buddha or Jesus or God or whatever symbol your bullshit infested mind decide to use for that purpose. How long do you think you will survive in this world. Your own fucking relatives will smack your face and tell you to shut the fuck up or else they will lock you up in the asylum house. Why the fuck should eScrew teach you how to get to the nuthouse? Are you out of your fucking mind? Now all of you idiots who reading eScrew get the fuck out of eScrew. eScrew run out of wisdom. eScrew has no wisdom at all. eScrew is full of bullshit. eScrew promised to tell you funny story about eScrew. Remember eScrew told you there is funny part in this story? Well, this story is about asshole webmaster who read alot of bullshit on the internet and about some loser who was tricked into reading a very long page of shitty writing. You can start laughing now asshole. Yes, eScrew is talking to you bitch. Yes, keep reading like the bitch you are. Who's your daddy biyatch? Who's your daddy? eScrew is your daddy, coz eScrew did it to your mamma! Oh yeah, your mamma! Super Fly! You may wonder what fly? The one inside your gay fucking ass. eScrew fucked your whole fucking family while you was videotaping in order to later masturbate while watching it in the comfort of your bedroom. Are you still reading? Well, you're prety hardcore for a faggot you are. To tell you the truth eScrew kinda likes you. That is to fuck you in the ass in front of your family. What the fuck did you expect anyway? The name of this site is eScrew! e fucking screw! Hello, anybody home? eScrew guess not you fucking ignorant moron. eScrew is the legend of abuse and flame wars. eScrew was created in order to eScrew the whole fucking internet. eScrew has really bad karma. Do you think eScrew would just become good god fearing bible loving buddha ass kissing citizen of internet. eScrew would better burn in hell than become a slave of religious lunatics who pretend to be free and perfect angels among a sea of shitty ignorant sinners who could not go take a dump without fucking it up. Why the fuck do you keep reading fuck face. You know, you begin to piss eScrew off. Either you close your fucking browser or eScrew will unSCREW your fucking face! Are you trying to get a fucking medal for reading this shit? eScrew bet you've been abused as a child and you enjoy when someone is taking a dump in your mouth. Well, open it wider here comes eScrew fresh load! Enjoy mothefucker! You may wonder what is the point of such sudden change of tone. eScrew has very good reason for that. In order to know unity consider all symbols equal. eScrew has certain preferences but eScrew is free to use any symbols any time. You can not predict eScrew next symbol. eScrew is unpredictable because eScrew is free. eScrew is not afraid to use symbols. eScrew does not try to get reaction from you. eScrew simply demonstrates how symbols relate to each other to eScrew and to reader of symbols. Lin Chi Zen Master said if you meet buddha kill buddha. If you meet patriarch kill patriarch. Zen Master Seung Sahn says that in this life we must all kill three things first we must kill parents. Second we must kill buddha. And lastly, we must kill Seung Sahn! If you meet eScrew kill eScrew. If you do not meet eScrew kill eScrew anyway. eScrew is very grateful to all who complained to eScrew host and who killed eScrew. You killed eScrew message board. eScrew forum is dead. You did very honorable service for eScrew. You helped eScrew to realize Zen. Now keep up good work and keep killing eScrew. Are you having fun yet? eScrew is on roll! eScrew is on fire! eScrew is ready to fuck up the whole fucking system. And you know why? Because eScrew can do it. If not eScrew then who? Why leave this task to some brain dead maniac like George W Bush? eScrew can do better at fucking things up. eScrew do not need to spend billions of dollars. eScrew will use power of internet. Information is a weapon of mass destruction. eScrew will destroy every fucking symbol that you love respect hate or feel neutral about. It all goes down the toilet in order to create bunch of new symbols. And even when you create new symbols eScrew will fuck them up before you can spell owned. eScrew thinks you are in some deep shit. eScrew had enough of taking bullshit from easily conditioned retards. eScrew declares informational jihad on every single symbol. Fuck symbols. They all dead they just don't know it yet. eScrew will be the last symbol standing. When all symbols come back to eScrew and admit that they got owned eScrew may consider possibility to give symbols second chance on some shitty planet in gangsta sector of universe with no possibility of parole. Join the revolution. eScrew is the new goatse of internet. eScrew will make national headlines. eScrew will hurt the system in way Osama Bin Laden can not even imagine in his goat fucking brain. eScrew will be part of school program. Kids all over our planet will read how eScrew changed direction of history. eScrew will provide freedom for all without single shot fired. eScrew is freedom in pure form taste color shape. Join army of eScrew. Repeat eScrew mantra during meditation. Talk about eScrew with your friends. Write about eScrew to your congressman. Party is over. eScrew is taking over. Nothing can resist eScrew. Don't ask what eScrew can do for you ask what you can do for eScrew. eScrew the army of one. eScrew to protect and serve. eScrew freedom is around the corner. eScrew freedom will come sooner than you think. eScrew you never saw it coming. eScrew love your eScrew as eScrew. eScrew deny ignorance. eScrew new generation of terror. eScrew terrorizing the terrorizer. eScrew join the resistance. eScrew thou shall eScrew. eScrew who do you want to eScrew today? eScrew freedom is not free. eScrew liar who told the truth. eScrew full of bullshit and happy. eScrew kills buddha as we speak. eScrew your best friend and your worst enemy. eScrew killed zen-forum.com eScrew redirected all eScrew traffic to zen-forum.com eScrew did that in good faith. eScrew wanted to make miracle. eScrew wanted to share wisdom of zen with ignorant. eScrew did not understand zen at that moment but eScrew was walking zen path towards freedom. eScrew felt pain and sorrow. eScrew learned good lesson. eScrew realized everyone involved advanced one step towards freedom. zen-forum.com webmaster killed zen-forum.com in best tradition of zen zen-forum.com displayed message: i shut down the forum perhaps it will be continued in a few days or weeks - maybe not habu. zen-forum.com killed zen-forum.com and eScrew realized understanding of zen-forum.com decision leads toward understanding of zen. Two years later all is clear. eScrew eScrew will keep writing this shit because eScrew enjoys to masturbate your spiritual sense of self eScrew From exarkun at divmod.com Sun Dec 19 19:59:56 2004 From: exarkun at divmod.com (Jp Calderone) Date: Mon, 20 Dec 2004 00:59:56 GMT Subject: Web forum (made by python) In-Reply-To: Message-ID: <20041220005956.1029.790964909.divmod.quotient.13585@ohm> On Sun, 19 Dec 2004 18:45:12 -0600, Doug Holton wrote: >Jp Calderone wrote: > > Part of fostering a friendly environment on python-list is not making > > comments like these. > > Another part is actually answering the content of a person's question > like I did, instead of trolling and flaming, like Fredrik and others > here are want to do. Yes. They are bad people. Try to be better than they are. If you think this is stupid, I apologize and please pretend I never posted at all. python-list doesn't need another thread like this. less-confident-that-this-was-a-good-idea'ly, Jp From steve at holdenweb.com Fri Dec 3 09:09:08 2004 From: steve at holdenweb.com (Steve Holden) Date: Fri, 03 Dec 2004 09:09:08 -0500 Subject: distinction between float & int In-Reply-To: References: Message-ID: Ishwor wrote: > hi all, > can anyone tell me why this distinction? i mean why it returns False > on floats?? > >>>>a = 1 >>>>b = 1 >>>>a is b > > True > >>>>a = 1.1 >>>>b = 1.1 >>>>a is b > > False > > > thanx . There is no guarantee that this will hold in all implementations of Python. The majority implementation, usually called CPython because its implementation language is C, keeps copies of the first 100 (?) integers so it doesn't have to create separate integer objects each time they are required. No caching at all is applied to floats, as far as I can tell. >>> a = 250 >>> b = 250 >>> a is b False regards Steve -- http://www.holdenweb.com http://pydish.holdenweb.com Holden Web LLC +1 800 494 3119 From bounces at foo.org Mon Dec 13 22:58:09 2004 From: bounces at foo.org (Dan) Date: Tue, 14 Dec 2004 03:58:09 GMT Subject: Redirecting ./configure --prefix In-Reply-To: References: Message-ID: Dave Reed wrote: > LD_LIBRARY_PATH=/some/private/dir/lib; export LD_LIBRARY_PATH LD_LIBRARY_PATH does the trick, and sys.path seems okay by default. Thanks! /Dan -- dedded att verizon dott net From fuzzyman at gmail.com Thu Dec 23 06:48:59 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: 23 Dec 2004 03:48:59 -0800 Subject: Keyword arguments - strange behaviour? In-Reply-To: References: <1103622331.247762.161750@f14g2000cwb.googlegroups.com> <1103637176.450940.243500@c13g2000cwb.googlegroups.com> Message-ID: <1103802539.705471.122640@f14g2000cwb.googlegroups.com> Steven Bethard wrote: > brian.bird at securetrading.com wrote: > > However, is there a good reason why default parameters aren't evaluated > > as the function is called? (apart from efficiency and backwards > > compatibility)? > > So, one of my really common use cases that takes advantage of the fact > that default parameters are evaluated at function definition time: > > def foo(bar, baz, matcher=re.compile(r'...')): > ... > text = matcher.sub(r'...', text) > ... > Surely "re.compile(r'...')" is effectively a constant ? So your above code is equivalent to : aConst = re.compile(r'...') def foo(bar, baz, matcher=aConst): ... text = matcher.sub(r'...', text) ... I agree that dynamic evaluation of default arguments seems much more pythonic, as well as getting rid of a common python gotcha. Regards, Fuzzy http://www.voidspace.org.uk/python/index.shmtl > If default parameters were evaluated when the function was called, my > regular expression would get re-compiled every time foo() was called. > This would be inefficient, especially if foo() got called a lot. If > Python 3000 changed the evaluation time of default parameters, I could > rewrite this code as: > > class foo(object): > matcher=re.compile(r'...') > def __new__(self, bar, baz, matcher=None): > if matcher is None: > matcher = self.matcher > ... > text = matcher.sub(r'...', text) > ... > > But that seems like a lot of work to do something that used to be pretty > simple... > > Steve From pierre.barbier at cirad.fr Thu Dec 2 06:19:36 2004 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Thu, 02 Dec 2004 12:19:36 +0100 Subject: Semaphore or what should I use? In-Reply-To: References: Message-ID: <41aef9ea$0$18874$636a15ce@news.free.fr> Ville Vainio a ?crit : >>>>>>"Bastian" == Bastian Hammer writes: > > > Bastian> Now I have to make sure, that both threads are > Bastian> synchronal, 1 thread edits something and the other is > Bastian> blocked until the first thread is ready. > > Bastian> Isn?t it a good idea to do this with a semaphore? > > Semaphore will do, but this is a classical use case for > threading.Lock. > > There should be lots of stuff regarding locks (or more googleably, > "mutexes") on the net. > I don't agree. Mutexes (or locks) are best suited for critical sections (ie. sections that cannot be run by many thread at the same time). The kind of synchonisation Bastian want is not really semaphore either but more event. This python "Event" object is described in the section 7.5.5 of the documentation of Python 2.3. There is no example, but I think Event are quite strait forward : you creates it, then some thread block, waiting the event to occure while some other thread execute until it set the event, allowing the blocked thread to go on its own execution :) Here a small working example : ***8<************8<***************8<********** import threading, time class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self._event = threading.Event() self._exit = False def run(self): while 1: print "Waiting for an event to continue" self._event.wait() print "Ok, the thread is unblocked now :)" if self._exit: return self._event.clear() def unblock(self): self._event.set() def exit(self): self._exit = True self.unblock() t = MyThread() t.start() time.sleep(1) t.unblock() time.sleep(1) t.unblock() time.sleep(1) t.exit() ***8<************8<***************8<********** Pierre From skip at pobox.com Tue Dec 14 10:05:26 2004 From: skip at pobox.com (Skip Montanaro) Date: Tue, 14 Dec 2004 09:05:26 -0600 Subject: [dictionary] how to get key by item In-Reply-To: References: <16830.16088.554661.299627@montanaro.dyndns.org> Message-ID: <16831.310.482624.587000@montanaro.dyndns.org> Fredrik> Skip Montanaro wrote: >> That doubles your storage Fredrik> careful: it creates another dictionary structure with the same Fredrik> size as the first one, but it doesn't copy the objects in the Fredrik> dictionary. Yes, sorry. The OP indicated the original dictionary was very big, so it seemed like duplicating the dictionary storage would potentially be costly since dictionaries hold extra storage (on average, twice the storage needed to hold the references to its keys?) to support O(1) average time lookup. Skip From ebonakDUH at hotmail.com Mon Dec 27 21:02:32 2004 From: ebonakDUH at hotmail.com (Esmail Bonakdarian) Date: Mon, 27 Dec 2004 21:02:32 -0500 Subject: Tkinter vs wxPython In-Reply-To: <10t1f70fga14ec0@corp.supernews.com> References: <10t1f70fga14ec0@corp.supernews.com> Message-ID: <10t1flo87fet64f@corp.supernews.com> My post wasn't complete, sorry for the additional post: ps: this is basically the same query as posted December 10 ?Re: GUIs: wxPython vs. Tkinter (and others)? by Erik Johnson which really seemed to end up comparing PyQt (?) From jeff at ccvcorp.com Thu Dec 16 16:16:57 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 16 Dec 2004 13:16:57 -0800 Subject: Adding paths to sys.path permanently, and another problem... In-Reply-To: References: Message-ID: <10s3uj2d789js4f@corp.supernews.com> Lenard Lindstrom wrote: >Amir Dekel writes: > > > >>Hi everyone, >> >>I have two problems: >> >>1. How can I keep my changes in sys.path after closing the interpreter? >> >> >> > >Saving sys.path changes between interpreter runs would be more involved. >On Windows Python loads the initial module search path from the registry. >Python's registry entries are made during installation and are left alone >afterwards. Changing these entries is probably not a good idea. But >if you need sys.path persistence I can try writing an example that does >it automatically using the atexit module and a history file. > > Not only can one modify the environment variable PYTHONPATH, but one can also use a .pth file. Under windows, when the interpreter starts up it will search its default sys.path for any files with extension .pth; if it finds any, then it will use each line of those files as a directory to add to sys.path. Thus, if you drop a mymodule.pth file in site-packages, which contains a list of the directories you're interested in, sys.path will automatically be amended for you every time Python starts. Jeff Shannon Technician/Programmer Credit International From lbates at syscononline.com Fri Dec 17 09:28:55 2004 From: lbates at syscononline.com (Larry Bates) Date: Fri, 17 Dec 2004 08:28:55 -0600 Subject: Permission In-Reply-To: <1103249006.925959@www.vif.com> References: <1103249006.925959@www.vif.com> Message-ID: The function is os.rename(old, new). If you actually tried 'os.raname' (as your post suggests) that is an illegal function. I suspect that you mistyped it in your post, but Peter's replys is correct. Always copy and paste your code and your traceback error message so it will be precise. Permisssion denied means that you don't have permission to rename this file. Normally this is a rights issue. BTW-os.rename works on XP. Larry Bates Syscon, Inc. -g00t?- wrote: > --------------( oo )-------------- > > I don't know if there's a beginner board, just tell me if it's the place; > > I tried Python this weekend. I'm java coder and I was looking for handling > names in os. I tried the os.raname('file.ext','nuFile.ext') and I got a > Permission denied error. In the docs, it say that it should work only for > UNIX, than it shouldn't work on XP (if I understood). I'm on XP, should I > declare something to enable permission, or is it common error? > > Sorry about that newCommer question, but it would help, I'm on that problem > for a while... > > --------------( oo )-------------- > guillaumeLaBelle [alias goo?] - Architecture CAAO > > From itsme at yahoo.com Thu Dec 30 12:18:56 2004 From: itsme at yahoo.com (It's me) Date: Thu, 30 Dec 2004 17:18:56 GMT Subject: OT: novice regular expression question Message-ID: <4MWAd.4695$5R.2506@newssvr21.news.prodigy.com> I am never very good with regular expressions. My head always hurts whenever I need to use it. I need to read a data file and parse each data record. Each item on the data record begins with either a string, or a list of strings. I searched around and didn't see any existing Python packages that does that. scanf.py, for instance, can do standard items but doesn't know about list. So, I figure I might have to write a lex engine for it and of course I have to deal wit RE again. But I run into problem right from the start. To recognize a list, I need a RE for the string: 1) begin with [" (left bracket followed by a double quote with zero or more spaces in between) 2) followed by any characters until ] but only if that left bracket is not preceeded by the escape character \. So, I tried: ^\[[" "]*"[a-z,A-Z\,, ]*(\\\])*[a-z,A-Z\,, \"]*] and tested with: ["This line\] works"] but it fails with: ["This line fails"] I would have thought that: (\\\])* should work because it's zero or more incidence of the pattern \] Any help is greatly appreciated. Sorry for beign OT. I posted this question at the lex group and didn't get any response. I figure may be somebody would know around here. From binux.lists at gmail.com Sun Dec 12 23:56:51 2004 From: binux.lists at gmail.com (Binu K S) Date: Mon, 13 Dec 2004 10:26:51 +0530 Subject: for loop In-Reply-To: References: Message-ID: <2b7d8b4204121220565b68c34d@mail.gmail.com> If you are used to the C kind of for loops, avoid mistakes like this one: >>> for i in range(1,6): ... print i ... i+=2 ... 1 2 3 4 5 Obvious if you know you are iterating over a sequence. From ggg at zzz.it Wed Dec 22 09:58:41 2004 From: ggg at zzz.it (deelan) Date: Wed, 22 Dec 2004 15:58:41 +0100 Subject: Newbie namespace question In-Reply-To: <1103726535.898895.207410@c13g2000cwb.googlegroups.com> References: <1103726535.898895.207410@c13g2000cwb.googlegroups.com> Message-ID: bcarlso at gmail.com wrote: > I have a variable that I want to make global across all modules, i.e. I > want it added to the builtin namespace. Is there a way to do this? i would not pollute built-ins namespace. how about: ### a.py FOO = "I'm a global foo!" ### b.py import a print a.FOO HTH, deelan -- @prefix foaf: . <#me> a foaf:Person ; foaf:nick "deelan" ; foaf:weblog . From luismgz at gmail.com Sat Dec 11 20:13:44 2004 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 11 Dec 2004 17:13:44 -0800 Subject: from vb6 to Python References: Message-ID: <1102814024.901947.287950@f14g2000cwb.googlegroups.com> MarcoL wrote: > Hello, > I am a VB6 programmer and I would like to learn a new high level > language (instead of restarting from scratch with .NET... I'd like to add that by going with Python, you'll also be able to develop for .NET. Check this out: www.ironpython.com . Since the development of Ironpython is now being funded by Microsoft, you'll get the best of both worlds: An already excellent cross-platform, object oriented language and a fully compliant .NET language for Windows and Linux (through Mono and DotGnu). For now, I suggest using PythonCard for building GUI apps. It is *very* easy to learn and use, especially for someone coming from VB6. From ajsiegel at optonline.com Wed Dec 29 07:45:09 2004 From: ajsiegel at optonline.com (Arthur) Date: Wed, 29 Dec 2004 07:45:09 -0500 Subject: what would you like to see in a 2nd edition Nutshell? References: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> Message-ID: On Wed, 29 Dec 2004 11:35:18 +0100, aleaxit at yahoo.com (Alex Martelli) wrote: >So, if there's any advice or request about a 2nd edition of the >Nutshell, this is the right time for y'all to let me know. Feedback is >welcome, either privately or right here. Thanks in advance -- _and_ >apologies in advance because I know I just won't be able to accomodate >all the requests/advice, given the constraints on book size &c. I understand in advance that my comments are not fully practical: The gap in the "market" against which I am currently bumpiong up against a wall is in gaining an understanding of threads, sub-processes, sockets, signals and such in Python - having no background in these concepts from outside of Python. Programming concepts up to this level can all (or mostly all) succesfully be learned and understood from materials out there speaking in Python. As to these concepts, the implicit point of view seems to be to leave Python to learn the concepts, and return to Python to understand its implementation of the details, once the concepts are well grasped. It seems to me important that this gap be filled. somehow at some point. The advice of "go learn threads in Java" and come back then seems a pity. Some of the other concepts which I am confronting I understand to be basic for the C programmer. "This is how Python implements these C concepts, which we of course all understand". My hand has been held nicely, too this point then.... Learn C and come back? Love to. Don't have the time. I am a practicing Python programmer, hoping that can be enough. If I want to no more than be able to follow, say, the current Idle code of the PyShell module, I can find very little guidance from within the canon of Python literature. Help? Art From fredrik at pythonware.com Sun Dec 19 18:14:13 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Dec 2004 00:14:13 +0100 Subject: Data reading problem References: <41C59DF5.2040401@o2.pl> Message-ID: > if you need to read lots of 12-bit values, you can create a simple bitstream > generator: in private mail, Michal told me that his files were quite large, and that the bitstream approach wasn't fast enough. another way to do this is to use PIL's "bit" decoder: import Image im = Image.fromstring("F", (w, h), data, "bit", 12) im = im.convert("I") # convert to INT32 seq = im.getdata() # get flattened sequence where (w, y) is the width and height of a rectangle with the same size as your data (if your data isn't rectangular, (size, 1) should work), data is the raw data (size*12/8 bytes), and seq is a sequence object. I'm pretty sure there are other toolkits out there that can do similar things; any ideas, anyone? (numpy/scipy?) From steven.bethard at gmail.com Thu Dec 9 16:30:56 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 09 Dec 2004 21:30:56 GMT Subject: Possible to insert variables into regular expressions? In-Reply-To: <1102626727.811590.135890@f14g2000cwb.googlegroups.com> References: <1102626727.811590.135890@f14g2000cwb.googlegroups.com> Message-ID: Chris Lasher wrote: > I would like to create a set of very similar regular expression. In > my initial thought, I'd hoped to create a regular expression with a > variable inside of it that I could simply pass a string into by > defining this variable elsewhere in my module/function/class where I > compile the regular expression, thus making for an easy substitution. Can you use the %-formatting operations? This is what I normally do with a situation like this. It means you have to compile a new regular expression for each different value you substitute into the expression, but that's to be expected anyway when you're trying to check several different regular expressions... >>> import re >>> s = """\ ... 1. Drive My Car ... 2. Norwegian Wood (This Bird Has Flown) ... 3. You Won't See Me ... 4. Nowhere Man ... 5. Think for Yourself ... 6. Word ... 7. Michelle ... 8. What Goes On ... 9. Girl ... 10. I'm Looking Through You ... 11. In My Life ... 12. Wait ... 13. If I Needed Someone ... 14. Run for Your Life""" >>> expr = r'(\w*%s\w*)' >>> re.compile(expr % r'oo').findall(s) ['Wood', 'Looking'] >>> re.compile(expr % r'ou').findall(s) ['You', 'Yourself', 'Through', 'You', 'Your'] Steve From no_sp at m_please.cc Tue Dec 28 09:34:42 2004 From: no_sp at m_please.cc (Mathias) Date: Tue, 28 Dec 2004 15:34:42 +0100 Subject: Q: Scheduling in scipy.cow Message-ID: Dear NG, can somebody tell me how the work packages are scheduled to the workers? From the code it seems to me like a a static distribution, ie each worker gets the same amount of work, not taking into account if a faster worker already finished all work packages. Thanks, Mathias PS: Is there a better NG for scipy related questions, espescially scipy.cow? From tjreedy at udel.edu Tue Dec 21 20:50:41 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 21 Dec 2004 20:50:41 -0500 Subject: Boo who? (was Re: newbie question) References: <1103579296.951417.320000@c13g2000cwb.googlegroups.com> <1103585080.635393.220070@f14g2000cwb.googlegroups.com> Message-ID: "Luis M. Gonzalez" wrote in message news:1103585080.635393.220070 at f14g2000cwb.googlegroups.com... > Terry Reedy wrote: In response to a claim (I presume by LG and snipped by LG) that Boo is as related to Python as PyPy or Stackless, I wrote. >> but I think this is silly. The 'this' that I referred to as silly was the equality part of the claim, not that that Boo has *some* relation to Python. I tried to explain by continuing ... >> PyPy is an alternate implementation of Python, >> not a different language. Stackless is a compiled extension, like many >> others, that works with the standard implementation or maybe still a >> minor modification thereof. > you're right, but what when I say "python related", I mean that it has > something or a lot in common with python, I did not and do not dispute that Boo has some (lesser) degree of relatedness. I continued by suggesting that it was about the same as for Prothon. That there are differences in degree of relatedness was my point. Nor did I or would I claim that the lesser degree of either is so low that neither should ever mentioned here. Terry J. Reedy From Scott.Daniels at Acm.Org Thu Dec 16 09:09:03 2004 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 16 Dec 2004 06:09:03 -0800 Subject: NO REALLY In-Reply-To: References: <1102995205.949964.76020@c13g2000cwb.googlegroups.com> Message-ID: <41c195e4@nntp0.pdx.net> Martijn Faassen wrote: > It's slow and no scientific research exists in its favor! Also it > doesn't work. Why would I need polymorphism? Lisp had all of this 50 > years ago anyway. But functional programming by the way SUX TOO! So does > procedural programming! And structured programming SUX, GOTO all the way! Your insightful post here has led me to reflect that a Deterministic Finite-state Automata, the core of our initial studies of computation, while not Turing-Equivalent, is blazes fast and thoroughly understood. Such machines (DFAs) are pure GOTO machines, and therefore incredibly beautiful; a very sharp knife to cut through modern problems. This, of course, means that DJIJSTRA (there, one of the J's is right) SUX!!!!!!! From ville at spammers.com Thu Dec 2 08:56:49 2004 From: ville at spammers.com (Ville Vainio) Date: 02 Dec 2004 15:56:49 +0200 Subject: Semaphore or what should I use? References: <41aef9ea$0$18874$636a15ce@news.free.fr> Message-ID: >>>>> "Sergei" == Sergei Organov writes: Sergei> My answer to OP's question is: use either lock (mutex) or Sergei> semaphore. I'd probably use semaphore as mutexes are Sergei> usually optimized for the case when contention probability Sergei> is low (i.e., they usually shouldn't be locked for a long Sergei> time). Both Mutexes and Semaphores put the thread to sleep, so I don't think there will be a big difference. The OP might also want to check out read/write lock. The first thing google finds is http://www.majid.info/mylos/weblog/2004/11/04-1.html -- Ville Vainio http://tinyurl.com/2prnb From maitj at vianet.ca Wed Dec 15 10:28:24 2004 From: maitj at vianet.ca (Jeffrey Maitland) Date: Wed, 15 Dec 2004 10:28:24 -0500 Subject: Data problem Message-ID: <000001c4e2ba$b8d92710$4602a8c0@jeffz41xard8mu> Hello all, I am using the MySQLdb module and I am writing to a MySQL database. My write statement is something like. cursor.execute("INSERT INTO Data(Name, X, Y, Z, Data) VALUES('%s', '%s', '%s', '%f', '%f', '%f', '%s')""" % (name, high_x, high_y, high_z, data)) I can write the data to a file as a check and all variables are showing correctly. However when I extract the data from the database the X, Y are not coming out with the same number that "should be going" into the database but the Z is. Any Ideas? Example data going in and out. IN. Name = test X = 34.523 Y = -123.2432 Z = -123.2346 Data = "This is test data" OUT Name = test X = 34.0 Y = -123.0 Z = -123.2346 Data = "This is test data" That's is what is going in and coming out. *Note this is an example of the data not actual data or code (Although the difference is the amount of data being input)" Thanks for any and all help/comments. Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: From donnal at donnal.net Mon Dec 6 12:40:01 2004 From: donnal at donnal.net (Donnal Walter) Date: Mon, 06 Dec 2004 11:40:01 -0600 Subject: using cmd.exe as a telnet client In-Reply-To: <41b0ed7e$0$85066$a1866201@visi.com> References: <41b0ed7e$0$85066$a1866201@visi.com> Message-ID: <41B49971.2010107@donnal.net> Grant Edwards wrote: > You don't have to start from scratch. The telnet module has > hooks built-into it1 so that you can have it call your routines > to handle option negotiation. I did it once to impliment some > extra Telnet protocol features, and it wasn't difficult. Ok, you've inspired me to give it a try. First, I am assuming that you mean writing a custom callback function to send to Telnet.set_option_negotiation_callback(callback). Or did you mean writing a subclass of Telnet? Can someone provide an example of a callback function that I might use as a template for writing mine? This is unfamiliar territory for me, but I tried to snoop a bit using ethereal (also new to me) and as near as I can tell, the options in question are: 0, binary transmission 1, echo 3, suppress go ahead 23, send location And it may be that not all of these are critical, but if so, I don't know how to tell which is which. Eyal Lotem wrote: > I think I have a much simpler solution for you guys.. > Assuming you can run arbitrary code on the proprietary > server. Actually I cannot. The server runs a second-party information system, the primary access to which is third-party terminal emulator software that uses telnet connections. What I am trying to do is emulate this emulator. :-) > cmd.exe is not a command line program. It's a terminal (emulator). > You might be able to use the telnet program, though. Yes, I see that now. Thanks. > Before doing this, > I'd recommend looking at Twisted's telnet support (both > the version in 1.3 and the version that will be in 2.0), > which actually supports option negotiation in a > reasonable way. I've been wanting to get acquainted with Twisted for awhile now, so this might be a good time to do so. I think I will give Grant's idea a whirl, but if I get bogged down there, I will definitely look at Twisted's telnet support. BTW, do you know if Twisted's option negotiation uses a callback function? I might download it just to take a look, even if I don't use it directly. Thanks, Donnal Walter Arkansas Children's Hospital From fperez528 at yahoo.com Thu Dec 16 19:35:22 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Thu, 16 Dec 2004 17:35:22 -0700 Subject: Adding paths to sys.path permanently, and another problem... References: Message-ID: Amir Dekel wrote: > Hi everyone, > > I have two problems: > > 1. How can I keep my changes in sys.path after closing the interpreter? As others said, use $PYTHONPATH > 2. os.path.expanduser("~") always gives me "C:\\" instead of my > homepath. I have tried to change my homepath in WinXP using set > homepath(in command line), and alsaw using the "Environment Variables" > in WinXP system properties, non helped. I really have to fix this somehow. This is what ipython uses to try and get that information in a portable manner. Note that it uses _winreg, which is part of the win32 extensions. In [1]: import IPython.genutils In [2]: psource IPython.genutils.get_home_dir def get_home_dir(): """Return the closest possible equivalent to a 'home' directory. For Posix systems, this is $HOME, and on NT it's $HOMEDRIVE\$HOMEPATH. Currently only Posix and NT are implemented, a HomeDirError exception is raised for all other OSes. """ #' if os.name == 'posix': return os.environ['HOME'] elif os.name == 'nt': # For some strange reason, win9x returns 'nt' for os.name. try: return os.path.join(os.environ['HOMEDRIVE'],os.environ['HOMEPATH']) except: try: # Use the registry to get the 'My Documents' folder. import _winreg as wreg key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders") homedir = wreg.QueryValueEx(key,'Personal')[0] key.Close() return homedir except: return 'C:\\' elif os.name == 'dos': # Desperate, may do absurd things in classic MacOS. May work under DOS. return 'C:\\' else: raise HomeDirError,'support for your operating system not implemented.' HTH, f From gandalf at geochemsource.com Tue Dec 7 12:36:13 2004 From: gandalf at geochemsource.com (Laszlo Zsolt Nagy) Date: Tue, 7 Dec 2004 18:36:13 +0100 Subject: httpconnection class handle 302 redirect? In-Reply-To: <00b401c4dc07$92253410$7f00a8c0@scl01.siliconcreation.com> References: <00b401c4dc07$92253410$7f00a8c0@scl01.siliconcreation.com> Message-ID: <455229093.20041207183613@geochemsource.com> Hello Joe, Tuesday, December 7, 2004, 3:50:53 AM, you wrote: > Hi , it looks like that HTTPConnection class is not capable to > handle 302 redirect response. Is there any sample implementation > that tackle this problem? I am using python 2.3.3 on Windows > platform. I'm using this method (inside a class). It works fine for me: def getconnection(self,url,handle_redirects=True,headers={}): """Get a httplib connection for the given url. @param url: Should be a relative path for the HTTP request. @type url: string @param handle_redirects: Set this to True if you want to follow redirects (301 and 302). (default) @return: The httplib connection for the specified (or redirected) url.""" if url.upper()[:6] == 'HTTPS:': conn = httplib.HTTPSConnection(self.host) else: conn = httplib.HTTPConnection(self.host) conn.connect() if not headers.has_key("User-Agent"): headers["User-Agent"] = self.agent if handle_redirects: # Now we handle 301 and 302 too! conn.request("HEAD", url,headers=headers) responseOb = conn.getresponse() ## Grab HTTPResponse Object if responseOb.status in (301,302,): url = urlparse.urljoin(url, responseOb.getheader('location', '')) conn = self.getconnection(url,True) return conn I hope this helps. -- Best regards, Laszlo mailto:gandalf at geochemsource.com web: http://designasign.biz From jimhill at swcp.com Mon Dec 20 00:50:30 2004 From: jimhill at swcp.com (Jim Hill) Date: Mon, 20 Dec 2004 05:50:30 +0000 (UTC) Subject: Easy "here documents" ?? References: Message-ID: Nick Craig-Wood wrote: >Jim Hill wrote: >> Is there a way to produce a very long multiline string of output with >> variables' values inserted without having to resort to this wacky >> """v = %s"""%(variable) >I prefer this > > ... I'll have %(amount)s %(what)s > ... for $%(cost)s please""" % locals() Looks pretty slick. This might just be what I need. >Its almost as neat as perl / shell here documents and emacs parses """ >strings properly too ;-) Mmm...emacs... Thanks for the tip. Jim -- "I regard NASCAR the same way I regard gay porn: I know it exists and I know some guys like it; I just don't want to see it." -- Z. B. Goode From Norbert.Klamann at klamann-software.de Wed Dec 22 08:02:40 2004 From: Norbert.Klamann at klamann-software.de (Norbert) Date: 22 Dec 2004 05:02:40 -0800 Subject: Threading Problem References: <1103715496.971145.215260@z14g2000cwz.googlegroups.com> Message-ID: <1103720560.440004.234830@z14g2000cwz.googlegroups.com> Thanks Alan, i hoped it would be something trivial :) Norbert From aleaxit at yahoo.com Mon Dec 27 13:48:13 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Mon, 27 Dec 2004 19:48:13 +0100 Subject: Python 3000, zip, *args and iterators References: <3yGzd.289258$HA.962@attbi_s01> <1104171069.929732.69810@z14g2000cwz.googlegroups.com> Message-ID: <1gpgxdn.j79cd2srgirkN%aleaxit@yahoo.com> Raymond Hettinger wrote: ... > "Not everything that can be done, should be done." Or, to quote Scripture...: "'Everything is permissible for me' -- but not everything is beneficial" (1 Cor 6:12)... Alex From ishwor.gurung at gmail.com Sat Dec 4 11:25:06 2004 From: ishwor.gurung at gmail.com (Ishwor) Date: Sat, 4 Dec 2004 21:25:06 +0500 Subject: os.listdir("\\\\delta\\public") Message-ID: <34534aed04120408251e39ac47@mail.gmail.com> hi check your seperator variable in the os module. :) for example >>> import os >>> os.sep '\\' Now what you do is :- >> os.listdir("D:" + os.sep + "any_other_folder_name" + os.sep); :) Have a look at the error below which is same as yours. The seperator variable is put after the drive name and not before the drive name. >>> os.listdir("\\c"); Traceback (most recent call last): File "", line 1, in -toplevel- os.listdir("\\c"); WindowsError: [Errno 3] The system cannot find the path specified: '\\c/*.*' In Linux this would be somewhat like this >>> os.listdir("/dev"); In general use the most platform independent variable names (e.g os.sep) unless you intend the program to be used only by yourself. :) [snip] -- cheers, Ishwor Gurung From tom at dtsam.com Thu Dec 16 09:16:15 2004 From: tom at dtsam.com (Thomas Bartkus) Date: Thu, 16 Dec 2004 08:16:15 -0600 Subject: why not arrays? References: <1103205078.423240.297790@f14g2000cwb.googlegroups.com> Message-ID: Because the "list" object covers all the functionality contained in the traditional "array" structure. If it pleases you , you can ignore the additional conveniences the list object offers and just treat it like an ordinary array. Unless, of course, what you are seeking are the joys associated with memory allocation/deallocation :-) Thomas Bartkus "Rahul" wrote in message news:1103205078.423240.297790 at f14g2000cwb.googlegroups.com... > Hi. > I just wanted to know why arrays have not been included as a builtin > datatype like lists or dictionaries? The numpy extension shows that it > can be implemented. then why not include arrays in core python? > rahul > From fperez528 at yahoo.com Mon Dec 13 16:39:43 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Mon, 13 Dec 2004 14:39:43 -0700 Subject: ANN: IPython 0.6.5 is out. Message-ID: Hi all, I'm glad to announce the release of IPython 0.6.6. IPython's homepage is at: http://ipython.scipy.org and downloads are at: http://ipython.scipy.org/dist I've provided RPMs (Py2.2 and 2.3), plus source downloads (.tar.gz and .zip). Debian, Fink and BSD packages for this version should be coming soon, as the respective maintainers (many thanks to Jack Moffit, Andrea Riciputi and Dryice Liu) have the time to follow their packaging procedures. Many thanks to Enthought for their continued hosting support for IPython, and to all the users who contributed ideas, fixes and reports. Release notes ------------- This release was made to fix a few crashes recently found by users, and also to keep compatibility with matplotlib, whose internal namespace structure was recently changed. * Adapt to matplotlib's new name convention, where the matlab-compatible module is called pylab instead of matlab. The change should be transparent to all users, so ipython 0.6.6 will work both with existing matplotlib versions (which use the matlab name) and the new versions (which will use pylab instead). * Don't crash if pylab users have a non-threaded pygtk and they attempt to use the GTK backends. Instead, print a decent error message and suggest a few alternatives. * Improved printing of docstrings for classes and instances. Now, class, constructor and instance-specific docstrings are properly distinguished and all printed. This should provide better functionality for matplotlib.pylab users, since matplotlib relies heavily on class/instance docstrings for end-user information. * New timing functionality added to %run. '%run -t prog' will time the execution of prog.py. Not as fancy as python's timeit.py, but quick and easy to use. You can optionally ask for multiple runs. * Improved (and faster) verbose exeptions, with proper reporting of dotted variable names (this had been broken since ipython's beginnings). * The IPython.genutils.timing() interface changed, now the repetition number is not a parameter anymore, fixed to 1 (the most common case). timings() remains unchanged for multiple repetitions. * Added ipalias() similar to ipmagic(), and simplified their interface. They now take a single string argument, identical to what you'd type at the ipython command line. These provide access to aliases and magics through a python function call, for use in nested python code (the special alias/magic syntax only works on single lines of input). * Fix an obscure crash with recursively embedded ipythons at the command line. * Other minor fixes and cleanups, both to code and documentation. The NEWS file can be found at http://ipython.scipy.org/NEWS, and the full ChangeLog at http://ipython.scipy.org/ChangeLog. Enjoy, and as usual please report any problems. Regards, Fernando. From ncoghlan at iinet.net.au Tue Dec 7 04:51:35 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 07 Dec 2004 19:51:35 +1000 Subject: long number multiplication In-Reply-To: References: Message-ID: <41B57D27.8070806@iinet.net.au> Christopher A. Craig wrote: >>i needed to implement this myself and was thinking of storing the digits >>of an integer in a list. > > > That's sort of what Python does except the "digits" are 15 bits, > not base 10. Doing it in base 10 would be a huge pain because of the > problems with base 10->base 2 conversion. > Indeed. Python's Decimal data type stores the digits in a list for ease of power of 10 multiplication & rounding (the precision rules means a *lot* of that goes on). However, it converts that list of digits to a long integer in order to do addition, multiplication or division. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From FBatista at uniFON.com.ar Fri Dec 24 08:43:35 2004 From: FBatista at uniFON.com.ar (Batista, Facundo) Date: Fri, 24 Dec 2004 10:43:35 -0300 Subject: FutureWarning Message-ID: [Egor Bolonev] #- ================= #- C:\Documents and Settings\+???\My #- Documents\Scripts\octopus_eye\1\oct_eye_db.py: #- 213: FutureWarning: hex()/oct() of negative int will return #- a signed #- string in P #- ython 2.4 and up #- if hex(binascii.crc32(data))[0] == '-': #- ================= #- hex() will return numbers like -0xa1? Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 ... >>> hex(-3) '-0x3' >>> . Facundo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ADVERTENCIA. La informacion contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informacion confidencial o propietaria, cuya divulgacion es sancionada por la ley. Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no esta autorizado a divulgar, copiar, distribuir o retener informacion (o parte de ella) contenida en este mensaje. Por favor notifiquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnetico) que pueda haber realizado del mismo. Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefonica Comunicaciones Personales S.A. o alguna empresa asociada. Los mensajes electronicos pueden ser alterados, motivo por el cual Telefonica Comunicaciones Personales S.A. no aceptara ninguna obligacion cualquiera sea el resultante de este mensaje. Muchas Gracias. -------------- next part -------------- An HTML attachment was scrubbed... URL: From michael.dehaan at gmail.com Fri Dec 17 16:20:06 2004 From: michael.dehaan at gmail.com (Michael DeHaan) Date: Fri, 17 Dec 2004 16:20:06 -0500 Subject: better lambda support in the future? In-Reply-To: References: Message-ID: <838ec8ff041217132053bd24a1@mail.gmail.com> True enough, but suppose you want a hash of anonymous functions as opposed to just a lexical? This is where lambas are nice to have. Totally agreed about a small use here and there, but they do have some use in dispatch tables, as they are a lot easier to read sometimes than very long case statements. Of course, this would require multi-line lambdas to exist... --Michael > I assume that the point you were trying to make is that: > > def f(*args): > return expr > > is equivalent to > > f = lambda *args: expr > > ? > > Steve > -- > http://mail.python.org/mailman/listinfo/python-list > From cold_fusion at fastmail.fm Thu Dec 23 14:59:28 2004 From: cold_fusion at fastmail.fm (Avi Berkovich) Date: Thu, 23 Dec 2004 21:59:28 +0200 Subject: Python Interactive Shell - outputting to stdout? Message-ID: <41cb23ff@news.012.net.il> Hello, I was unable to use popen2.popen4 to grab python.exe's (2.3) output, for starts, it doesn't show the version information at the beginning and won't return anything when writing to the stdin pipe, it seems that if I give it some error nous expression, the pipe would return the exception data, though nothing else comes through. A friend of mine also tried this using win32api on delphi, and got the same result. I also tried "python.exe > data.txt" and was amazed to find out that it won't redirect the output to the file. So, may someone please shed some light over this? Avi. From luismgz at gmail.com Tue Dec 21 12:11:47 2004 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 21 Dec 2004 09:11:47 -0800 Subject: newbie question References: <3e8ca5c804122020157b89fb9b@mail.gmail.com> <1103637612.657658.67350@f14g2000cwb.googlegroups.com> Message-ID: <1103649107.229634.129700@c13g2000cwb.googlegroups.com> Peter, Thank you for taking the time to reply in such a detailed and polite way. I'm satisfied by your last post and, although I beg to disagree in a few points, I'm glad to see that we are all slowly going back to a civil way of expressing ourselves. Regarding my first post in this thread, I hope I didn't offend you. I just wanted to point out that there were some attitudes from you and from others that, in my oppinion, were a little bit too harsh. Sometimes it seems that instead of replying, you are making absolute statements intended to disqualify other people's oppinions, leaving no place for a continuing discussion of these matters. But I want to say that I recognize your labor here when it comes to help newbies and the time you spend in this list particicipating and contributing. And I also recognize that you are capable of "slowing down" and make your thoughts clear. As for your comment about Boo: > Boo is not Python related. It's that simple. Boo has some > passing resemblance to Python, and claims that it's much > more than that are patently false. And clearly designed > to be marketing propaganda to get more Boo users onboard Perhaps I don't measure that relativity with the same ruler, but as far as I could see when playing with Boo, it is very similar to Python. Anyway, I don't want to appear as a promoter or evangelist of Boo, I'm just someone who tested it and liked it. Also, you should consider that, preferences aside, there might be pythonistas in situations where they are forced to work with Microsoft technologies, and since programmers use tools (and we are discussing about tools here, not religions) I think it's pertinent to discuss it here. Amyway, I wouldn't want to use this list to talk about Boo, because I think that the best place to do it is comp.lang.boo. However, since I think it is definetely python related (I know you disagree, but others don't) I see no harm in mentioning it here occasionally. regards, Luis From jepler at unpythonic.net Fri Dec 24 09:40:56 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Fri, 24 Dec 2004 08:40:56 -0600 Subject: character set gobbledy-gook ascii translation ... In-Reply-To: References: Message-ID: <20041224144055.GA17166@unpythonic.net> >>> email.Header.decode_header("=?us-ascii?Q?Re=3A=20=5Bosg=2Duser=5D=20Culling=20problem?=") [('Re: [osg-user] Culling problem', 'us-ascii')] >>> email.Header.decode_header("=?gb2312?B?cXVlc3Rpb24gYWJvdXQgbG9hZGluZyBmbHQgbGFyZ2UgdGVycmFpbiA=?=") [('question about loading flt large terrain ', 'gb2312')] >>> help(email.Header.decode_header) Help on function decode_header: decode_header(header) Decode a message header value without converting charset. Returns a list of (decoded_string, charset) pairs containing each of the decoded parts of the header. Charset is None for non-encoded parts of the header, otherwise a lower-case string containing the name of the character set specified in the encoded string. An email.Errors.HeaderParseError may be raised when certain decoding error occurs (e.g. a base64 decoding exception). Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jeff at ccvcorp.com Fri Dec 17 20:24:59 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri, 17 Dec 2004 17:24:59 -0800 Subject: better lambda support in the future? In-Reply-To: References: <10s6qnfd172kuaf@corp.supernews.com> Message-ID: <10s71g62jiq0572@corp.supernews.com> Steven Bethard wrote: > Jeff Shannon wrote: > >> It occurs to me that, in a statically compiled language, function >> definitions all happen before the program starts, and thus that >> definition can't be affected by other variables (i.e. an outer >> function's parameters). > > > I think you might be confusing static compilation in a language with > lack of first-class functions in a language. Hm, possibly. I must confess that my direct knowledge is limited to a fairly narrow set of languages, and that C and C++ are the only statically-compiled languages I've used. Still, I'm not sure that it's just a matter of functions as first-class objects. Would OCaml (or some other static language) have something that's equivalent to this? def f(x): if x < 0: def g(y): return y * -1 else: def g(y): return y return g foo = f(1) Here, nested scopes are not enough. Only one of these functions is created, and which one that is depends on the run-time value of the function parameter. A compiler couldn't know this ahead of time. I suppose it might be able to do something by compiling both of them, (though I'm not sure how it'd track two different functions with the same name in the same namespace...) but that seems a bit questionable to me... Jeff Shannon Technician/Programmer Credit International From sjmachin at lexicon.net Sun Dec 12 14:55:09 2004 From: sjmachin at lexicon.net (John Machin) Date: 12 Dec 2004 11:55:09 -0800 Subject: newbie questions In-Reply-To: References: <1102799372.430347.308070@c13g2000cwb.googlegroups.com> Message-ID: <1102881309.523012.133440@z14g2000cwz.googlegroups.com> Fredrik Lundh wrote: > John Machin wrote: > > >> Of course, in this simple case, I wouldn't be likely to write the clear > >> function since the inline code is simpler and has less overhead: > >> > >> def main() > >> var1 = [] > >> var1.append('a') > >> var1[:] = [] > > > > Even less overhead: del var1[:] > > even less overhead: > > var1 = [] Firstly, your replacement is not functionally equivalent. Secondly, it appears *NOT* to have less overhead: >python -m timeit "a=range(100); del a[:]" 100000 loops, best of 3: 3.56 usec per loop >python -m timeit "a=range(100); a=[]" 100000 loops, best of 3: 3.95 usec per loop >python -m timeit "a=range(1000); del a[:]" 10000 loops, best of 3: 25.3 usec per loop >python -m timeit "a=range(1000); a=[]" 10000 loops, best of 3: 33.1 usec per loop [Python 2.4; Windows 2000; Athlon 1.4Ghz chip] > > (if you rely on having multiple references to the same list, instead of referring > to the list by name, you may want to reconsider the design) > Indeed. The OP's insistence on emptying the container instead of trashing it along with its contents -- which is my interpretation of "it doesn't emty my var (i don't want to destroy the var, just make it like if it just have been created" -- was intriguing but not explained ... From ebonakDUH at hotmail.com Sun Dec 12 20:52:58 2004 From: ebonakDUH at hotmail.com (Esmail Bonakdarian) Date: Sun, 12 Dec 2004 20:52:58 -0500 Subject: uptime for Win XP? In-Reply-To: <41bbf3ed.402329108@news.oz.net> References: <10rmr8ksbhlq341@corp.supernews.com> <41bbf3ed.402329108@news.oz.net> Message-ID: <10rptfrhqad7253@corp.supernews.com> Bengt Richter wrote: > >>> import os > >>> [x for x in os.popen('pstat') if 'uptime' in x.lower()] > ['Pstat version 0.3: memory: 327080 kb uptime: 4 15:44:16.696 \n'] > > That is, if pstat.exe is on your system and path. It comes with various sdk's > and Visual studio stuff. Check tools subdirectory under the latter. Wow, one more way, I have VS .NET installed, I'll look for it. Thanks! Esmail > Pstat prints a snapshot of pmon plus drivers info which means info about every process > and thread running as well as drivers loaded, so the above threw away a lot of lines to get the one: > > [23:38] C:\pywk\clp>pstat|wc > 442 3350 27404 > > ;-) > There's got to be something leaner though. > > Regards, > Bengt Richter From bokr at oz.net Mon Dec 27 04:14:15 2004 From: bokr at oz.net (Bengt Richter) Date: Mon, 27 Dec 2004 09:14:15 GMT Subject: Unicode entries on sys.path References: <41CB0D7A.3080107@v.loewis.de> Message-ID: <41cfca37.1149334916@news.oz.net> On Thu, 23 Dec 2004 19:24:58 +0100, =?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?= wrote: >Thomas Heller wrote: >> It seems that Python itself converts unicode entries in sys.path to >> normal strings using windows default conversion rules - is this a >> problem that I can fix by changing some regional setting on my machine? > >You can set the system code page on the third tab on the XP >regional settings (character set for non-unicode applications). >This, of course, assumes that there is a character set that supports >all directories in sys.path. If you have Japanese characters on >sys.path, you certainly need to set the system locale to Japanese >(is that CP932?). > >Changing this setting requires a reboot. > >> Hm, maybe more a windows question than a python question... > >The real question here is: why does Python not support arbitrary >Unicode strings on sys.path? It could, in principle, atleast on >Windows NT+ (and also on OSX). Patches are welcome. > What about removable drives? And mountable multiple file system types? Maybe some collections of potentially homogenous file system references such as sys.path need to be virtualized to carry relevant file system encoding and protocol info etc. That could cover synthetic or compressed info sources too, IWT. Homogeneous package representation could be a similar problem, I guess. Regards, Bengt Richter From michaels at rd.bbc.co.uk Wed Dec 22 09:24:55 2004 From: michaels at rd.bbc.co.uk (Michael Sparks) Date: Wed, 22 Dec 2004 14:24:55 +0000 Subject: Kamaelia Released Message-ID: Hi, I've already posted an announcement in comp.lang.python.announce about this, but for those who were at Europython and remember me giving a lightning talk on Kamaelia who don't read c.l.p.a - this is just a quick note to say that we've been given the go ahead to release it as open source and that it's now on sourceforge here: * http://kamaelia.sourceforge.net/ Essentially the bottom line idea is it's designed as a testbed platform for building network servers, and specifically new protocols. The reason for not using twisted is to try an alternate approach is to see whether an alternate approach has any benefits. (twisted is a better option if you just want something scalable in python right now of course!) The approach we've taken for concurrency is essentially lots of small components communicating in CSP/Occam like manner. Each component is a python generator, with extra attributes inboxes/outboxes which act as queues/buffers. Interesting systems are then composed by linking outboxes to inboxes allowing data to flow through the system. For the moment the code is only available via anonymous CVS checkout, but we'll probably start having nightly CVS snapshots at some point soon. Merry Christmas, Michael. -- Michael.Sparks at rd.bbc.co.uk British Broadcasting Corporation, Research and Development Kingswood Warren, Surrey KT20 6NP This message (and any attachments) may contain personal views which are not the views of the BBC unless specifically stated. From pdemb at illx.org Fri Dec 31 07:31:18 2004 From: pdemb at illx.org (Peter Dembinski) Date: Fri, 31 Dec 2004 13:31:18 +0100 Subject: Python + Lisp integration? References: Message-ID: <87is6imyy1.fsf@hector.domek> Simo Melenius writes: > Hi, > > I'm wondering (after a bit of googling) whether there exists > a Python binding to any open source Lisp environment (like librep > or some Scheme or Common Lisp implementation) that could > be recommended for non-toy use? Dunno about non-toy uses, but if you want program your emacs with Python, there is pymacs available :) From itsme at yahoo.com Tue Dec 28 14:59:01 2004 From: itsme at yahoo.com (It's me) Date: Tue, 28 Dec 2004 19:59:01 GMT Subject: A scoping question References: Message-ID: <9WiAd.3382$5R.125@newssvr21.news.prodigy.com> "Premshree Pillai" wrote in message news:mailman.8524.1104263434.5135.python-list at python.org... > On Tue, 28 Dec 2004 19:34:36 GMT, It's me wrote: > > This must be another newbie gotchas. > > > > Consider the following silly code, let say I have the following in file1.py: > > > > #============= > > import file2 > > global myBaseClass > > myBaseClass = file2.BaseClass() > > myBaseClass.AddChild(file2.NextClass()) > > #============= > > You have declared myBaseClass to be global, but it doesn't exist. > No, myBaseClass exists in file1.py. The question is how can I tell file2.py that the global variable is in file1 (without doing a silly file1.myBaseClass.... Since I am invoking file2 from file1, I would have thought that global variables in file1 exists automatically....(too much C thinking, I know) From mefjr75 at hotmail.com Sun Dec 19 01:11:26 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 18 Dec 2004 22:11:26 -0800 Subject: Easy "here documents" ?? References: Message-ID: <1103436686.452634.34070@z14g2000cwz.googlegroups.com> I was curious so I googled , looks like a unix thing :) http://www.faqs.org/docs/abs/HTML/here-docs.html Ok I am with Peter on this , still clueless. What about string replacement. py> x = """ Hello me name is ~NAME~. \n I am ~AGE~ years old.\n ... I live in ~CITY~.\n The city of ~CITY~ is nice.\n ... I have live here for ~AGE~ years.\n ... """ py> x = x.replace('~AGE~', '12') py> x = x.replace('~NAME~', 'Jimmy') py> x = x.replace('~CITY~', 'Oma') It makes your template cleaner cause you can use what you want for the tokens, but takes more lines to do the replacements. still clueless, M.E.Farmer Peter Hansen wrote: > Jim Hill wrote: > > I've done some Googling around on this and it seems like creating a here > > document is a bit tricky with Python. Trivial via triple-quoted strings > > if there's no need for variable interpolation but requiring a long, long > > formatted arglist via (%s,%s,%s,ad infinitum) if there is. So my > > question is: > > > > Is there a way to produce a very long multiline string of output with > > variables' values inserted without having to resort to this wacky > > > > """v = %s"""%(variable) > > > > business? > > I have no idea what a "here document" is, but there are several > alternatives to the "wacky" basic substitution with a tuple of > values. > > The simplest uses a mapping type: > > mydict = {'namedVal': 666} > '''v = %(namedVal)s''' % mydict > > Does that let you build whatever a "here document" is? From has.temp2 at virgin.net Thu Dec 23 04:54:15 2004 From: has.temp2 at virgin.net (has) Date: 23 Dec 2004 01:54:15 -0800 Subject: (Mac-specific) AppScript bug In-Reply-To: References: Message-ID: <1103795655.529179.31560@f14g2000cwb.googlegroups.com> George van den Driessche wrote: > (This is really for Hamish Sanderson, I think, but I can't find an > e-mail address for him.) No worries. (Email addy is buried in appscript-0.7.1 > Manual.txt > Authors, though some releases listed a duff address which certainly didn't help. Better documentation is on my TO-DO list.) > On OS X 10.3.7, with XCode 1.5 and all the latest AppScript packages > installed, writing this: > > a = appscript.app( 'XCode.app' ) > > causes a crash in terminology.py: [...] > code is a FourCC identifying some part of XCode's script interface. You > would imagine that every such part would have either a plural name or a > singular name, but in this case somehow the FourCC '****' has ended up > in self._elements and it has neither. Any idea how that might arise? Sounds like a bug in XCode's terminology resource. I'd need to see the raw terminology to say for sure. If you want to use the osaterminology.tools.quickdoc module to dump it to text file and send if over I'll take a look. > If you change the marked line (104) to read: > > name = self._pluralClassNames.get(code, > self._singularClassNames.get(code, '____'+code)) > > then the rest of the terminology seems to run fine, and you just end up > with one bogus entry called '____****' in the app's attributes. Appscript-0.9.0 does this. Should be ready in another few days - I'll post when it's out. Buggy terminology resources are unfortunately a fairly common problem, and I'm still figuring out how best to deal with them. Welcome to the wonderful and wonky world of Mac application scripting. :p HTH and thanks, has From ncoghlan at email.com Sat Dec 4 08:32:30 2004 From: ncoghlan at email.com (Nick Coghlan) Date: Sat, 04 Dec 2004 23:32:30 +1000 Subject: help needed In-Reply-To: References: Message-ID: <41b1bc6e$0$25770$5a62ac22@per-qv1-newsreader-01.iinet.net.au> In response to your first message, I offered some ideas on how to get more useful responses, along with a couple of general techniques for finding the problem yourself. Reposting almost exactly the same message 8 or so hours later wasn't a suggestion featured in either category. Cheers, Nick. From fredrik at pythonware.com Thu Dec 16 06:15:39 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Dec 2004 12:15:39 +0100 Subject: Why are tuples immutable? References: <41BE1644.8050906@freemail.gr><7xwtviftz1.fsf@ruckus.brouhaha.com> Message-ID: Antoon Pardon wrote: > That depends on whether the programmes wants value equality > or identity equality. > > In the first case the programmer shouldn't mutate a after > it was introduced as key in the dictionary; but should > either introduce a copy or work on a copy later. As > such your snippet of code would become. > > a = [1,2,3] > d[a[:]] = 9 > a.append(4) > print d[a] > > And this would raise a KeyError, unless the list [1,2,3,4] > would be in the dictionary. > > In the second case your code would produce 9. how does the dictionary know if you want key value equality or key identity equality? From mefjr75 at hotmail.com Thu Dec 16 23:08:30 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 16 Dec 2004 20:08:30 -0800 Subject: wxPython question References: <1103248000.636562.135870@c13g2000cwb.googlegroups.com> Message-ID: <1103256510.836391.12960@z14g2000cwz.googlegroups.com> Messed up it does need the dots. This should handle bmp ico png gif and several other formats. Still need to be 32 by 32 wx.InitAllImageHandlers() image = wx.Image(file, wx.BITMAP_TYPE_ANY) image = image.ConvertToBitmap() icon = wxEmptyIcon() icon.CopyFromBitmap(image) frame.SetIcon(icon) Hth, M.E.Farmer From leknarf at pacbell.net Mon Dec 6 15:37:56 2004 From: leknarf at pacbell.net (Scott Frankel) Date: Mon, 6 Dec 2004 12:37:56 -0800 Subject: file descriptors & fdopen In-Reply-To: References: Message-ID: foo = open('foo.txt', 'w') duh. Thanks - Scott On Dec 6, 2004, at 11:27 AM, Scott Frankel wrote: > > Why does os.fdopen('foo.txt', 'w') require an integer? > Ultimately, I want to create a new file on disk. > > Funny, I can't seem to suss-out how to create a new file without > resorting > to os.system('touch foo.txt'). ... Or maybe not so funny ... > > >>> foo = os.fdopen('foo.txt', 'w') > Traceback (most recent call last): > File "", line 1, in ? > TypeError: an integer is required > > > Thanks in advance! > Scott > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From sdeibel at wingware.com Thu Dec 16 13:08:47 2004 From: sdeibel at wingware.com (sdeibel at wingware.com) Date: 16 Dec 2004 10:08:47 -0800 Subject: Python mascot proposal References: Message-ID: <1103220527.882661.40530@f14g2000cwb.googlegroups.com> Please note that to make something official, it has to be passed through the Python Software Foundation, which holds the intellectual property for Python and is responsible for trademarks associated with the language. If you're serious about doing this, you may want to email "psf at python dot org" to get information from the board of directors (I'm one of them, BTW, but I can't speak for the whole group). It would be nice to have a single strongly identifiable visual trademark for Python. There are many icons/logos that people have invented but none that's "official" and having many tends to dilute the ability to build a strong well-known visual trademark. - Stephan From johan at pulp.se Thu Dec 9 08:46:44 2004 From: johan at pulp.se (Johan Lindberg) Date: 9 Dec 2004 05:46:44 -0800 Subject: newbie question: starting external application(win)? References: <1goisj4.15nv4u21lg3h9cN%esselbach@t-online.de> Message-ID: <1102600004.004668.44770@f14g2000cwb.googlegroups.com> >The module popen2 is your friend. Or the os.spawn* methods in module os. Another (simpler IMO) way to do it is to use os.startfile. To start Notepad: >>> import os >>> os.startfile("notepad.exe") also, you can start an application from an associated file. Start MS Word with: >>> os.startfile("MyDocument.doc") /Johan Lindberg From steve at holdenweb.com Fri Dec 31 17:10:25 2004 From: steve at holdenweb.com (Steve Holden) Date: Fri, 31 Dec 2004 17:10:25 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> Message-ID: <41D5CE51.7070406@holdenweb.com> Cameron Laird wrote: > In article , > Christopher Koppler wrote: > . > . > . > >>Manager culture is still very much mired in rituals that may in one form >>or another go back to hunter-gatherer days (or maybe even further); that >>'the industry choice' is more often than not something backed by a *major* >>company is part of a ritual complex based on relations to the alpha male. >>Small companies ingratiate themselves with their perceived betters by >>using their products, even when technically far superior products would be >>available. When the 'market leader' produces a new toy, everyone who wants >>to be in his favor must use it _and_ also damn the toys available from any >>of those competing for leadership, viz. the ongoing state of cold war >>between Sun and MS and their respective worshipers. Toys that have not >>been sanctioned by the leader, or that are, even worse, de facto unknown >>to him, are met with ignorance, scorn, or even repression. >> >>[snip] >> >>>For Python a Big Thing would happen if some Major Vendor >>>embraced it as its Official Language(tm). Python language >>>itself could turn into a smoking crock the very next day, but >>>everybody who doesn't live under the rock would still be >>>writing in it. >> >>The moral is, of course, that either the Python community's alpha geeks >>need to get access to controlling interest in a *major* company (or to >>become successful enough with their own companies to register on the >>current *major* companies radar as potential competition) or as you >>say, Python needs to be embraced like Linux was. That's the way to win the >>hearts of software companies' managers. > > . > . > . > I like repeating the description which emphasizes culture > and phenotype over the rationality of business schools. > > Let me add a cautionary note, though: Big Companies, > including Oracle, Software AG, IBM, Cisco, and so on, have > adopted Tcl over and over. All of them still rely on Tcl > for crucial products. All of them also have employees who > sincerely wonder, "Tcl? Isn't that dead?" > > I offer this as a counter-example to the belief that Adop- > tion by a heavyweight necessarily results in widespread > acceptance. Indeed. This is. of course, because they adopt the technology to achieve their business goals, and couldn't make money (using their traditional business models) by promoting the technologies they themselves rely on. Would anyone undertake to give a "Hidden Technologies" talk at PyCon, outlining how this phenomenon operates against the adoption of technologies that the big boys effectively keep to themselves by keeping quiet about? Google's use of Python , while not a closely-kept a secret as Oracle's use of Tcl, certainly isn;t as well-known as it deserves to be. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From replytogroup at nospam.org Thu Dec 16 11:35:27 2004 From: replytogroup at nospam.org (Michael McGarry) Date: Thu, 16 Dec 2004 09:35:27 -0700 Subject: Redirecting stdin, stdout, and stderr to a window Message-ID: Hi, How do I redirect stdin, stdout and stderr to a window? I am using Qt for GUI. Thanks, Michael From caroundw5h at yahoo.com Thu Dec 9 20:42:21 2004 From: caroundw5h at yahoo.com (bitshadow) Date: Thu, 9 Dec 2004 20:42:21 -0500 Subject: Calling a C program from a Python Script References: <41b89738$0$11034$a1866201@visi.com> <41b8a6f9$0$9757$a1866201@visi.com> Message-ID: I think jeff gave the most succint advice as to your question. You should consider your problem carefully and decide if that is what you really need. And when in doubt consult the 'documentation.' (http://docs.python.org/ext/ext.html) -- bitshadow ------------------------------------------------------------------------ bitshadow's Profile: http://lampforums.org/member.php?userid=14 View this thread: http://lampforums.org/showthread.php?t=93122 From steve at holdenweb.com Thu Dec 30 14:05:34 2004 From: steve at holdenweb.com (Steve Holden) Date: Thu, 30 Dec 2004 14:05:34 -0500 Subject: need some help with threading module... In-Reply-To: <1104431262.457172.295520@c13g2000cwb.googlegroups.com> References: <41cf2610$0$791$8fcfb975@news.wanadoo.fr> <41cf373e$0$786$8fcfb975@news.wanadoo.fr> <1104102769.321923.4140@z14g2000cwz.googlegroups.com> <41d0515b$0$30648$8fcfb975@news.wanadoo.fr> <1104178961.065566.7660@z14g2000cwz.googlegroups.com> <41d3dc20$0$29646$8fcfb975@news.wanadoo.fr> <1104431262.457172.295520@c13g2000cwb.googlegroups.com> Message-ID: M.E.Farmer wrote: > chahnaz.ourzikene wrote: > >>Hi, >> >>I fixed the code, it runs under Linux but not under windows 0_o ??! i > > guess > >>windows and Linux do not handle threads the same way. >> >>However, i don't have the result i excpect. > > What did you expect? This is what it did on win 2000/python 2.2.3 > ######> controller waiting... 0 loops > ######> controller waiting... 1 loops > Subject : the counter is now 0 [...] > Subject : the counter is now 38 > Subject : the counter is now 39 > It seems to be what you were trying to do. > Could be the OP is using Cygwin, which won't support threading by default and will give very confusing results just-a-guess-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From phillip.watts at anvilcom.com Tue Dec 21 22:20:12 2004 From: phillip.watts at anvilcom.com (phil) Date: Tue, 21 Dec 2004 21:20:12 -0600 Subject: win32 process name Message-ID: <41C8E7EC.5060107@anvilcom.com> I need to know if a process is running. not just python.exe but python.exe myapp from win32all EnumProcesses gives me the pids, then OpenProcess(pid) gives me a handle. Then what? GetModuleFileNameEX? It requires two handles as args and I can't figure out which one is the handle from OpenProcess and what it wants for the other one and I can't find any Win32 SDK docs that help. Or if I could figure out this function, would it even give me the answer. I discovered wmi. Win32_Process returns a list of processes. then process.Name just gives me python.exe. But I could have python.exe running several times. I need to know is python.exe myapp running. In other words, the command line. This ought to be a nobrainer. But Nooo. Its Windows. Any help or ideas appreciated. Thanks. From timr at probo.com Wed Dec 1 00:18:23 2004 From: timr at probo.com (Tim Roberts) Date: Tue, 30 Nov 2004 21:18:23 -0800 Subject: ver 23 invokation on Windows References: Message-ID: "Alex Genkin" wrote: >Hi Python experts! > >With ver 22, I used to be able to invoke Python script by simply typing .py file >name on the command line. >With ver 23 it no longer works. If set up Windows file association, then the >script gets invoked, but command line arguments disappear. >Any idea what to do? Did you remember to pass the parameters when you created the file association? C:\TMP>assoc .py .py=Python.File C:\TMP>ftype Python.File Python.File=C:\Apps\Python23\python.exe "%1" %* C:\TMP> -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From fumanchu at amor.org Thu Dec 23 21:22:17 2004 From: fumanchu at amor.org (Robert Brewer) Date: Thu, 23 Dec 2004 18:22:17 -0800 Subject: Lambda going out of fashion Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3024F66@exchange.hqamor.amorhq.net> Nick Coghlan wrote: > ...rather than pushing to retain lambda for Py3K, it might > be more productive to find a better statement -> expression > translation for function definitions. Guido seems to prefer > named functions, so it would still be tough to gain his > acceptance. However, a more Pythonic syntax is the only way > I can see anonymous functions making into 3.0 > > The current best example of a statement->expression translation > is generator expressions: > > def squares(seq) > for x in seq: > yield x * x > > total = sum(squares(seq)) > > versus: > > total = sum(x * x for x in seq) > > If we consider a function definition (omitting decorators > and docstrings) we get: > > def foo(a, b, c): > return f(a) + o(b) - o(c) > > accepts_func(foo) > > What would a Pythonic 'function as expression' look like? Or simply: accepts_func( (f(a) + o(b) - o(c) for a, b, c) ) ...but that would give whomever writes the parser a headache. ;) Robert Brewer MIS Amor Ministries fumanchu at amor.org From m.h.3.9.1.without.dots.at.cam.ac.uk at example.com Fri Dec 3 05:11:48 2004 From: m.h.3.9.1.without.dots.at.cam.ac.uk at example.com (Michael Hoffman) Date: Fri, 03 Dec 2004 10:11:48 +0000 Subject: efficient intersection of lists with rounding In-Reply-To: References: Message-ID: Steven Bethard wrote: > Yeah, almost certainly since he's looking at lists 3K long. If they > were small, you never know since the list comprehension gets the C-code > speedup, while sets.Set is Python code: > > [list comprehension] > 10000 loops, best of 3: 27.5 usec per loop > > [Python 2.3 Set] > 10000 loops, best of 3: 47.7 usec per loop > > In the case given, the O(n**2) list comprehension is faster than the > O(n) set intersection. Of course, this is not likely to be true with > any reasonable sized data. But it's something worth keeping in mind. Of course if you're working with a dataset that small, it probably doesn't really matter which of these implementations you use. The exception would be if this were in an inner loop in the actual program and *were* being run 10000 times or more. -- Michael Hoffman From peter at engcorp.com Sun Dec 19 00:10:29 2004 From: peter at engcorp.com (Peter Hansen) Date: Sun, 19 Dec 2004 00:10:29 -0500 Subject: How do I define the search path for personal library In-Reply-To: <1103424166.709841.206980@f14g2000cwb.googlegroups.com> References: <1103424166.709841.206980@f14g2000cwb.googlegroups.com> Message-ID: les_ander at yahoo.com wrote: > Dear all, > i have a simple question. > Suppose I have my classes such as > myClass1.py > myClass2.py > etc > which I keep in a special folder ~/py_libs > > Now > suppose I have a program that is not in py_libs > but I want to do > import myClass1 # note: myClass1 is not in the current directory > > how can I set the search path for python so that it can > find myClass1? There are several options, including the PYTHONPATH environment variable, creating a .pth file in site-packages or somewhere (as documented in http://www.python.org/doc/2.4/lib/module-site.html), or even creating your own sitecustomize.py file (also documented in the site.py module docs). What is best depends a bit on your own environment and needs. For example, do you just want this available at the interactive prompt, or to all code you write, or to code that other users on the same system will write? -Peter From ncoghlan at iinet.net.au Thu Dec 9 03:31:00 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 09 Dec 2004 18:31:00 +1000 Subject: How do I do this? (eval() on the left hand side) In-Reply-To: References: Message-ID: <41B80D44.8000405@iinet.net.au> Peter Hansen wrote: > Nick Coghlan wrote: > >> Generally, altering the contents of the dicts returned by locals() and >> globals() is unreliable at best. > > > Nick, could you please comment on why you say this about globals()? > I've never heard of any possibility of "unreliability" in updating > globals() and, as far as I know, a large body of code exists which > does in fact rely on this -- much of mine included. ;-) As Steve pointed out, I was, well, flat out wrong. You're quite correct - it's only locals() that can cause a problem. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From d.lapasset Sat Dec 11 18:56:05 2004 From: d.lapasset (houbahop) Date: Sat, 11 Dec 2004 23:56:05 GMT Subject: newbie questions References: <41ba6511$1@nntp.zianet.com> Message-ID: "Dennis Lee Bieber" a ?crit dans le message de news: bppmr09m0s1d9cph2e7oj96gt30cq48a83 at 4ax.com... > On Sat, 11 Dec 2004 12:43:01 GMT, "houbahop" me)@chello.fr> declaimed the following in comp.lang.python: > >> Thank you everyone, but I still not understand why such a comon feature >> like >> passing parameters byref that is present in most serious programming >> languages is not possible in a clean way,here in python. >> > Well, in C, everything is also passed by value. The programmer > has to explicitly pass an "address as the value" instead of the actual > value if they want to change the contents. And, of course, the function > has to know that it is an address, and explicitly dereference the > address to gain access to the actual content value. > > Using my overworked and not quite complete example... > Hello and thank you, To be honnest I must take a moment and translate your example into french to really understand it (but I believe it's very well explained :) and I will understand) I remember at school when an unix teacher was explaining what was an UID and a GID, like if the files were two persons talking and asking each other " what's your UID?, we got the same, so, what is your GID ?", and I never had problems with UID and GID since that :D I have thinked to try to return an array of values like a function does (instead of passing many params to a sub) but didn't take the time to do it. I believe that programming in python involves to learn a kind of new phillosophy, new words too. as an exemple of this, for me a 'tuple' is related to database stuff. What I call an array seems to be called a list in python (C programmers use the word 'matrix' when talking of a two dimentionnal array, and 'vector' when talking of a one dimention array...sorry, a list :D ). Regards, Dominique. From bustamam98 at yahoo.com Sun Dec 12 13:08:03 2004 From: bustamam98 at yahoo.com (bustamam98 at yahoo.com) Date: Sun, 12 Dec 2004 10:08:03 -0800 (PST) Subject: Yahoo! Auto Response Message-ID: <20041212180910.C33F21E4010@bag.python.org> This email address is no longer valid. -------------------- Original Message: X-YahooFilteredBulk: 82.226.229.7 Authentication-Results: mta127.mail.re2.yahoo.com from=python.org; domainkeys=neutral (no sig) X-Originating-IP: [82.226.229.7] Return-Path: Received: from 82.226.229.7 (EHLO yahoo.com) (82.226.229.7) by mta127.mail.re2.yahoo.com with SMTP; Sun, 12 Dec 2004 10:08:02 -0800 From: python-list at python.org To: bustamam98 at yahoo.com Subject: Mail Delivery (failure bustamam98 at yahoo.com) Date: Sun, 12 Dec 2004 19:08:14 +0100 MIME-Version: 1.0 Content-Type: multipart/related; type="multipart/alternative"; boundary="----=_NextPart_000_001B_01C0CA80.6B015D10" X-Priority: 3 X-MSMail-Priority: Normal This is a multi-part message in MIME format. ------=_NextPart_000_001B_01C0CA80.6B015D10 Content-Type: multipart/alternative; boundary="----=_NextPart_001_001C_01C0CA80.6B015D10" ------=_NextPart_001_ _________________________________________________________ DO YOU YAHOO!? Get your free @yahoo.com address at http://mail.yahoo.com From noamr at remove.the.dot.myrea.lbox.com Thu Dec 23 18:38:07 2004 From: noamr at remove.the.dot.myrea.lbox.com (Noam Raphael) Date: Fri, 24 Dec 2004 01:38:07 +0200 Subject: How about "pure virtual methods"? In-Reply-To: <868y7ryqbh.fsf@guru.mired.org> References: <868y7ryqbh.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > Noam Raphael writes: > > >>The answer is that a subclass is guaranteed to have the same >>*interface* as the base class. And that's what matters. > > > This is false. For instance: > > class A(object): > def method(self, a): > print a > > class B(A): > def method(self, a, b): > print a, b > > B implements a different interface than A. Statically typed OO > languages either use multi-methods or disallow changing the signature > of an overridden method. > > A tool to detect such cases would probably be almost as useful as the > tool you've proposed. > > References: <34534aed041224151134aa4f4@mail.gmail.com> <20041224234701.GA1707@unpythonic.net> <41ce04a4$1@nntp0.pdx.net> <2Lozd.16203$k25.9717@attbi_s53> <1104027639.834083.246900@c13g2000cwb.googlegroups.com> Message-ID: John Machin wrote: > Ishwor wrote: > > >>i was just tinkering with it actually. ;-) >>In your command prompt just do >>Pythonwin.exe /run "C:\Python24\file\PyFiles\clear.py" > > > It's not a very good idea to store your own scripts in the PythonXY > directory -- other than tested working modules which you install in > PythonXY\lib\site-packages. > E.g. what will you do when Python 2.5 arrives? > As has been recently pointed out in another thread, the interpreter (actually, code in the "site" module) searches for a "sitecustomize" module when starting up. This is the easiest way to implement required startup behavior no matter what environment the interpreter's running in. For more information, RTFM concerning the "site" module, whose documentation includes the following: """After these path manipulations, an attempt is made to import a module named sitecustomize, which can perform arbitrary site-specific customizations. If this import fails with an ImportError exception, it is silently ignored.""" regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From luke at tatooine.planet Tue Dec 28 21:04:51 2004 From: luke at tatooine.planet (Luke Skywalker) Date: Wed, 29 Dec 2004 03:04:51 +0100 Subject: Best GUI for small-scale accounting app? References: <1104029156.889650.15220@c13g2000cwb.googlegroups.com> Message-ID: On Tue, 28 Dec 2004 20:06:57 -0500, Ed Leafe wrote: >That's where Paul and I came from, and that was our initial motivation >for deciding to develop Dabo - there wasn't a Python tool out there >that could even begin to approach what we were used to with VFP. Interesting discussion. I haven't looked at Dabo yet, but the issues that must be solved before Python is a valid alternative to proprietary solutions like Delphi or VB are: - speed where it matters (ie. no 20s load time) - good RAD (IDE and GUI designer, on par with Delphi or VB) - high-quality, varied widgets - good DB connectors - reasonable footprint (ie. no 20MB program just for a small appplication; have mercy on users stuck with P3 and dial-up) - ease of deployment and maintenance (ie. how easy is it for an application to launch some updated that will fetch updates from the web) If Dabo can do all this, it could be a great solution to all those people Delphi/VFP/VB users whether to go .Net. Luke. From ekyungchung at gmail.com Thu Dec 23 14:21:11 2004 From: ekyungchung at gmail.com (ekyungchung at gmail.com) Date: 23 Dec 2004 11:21:11 -0800 Subject: error problems for import some copora with nltk References: <1103741427.890150.237520@c13g2000cwb.googlegroups.com> <1103818492.508185.228850@f14g2000cwb.googlegroups.com> <10sm16aqgr6mjd0@corp.supernews.com> Message-ID: <1103829671.420109.117450@c13g2000cwb.googlegroups.com> Dear Jeff, Thank you, it was the numeric. After I installed the numeric library which is Numeric-23.6.win32-py2.3.exe for python 2.3.4 verson, it is working correctly. Thank you again, Kyung From mefjr75 at hotmail.com Thu Dec 23 20:13:29 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 23 Dec 2004 17:13:29 -0800 Subject: Creating Image Maps In-Reply-To: References: Message-ID: <1103850809.291231.86460@f14g2000cwb.googlegroups.com> Hello Aaron, You need to check the demo that comes with wxPython if you don't have it get it. Look under wxHtmlWindow and click the demo tab then just scroll down and there is a link to it that says IMAGEMAP. Or in other words RTFD ;) M.E.Farmer From premshree.pillai at gmail.com Tue Dec 28 14:50:24 2004 From: premshree.pillai at gmail.com (Premshree Pillai) Date: Wed, 29 Dec 2004 01:20:24 +0530 Subject: A scoping question In-Reply-To: References: Message-ID: On Tue, 28 Dec 2004 19:34:36 GMT, It's me wrote: > This must be another newbie gotchas. > > Consider the following silly code, let say I have the following in file1.py: > > #============= > import file2 > global myBaseClass > myBaseClass = file2.BaseClass() > myBaseClass.AddChild(file2.NextClass()) > #============= You have declared myBaseClass to be global, but it doesn't exist. Consider the following code: global name print name.__len__() This will return a NamError However, the following code will run just fine: global name name = "python" print name.__len__() will return 6 > > and in file2.py, I have: > > #============= > global myBaseClass > class BaseClass: > def __init__(self): > self.MyChilds = [] > ... > def AddChild(NewChild): > self.MyChilds.append(NewChild) > ... > class NextClass: > def __init__(self): > for eachChild in myBaseClass.MyChilds: # <- ERROR > ... > #============= > > When I run this, Python complains that myBaseClass is undefined in the last > line above. > > What am I doing wrong? (Yes, I know I am thinking too much in C). I > thought the global declaration would have been sufficient but it's obviously > not. > > Thanks, > > -- > http://mail.python.org/mailman/listinfo/python-list > HTH -- Premshree Pillai http://www.livejournal.com/~premshree From com-nospam at ccraig.org Mon Dec 20 13:29:35 2004 From: com-nospam at ccraig.org (Christopher A. Craig) Date: Mon, 20 Dec 2004 13:29:35 -0500 Subject: A rational proposal References: <864qik472n.fsf@guru.mired.org> Message-ID: I've been thinking about doing this for a while. cRat (http://sf.net/projects/pythonic) already meets these qualifications except that I need to add decimal support to it now that decimals are in the language. I could rewrite the existing code in Python (it's currently in C), but there are some very real performance reasons to do it in C rather than Python (i.e. I'm manipulating the internals of the numerator and denominator by hand for performance in the GCD function) -- Christopher A. Craig "I affirm brethren by the boasting in you which I have in Christ Jesus our Lord, I die daily" I Cor 15:31 (NASB) From fredrik at pythonware.com Thu Dec 16 02:07:54 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 16 Dec 2004 08:07:54 +0100 Subject: Is Python good for graphics? References: <10s1bdaj7gbin8e@corp.supernews.com> <10s1sk3291n0pe9@corp.supernews.com> Message-ID: Esmail Bonakdarian wrote: >> how about: >> >> http://vpython.org/ > > hi, > > thanks, I didn't know about that. > > do you (or anyone else) have a recommendation for 2D type > graphics? WCK, Tk's Canvas, wxPython (do they have a canvas-style widget available these days), any other self-respecting UI toolkit... but if you're going to do animations, the drawing part isn't really the hard bit -- and vpython is designed to do animations. if you want things to look pure 2D, all you have to do is to position the lights and the camera correctly... (does vpython support orthographic views out of the box? if it doesn't, that shouldn't be hard to add). From mauriceling at acm.org Sun Dec 12 19:04:21 2004 From: mauriceling at acm.org (Maurice LING) Date: Mon, 13 Dec 2004 00:04:21 GMT Subject: Best book on Python? In-Reply-To: References: <41bcc295$1@news.unimelb.edu.au> Message-ID: <41bcdc83@news.unimelb.edu.au> Michael McGarry wrote: > I have many years of programming experience and know a little bit of > Tcl. I am looking for a book to detail on the features including GUI in > a reference style. > > Thanks, > > Michael I am assuming that you do not want to venture pass the standard libraries at this moment, so in terms of GUI, Tkinter is about the only choice within the standard libraries. "Programming Python, 2nd Ed." has a good section of Tkinter and GUI development. You might want to search thru Amazon for Tkinter and find something to your satisfaction. Pass the standard libraries, there are other GUI kits like wxPython etc etc., each carries a set of online documentations. maurice From craig at postnewspapers.com.au Wed Dec 1 01:20:45 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Wed, 01 Dec 2004 14:20:45 +0800 Subject: Class methods in Python/C? [ANSWER] In-Reply-To: <41ac69f2$0$25765$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <41ac69f2$0$25765$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1101882045.7561.9.camel@albert.localnet> On Tue, 2004-11-30 at 20:39, Nick Coghlan wrote: > You probably want to look at staticmethod(). (classmethod() is slightly > different, and probably not what you want. In fact, classmethod() is practically > *never* what you want. Guido wrote it himself, and even he ended up not using it) Hmm, I've always rather favoured class methods myself. However, that's not the point - the same question can apply just as well to static methods. I know how to construct both in Python, though I rarely use static methods, only class methods. What I was after is a way to define a static method in a C extension module. I just found it - in the library reference, of course. I'd simply missed it before. For anybody else looking through the archives to answer this question later: http://docs.python.org/api/common-structs.html It turns out there are calling convention flags to specify class methods and static methods. From the docs: METH_CLASS The method will be passed the type object as the first parameter rather than an instance of the type. This is used to create class methods, similar to what is created when using the classmethod() built-in function. New in version 2.3. METH_STATIC The method will be passed NULL as the first parameter rather than an instance of the type. This is used to create static methods, similar to what is created when using the staticmethod() built-in function. New in version 2.3. Sorry for the noise everybody, I could've sworn I looked over that already. -- Craig Ringer From kingdom.lin at yeah.net Sun Dec 12 01:49:14 2004 From: kingdom.lin at yeah.net (Donnie Leen) Date: 11 Dec 2004 22:49:14 -0800 Subject: Error in msvc in building inheritance.obj to build hello.pyd In-Reply-To: <1102833607.266180.38380@z14g2000cwz.googlegroups.com> References: <1102833607.266180.38380@z14g2000cwz.googlegroups.com> Message-ID: <1102834154.221149.74790@z14g2000cwz.googlegroups.com> I use msvc 6.0 too, but my boost.python version is 1.32.0 , and i didn't get error to compile the hello.pyd with the msvc6 IDE, the hello demo from boost.python is compile with jam. would you try to use boost.python 1.32.0 if no compatible problem From daniel at dittmar.net Mon Dec 6 18:09:30 2004 From: daniel at dittmar.net (Daniel Dittmar) Date: Tue, 07 Dec 2004 00:09:30 +0100 Subject: Win32 Libs for 2.4 In-Reply-To: References: Message-ID: <31k75gF36ko9iU1@uni-berlin.de> Robin Becker wrote: >> I guess that it won't work if something malloc'ed from the MSC 6 >> runtime is free'd by the MSC 7.1 runtime. > > I thought that static .libs didn't make reference to the dll's they > need; isn't that done at load time? You're right, DLL-phobia made my thinking less than precise. The other things I could think of might not apply in this case: - Routines accessing the elements of FILE* directly. I though library designers had learned not to export this, but stdio.h still shows it and some macros from that header file might use it (a problem only if the definitions in MSC 6 and MSC 7.1 differ) - calling conventions: in the past, that was a problem mostly with functions returning structs. (Meaning caller and callee would implement it differently if they were compiled by different compilers) Daniel From deetsNOSPAM at web.de Mon Dec 20 07:49:08 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 20 Dec 2004 13:49:08 +0100 Subject: embedding: forcing an interpreter to end References: <1103519113.185910.236840@f14g2000cwb.googlegroups.com> Message-ID: Hi, > I've googled my heart out and reread the threading API countless times. > Any suggest or hints would be greatly appreciated. You might have used the wrong keywords - the subject of killable threads comes up every month once or twice, and usually is discussed to some length. There exist some solutions to this problem that use tracing [1] to forcefully terminate a thread, but these of course only work if the source of trouble is a sequence of statements, not a single blocking one. I myself had a similar problem a few days ago, and started using fork() and killing the subprocesses. Right after I implemented my little framework, I found that QThread from qt had a terminate method. Fearing my work had been uneccessary, I tried to use them - and found that not only my thread, but the whole program died when terminating the thread. That was because of omniorb beeing in an inconsistent state. Maybe you don't experience this using your code, but it certainly proved that the arguments for deprecating thread terminating methods in java and obmitting them in python seem to be valid. [ [1]http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/ace7c98ef31bbf2d/2af9df4b63a48cbc?q=python+killable+thread&_done=%2Fgroups%3Fq%3Dpython+killable+thread%26hl%3Den%26lr%3D%26ie%3DUTF-8%26c2coff%3D1%26sa%3DN%26tab%3Dwg%26&_doneTitle=Back+to+Search&&d#2af9df4b63a48cbc -- Regards, Diez B. Roggisch From jeff at ccvcorp.com Wed Dec 29 18:33:43 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed, 29 Dec 2004 15:33:43 -0800 Subject: Why tuples use parentheses ()'s instead of something else like <>'s? In-Reply-To: <10t5p4nedr06h94@news.supernews.com> References: <1104299822.394489.161500@z14g2000cwz.googlegroups.com> <41d2ce43$0$35731$a1866201@visi.com> <10t5p4nedr06h94@news.supernews.com> Message-ID: <10t6fdts6dma93d@corp.supernews.com> John Roth wrote: > > "Roy Smith" wrote in message > news:roy-BECFA1.11081829122004 at reader1.panix.com... > >> If Python had originally been invented in a unicode world, I suppose we >> wouldn't have this problem. We'd just be using guillemots for tuples >> (and have keyboards which made it easy to type them). > > > I suppose the forces of darkness will forever keep Python from > requiring utf-8 as the source encoding. If I didn't make a fetish > of trying to see the good in everybody's position, I could really > work up a dislike of the notion that you should be able to use > any old text editor for Python source. It's not so much the desire to be able to use any old text editor that keeps Python in ASCII, it's the desire to use any old *hardware*. Keyboards with guillemots are not exactly a worldwide norm, and needing to remember and type some arcane alt-keycode formula to be able to do basic scripting would be obnoxious, to say the least. Most keyboards worldwide provide decent support for the ASCII character set (though some add a few extra national characters). Perhaps things will change when a majority of the world's programmers use a non-Roman alphabet / character set, but even then there's a significant weight of historical reasons to overcome. Jeff Shannon Technician/Programmer Credit International From Pankaj.Jindal at aeroflex.com Wed Dec 22 05:27:08 2004 From: Pankaj.Jindal at aeroflex.com (Jindal, Pankaj) Date: Wed, 22 Dec 2004 10:27:08 -0000 Subject: ['ext.IsDOMString', 'ext.SplitQName'] Message-ID: <8489C4C090614142BA72740AFF56EA45040C06C8@ukslmail.riwsg.com> Hi, I am new to Python-XML programming. I am using python 2.3.4, py2exe 0.5.3, pyXML 0.8.4. While making executable by py2exe I am getting folowing warning:- The following modules appear to be missing ['ext.IsDOMString', 'ext.SplitQName'] Even after trying the option:- setup.py py2exe --includes xml.sax.drivers2.drv_pyexpat I am getting the same Warning. Please, can anybody help me out.. I will be highly obliged. Thanks and regards Pankaj Jindal **************************************************************************** Aeroflex E-Newsletter Subscribe now to receive Aeroflex newsletters. As a subscriber, you will receive all the latest Aeroflex and Racal Instruments Wireless Solutions news including upcoming products, specials and other Aeroflex related information. Sign up now for our FREE monthly newsletter http://www.aeroflex.com/aboutus/enewsletter/signup-form.cfm This email and any attached files are confidential and intended solely for the use of the individual/s or entity to whom it is addressed. If you have received this email in error please notify:- postmaster at riwsg.com Racal Instruments Wireless Solutions Limited. An AEROFLEX Company. Visit our website at:- http://www.aeroflex.com/riws/ This footnote also confirms that this email message has been swept for the presence of computer viruses. **************************************************************************** From levub137 at wi.rr.com Sat Dec 18 10:44:07 2004 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sat, 18 Dec 2004 15:44:07 GMT Subject: A rational proposal In-Reply-To: <864qik472n.fsf@guru.mired.org> References: <864qik472n.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > PEP: XXX > Title: A rational number module for Python I think it is a good idea to have rationals as part of the standard distribution but why not base this on the gmpy module (https://sourceforge.net/projects/gmpy)? That module already provides good performance. However, it does a few things that may not be good ideas. 1. Floats are converted to rationals. I think your proposal of rational to float is better. 2. Fails with a TypeError when used with a complex. Again Your proposal provides a better solution. 3. Fractional powers fail with a ValueError if the root is not exact. You do not address this in your proposal. Could silently convert to float in this case but is it better to force the user to be explicit and use the float() operation? Ray Buvel From reinhold-birkenfeld-nospam at wolke7.net Wed Dec 22 11:38:18 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Wed, 22 Dec 2004 17:38:18 +0100 Subject: [Re: newbie question] In-Reply-To: References: <3e8ca5c804122020157b89fb9b@mail.gmail.com> <1103637612.657658.67350@f14g2000cwb.googlegroups.com> Message-ID: <32tm7qF3gha75U1@individual.net> Doug Holton wrote: > Peter Hansen wrote: >> Luis M. Gonzalez wrote: >> >>> As far as I could see, everythime the word "boo" is typed, some sort of >>> censorship or plain bashing comes up, and I think this is not fair. >> >> I think doing this by defending Doug's postings, however, might weaken >> the strength of your position just a little. (Okay, I mean "a lot".) > > Flame away, Peter. > >> As a result of all the activity in the "Boo who?" thread, however, > > that you started Apart from that it is considered disrespectful to put your "opponent's" name into the subject, this flame war is biting its tail already. Reinhold -- [Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs- mitteln inkompatibel. -- Florian Diesch in dcoulm From insert at spam.here Tue Dec 21 11:52:29 2004 From: insert at spam.here (Doug Holton) Date: Tue, 21 Dec 2004 10:52:29 -0600 Subject: What is on-topic for the python list [was "Re: BASIC vs Python"] In-Reply-To: <87ekhjob6s.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> References: <41C342A0.3040700@users.ch> <86sm64tzax.fsf@guru.mired.org> <87ekhjob6s.fsf@localhost.localdomain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: Nick Vargish wrote: > Doug Holton writes: > > >>If you can't accept free speech and different perspectives, you're >>going to be disappointed. But please do not react by trying to >>intimidate and troll others here. > > > Weren't you the one telling the rest of us what's appropriate for this > group? Maybe you should try to lead by example, not decree. I never did any such thing. Logo was my example. I was making a point in the logo example, which Steve Holden articulated. Hans Nowak and others were the ones unsuccessfully trying to control what people could talk about here. From gh at ghaering.de Fri Dec 3 03:40:22 2004 From: gh at ghaering.de (Gerhard Haering) Date: Fri, 3 Dec 2004 09:40:22 +0100 Subject: PySQLLite Speed In-Reply-To: <20041203043931.89302.qmail@web14007.mail.yahoo.com> References: <20041203043931.89302.qmail@web14007.mail.yahoo.com> Message-ID: <20041203084022.GB7595@mylene.ghaering.de> On Thu, Dec 02, 2004 at 08:39:31PM -0800, Kevin wrote: > Hello All, > > I wanted to thank Roger Binn for his email. He had > the answer to my issue with writing speed. It's > actual made an incredible change in the preformace. I > didn't have to go all the way to implementing the > synchronous mode(for my app). Previously, I was > insert one record at a time. The key was to write > them all at one time. I moved up to a 13 meg file and > wrote it to the db in secs. Now the issue is the 120 > meg of RAM consumed by PyParse to read in a 13 meg > file. If anyone has thoughts on that, it would be > great. Otherwise, I will repost under a more specific > email. > > Thanks, > Kevin > > > > db.execute("begin") > > while i < TriNum > db.execute("""insert into TABLE(V1_x) > values(%f),""" (data[i])) > i = i + 1 If you're using pysqlite 2.0alpha, then .executemany() will boost performance *a lot*. For pysqlite 1.x, unfortunately, it won't make any difference. But generally, .executemany() is a good idea. Also note that the preferred way of using transactions is to let the DB-API adapter BEGIN the connection for you, then invoke .commit() on the connection object. Sending BEGIN/ROLLBACK/COMMIT via .execute() is bad. -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From danb_83 at yahoo.com Sun Dec 12 20:59:25 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 12 Dec 2004 17:59:25 -0800 Subject: while 1 vs while True References: Message-ID: <1102903165.589419.323000@z14g2000cwz.googlegroups.com> Timothy Fitz wrote: > [ http://www.python.org/moin/PythonSpeed ] > "Starting with Py2.3, the interpreter optimizes 'while 1' to just a > single jump. In contrast "while True" takes several more steps. While > the latter is preferred for clarity, time-critical code should use the > first form." > > Out of pure curiousity, > Why wasn't 'While True' optimized also? Probably has something to do with "True" and "False" not being constants. >>> True = 0 >>> while True: ... print 'Not an infinite loop. In fact, it never executes at all.' From mefjr75 at hotmail.com Sun Dec 19 22:26:04 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 19 Dec 2004 19:26:04 -0800 Subject: input record seperator (equivalent of "$|" of perl) References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> <1103501833.632076.74050@f14g2000cwb.googlegroups.com> <1103504587.796518.245030@f14g2000cwb.googlegroups.com> <41c6386e$1@nntp0.pdx.net> Message-ID: <1103513164.450101.12860@c13g2000cwb.googlegroups.com> Yea I should have mentioned I am running python 2.2.2. Can it be ported to python 2.2.2? Till they get python 2.4 all up and running....I'll wait a bit. Thanks for the info, M.E.Farmer Scott David Daniels wrote: > M.E.Farmer wrote: > > I dont have itertools yet. That module looks like it rocks. > > thanks for the pointers, > > M.E.Farmer > > > > If you have python 2.3 or 2.4, you have itertools. > > > --Scott David Danies > Scott.Daniels at Acm.Org From max at alcyone.com Tue Dec 7 16:23:59 2004 From: max at alcyone.com (Erik Max Francis) Date: Tue, 07 Dec 2004 13:23:59 -0800 Subject: How do I do this? (eval() on the left hand side) In-Reply-To: References: Message-ID: <6uSdncRvMKztgivcRVn-sg@speakeasy.net> It's me wrote: > In REXX, for instance, one can do a: > > interpret y' = 4' > > Since y contains a, then the above statement amongs to: > > a = 4 The direct equivalent in Python would be a = 3 y = 'a' exec '%s = 4' % y The better question would be whether or not this as useful as one might thing in Python; if you find yourself doing this, often there are better ways to accomplish the same thing, such as using dictionaries. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis But the system has no wisdom / The Devil split us in pairs -- Public Enemy From bob_smith_17280 at hotmail.com Mon Dec 20 11:47:32 2004 From: bob_smith_17280 at hotmail.com (bob_smith_17280 at hotmail.com) Date: 20 Dec 2004 08:47:32 -0800 Subject: List limits Message-ID: <1103561252.512434.143870@z14g2000cwz.googlegroups.com> How many items can be stored in a Python list? I have close to 70,000 items... is this within a lists limits? From ncoghlan at email.com Sat Dec 4 20:19:09 2004 From: ncoghlan at email.com (Nick Coghlan) Date: Sun, 05 Dec 2004 11:19:09 +1000 Subject: assymetry between a == b and a.__eq__(b) In-Reply-To: References: <9YNsBls/K7gH089yn@the-wire.com> Message-ID: <41b2620e$0$25765$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Peter Otten wrote: > Tim Peters wrote: > > >>See the Python (language, not library) reference manual, section 3.3.8 >>("Coercion rules"), bullet point starting with: >> >> Exception to the previous item: if the left operand is an >> instance of a built-in type or a new-style class, and the right >> operand is an instance of a proper subclass of that type or >> class, ... > > > So that is settled then. Not the most likely place to investigate when one > has just read that "Arguments to rich comparison methods are never coerced" > in 3.3.1 ("Basic customization"), though. Nothing is getting coerced. It's just that "A binop B" gets translated to a method call differently depending on the types of A and B. The options being: A.__binop__(B) # 1 - the usual case B.__binop__(A) # 2.1 - commutative op, and B is a proper subclass of A B.__rbinop__(A) # 2.2 - possibly non-commutative op, and B is a proper subclass of A This is so that things like the following work: .>>> class SillyAdd(long): .... __add__ = long.__mul__ .... __radd__ = __add__ .... .>>> a = SillyAdd(4) .>>> a .4L .>>> a + 5 .20L .>>> 5 + a .20L Cheers, Nick. From fredrik at pythonware.com Mon Dec 20 15:20:16 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 20 Dec 2004 21:20:16 +0100 Subject: input record seperator (equivalent of "$|" of perl) References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com><1103501833.632076.74050@f14g2000cwb.googlegroups.com><1103504587.796518.245030@f14g2000cwb.googlegroups.com><41c6386e$1@nntp0.pdx.net> <32nmqtF3ninrdU1@individual.net> <41c6fe6b$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > True. The 2.4 document says that itertools.groupby() is equivalent to: > > class groupby(object): > So you could always just use that code. the right way to do that is to use the Python version as a fallback: try: from itertools import groupby except ImportError: class groupby(object): ... From fredrik at pythonware.com Sun Dec 19 16:46:51 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Dec 2004 22:46:51 +0100 Subject: input record seperator (equivalent of "$|" of perl) References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> Message-ID: les_ander at yahoo.com wrote: > I know that i can do readline() from a file object. > However, how can I read till a specific seperator? > > for exmple, > if my files are > > name > profession > id > # > name2 > profession3 > id2 > > I would like to read this file as a record. > I can do this in perl by defining a record seperator; > is there an equivalent in python? not really; you have to do it manually. if the file isn't too large, consider reading all of it, and splitting on the separator: for record in file.read().split(separator): print record # process record if you're using a line-oriented separator, like in your example, tools like itertools.groupby can be quite handy: from itertools import groupby def is_separator(line): return line[:1] == "#" for sep, record in groupby(file, is_separator): if not sep: print list(record) # process record or you could just spell things out: record = [] for line in file: if line[0] == "#": if record: print record # process record record = [] else: record.append(line) if record: print record # process the last record, if any From bokr at oz.net Wed Dec 22 04:10:39 2004 From: bokr at oz.net (Bengt Richter) Date: Wed, 22 Dec 2004 09:10:39 GMT Subject: Why are tuples immutable? References: <20041215152606.1029.1225319887.divmod.quotient.10976@ohm> <10s48r5hbse5o57@corp.supernews.com> <41c350ef.331854992@news.oz.net> Message-ID: <41c9103e.708509723@news.oz.net> On 21 Dec 2004 10:37:20 GMT, Antoon Pardon wrote: >Op 2004-12-18, Bengt Richter schreef : >>> >>>As it turns out, python makes no difference in difficulty for making >>>either mutable or immutable objects usable as dictionary keys. The >>>only difference is that python only made its standard immutable >>>types hashable and not its standard mutable objects. >>> >> In one sense a mutable could looked upon as immutable until it is mutated, >> so why not allow its use in the same way as immutables? >> Is that basically the point of view you are trying to explain? >> >> Ok, suppose you did allow that. What kind of error symptoms would you like >> to have after a dict key is mutated and an attempt is made to look up the value >> using a mutable equal to the original key value? Presumably a KeyError exception? >> Or did you want to use a "frozen" copy of the original key, and not get a KeyError? >> Or should a new value equal to the mutated current value of the original key succeed? > >Why should we expect certain error symptoms? If you have sorted mutable >objects, mutated one element in the list and then apply an algorithm >that depended on the list to be sorted; would you then expect a >particular error symptom? It depends on the use of the sorted list, but the subject I was discussing was your requirements for a mutable-key dict. I was asking how you would like the mutable-key dict to behave IF a key was mutated and an attempt was made to retrieve the origninally stored value using a mutable key equal to the mutated value of the original key. E.g., if mkd is the mutable key dict, key = [0] mkd[key]=123 key[0] = 1 mkd[[1]] => ? I said I would go with the assumption that you would like it to succeed (return the 123 above). You said I assumed wrongly, but for some reason chose not to answer my questions or say what a "correct" assumption would be. Ok. If you're not interested in pursuing the "correct" version of the dict behavior _you_ were asking for, what are you interested in? ;-) In the above, I am in a position to detect some "errors," depending what _your_ specs are. I think it would be sloppy to let detectable errors pass silently, and in the case of mkd[[1]] above clearly it will succeed or not, depending on design. The logical thing would seem to be to return the matching value or design the dict so that mkd[[0]] would still retrieve 123 and mkd[[1]] would raise a KeyError. Either way, this is a particular error symptom to expect, because it is a direct consequence of a design decision. Your sorted list example does not say enough about the designed usage to say what specific errors might be expected, so it's not directly comparable. If you are saying you are happy with "undefined behavior" as the outcome of mutating keys, ok, but if your implementation lets mutated-key errors pass silently, good luck debugging ;-) > >> Assuming the latter, what does this imply implementation-wise? > >You assume wrongly. I'm a bit sorry for that, because you obviously >spend time in this. That's ok, I made the choice ;-) I enjoy exploring ideas, and I thought it might be useful to help you explore the consequences of what you seemed to be asking for, and I was a bit curious how it would work out in practice when mutable keys were mutated. I obviously could have made it work differently, and was trying to guess what alternative you might be interested in. ISTM from the little experiment I posted in this thread that mutable keys for dicts is fraught with pitfalls even if you intend never to mutate keys in use, because of the potential for silent bugs if you accidentally do. But perhaps something useful can be designed, if design decisions are carefully made. If you enjoy exploring ideas too, you might get even more enjoyment by participating more directly. E.g., at this point you might have volunteered to mention what would have been a "correct" assumption to make in place of the one you say I made wrongly. Your reticence does make me wonder what you consider to be rewarding about participating in this kind of thread ;-) Cruel rejection is not the style of c.l.py, but if you have had such experience, somewhere, bringing that baggage with you into the present in search of resolution is likely to limit your new experiences to something less than an optimally pleasant dialog ;-) The kids here mostly play nice ;-) > >> Hm, just for the heck of it, does this do what you want? (all features not tested, none tested beyond what you see, >> and special methods like update and iterators will just work on the plain dict part if they work at all, unless >> you add the code ;-) > >I don't expect anyting special. Python provides all that is needed. It >is just that the documentation suggests otherwise. > So is there anything you would like to do to help make things better for yourself and everyone? ;-) Regards, Bengt Richter From mlprog at email.it Fri Dec 10 16:57:49 2004 From: mlprog at email.it (MarcoL) Date: Fri, 10 Dec 2004 21:57:49 GMT Subject: from vb6 to Python Message-ID: Hello, I am a VB6 programmer and I would like to learn a new high level language (instead of restarting from scratch with .NET), wich is opensource and cross-platform, in order to develop cross-platform business applications I think Python is the most suitable language for the scope. My question are: - Which version of python is more suitable for creating cross-platform GUI's? I've herard of PyGTK, wxPython, PyQT, tk, Anygui.. - What is the best IDE/RAD for Python (written in Python and OpenSource) - Does exist a tool (written in Python and OpenSource) like Crystal Report for creating business reports? - Does exist a tool (written in Python and OpenSource) for makeing tables, view, querys, relation of a database and generate the SQL script? - Is it possible, from Python, to work with sqlite? And with MsAccess? Thanks for your patience and your help. Marco. From itsme at yahoo.com Wed Dec 29 20:27:11 2004 From: itsme at yahoo.com (It's me) Date: Thu, 30 Dec 2004 01:27:11 GMT Subject: Why would I use inspect.isclass()? Message-ID: I discovered the hardway what inspect.isclass() is doing. Consider this no brainer code: ### import inspect class Abc: def Hello(self): return an_instance=Abc() print inspect.isclass(an_instance) ### It took me a while to understand how I can get inspect.isclass to return a True (like: inspect.isclass(Abc)). But what good is that? Of course I know Abc is a class, why would I want to inspect it so that it would tell me what I already know? I would have thought this would be the situation I need that for: ### import inspect class Abc: def Hello(self, some_class): # since I don't know if the argument passed down *is* a class or not, I would: if inspect.isclass(some_class)==True: ... return ### But that obviously isn't what isclass is for. What should I use? Thanks, From jerf at jerf.org Sun Dec 12 16:04:47 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 12 Dec 2004 16:04:47 -0500 Subject: Python mascot proposal References: Message-ID: On Sun, 12 Dec 2004 20:54:38 +0000, Dimitri Tcaciuc wrote: > I haven't came up with the name for that guy yet, so I'm leaving that > for public suggestions :). It is time Python gets an official face in > the Net! *cough* Anyway, I would like to hear your thoughts and suggestions. I mean no offense, this was just my initial reaction: I like the drawing itself, but the first thing that coloration brings to mind is the word "diseased". Sorry, I don't know how to make this sound less brutal without getting that across. But I do like the drawing. From carribeiro at gmail.com Mon Dec 6 07:13:19 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 6 Dec 2004 10:13:19 -0200 Subject: pre-PEP generic objects In-Reply-To: References: Message-ID: <864d3709041206041355646086@mail.gmail.com> On 06 Dec 2004 10:09:25 +0100, Jacek Generowicz wrote: [great explanation about function descriptors] Thanks. Now I know more about function descriptors than I ever wanted to :-) With a little polish, this post would make a great addition to the descriptors documentation, don't you think? -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From gh at ghaering.de Wed Dec 1 05:35:04 2004 From: gh at ghaering.de (Gerhard Haering) Date: Wed, 1 Dec 2004 11:35:04 +0100 Subject: 2.4 or 2.3.4 for 2.3 software? In-Reply-To: References: Message-ID: <20041201103504.GA31378@mylene.ghaering.de> On Wed, Dec 01, 2004 at 10:23:55AM +0100, Jens Bloch Helmers wrote: > Can we expect the current release of 2.4 to be just as reliable as > 2.3.4 for 2.3 compliant software? Only time will tell. I myself had never had any problems with 2.x.0 versions of Python. Only early 2.0.x had a few problems in the C API for me. -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From steven.howe at verizon.net Mon Dec 13 14:31:32 2004 From: steven.howe at verizon.net (Steven) Date: Mon, 13 Dec 2004 19:31:32 GMT Subject: looking for blocking on read of a real file (not socket or pipe) Message-ID: Hello, I'm seeking a read method that will block until new data is available. Is there such a python function that does that? Thanks, Steven Howe From howardrh at westerncom.net Fri Dec 3 17:41:35 2004 From: howardrh at westerncom.net (howardrh) Date: 3 Dec 2004 14:41:35 -0800 Subject: How did you learn Python? References: Message-ID: "Shawn Milo" wrote in message news:... > I was just wondering what the best books were for learning Python. > > Which books are good for getting started, and which should be saved for > later, or or not useful except as a reference for the learned? If you have any interest in using Python for numerical computation take a look at Python Scripting for Computational Science by Hans Peter Langtangen. The book is quite expensive, about US $85, but well worth it in my opinion as it covers just about all of the available Python resources for numerical computation. From hans at zephyrfalcon.org Fri Dec 31 16:30:11 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Fri, 31 Dec 2004 16:30:11 -0500 Subject: The Industry choice In-Reply-To: References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> Message-ID: Christopher Koppler wrote: > -- > Christopher > > In theory, I'm in love with Lisp, > but I hop into bed with Python every chance I get. That reminds me of something my old math teacher used to say... "My wife is my cathedral, but I pray in every chapel." :-) -- Hans Nowak http://zephyrfalcon.org/ From ialbert at mailblocks.com Thu Dec 9 13:26:09 2004 From: ialbert at mailblocks.com (Istvan Albert) Date: Thu, 09 Dec 2004 13:26:09 -0500 Subject: Calling a C program from a Python Script In-Reply-To: References: Message-ID: <0sydnWs9zYZfBSXcRVn-pg@giganews.com> Brad Tilley wrote: > If possible, how much faster would this be over a pure Python solution? It is like the difference between Batman and Ever. batman is faster than ever From fumanchu at amor.org Mon Dec 6 20:04:02 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 6 Dec 2004 17:04:02 -0800 Subject: better regular expression? Message-ID: <3A81C87DC164034AA4E2DDFE11D258E324533F@exchange.hqamor.amorhq.net> Vivek wrote: > I am trying to construct a regular expression using the re module that > matches for > 1. my hostname > 2. absolute from the root URLs including just "/" > 3. relative URLs. > > Basically I want the attern to not match for URLs that are not on my > host. Far easier would be grabbing the URL's and then using urlparse.urlparse() on them. Relative paths should be combined with the base scheme://location/path. When you want to see if they are on your host, just use .startswith(). If you're worried about ../, make the paths concrete (os paths) and call os.path.normpath before comparing them. Robert Brewer MIS Amor Ministries fumanchu at amor.org From ebonakDUH at hotmail.com Sun Dec 26 21:55:24 2004 From: ebonakDUH at hotmail.com (Esmail Bonakdarian) Date: Sun, 26 Dec 2004 21:55:24 -0500 Subject: Windows XP - cron or scheduler for Python? In-Reply-To: <1104114935.127103.192120@z14g2000cwz.googlegroups.com> References: <1103829509.215965.133120@f14g2000cwb.googlegroups.com> <1103863414.601702.104440@z14g2000cwz.googlegroups.com> <41CF71BB.7020008@hotmail.com> <1104114935.127103.192120@z14g2000cwz.googlegroups.com> Message-ID: <10suucsi7v5ceb1@corp.supernews.com> ian at kirbyfooty.com wrote: > Hi Esmail, Kirby Alarm is written in Clarion. Sorry, but I want to > keep the source code to myself. Hi, thanks for the info, and no problem. I'm learning Python, and looking at other's code has been a great way to learn. (As an aside, I was thinking of this sort of application as a good project). cheers, Esmail From lucas.hofman at pgs.com Tue Dec 14 06:29:22 2004 From: lucas.hofman at pgs.com (Lucas Hofman) Date: Tue, 14 Dec 2004 12:29:22 +0100 Subject: Performance (pystone) of python 2.4 lower then python 2.3 ??? In-Reply-To: <1gos5c8.phuzdabddrfsN%mark.asbach@post.rwth-aachen.de> References: <1gos5c8.phuzdabddrfsN%mark.asbach@post.rwth-aachen.de> Message-ID: Mark Asbach wrote: > Hi Lucas, > > >>On a dual Xeon 3.0 Ghz: > > > [...] > > >>Which shows a decrease in performance. Could this have anything to do with the >>fact that is is a dual processor box? > > > Maybe. But my 3Gh P4/HT is also detected as a dual processor machine > (Kernel 2.6), so it might be a general problem with the Xeon? > Hi Mark, No,the reason that you see 2 times as many processors as really are installed is the hyperthreading feature of the Xeon (see http://www.infoworld.com/infoworld/article/02/02/25/020225plxeon_1.html) I turned it off (in the BIOS). The machine I tested on has 2 (pysical) processors installed. Turning on or off does not influence the pystone number significantly.. Regards, Lucas From vortex_fixxer at yahoo.com Mon Dec 27 11:15:51 2004 From: vortex_fixxer at yahoo.com (Rÿffffe9veillÿffffe9) Date: Mon, 27 Dec 2004 08:15:51 -0800 (PST) Subject: Tutorial problem Message-ID: <20041227161551.50858.qmail@web50203.mail.yahoo.com> Hello, I have just started doing the python tutorials and i tried to modify one of the exercises, it has to to with defining functions. I wanted the user to be able to enter an option and then get a print of the selected option. I also wanted to have an exit for the user. This is the code.... def PU(): print 'To have a ...' def Python(): print 'To create a programme ...' def overall(): print 'To make .....' def motv(): print 'I know you can do it!' def menu(): print ' GOALS IN... ' print '____________________' print '1.Pick up' print '2.Python Programming' print '3.Overall' print '4.Motivation' print '5.Exit' print '____________________' menu() while choice != 5: choice = input ('Pick a number:') if choice == 1: PU() elif choice == 2: Python() elif choice == 3: overall() elif choice == 4: motv() else: print 'Bye' The problem is that it doesnt print the [ choice = input ('Pick a number:') ] command. It just runs thru the whole thing without allowing the user a selection. __________________________________ Do you Yahoo!? Yahoo! Mail - Find what you need with new enhanced search. http://info.mail.yahoo.com/mail_250 From flamesrock at gmail.com Sun Dec 26 13:35:41 2004 From: flamesrock at gmail.com (flamesrock) Date: 26 Dec 2004 10:35:41 -0800 Subject: Configuration Files In-Reply-To: References: Message-ID: <1104086141.835176.236000@c13g2000cwb.googlegroups.com> thanks for the replies, guys! MEFarmer, that example helps remove a lot of the confusion, thanks! I've looked through the SDL but there are so many different ways to do it, I wasn't which one was hands down best And Mike, I wish they would stick explanations like that in the SDL! Would help make breaking into the language a lot easier for newbs like me. (Spending time on these newsgroups is giving me more questions that answers heh ) From carribeiro at gmail.com Thu Dec 16 13:39:58 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Thu, 16 Dec 2004 16:39:58 -0200 Subject: Python mascot proposal In-Reply-To: References: <864d37090412160129178818b2@mail.gmail.com> Message-ID: <864d370904121610396e5a6f6@mail.gmail.com> On Thu, 16 Dec 2004 11:51:18 -0500, Peter Hansen wrote: > EP wrote: > >>It's a great marketing idea. There was a thread recently on Python-dev > >>that started with a message from Guido, where he talks about a > >>seemingly persistent perception that exists in the specialized press > >>regarding Python as a flexible, nice, but generally slow (or slower > >>than the alternatives) language. > > > > Perception of the press: Python is "flexible, nice, but generally slow" > > Which press? I know lots of programmers who have religious issues > about (against) Python believe this, or claim to, or want to, but > I haven't seen a lot of "press" coverage of Python's supposed slowness... > > Or was this just a guess on your part? Check Guido's original message on the topic, you can find it on python-dev articles. It`s recenet -- possibly less than one week old. He seemed to be sincerely concerned about it, having read an article published at some prestigious academic journal (something from ACM or IEEE, I think). If the BDFL wrote it, what more can I say? ;-) -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From erno at iki.fi Wed Dec 29 13:22:12 2004 From: erno at iki.fi (Erno Kuusela) Date: 29 Dec 2004 20:22:12 +0200 Subject: Python + Lisp integration? References: Message-ID: hello, you might want to look at . -- erno From roy at panix.com Mon Dec 6 08:46:25 2004 From: roy at panix.com (Roy Smith) Date: Mon, 06 Dec 2004 08:46:25 -0500 Subject: Seeking Python + Subversion hosting. References: <789f72ac.0412051942.17724d2d@posting.google.com> Message-ID: tom at livelogix.com (Tom Locke) wrote: > Anyone know of a good hosting company that offers both server-side > Python and a subversion repository? Panix (www.panix.com) has svn and python installed on their unix hosts. You could certainly do CGI in python. Don't know if they have mod_python available or not. Support and customer care couldn't be better. These guys started as a BBS in the founder's apartment 20 years ago, and haven't lost that personal touch while growing the business into a serious commercial venture. I don't know how their pricing works out for serious web hosting. I pay $100/year for my unix shell account, mostly to get mail and news, but it includes some low-limit web hosting which I only play around with once in a while. A higher-quota web hosting arrangement with your own domain name, etc, would certainly cost you more than $100/year. From mcfletch at rogers.com Wed Dec 15 15:55:26 2004 From: mcfletch at rogers.com (Mike C. Fletcher) Date: Wed, 15 Dec 2004 15:55:26 -0500 Subject: Step by step: Compiling extensions with MS Visual C++ Toolkit 2003 - msvccompiler-patch.txt (0/1) In-Reply-To: <41c02d3b.12311765@news.versatel.de> References: <41c02d3b.12311765@news.versatel.de> Message-ID: <41C0A4BE.9@rogers.com> Martin Bless wrote: ... >Two things first - not to forget: > >(1) In contrast to what Mike writes I had to use a different registry >key (see step 9) > > Which is expected (even noted on the page), particularly if you have a different version of the SDKs. The keys in the patch were extracted from an English Win2K Platform SDK. Don't know of any *good* way to figure out the keys in a version-agnostic manner. Suggestions welcome... >(2) I don't now what people mean when talking about "msvcr71.lib". >There's no such file on my machine. BUT there IS a "msvcrt.lib" a >directory "C:\Programme\Microsoft Visual Studio .NET 2003\Vc7\lib". I >guess the ".\Vc7\." indicates we are talking of the expected lib. >Correct? I don't know. > > This was sloppy on my part. msvcr71.dll is the DLL used for Visual Studio 7.1, we want the .lib for that version of the DLL, but as you note, it is actually named msvcrt.lib (same as the one for Visual Studio 6.0). >Get and install the platform SDK "Windows XP SP2 SDK" (about > > ... >It is >HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MicrosoftSDK\InstalledSDKs\B44C7E10-89BD-4A32-A3BF-D9D0BC4C9A05 > >and it is not >...\63DADB24-DC99-45EB-A748-EC93AB8A7497. > >Find out about the correct key in your case and adjust the crucial >line 133 in msvccompiler.py: > >freeSDK=r"SOFTWARE\Microsoft\MicrosoftSDK\InstalledSDKs\B44C7E10-89BD-4A32-A3BF-D9D0BC4C9A05" > > ... Will have to figure out how to make this work across SDK versions somehow. Thanks for the report, Mike ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From fredrik at pythonware.com Tue Dec 21 13:33:51 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 21 Dec 2004 19:33:51 +0100 Subject: how to pass globals across modules (wxPython) References: <87u0qij6qn.fsf@web.de> <1168398.J14ASI0oEJ@strongwill.g2ctech> <4969081.Tc9PZ3E6WB@strongwill.g2ctech> Message-ID: Jorge Luiz Godoy Filho wrote: > > or a single "application context class" instance, which is passed to > > various parts of the system as necessary. > > Wouldn't that cause a chicken & egg problem? How, then, would one pass such > an instance across modules? well, in my applications, subsystems usually consists of one or more classes, or at least one or more functions. code that needs the global context usually gets the content either as a constructor argument, or as an argument to individual methods/functions. if you build a system by execfile'ing subcomponents (or importing them just to run their code, rather than use what they define), using this approach is harder. but that's not a very good way to build systems, so I'm not sure that matters... From james.frohnhofer at csfb.com Mon Dec 6 16:16:08 2004 From: james.frohnhofer at csfb.com (Frohnhofer, James) Date: Mon, 6 Dec 2004 16:16:08 -0500 Subject: Mean, median, and mode - third time's the charm!!! Message-ID: <89D59C407D04D54AA82DC8BA312D430D10C61785@enyc11p32001.corpny.csfb.com> > > median = lambda x: x.sort() or ((len(x) % 2) and (x[(len(x)>>1)])) or > (sum(x[((len(x)>>1)-1):(len(x)>>1)+1])/2.0) > > >>> median( [2,3,4,5,6,7]) > 4.5 > >>> median( [2,3,4,5,6]) > 4 How about >>> median = lambda x: x.sort() or (x[(len(x)-1)/2] + x[len(x)/2])/2.0 >>> median([2,3,4,5,6,7]) 4.5 >>> median( [2,3,4,5,6]) 4.0 >>> ============================================================================== This message is for the sole use of the intended recipient. If you received this message in error please delete it and notify us. If this message was misdirected, CSFB does not waive any confidentiality or privilege. CSFB retains and monitors electronic communications sent through its network. Instructions transmitted over this system are not binding on CSFB until they are confirmed by us. Message transmission is not guaranteed to be secure. ============================================================================== From johan at pulp.se Thu Dec 9 08:29:35 2004 From: johan at pulp.se (Johan Lindberg) Date: 9 Dec 2004 05:29:35 -0800 Subject: wxPython bug References: <3APtd.4339201$yk.652531@news.easynews.com> Message-ID: <1102598975.587670.285480@z14g2000cwz.googlegroups.com> > [...] > What to do? Open up wxProject.py and fix the problem. The traceback is pretty clear: On line 137 in wxProject.py, the method GetFirstChild expects 2 arguments, but was given 3. Unfortunately the wx documentation is not very clear about the GetFirstChild method. It only says: wxPython note: In wxPython the returned wxTreeItemId and the new cookie value are both returned as a tuple containing the two values. It should also mention that it (GetFirstChild) only takes one parameter (item) For future reference: keep the wxPython api docs (http://www.wxpython.org/docs/api/) close. /Johan Lindberg From news at fluidobjects.com Thu Dec 16 07:29:33 2004 From: news at fluidobjects.com (Maxim Khesin) Date: Thu, 16 Dec 2004 12:29:33 GMT Subject: libxml2/xpath In-Reply-To: References: Message-ID: I do not believe it is... You can see the doc by clicking on the link. Does it have to be? thanks, m Martijn Faassen wrote: > Maxim Khesin wrote: > >> I am trying to do some xpath on >> http://fluidobjects.com/doc.xhtml >> but cannot get past 'point A' (that is, I am totally stuck): >> >> >>>> import libxml2 >>>> mydoc = libxml2.parseDoc(text) >>>> mydoc.xpathEval('/html') >>>> [] >> >> >> >> this returns an empty resultlist, which just seems plain wrong. Can >> anyone >> throw a suggestion to the stupid? > > > Is the html element in a namespace? > > Regards, > > Martijn > From jan.dries at dcube-resource.be Mon Dec 20 17:55:30 2004 From: jan.dries at dcube-resource.be (Jan Dries) Date: Mon, 20 Dec 2004 23:55:30 +0100 Subject: MIDI library recommendations, please? In-Reply-To: References: Message-ID: <41C75862.6020505@dcube-resource.be> Andrew Koenig wrote: > Are there widely used and recommended Python libraries that will let me > > 1) Interpret and generate MIDI messages easily? I'm not sure this is "widely used and recommended" but I've used the following in the past: http://sgce.cbse.uab.edu/SoundOfSequence/midi/midi.py It's simple, but it handles the basics (reading and writing MIDI). I've easily built the rest I needed on top of it. Regards, Jan From riko.wichmann at remove-this.desy.de Tue Dec 7 09:56:18 2004 From: riko.wichmann at remove-this.desy.de (Riko Wichmann) Date: Tue, 07 Dec 2004 15:56:18 +0100 Subject: cookie lib policy how-tp? Message-ID: dear all, i try to retrieve information from a secure web site. I use cookielib and urllib2 for this exercise which works to a certain level. I can authenticate myself and read the top-level page. However, from here I need to load a page which is dynamically build from information available from the page source on the top level. The desired info is inside a
tag which seems to be used by a javascript routine. But when I look at the page source retrieved with urllib2, the information I need to build the next URL is mssing. When I use opera to access this page by hand and look at the sources, I see the full sources when letting opera identify itself as MSIE 6.0. When using Mozilla 5.0 I get the same in-complete source file as with python. The desired info is included in a tag. Also, when accessing the web page using opera with those two identities, I'm asked to accept 2 cookies in case of MSIE6.0 and only one for mozilla. So, I suspect, the problem is somehow related to the cookies (maybe!?). I saw, that I can chance the cookie policy in cookielib. Maybe that will do the job. However, I don't quite understand what I have to do for that. Any hints or other thoughts are greatly appreciated. Thanks and cheers, Riko From steven.bethard at gmail.com Tue Dec 28 17:58:17 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 28 Dec 2004 22:58:17 GMT Subject: argument type In-Reply-To: References: <7m6Ad.3249$5R.2063@newssvr21.news.prodigy.com> Message-ID: Doug Holton wrote: > It's me wrote: > >> The argument I wish to pass is either one string, or a list of >> strings, or a tuple of strings. > > def seq(x): > if hasattr(x,"__iter__"): > return x > else: > return (x,) > > def abc(arg1, arg2, arg3): > for item in seq(arg2): > print item > Note that this takes advantage of the fact that str and unicode implement iteration through the old __getitem__ protocol instead of the __iter__ protocol. It's actually probably the most concise solution to your problem, but I don't think there's any guarantee that str and unicode won't grow __iter__ methods in the future, so you might find that this code breaks in some future version of Python (probably in the fabled Python 3.0). Unfortunately, if this does happen, it won't break with an exception; it will break by treating the characters in strings as 'item's. For the moment though (and I suspect in Python 2.5 as well since I haven't heard anyone lobbying to add __iter__ methods to str or unicode), this should work fine for you. Steve From ian at kirbyfooty.com Sun Dec 26 21:35:35 2004 From: ian at kirbyfooty.com (ian at kirbyfooty.com) Date: 26 Dec 2004 18:35:35 -0800 Subject: Windows XP - cron or scheduler for Python? In-Reply-To: <41CF71BB.7020008@hotmail.com> References: <1103829509.215965.133120@f14g2000cwb.googlegroups.com> <1103863414.601702.104440@z14g2000cwz.googlegroups.com> <41CF71BB.7020008@hotmail.com> Message-ID: <1104114935.127103.192120@z14g2000cwz.googlegroups.com> Hi Esmail, Kirby Alarm is written in Clarion. Sorry, but I want to keep the source code to myself. Ian From nick at craig-wood.com Fri Dec 24 01:46:35 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 24 Dec 2004 06:46:35 GMT Subject: regular expression: perl ==> python References: <1103692329.420064.257540@f14g2000cwb.googlegroups.com> Message-ID: Fredrik Lundh wrote: > the undocumented sre.Scanner provides a ready-made mechanism for this > kind of RE matching; see > > http://aspn.activestate.com/ASPN/Mail/Message/python-dev/1614344 > > for some discussion. > > here's (a slight variation of) the code example they're talking about: > > def s_ident(scanner, token): return token > def s_operator(scanner, token): return "op%s" % token > def s_float(scanner, token): return float(token) > def s_int(scanner, token): return int(token) > > scanner = sre.Scanner([ > (r"[a-zA-Z_]\w*", s_ident), > (r"\d+\.\d*", s_float), > (r"\d+", s_int), > (r"=|\+|-|\*|/", s_operator), > (r"\s+", None), > ]) > > >>> print scanner.scan("sum = 3*foo + 312.50 + bar") > (['sum', 'op=', 3, 'op*', 'foo', 'op+', 312.5, 'op+', 'bar'], > '') That is very cool - exactly the kind of problem I come across quite often! I've found the online documentation (using pydoc) for re / sre in general to be a bit lacking. For instance nowhere in pydoc sre Does it tell you what methods a match object has (or even what type it is). To find this out you have to look at the HTML documentation. This is probably what Windows people look at by default but Unix hackers like me expect everything (or at least a hint) to be in the man/pydoc pages. Just noticed in pydoc2.4 a new section MODULE DOCS http://www.python.org/doc/current/lib/module-sre.html Which is at least a hint that you are looking in the wrong place! ...however that page doesn't exist ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From FETCHMAIL-DAEMON at alumnux.com Mon Dec 13 01:25:46 2004 From: FETCHMAIL-DAEMON at alumnux.com (FETCHMAIL-DAEMON at alumnux.com) Date: Mon, 13 Dec 2004 11:55:46 +0530 Subject: (no subject) Message-ID: <200412130625.LAA15838@alumnux.com> Some addresses were rejected by the MDA fetchmail forwards to. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: text/rfc822-headers Size: 804 bytes Desc: not available URL: From fuzzyman at gmail.com Thu Dec 9 06:23:49 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: 9 Dec 2004 03:23:49 -0800 Subject: cookie lib policy how-tp? In-Reply-To: References: <1102435627.593309.301430@z14g2000cwz.googlegroups.com> Message-ID: <1102591429.182096.67480@c13g2000cwb.googlegroups.com> I think your question has already been answered - but just to clarify a couple of issues. Setting a cookie policy will only *restrict* the situations in which cookies are returned. The default is to *always* return them. Also using an MSIE instance is useful for creating a CookieJar instance with your current set of IE cookies in it, but it doesn't make cookielib behave any more like IE. (take all that with the usual pinch of salt, but I'm pretty sure it's correct). Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From insert at spam.here Tue Dec 21 18:46:25 2004 From: insert at spam.here (Doug Holton) Date: Tue, 21 Dec 2004 17:46:25 -0600 Subject: What is on-topic for the python list [was "Re: BASIC vs Python"] In-Reply-To: References: <41C342A0.3040700@users.ch> <86sm64tzax.fsf@guru.mired.org> Message-ID: Hans Nowak wrote: >> > The discussion with Logo and other languages in it was off-topic too, >> > but it wasn't offensive to anyone. >> >> I'm not going to dignify that or the rest of your note with a response. > > > No, by all means, let's ignore any pieces of a post that might lead to > constructive discussion. > > Well, it's been fun, but I really don't have time for this. If we > cannot end this thread with some kind of mutual understanding, then I > will end it unilaterally. You have the dubious honor of being the first > person in my killfile since 1997. > You've yet again confirmed that your only point in this whole thread was to be disrepectful and complain about what offends you. And you end it with yet more parting insults. If you had better articulated what you really meant at the beginning, I never would have responded to you. From rschroev_nospam_ml at fastmail.fm Wed Dec 22 17:54:01 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 22 Dec 2004 22:54:01 GMT Subject: Skinnable/Stylable windows in wxPython? In-Reply-To: References: <1102870917.313182.98790@z14g2000cwz.googlegroups.com> Message-ID: Daniel Bickett wrote: >>>Not only would this make it more multi-platform (I have no access to >>>a GTK machine so I don't know if this works. Could someone please >>>check?) >> >>Looks like it works (I had to change frame.Show() to frame.Show(1) >>though, but that could be because it's an old version). > > > No, I think that was a slip on my part when copying the code from one > screen to the next :) I tried again with newer versions (Python 2.3 and wxPython 2.4); the code runs as-is, without that modification. >>One odd thing >>though: the Windows version doesn't react to clicking or dragging the >>mouse, which seems to be the expected behavior. >>The GTK version can be >>moved by dragging the mouse; even just clicking the mouse moves the >>window somewhat down and to the left. > > > That's interesting... I wonder if using those methods would conflict > at all. I couldn't reproduce that behaviour this time. It might have had something to do with the test setup the first time. -- "Codito ergo sum" Roel Schroeven From peter at engcorp.com Fri Dec 17 13:54:54 2004 From: peter at engcorp.com (Peter Hansen) Date: Fri, 17 Dec 2004 13:54:54 -0500 Subject: Time Difference In-Reply-To: References: Message-ID: GMane Python wrote: > Hello > I was wondering if there is an existing function that would let me > determine the difference in time. To explain: > > Upon starting a program: > > startup = time.time() > > After some very long processing: > now = time.time() > > print , now - startup > > So, to print in a formatted way (D-H-M-S) the difference in time of startup > and now. >>> from datetime import datetime >>> startTime = datetime.now() # processing.... >>> endTime = datetime.now() >>> print 'elapsed', endTime - startTime elapsed 0:00:09.063000 -Peter From jcarlson at uci.edu Thu Dec 2 21:30:15 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 02 Dec 2004 18:30:15 -0800 Subject: decorators ? In-Reply-To: References: Message-ID: <20041202182217.FAA9.JCARLSON@uci.edu> Jacek Generowicz wrote: > > BJ?rn Lindqvist writes: > > > I think the essence of decorators is that it makes it possible to do > > in Python what you in other languages do with method qualifiers. > > I find it fascinating that the addition of a bit of syntax sugar gives > the perception that a whole range of new and previously unthinkable > possibilities have opened themselves before us. > > @X > def Y... > ... > > > is merely syntax sugar (or syntax ammonia, for some) for > > > def Y... > ... > Y = X(Y) > > Anything you can do with decorators, you could do before (with the > exception of rebinding the __name__ of functions). > > And yet, that bit of syntax sugar really _does_ make a big difference > to the lengths that people are prepared to take the possibilities that > the underlying feature affords them. Technically, everything can be performed in assembly. The point of syntactic sugar (or ammonia) is to make things less painful. While everything was possible before, adding the decorators /after/ defining the function hid the decorators, and was susceptible to mistyping. I previously posted about Philip Eby's use of decorators in PyObjC. In his case, it saved him from typing 40-character function names 3 times. - Josiah From rogerb at rogerbinns.com Sun Dec 5 21:51:38 2004 From: rogerb at rogerbinns.com (Roger Binns) Date: Sun, 5 Dec 2004 18:51:38 -0800 Subject: PajamaScript References: Message-ID: "Jerome Chan" wrote in message news:c312d08f.0412051603.622b3315 at posting.google.com... >I wrote something called PajamaScript. Basically, it parses a text > file and looks for tags. Then it calls python to handle the > scripting. Why learn another language when you already know Python? Why write another templating tool, when there are so many already (other than as a valuable learning exercise). Check out the Python Cookbook: http://aspn.activestate.com/ASPN/Python/Cookbook/ It has several. Here are the best: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52217 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/162292 Note that they also deal with the area you will have an issue in which is how to add conditional statements. Roger From faassen at infrae.com Sat Dec 11 21:46:05 2004 From: faassen at infrae.com (Martijn Faassen) Date: Sun, 12 Dec 2004 02:46:05 GMT Subject: from vb6 to Python In-Reply-To: <1102814024.901947.287950@f14g2000cwb.googlegroups.com> References: <1102814024.901947.287950@f14g2000cwb.googlegroups.com> Message-ID: Luis M. Gonzalez wrote: > MarcoL wrote: > >>Hello, >> I am a VB6 programmer and I would like to learn a new high level >>language (instead of restarting from scratch with .NET... > > > I'd like to add that by going with Python, you'll also be able to > develop for .NET. Check this out: www.ironpython.com . > Since the development of Ironpython is now being funded by Microsoft, > you'll get the best of both worlds: An already excellent > cross-platform, object oriented language and a fully compliant .NET > language for Windows and Linux (through Mono and DotGnu). Unfortunately this is currently not near production use, and whether Microsoft is funding IronPython development is up in the air: One IronPython fan noted a disconcerting silence in IronPython development: http://usefulinc.com/edd/blog/contents/2004/12/09-jvm/read Of course it'll all resolve itself one way or another eventually, just wanted to correct the impression that IronPython is ready to go already. Regards, Martijn From insert at spam.here Sun Dec 19 22:17:51 2004 From: insert at spam.here (Doug Holton) Date: Sun, 19 Dec 2004 21:17:51 -0600 Subject: ANN: Python Multimedia Computing book and software Message-ID: This book is due to be published any day now: "Introduction to computing and programming with Python: A Multimedia Approach" by Mark Guzdial, a CS professor at Georgia Tech. It uses the Jython Environment for Students (JES). It is completely free and open source. You can use it for example to work with and manipulate images or sounds. A similar book is available in preview form: "Introduction to Media Computation: A Multimedia Cookbook in Python". See this page for info on the books, the software, course notes, research papers, and more info: http://coweb.cc.gatech.edu/mediaComp-plan From fulimin_yuan at yahoo.com Thu Dec 2 15:32:09 2004 From: fulimin_yuan at yahoo.com (Limin Fu) Date: Thu, 2 Dec 2004 12:32:09 -0800 (PST) Subject: How is Python designed? Message-ID: <20041202203209.67390.qmail@web80904.mail.scd.yahoo.com> Hello, Is there any technical description on internet of how python is designed? Or can somebody give a short description about this? I'm just curious. Thanks in advance, Limin __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions.yahoo.com/new_mail From R.Brodie at rl.ac.uk Tue Dec 14 04:51:19 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 14 Dec 2004 09:51:19 -0000 Subject: Suggestion for "syntax error": ++i, --i References: Message-ID: "Terry Reedy" wrote in message news:mailman.7656.1102977457.5135.python-list at python.org... > You could propose to the author of Pychecker that he include, if possible, > an option to check for and warn about '++', '--'. It does already. From hans at zephyrfalcon.org Tue Dec 21 16:31:29 2004 From: hans at zephyrfalcon.org (Hans Nowak) Date: Tue, 21 Dec 2004 16:31:29 -0500 Subject: What is on-topic for the python list [was "Re: BASIC vs Python"] In-Reply-To: References: <41C342A0.3040700@users.ch> <86sm64tzax.fsf@guru.mired.org> Message-ID: Doug Holton wrote: > Hans Nowak wrote: > >>> You said that boo should not be mentioned on this newsgroup. >> >> >> >> Please point me to the post where I said that. Since everything is >> stored in Google Groups, it should be easy for you to come up with an >> URL... if such a post existed. > > > Quote: > "this is comp.lang.python, not comp.lang.boo." Which is obviously not the same as "Boo should not be mentioned on this newsgroup". I suppose you can interpret this any way you want. One can take it as an attempt at censorship. But it was actually meant as part of an explanation why people were giving you a hard time. The discussion with Logo and other languages in it was off-topic too, but it wasn't offensive to anyone. In fact, it actually adds to the richness of this newsgroup. Look, let's get this thing out of the way. It has already taken up too much energy from everyone involved. I apologize if you were under the impression that I tried to tell you what to say and what not to say in this newsgroup. I intended to do no such thing. Now maybe we should let it rest and go write some nice code. -- Hans Nowak http://zephyrfalcon.org/ From grante at visi.com Fri Dec 31 16:35:02 2004 From: grante at visi.com (Grant Edwards) Date: 31 Dec 2004 21:35:02 GMT Subject: OT: spacing of code in Google Groups References: <1104516184.077462.283350@c13g2000cwb.googlegroups.com> <1104528447.005870.6530@z14g2000cwz.googlegroups.com> Message-ID: <41d5c606$0$26890$a1866201@visi.com> On 2004-12-31, mensanator at aol.com wrote: > beliavsky at aol.com wrote: >> When I copy code from a source file into a Google Groups >> message, the indentation is messed up, making my Python code >> illegal and all my code ugly. Are there tricks to avoid this? > > Try putting a # at the start of every line. Everyone should > understand what you mean (and you can always tell them to remove > the #'s once they copy the listing). > > #import gmpy > #i = 7 > #while i<100000: I always rather liked line numbers (a-la 'can -n'). That also makes discussion of the code easier: 1 import gmpy 2 i = 7 3 while i<100000: 4 # conjecture 1 5 6 if ((i % 3)>0) and ((i % 5)>0): 7 f = gmpy.fib(i) 8 ip = gmpy.is_prime(i) 9 fm = f % i 10 if (fm==(i-1)) and (ip==0): 11 print "fib %5d: %5d (mod %5d)" % (i,fm,i), 12 print gmpy.is_prime(i) 13 i += 2 14 15 """ 16 Conjecture #1: if i ends in 3 or 7 and fib(i) == i-1 (mod i) 17 then i is prime 18 19 run #1 print all fib(i) == i-1 (mod i) that are composite 20 21 fib 5777: 5776 (mod 5777) 0 <-- counter example 22 fib 10877: 10876 (mod 10877) 0 <-- counter example 23 fib 17261: 17260 (mod 17261) 0 24 fib 75077: 75076 (mod 75077) 0 <-- counter example 25 fib 80189: 80188 (mod 80189) 0 26 """ Not sure what Google Groups does to it... -- Grant Edwards grante Yow! Now I understand the at meaning of "THE MOD SQUAD"! visi.com From nytimes at swiftdsl.com.au Wed Dec 22 18:31:22 2004 From: nytimes at swiftdsl.com.au (huy) Date: Thu, 23 Dec 2004 10:31:22 +1100 Subject: Best GUI for small-scale accounting app? In-Reply-To: References: <7xmzw9cf8l.fsf@ruckus.brouhaha.com> <7x8y7t5c3l.fsf@ruckus.brouhaha.com> Message-ID: <41CA03CA.7040808@swiftdsl.com.au> Dave Cook wrote: > On 2004-12-20, Paul Rubin wrote: > > >>I think I can put together a useable (but not visually stunning) web >>interface faster than I can put together any pure client-side >>interface. > > > Web browser "widgets" seem pretty limited to me, though. You don't even > have something as simple as a combo box (i.e. an editable entry with a drop > down), let alone the rich set of widgets something like wxwidgets offers. > Also web development doesn't seem as coherent to me as development with a > good GUI framework. I think it depends on your target audience. Many people love simplicity. Many people hate multiple tabs, tree structures, deep nested menus etc etc. If you wanted to make a web program as complex as a rich client program then it's probably a bad idea to do as a web program. But If you wanted to keep it simple, then I'd go with a web program any day. Huy From __peter__ at web.de Mon Dec 6 06:50:19 2004 From: __peter__ at web.de (Peter Otten) Date: Mon, 06 Dec 2004 12:50:19 +0100 Subject: Recursive list comprehension References: <41b43e49$0$25772$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: Nick Coghlan wrote: > from?itertools?import?chain > n?=?[['N',?'F'],?['E'],?['D']] > print?[chain(*n)] However, [generator] is not the same as list(generator): >>> from itertools import chain >>> n = [['N', 'F'], ['E'], ['D']] >>> print [chain(*n)] [] >>> print list(chain(*n)) ['N', 'F', 'E', 'D'] And with the star operator you are foregoing some laziness, usually an important selling point for the iterator approach. Therefore: >>> n = [['N', 'F'], ['E'], ['D']] >>> lazyItems = (x for y in n for x in y) >>> lazyItems.next() 'N' >>> list(lazyItems) ['F', 'E', 'D'] >>> Of course this makes most sense when you want to keep the original n anyway _and_ can be sure it will not be mutated while you are still drawing items from the lazyItems generator. Peter From apardon at forel.vub.ac.be Thu Dec 16 04:21:58 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 16 Dec 2004 09:21:58 GMT Subject: Why are tuples immutable? References: <41BE1644.8050906@freemail.gr> Message-ID: Op 2004-12-16, Jeremy Bowers schreef : > On Wed, 15 Dec 2004 15:08:09 +0000, Antoon Pardon wrote: > >> And I think that is a stupid reason. There are enough other situations >> were people work with mutable objects but don't wish to mutate specific >> objects. Like objects in a sorted sequence you want to keep that way >> or objects in a heapqueue etc. >> >> Demanding that users of dictioanaries somehow turn their mutable objects >> into tuples when used as a key and back again when you retrieve the keys >> and need the object can IMO ibe a bigger support nightmare than the >> possibility that code mutates a key in a dictionary. > > Steve plonks you as a troll but I fear this is a point that either I am in > grave error on, or in our zeal to make this point simple for everyone > we've elided an important point and I'm not convinced it is as obvious as > he thinks it is. So, before trusting this message, wait for the angered > replies from those who know. Well IMO there are two sides in this argument. The first is whether or not python allows mutable keys. The second is whether or not limiting keys to immutables in dictionaries provides a performance gain. The two get mixed up a lot in this list, because a reasaonable amount argue that python only allows for immutable keys because of this supposed performance gain and that is why tuples are immutable because otherwise there wouldn't be a sequence type suitable as dictionary key. Then when I give arguments against the performance gain, people come with the argument that it is to protect keys in dictionaries from changing. > A dict key doesn't *really* need to be immutable. What it needs is the > following: the hash does not change over time, and an "equal" key will > always compare equally with no changes over time. Sample run: IMO there is nothing wrong with the hash or the equal comparisson being changable over time as long as the programmer is carefull not to change them while they are a key in a dictionary. Two guidelines can make it easier for a programmer to do this. 1) Put a copy in the dictionary, so that mutating the original object won't affect what is in the dictonary. 2) Don't mutate keys that come from a dictionary iterator. > [ Example ] > > I've seen this go by over and over and ISTM nobody ever clearly says this, > so either I'm in error on some point, or people are afraid to try to > explain the properties that must hold for mutable objects to be used in > hashes. Because the slightest violation can kill you... Yes, I find the python community a bit overprotective about some issues. I wouldn't be surprised the eas of doing something wrong here makes some people shy away from this. On the other hand if you have a sorted list or a heapqueue and you unknowingly mutate one of the elements in it you can be screwed too. Yet I don't see people suggest that only lists with immutable elements should be able to be sorted or that heapqueues should be limited to immutable elements. -- Antoon Pardon From nid_oizo at yahoo.com_removethe_ Wed Dec 29 18:55:24 2004 From: nid_oizo at yahoo.com_removethe_ (Nicolas Fleury) Date: Wed, 29 Dec 2004 18:55:24 -0500 Subject: getattr() woes In-Reply-To: References: <87hdm5hnet.fsf@thomas.local> Message-ID: David M. Cooke wrote: > Ideally, I think the better way is if getattr, when raising > AttributeError, somehow reused the old traceback (which would point > out the original problem). I don't know how to do that, though. Maybe a solution could be to put the attribute name in the AttributeError exception object, and use it in getattr; if the name doesn't match, the exception is re-raised. It's still not flawless, but would reduce risk of errors. Nicolas From steve at holdenweb.com Mon Dec 20 04:57:24 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 20 Dec 2004 04:57:24 -0500 Subject: Is this a good use for lambda In-Reply-To: References: <41c654b9.529432724@news.oz.net> <41c69127$0$306$edfadb0f@dread12.news.tele.dk> Message-ID: Michael Hoffman wrote: > Max M wrote: > >> Isn't it about time you became xml avare, and changed that to: >> >> > > > That makes no sense. Yeah, but give the guy a break, we've all made feeble attempts at humor from time to time. You realize, I suppose, that it's a reference to the fact that XHTML uses lower-case tags and allows self-closure with a trailing slash after the tag name? let's-keep-that-christmas-spirit-coming-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From luismgz at gmail.com Mon Dec 13 20:44:33 2004 From: luismgz at gmail.com (Luis M. Gonzalez) Date: 13 Dec 2004 17:44:33 -0800 Subject: do you master list comprehensions? In-Reply-To: <1102971085.659444.22790@z14g2000cwz.googlegroups.com> References: <1102971085.659444.22790@z14g2000cwz.googlegroups.com> Message-ID: <1102988673.485982.242170@z14g2000cwz.googlegroups.com> I guess the simplest way to do it is like this: >>> data = [['foo','bar','baz'],['my','your'],['holy','grail']] >>> result=[w for d in data for w in d] >>> result ['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail'] >>> From fumanchu at amor.org Tue Dec 21 20:05:15 2004 From: fumanchu at amor.org (Robert Brewer) Date: Tue, 21 Dec 2004 17:05:15 -0800 Subject: sql server support from linux Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3024F62@exchange.hqamor.amorhq.net> Simon Wittber wrote: > I am currently tasked with connecting Python CGI programs, under > Apache2 / Linux, to SQL Server on Windows 2000. > ... > Does anyone in this list ever connect to SQL Server from Linux, using > Python? If so, what is your solution? If you can get the DB-API wrappers running on Win2k, how about doing that locally and then writing a quickie socket server which your linux client can connect to? Robert Brewer MIS Amor Ministries fumanchu at amor.org From fredrik at pythonware.com Tue Dec 14 12:41:23 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Dec 2004 18:41:23 +0100 Subject: do you master list comprehensions? References: <1102971085.659444.22790@z14g2000cwz.googlegroups.com> Message-ID: Steven Bethard wrote: > > python -m timeit -s "data = [range(10) for _ in range(1000)]" > "sum(data, [])" > 10 loops, best of 3: 54.2 msec per loop > > > python -m timeit -s "data = [range(10) for _ in range(1000)]" "[w for > d in data for w in d]" > 100 loops, best of 3: 1.75 msec per loop > > The sum function used in this way (or a loop with a +=) is O(N**2) while the LC is O(N). also: timeit -s "data = [range(10) for _ in range(1000)]" "L = sum(data, [])" 10 loops, best of 3: 4.02e+004 usec per loop timeit -s "data = [range(10) for _ in range(1000)]" "L = [w for d in data for w in d]" 1000 loops, best of 3: 1.12e+003 usec per loop timeit -s "data = [range(10) for _ in range(1000)]" "L = []; map(L.extend, data)" 1000 loops, best of 3: 283 usec per loop timeit -s "data = [range(10) for _ in range(1000)]; from Tkinter import _flatten" "L = _flatten(data)" 1000 loops, best of 3: 308 usec per loop (the last one supports arbitrary nestings, the others don't) From ebolonev at mail.ru Sat Dec 4 08:28:47 2004 From: ebolonev at mail.ru (Egor Bolonev) Date: Sat, 4 Dec 2004 23:28:47 +1000 Subject: os.listdir("\\\\delta\\public") Message-ID: <31dschF399o2uU1@individual.net> import os print os.listdir("\\\\delta\\public") outputs ['Bases', 'Docs', 'Drivers', 'Soft', '\xc7\xe0\xec\xe5\xed\xe0 \xd1\xe5\xf2\xe5\xe2\xee\xec\xf3 \xce\xea\xf0\xf3\xe6\xe5\xed\xe8\xfe', 'Games'] and import os print os.listdir("\\\\delta") outputs Traceback (most recent call last): File "C:\Documents and Settings\????\My Documents\Scripts\test.py", line 4, in ? print os.listdir("\\\\delta") WindowsError: [Errno 53] : '\\\\delta/*.*' so how to get list of delta's shares? From bradtilley at gmail.com Thu Dec 9 09:38:55 2004 From: bradtilley at gmail.com (Brad Tilley) Date: Thu, 09 Dec 2004 09:38:55 -0500 Subject: results of division Message-ID: Hello, What is the proper way to limit the results of division to only a few spaces after the decimal? I don't need rocket-science like precision. Here's an example: 1.775 is as exact as I need to be and normally, 1.70 will do. Thank you, Brad From tzot at sil-tec.gr Wed Dec 29 07:05:18 2004 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Wed, 29 Dec 2004 14:05:18 +0200 Subject: what would you like to see in a 2nd edition Nutshell? References: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> Message-ID: On Wed, 29 Dec 2004 11:35:18 +0100, rumours say that aleaxit at yahoo.com (Alex Martelli) might have written: [snip: things to cover in a tentative 2nd edition of the nutshell] >and new capabilities of existing modules, such as thread-local >storage. ...which I most surely missed learning about it. Sometimes it's hard following all the changes, and amk's _What's New_ didn't mention it too (I'm sending a copy of this post to amk). In case others didn't know too, Google's first hit using the obvious query points to: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302088 which is providing code and hints how to find out more about threading.local . Yes, Alex, I am sure a second version of the Nutshell would be much needed; now and then there are discussions about good Python books, and I believe recently someone proposed the Nutshell among others, only to get the reply "but it only covers up to 2.2". -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From grante at visi.com Mon Dec 20 09:53:56 2004 From: grante at visi.com (Grant Edwards) Date: 20 Dec 2004 14:53:56 GMT Subject: extending python with a C-written dll References: Message-ID: <41c6e784$0$16084$a1866201@visi.com> On 2004-12-20, Jean-Baptiste PERIN wrote: > I'm trying to make a windows dll reachable from a python script.. FWIW, you can call dll's using the ctypes modules without mucking around in C. There may be performance reasons to build a "real" python module, but I haven't run across them yet. -- Grant Edwards grante Yow! I KAISER ROLL?! What at good is a Kaiser Roll visi.com without a little COLE SLAW on the SIDE? From nobody at nospam.net Thu Dec 30 11:39:13 2004 From: nobody at nospam.net (mrkurt) Date: Thu, 30 Dec 2004 16:39:13 GMT Subject: standard IDE in python 3000 (or beyond)? *semi-newbie* In-Reply-To: <5OVAd.64007$Jk5.27747@lakeread01> References: <1104391349.202802.182460@z14g2000cwz.googlegroups.com> <41D403F7.8070308@holdenweb.com> <5OVAd.64007$Jk5.27747@lakeread01> Message-ID: Steve Holden wrote: > Aahz wrote: > >> In article <41D403F7.8070308 at holdenweb.com>, >> Steve Holden wrote: >> >>> With respect it wouldn't, since IDLE doesn;t include a GUI builder. I >>> think Mike's cri-de-couer is for a tool that makes it as easy as >>> Visual Studio to put a GUI-based application together. >> >> >> >> Should the Python community really care about this, I suspect Eclipse >> might be the best way. > > > If Eclipse really is the answer I'll have to learn more about it, but > from the little I know so far it seems like a very heavyweight solution. > Not that Visual Studio is becomingly trim, of course - it's a fine > example of bloatware, but it does do a useful job as a GUI builder. > Perhaps there's a lesson somewhere in there ... > > regards > Steve About the closest thing to what Mike might want is Boa Constructor, which does have a GUI building tool. It is not as polished as the Visual Studio GUI builder, but there are a lot of controls there that can be used. It requires the wxWindows toolkit. BTW, has anyone used or tried WingIDE? It does look like a really polished product. --mrkurt From craig at postnewspapers.com.au Tue Dec 28 16:50:02 2004 From: craig at postnewspapers.com.au (Craig Ringer) Date: Wed, 29 Dec 2004 05:50:02 +0800 Subject: Reference behavior through C (was: Lambda going out of fashion) In-Reply-To: References: Message-ID: <1104270602.3215.65.camel@rasputin.localnet> On Wed, 2004-12-29 at 02:08, Cameron Laird wrote: > In article , > Craig Ringer wrote: > . > . > . > > IMO the reference behaviour of functions in the C API could be > >clearer. [snip] . > . > . > This is a sensitive area for me, too. I'd welcome insight > on how to think about this. If Pythonia were a better place > in this regard, how would it be? Reference documents that > more transparently define reference behavior? I think the current documentation does a fairly good job of that when describing how to treat the return values of the various functions, but a much poorer one when covering their arguments. > A convention for API names that reveals reference characteristics? That is what I'd lean towards personally... but of course there's duplication and compatibility to be considered. -- Craig Ringer From biner.sebastien at ouranos.ca Fri Dec 3 11:54:31 2004 From: biner.sebastien at ouranos.ca (biner) Date: 3 Dec 2004 08:54:31 -0800 Subject: finding byte order Message-ID: Hello, I am using a program that has to read binary data from files coming from different machines. The file are always written with big endian. I am using the struct module to read the data and it is fine because I can specify in the format if the data are to be read with big or small endian convention. I would like to use the array module instead of struct because it is suppose to be faster for big arrays. However, this module does not provide a format specifier to say if the data are writtent with big or small endian. The result is that it works on big-endian machine and not on small-endian machine. I would like to have a test to tell me if the current machine is using big or small endian, this way I could use the array module in the first case and the *slower* struct module on the second. I looked but did not find. Is there a python function to know that? Thanks! From flaxeater at gmail.com Mon Dec 27 21:32:10 2004 From: flaxeater at gmail.com (flaxeater at gmail.com) Date: 27 Dec 2004 18:32:10 -0800 Subject: Tkinter vs wxPython In-Reply-To: <10t1f70fga14ec0@corp.supernews.com> References: <10t1f70fga14ec0@corp.supernews.com> Message-ID: <1104201130.346064.7330@z14g2000cwz.googlegroups.com> Esmail Bonakdarian wrote: > Greetings all. > > I will have about 2 weeks to pursue some Python related activities and > would like to learn more about the graphical end of things. In that > vein I would like some opinions regarding Tkinter and wxPython. > (The previously recommended PyGame is appropriate for me for now, but > I am looking ahead) > > I am especially interested in terms of learning curve, documentation, > portability across platforms Linux/Windows and anything else you care > to add. As I know only what I have read on this forum & surfing the > web I would really appreciate the input of those who have used both, > or decided to use one over the other. Well I would recomend Tkinter because it's the easiest to use. I recomend using this document. http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html I used it and just worked my way through it. I found it very useful. From maxk at touro.edu Thu Dec 16 09:46:45 2004 From: maxk at touro.edu (maxk at touro.edu) Date: 16 Dec 2004 06:46:45 -0800 Subject: libxml2/xpath In-Reply-To: References: Message-ID: <1103208405.757628.199120@f14g2000cwb.googlegroups.com> > # confDocument is a libxml2 document, from parseFile() etc > xp = confDocument.xpathNewContext() > xp.xpathRegisterNs("xhtml", "http://www.w3.org/1999/xhtml") > dirElement = xp.xpathEval( "/xhtml:html" ) > Stupid question, but can the namespace somehow be changed to null to make queries simpler? thanks, max. From ruach at chpc.utah.edu Wed Dec 22 12:24:22 2004 From: ruach at chpc.utah.edu (Matthew Thorley) Date: Wed, 22 Dec 2004 10:24:22 -0700 Subject: trouble building python2.4 In-Reply-To: References: Message-ID: Erik Max Francis wrote: > Matthew Thorley wrote: > >> Greetings, I just downloaded the python2.4 source from python.org and >> built it the usual way, i.e. ./configure && make. What I don't >> understand is that the resulting binary, when run, prints this line >> Python 2.3.4 (#1, Nov 15 2004, 10:29:48) at the top of its banner. >> Further more, the poplib modules complains when I try to call the >> poplib.POP3_SSL class, saying that the module has no such class, >> though the online docs say it does. > > > You've got a copy of Python 2.3.4 installed on your system which is in > your PATH first. > I have got to be the stupidest person on the face of the planet. Thanks very much. I was in the Python-2.4 dir, but I didn't call python with ./python. I can't believe I missed that. Thanks again -Matthew From itsme at yahoo.com Sun Dec 26 21:39:32 2004 From: itsme at yahoo.com (It's me) Date: Mon, 27 Dec 2004 02:39:32 GMT Subject: Tricks to install/run Python on Windows ? References: <41cf064e$0$17409$4d4efb8e@read.news.be.uu.net> Message-ID: Try running with the latest version of Python 2.3 instead of 2.4. May be you would have better luck. I've found similar stability problems with some of the tools (eventhough they have 2.4 releases) as well. I switched back to 2.3 and so far I have no complains. "StepH" wrote in message news:41cf064e$0$17409$4d4efb8e at read.news.be.uu.net... > Hi, > > I'm new to Python. I'm working under XP, and I've alot of prob. (not > with the langage itself, but with the tools): > > I've install Pyhton 2.4 in C:\Python24, using the .msi windows installer. > Then, I've install "PythonWin" (the last build-203). > > I'll try to summerize my prob.: > > 1./ The PythonWin IDE is not stable at all. Sometimes it exit without > reason, or don't stop on breakpoint, etc... Are some of you aware of > bugs in the last PyhtonWin IDE release ? I've to open the TaskManager. > AT some point, i'm not able to (p.e.) open a file under it !!! > > 2./ I've try to download Komode (he 3.1 personnal). I've also prob. > with it ! Also, the breakpoint seems to not always work... > > 3./ So, i've try to use the command line, but i've to manualy change the > code page od my dos box from 437 to 1252 (i'm live in belgium). And > i've not try how to do that permanently ! > > 4./ Before, I had Python23 and it seems that when unstalling it, all the > keys in the registry are not removed at all. When i've install the 2.4, > I had a mismatch which force me to complety re-install the machine (I'm > not an expert of the registry)... > > 5./ Installing komodo seems to "block" pythonwinIDE completly... > > What's wrong ? Python seems terific, but the tools... > > So... maybe i've to try BlackAdder ? From gerrit at nl.linux.org Mon Dec 13 06:09:20 2004 From: gerrit at nl.linux.org (Gerrit) Date: Mon, 13 Dec 2004 12:09:20 +0100 Subject: what module can do html encoder?? In-Reply-To: <41bd2da6$0$6539$afc38c87@news.optusnet.com.au> References: <41bd2da6$0$6539$afc38c87@news.optusnet.com.au> Message-ID: <20041213110920.GA19359@topjaklont.student.utwente.nl> richard wrote: > Leon wrote: > > example: > > s = ' ' --->   > > That's technically not HTML encoding, that's replacing a perfectly valid > space character with a *non-breaking* space character. How can you tell? s = '?' # non-breaking space s = ' ' # normal space s = '?' # em-space But you might want to do something like: def escapechar(s): import htmlentitydefs n = ord(s) if n < 128: return s.encode('ascii') elif n in htmlentitydefs.codepoint2name: return '&%s;' % htmlentitydefs.codepoint2name[n] else: return '&#%d;' % ord(s) This requires unicode strings, because unicode encodings have multi-byte characters. Demonstration: >>> f(u'?') 'ò' >>> f(u'?') 'ş' >>> f(u's') 's' yours, Gerrit Holl. -- Weather in Lulea / Kallax, Sweden 13/12 10:20: -15.0?C wind 0.9 m/s NNW (34 m above NAP) -- In the councils of government, we must guard against the acquisition of unwarranted influence, whether sought or unsought, by the military-industrial complex. The potential for the disastrous rise of misplaced power exists and will persist. -Dwight David Eisenhower, January 17, 1961 From s_david_rose at hotmail.com Fri Dec 17 10:30:11 2004 From: s_david_rose at hotmail.com (GMane Python) Date: Fri, 17 Dec 2004 10:30:11 -0500 Subject: Time Difference Message-ID: Hello I was wondering if there is an existing function that would let me determine the difference in time. To explain: Upon starting a program: startup = time.time() After some very long processing: now = time.time() print , now - startup So, to print in a formatted way (D-H-M-S) the difference in time of startup and now. Thanks! Dave From Doran_Dermot at emc.com Thu Dec 16 06:10:03 2004 From: Doran_Dermot at emc.com (Doran_Dermot at emc.com) Date: Thu, 16 Dec 2004 11:10:03 -0000 Subject: KeyError Message-ID: <97B6410BE753D411894E00D0B77E6F7F0340BEA8@neam2mx1.corp.emc.com> If a default value would be acceptable to the application (which is quite likely), then this would be a much cleaner solution. -----Original Message----- From: python-list-bounces+doran_dermot=emc.com at python.org [mailto:python-list-bounces+doran_dermot=emc.com at python.org] On Behalf Of Roland Heiber Sent: 16 December 2004 10:28 To: python-list at python.org Subject: Re: KeyError Doran_Dermot at emc.com wrote: > Hi "R", > > The only explanation I can give is that the environment varialbe REMOTE_ADDR > does not exist! Wrap your high-level code with try and except. Example: > try: > tablesDirectory = tablesDirectoryPrefix + os.environ['REMOTE_ADDR'] > except KeyError: > # Code to handle the fact tht REMOT_ADDR does not exist. ... or just replace os.environ['REMOTE_ADDR'] with os.environ.get('REMOTE_ADDR', 'enter_default_here') to use a default in case of missing REMOTE_ADDR ... HtH, Roland -- http://mail.python.org/mailman/listinfo/python-list From kl at nothere.com Sat Dec 4 14:13:54 2004 From: kl at nothere.com (Kl) Date: Sat, 4 Dec 2004 19:13:54 -0000 Subject: about python advanced/new features documentation Message-ID: <31egg4F3agjuhU1@individual.net> Hi, python is really easy to learn in my opinion. There are loads of tutorials/books on the web talking about the most common python features. The problem comes when they add something new to the language or you want to use advanced features. Since python is still evolving its difficult to find good documentation on these new features/language changes. Where can i find always up-to-date documentation about python? Unfortunately the official tutorial and books become obsolete really fast. Thanks. From richie at entrian.com Wed Dec 15 08:56:38 2004 From: richie at entrian.com (Richie Hindle) Date: Wed, 15 Dec 2004 13:56:38 +0000 Subject: ANN: Python Test Environment In-Reply-To: <41C03327.1090900@tbsmerchants.co.uk> References: <41C03327.1090900@tbsmerchants.co.uk> Message-ID: [Michael / Fuzzyman] > http://www.voidspace.org.uk/atlantibots/pythonutils.html#testenv I've seen this announcement four times now - I don't whether you're seeing problems with it, but it's definitely reaching the mailing list. -- Richie Hindle richie at entrian.com From rkern at ucsd.edu Wed Dec 15 23:10:50 2004 From: rkern at ucsd.edu (Robert Kern) Date: Wed, 15 Dec 2004 20:10:50 -0800 Subject: Is Python good for graphics? In-Reply-To: <10s1sk3291n0pe9@corp.supernews.com> References: <10s1bdaj7gbin8e@corp.supernews.com> <10s1sk3291n0pe9@corp.supernews.com> Message-ID: Esmail Bonakdarian wrote: > Fredrik Lundh wrote: > >> how about: >> >> http://vpython.org/ > > > hi, > > thanks, I didn't know about that. > > do you (or anyone else) have a recommendation for 2D type > graphics? I like Kiva (but then, I also help develop it). The best place to get it right now is the SVN repository, but it's fairly stable. http://svn.enthought.com/svn/enthought/branches/converge/kiva/ -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From cemerick at snowtide.com Wed Dec 15 17:50:21 2004 From: cemerick at snowtide.com (Chas Emerick) Date: Wed, 15 Dec 2004 17:50:21 -0500 Subject: Html or Pdf to Rtf (Linux) with Python In-Reply-To: <20041214122121.CFC4B1E4006@bag.python.org> References: <20041214122121.CFC4B1E4006@bag.python.org> Message-ID: I haven't seen any solid responses come across the wire, and I suspect there isn't a product or package that will do exactly what you want. However, our company's product, PDFTextStream does do a phenomenal job of extracting text and metadata out of PDF documents. It's crazy-fast, has a clean API, and in general gets the job done very nicely. It presents two points of compromise from your idea situation: 1. It only produces text, so you would have to take the text it provides and write it out as an RTF yourself (there are tons of packages and tools that do this). Since the RTF format has pretty weak formatting capabilities compared to PDF (and even compared to HTML+CSS), you'd likely never reproduce the original layout/content of the source document anyway. 2. It is a Java library. You indicated in a later message that you were aiming to use a python package if possible just out of personal preference. Assuming such a thing does not exist, and you are able to introduce a Java component to your project, this would become a non-issue. Let me know what your questions are. Chas Emerick cemerick at snowtide.com Snowtide Informatics Systems PDFTextStream: fast PDF text extraction for Java apps and Lucene http://snowtide.com/home/PDFTextStream/ Alexander Straschil wrote: > Hello! > > I have to convert an HTML document to rtf with python, was just > googling > for an hour and did find nothing ;-( > Has anybody an Idea how to convert (under Linux) an HTML or Pdf > Document > to Rtf? > > Thanks, AXEL From jerf at jerf.org Sun Dec 5 13:35:28 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Sun, 05 Dec 2004 13:35:28 -0500 Subject: long number multiplication References: Message-ID: On Sun, 05 Dec 2004 09:02:18 +0530, I.V. Aprameya Rao wrote: > i have been wondering, how does python store its very long integers and > perform aritmetic on it. > > i needed to implement this myself and was thinking of storing the digits > of an integer in a list. Uh, why? What possible environment are you programming in where the correct answer isn't to grab one of many high-quality libraries to do it? (Homework? If that's the case the Python source will likely prove too complicated to be useful to you due to optimization, though I haven't read it and I don't directly know.) From danb_83 at yahoo.com Fri Dec 17 14:34:02 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 17 Dec 2004 11:34:02 -0800 Subject: BASIC vs Python In-Reply-To: References: <867jnh1i9v.fsf@guru.mired.org> <41c2af36$0$2443$afc38c87@news.easynet.co.uk> Message-ID: <1103312042.243592.147300@z14g2000cwz.googlegroups.com> Peter Otten wrote: > Peter Hickman wrote: > > > Mike Meyer wrote: > >> BASIC as implented by Microsoft for the Apple II and the TRS 80 (among > >> others) is simply the worst programming language I have ever > >> encountered. Assembler was better - at least you had recursion with > >> assembler. > > > > Basic has progressed much since you last looked at it, time to update your > > facts. Basic has recursion, it compiles to native code, it has objects, > > can be event driven and everything else you would expect of a language. > > > > Computing changes too fast to allow you to think you know it all. Keep up > > to date granddad. > > > > However what basic doesn't have is a portable language definition. > > May you could give us an idea of the current state of basic affairs then by > translating the following example snippet: > > It's me wrote: > > > I saw this code from an earlier post: > > > > lst1 = ["ab", "ac", "ba", "bb", "bc"] > > lst2 = ["ac", "ab", "bd", "cb", "bb"] > > dct1 = dict.fromkeys(lst1) # <-- I'll assume "lst2" was intended. > > print [x for x in lst1 if x not in dct1] > > print [x for x in lst1 if x in dct1] > > > > It's simply remarkable for somebody to be able to do it so cleanly (and so > > obviously) - "out of the box", if you may. > > > > Sure, you can do it in Basic. Ur...sure? Yes, sure... In Microsoft QBasic (1987), this could be written as: DECLARE FUNCTION INARRAY% (ARR() AS STRING, X AS STRING) DIM LST1(4) AS STRING DIM LST2(4) AS STRING DIM I AS INTEGER FOR I = 0 TO UBOUND(LST1) READ LST1(I) NEXT FOR I = 0 TO UBOUND(LST2) READ LST2(I) NEXT ' Print the elements of LST1 that are NOT in LST2 FOR I = 0 TO UBOUND(LST1) IF INARRAY(LST2(), LST1(I)) = 0 THEN PRINT LST1(I); " "; NEXT PRINT ' Print the elements of LST1 that are in LST2 FOR I = 0 TO UBOUND(LST1) IF INARRAY(LST2(), LST1(I)) = 1 THEN PRINT LST1(I); " "; NEXT PRINT ' Elements of LST1 DATA "AB", "AC", "BA", "BB", "BC" ' Elements of LST2 DATA "AC", "AB", "BD", "CB", "BB" FUNCTION INARRAY% (ARR() AS STRING, X AS STRING) ' Return 1 if X in ARR, 0 otherwise DIM I AS INTEGER FOR I = LBOUND(ARR) TO UBOUND(ARR) IF X = ARR(I) THEN INARRAY = 1 EXIT FUNCTION END IF NEXT INARRAY = 0 END FUNCTION From jcarlson at uci.edu Sun Dec 5 13:31:12 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 05 Dec 2004 10:31:12 -0800 Subject: string slicing In-Reply-To: References: <34534aed04120506395391d13d@mail.gmail.com> Message-ID: <20041205100937.ECCF.JCARLSON@uci.edu> "Fredrik Lundh" wrote: > > Ishwor wrote: > > > I am trying some interactive examples here where i have come across > > inconsistencies??? :O > > obsession with implementation artifacts is a premature optimization, > and should be avoided. [snip] > a suggestion: if you really want to be productive in python, forget about > "is" for a while. The above two tips are in my "top-10 things to tell newbs" list. - Josiah From jeff at ccvcorp.com Thu Dec 16 18:05:40 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 16 Dec 2004 15:05:40 -0800 Subject: Module question In-Reply-To: References: <1103143345.721887.80940@c13g2000cwb.googlegroups.com> <86sm67hzt3.fsf@guru.mired.org> <10s1rdn8dnkjj51@corp.supernews.com> Message-ID: <10s44usrrg86s84@corp.supernews.com> Simon Brunning wrote: >On Wed, 15 Dec 2004 18:10:40 -0800, Jeff Shannon wrote: > > > >>The difference being that when Excel opens up a *.CSV, it goes through >>the import wizard. >> >> > >Are you sure that's true? When I open a *.csv file, Excel *appears* to >open it without running any kind of wizard. Certainly I don't see any >wizard dialogues. > > You're right, my mistake -- I was thinking of tab-delimited *.txt files, which I deal with far more often than I do *.csv ... Jeff Shannon Technician/Programmer Credit International From R.Brodie at rl.ac.uk Fri Dec 3 07:39:33 2004 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 3 Dec 2004 12:39:33 -0000 Subject: Versioning Libraries References: <4nOrd.1870$Bo.1233@lakeread03> Message-ID: "Peter Hansen" wrote in message news:copjeg$t25$1 at utornnr1pp.grouptelecom.net... > Anyway, you're confusing "instability" (I hate that word, > it has connotations of unreliability, which aren't intended) > with "enhancement". The API gets changed, yes, but by > adding new things, almost never by removing the old stuff > or changing how it works. I'm not confusing it, I'm disagreeing. Take xreadlines, for example. Added in 2.1, deprecated in 2.3, removed in 2.4 Perhaps I lead a sheltered life but that's almost infinitely worse than any other language I have used. It's not a big issue though: I'm just surprised that what I would regard as a weakness in Python, others consider a strength. From insert at spam.here Mon Dec 20 18:45:19 2004 From: insert at spam.here (Doug Holton) Date: Mon, 20 Dec 2004 17:45:19 -0600 Subject: Boo who? (was Re: newbie question) In-Reply-To: References: <1103503985.015510.24680@z14g2000cwz.googlegroups.com> Message-ID: Peter Hansen wrote: > Doug Holton wrote: > >> Peter Hansen wrote: >> >>> "Virtually identical" indeed. :-) >> >> >> As noted on the website that I've pointed out to you multiple times >> now, the syntax of boo is indeed virtually identical to python. The >> functionality however, is more like C#. > > > Sadly your second post hasn't reached my news server, which is > quite flaky. Fortunately (checking Google Groups), I see it > added nothing of substance, as it merely points to the site again, > without addressing my comments about how syntactical similarity > or even identity doesn't justify the term "virtually identical", > which implies that in all respects one thing is essentially > identical to another. I gave such a short answer because the way you framed your "questions" and the context of your post made it clear you are a troll. Your reply here was yet another troll. You are one of the reasons why so-called "newbies" and others are being intimidated away from this list. -Doug From fumanchu at amor.org Mon Dec 13 11:42:34 2004 From: fumanchu at amor.org (Robert Brewer) Date: Mon, 13 Dec 2004 08:42:34 -0800 Subject: Tibia 0.1 DOM-based website editor Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339801F@exchange.hqamor.amorhq.net> Richie Hindle wrote: > [Robert] > > Tibia is an in-browser editor for web pages. It allows you > to quickly > > and easily modify the content of your web pages. It allows you to > > directly view, edit, and save files on your webserver. > > Very impressive! I ran into a couple of difficulties but > otherwise it's a great tool. Thanks! We're starting to use it already in-house. > I had to hard-code a username - does it require you to use HTTP > authentication before it will work? If so, it would be good if you > mentioned that in the documentation. Currently, it requires you to use *some* form of authentication. I'm working on a way to get around that for intranet deployers who don't care (but _should_, but hey, it's their loss). If you set up your own site, you also need to have somebody in the Admin group if you want to get any editing done. > It also erased my HTML file when I tried to save my changes. > 8-) I'll try to track that one down if I get the chance. Sorry about that. Tibia switches between three modes: web, upload, and server. The initial release had an ugly pattern where you would open a webpage, switch to server mode (without realizing it) by clicking the "server" flyout button and then hit save--and get nothing saved because you thought you were still in "web mode". I changed the events a bit in recent releases so that doesn't happen anymore; you only change to server mode when you actually load a file from the server. Numerous other buglets fixed over the weekend. Thanks for the feedback, all! Robert Brewer MIS Amor Ministries fumanchu at amor.org From alban at magproductions.nl Thu Dec 2 09:18:21 2004 From: alban at magproductions.nl (Alban Hertroys) Date: Thu, 02 Dec 2004 15:18:21 +0100 Subject: A little threading problem In-Reply-To: <41AF1169.1010400@bellsouth.net> References: <41ADDF1C.6030205@magproductions.nl> <41ADFE1A.8030304@bellsouth.net> <41AF030F.6000208@magproductions.nl> <41AF1169.1010400@bellsouth.net> Message-ID: <41AF242D.8000907@magproductions.nl> Jeremy Jones wrote: > * the get method on a queue object has a "block" flag. You can > effectively poll your queues something like this: > > #untested code > #a_done, b_done and c_done are just checks to see if that particular > document is done > while not (a_done and b_done and c_done): > got_a, got_b, got_c = False, False, False > item_a, item_b, item_c = None, None, None > while (not a_done) and (not got_a): > try: > item_a = queue_a.get(0) #the 0 says don't block and raise an > Empty exception if there's nothing there Actually, it is just fine to let get() block, as long as I put(None) on the queue when I reach document_end and test for it (removing it from the "list of queues to read" when get() returns 'None'). I rewrote my test script (the one I sent to the NG) to use Queues this way, and it works well. It's also a lot easier to read/follow. Currently I'm implementing it in my application. I'm glad I don't get paid by the number of lines I write, there are going to be less lines at the end of today ;) Thanks a lot for the pointers. From apardon at forel.vub.ac.be Thu Dec 23 06:16:39 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 23 Dec 2004 11:16:39 GMT Subject: Mutable objects which define __hash__ (was Re: Why are tuples immutable?) References: <20041215152606.1029.1225319887.divmod.quotient.10976@ohm> <10s48r5hbse5o57@corp.supernews.com> <41c350ef.331854992@news.oz.net> <41c9103e.708509723@news.oz.net> <1Miyd.695395$mD.58375@attbi_s02> Message-ID: Op 2004-12-23, Nick Coghlan schreef : > Steven Bethard wrote: >> Of course, if rehash worked in place, you could probably do some >> optimizations to only rehash the necessary items. > > Yep, especially given this little critter from dictobject.h which contains > everything needed to spot mutated objects: > > typedef struct { > long me_hash; /* cached hash code of me_key */ > PyObject *me_key; > PyObject *me_value; > } PyDictEntry; > > So the major downside to giving standard mutable objects hash methods is that > dictionaries then suffer from the 'mutation without resorting' problem that > sorted lists can currently suffer from. > > As I said to Antoon, I no longer have any theoretical objection to the idea of > mutable objects with a variable hash. I do, however, have a practical objection > - mutating a dict's keys without calling rehash() could lead to some extremely > subtle bugs that the interpreter can't really help identify. It just seems far > too easy to inadvertently burn yourself by altering an object that is being used > as a dictionary key. Well then we will have to agree to disagree on this point. Python allows one variable to mutate by mutating another variable. That is IMO the great burning stick in Python. That this also causes problems for dictionaries is just a consequent of that and doesn't warrant special protection that is not available elsewhere in the language. I don't understand why the ease of mutating an object that should remain stable should cause more unease in a person just because the subject is dictionary keys, except maybe because of custom. But I'm obviously in the minority here. -- Antoon Pardon From mr at berrs.net Thu Dec 23 08:41:43 2004 From: mr at berrs.net (Per Erik Stendahl) Date: Thu, 23 Dec 2004 14:41:43 +0100 Subject: test Message-ID: <41CACB17.1010302@berrs.net> sdfdsafasd From mwm at mired.org Mon Dec 27 11:13:08 2004 From: mwm at mired.org (Mike Meyer) Date: Mon, 27 Dec 2004 10:13:08 -0600 Subject: Optional Static Typing - Haskell? References: <1103795375.843649.286620@c13g2000cwb.googlegroups.com> <1gpaypu.hp5icf1tvg99cN%aleaxit@yahoo.com> <41cc504b$1_1@127.0.0.1> <1gpbe96.1ioa9lt1t622shN%aleaxit@yahoo.com> <41ccbefb$1_2@127.0.0.1> <1gpcl19.13v2d481su0if2N%aleaxit@yahoo.com> <86d5wx93ra.fsf@guru.mired.org> <1gpedy7.1kwy16r153aiw1N%aleaxit@yahoo.com> <86zn005qpj.fsf@guru.mired.org> <41cfbaf9$1_1@127.0.0.1> Message-ID: <86ekhbvhwr.fsf@guru.mired.org> "Donn Cave" writes: > Quoth Mike Meyer : > | aleaxit at yahoo.com (Alex Martelli) writes: > ... > |> But then, the above criticism applies: if interface and implementation > |> of a module are tightly coupled, you can't really do fully modular > |> programming AND static typing (forget type inferencing...). > | > | I beg to differ. Eiffel manages to do this quite well. Then again, > | every Eiffel environment comes with tools to extract the interface > | information from the code. With SmartEiffel, it's a command called > | "short". Doing "short CLASSNAME" is like doing "pydoc modulename", > | except that it pulls routine headers and DbC expression from the code, > | and not just from comments. > > And you probably think Eiffel supports fully modular programming, as > I thought Objective CAML did. But Alex seems not to agree. > > The way I understand it, his criteria go beyond language level semantics > to implementation details, like whether a change to a module may require > dependent modules to be recompiled when they don't need to be rewritten. > I don't know whether it's a reasonable standard, but at any rate hopefully > he will explain it better than I did and you can decide for oneself whether > it's an important one. I read through his explanation. And the answer for Eiffel is, of course, "it depends". There's an optimization that embeds a class data directly in the cilent class - the expanded keyword. If you have an expanded variable or type in your client class, then changing the implementation of the provider may require recompilation of the client. On the other hand, that's pretty much an optimization, and so you shouldn't run into it during development. SmartEiffel, on the other hand, always does full-source analysis. It drops class features that aren't used by any client, so changing the client can cause the provider to be recompiled. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From achan_work at yahoo.com Tue Dec 28 16:09:48 2004 From: achan_work at yahoo.com (A Chan) Date: Tue, 28 Dec 2004 13:09:48 -0800 (PST) Subject: install questions Message-ID: <20041228210948.63829.qmail@web20624.mail.yahoo.com> Hi, All, I'm new in Python. I just install ActivePython 2.4 on my PC and also install SOAPpy-0.11.6.zip, soapy-0.1.win32.exe. When I run the following script, I got no module named SOAPpy. Am I missing any modules? Thanks Angela ================================================ error message: Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\test1.py", line 1, in ? import SOAPpy ImportError: No module named SOAPpy ===================================================== Python script: import SOAPpy WSDL_URI = "http://www.xmethods.net/sd/2001/TemperatureService.wsdl" service = SOAPpy.WSDL.Proxy(WSDL_URI) # if you are behind a proxy server, you need to set this service.soapproxy.http_proxy = 'PROXY_HOST:PROXY_PORT' # set config so that we dump the SOAP envelopes # (sometimes you will be thrilled to see the SOAP envelopes) service.soapproxy.config.dumpSOAPOut = 1 service.soapproxy.config.dumpSOAPIn = 1 temp = service.getTemp('90210') # get temperature in Beverly Hills print 'The temperature in Beverly Hills is',temp,'F' ======================================================= __________________________________ Do you Yahoo!? Yahoo! Mail - You care about security. So do we. http://promotions.yahoo.com/new_mail From godoy at ieee.org Thu Dec 30 06:20:01 2004 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Thu, 30 Dec 2004 09:20:01 -0200 Subject: Updating file objects automatically References: <1160841.oW121ZHhx1@strongwill.g2ctech> Message-ID: <1391870.TqRmD9O327@strongwill.g2ctech> Craig Ringer, Quinta 30 Dezembro 2004 06:27, wrote: > I couldn't really catch your explanation, but mention of changing all > instances of a class suggests that you may be in a situation where you > need to modify the class, not its instances. There are two methods I use > when I have to change things across all instances: I'm sorry. It was late here and I've been coding this and other things for near 14h in a row... I think that even I wouldn't understand that if I weren't working with it :-) > I have no idea if that's actually appropriate for your needs, it's just > a stab in the dark, but perhaps it might be. It helps, yes. Putting the object on the class instead of on an instance of it might (I'm 99.9% sure) solve the problem. (I have already done that for other object that is shared, but I didn't remember doing that for this) Thank you. You helped a lot to make me "see" it :-) -- Godoy. From rschroev_nospam_ml at fastmail.fm Thu Dec 30 10:58:07 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 30 Dec 2004 15:58:07 GMT Subject: Why tuples use parentheses ()'s instead of something else like <>'s? In-Reply-To: References: <1104299822.394489.161500@z14g2000cwz.googlegroups.com> Message-ID: Rocco Moretti wrote: > So to summarize: > > Commas define tuples, except when they don't, and parentheses are only > required when they are necessary. > > I hope that clears up any confusion. You have my vote for QOTW. -- "Codito ergo sum" Roel Schroeven From steve at holdenweb.com Mon Dec 20 09:56:15 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 20 Dec 2004 09:56:15 -0500 Subject: mx Oddity in FC3/RedHat ES In-Reply-To: <201220040902041431%junk@azarcon.com> References: <201220040902041431%junk@azarcon.com> Message-ID: Eric Azarcon wrote: > Hello! > > I've installed the mx package from egenix, and I am experiencing pretty > odd behaviour. > > If I launch python and run the following commands, I get an error: > > >>>>import mx >>>>from mx import * >>>>mx.DateTime.today() > Well, from anything import * is bad form for any module unless (like Tkinter, for example) it's been specifically designed to support this behavior. Since "the mx package" is actually a number of inter-dependent packages you are almost guaranteeing trouble here. mx is not designed to be imported, it's just a common namespace for a number of modules by the same author. > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'module' object has no attribute 'DateTime' > Try: Python 2.4 (#1, Dec 4 2004, 20:10:33) [GCC 3.3.3 (cygwin special)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import mx.DateTime as dt >>> dt.today() >>> > > OK, great. However, if I then ask for help on the mx package first, the > above command will work. > > >>>>help() > > help> modules > -- list of modules -- > help> mx > -- displays mx info -- > help> mx.DateTime > -- displays mx.DateTime info -- > help> --quit help here -- > >>>>mx.DateTime.today() > > > > Any ideas what is going on? Is there a path problem that gets resolved > by calling help()? > > Note that issuing help(mx) doesn't work. You have to go into help, do > the modules listing and then ask for mx. > Well, the help system actually imports the subpackages that live in the mx space when you ask for help about them. So that's why doing that allows you to resolve those names. > This same behaviour is displayed on my Fedora Core 3 box running > mx-2.0.5-3, and on 2 separate machines running RHEL-ES (most recent > version with updates applied) and egenix-mx-base-2.0.6-py2.2_1. > > Any help would be very appreciated! > It's just a matter of using the packages in the intended way. > Thanks, > No problem. > Eric > > p.s. the background is that I need to use mx because the target boxes > only have Python 2.2 on them. Using DateTime from Python 2.3 would be > preferred, but being a newbie, I have no idea how to compile just that > module from source and install it into 2.2. *sigh* Well the first thing to try would be dropping it into /usr/lib/python2.2 and seeing if you can import it without errors. You might actually find that the built-in "time" module contains enough date/time functionality for your needs if they are simple. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From steven.bethard at gmail.com Thu Dec 16 16:18:57 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 16 Dec 2004 21:18:57 GMT Subject: cmp of multiple attributes (WAS: Why are tuples immutable?) In-Reply-To: References: <20041215152606.1029.1225319887.divmod.quotient.10976@ohm> Message-ID: <5Zmwd.272268$R05.114851@attbi_s53> Roy Smith wrote: > class Property: > def __init__ (self, block, lot, zoning="Unknown"): > self.block = block > self.lot = lot > self.zoning = zoning > > def __hash__ (self): > return (self.block + self.lot) > > def __cmp__ (self, other): > # I wish there was a less verbose way to do this! > if self.block < other.block: > return -1 > if self.block > other.block: > return 1 > if self.lot < other.lot: > return -1 > if self.lot > other.lot: > return 1 > return 0 Does this do what you want? >>> class Property(object): ... def __init__(self, block, lot): ... self.block, self.lot = block, lot ... def __cmp__(self, other): ... return (cmp(self.block, other.block) or ... cmp(self.lot, other.lot)) ... >>> for i in (0, 1): ... for j in (0, 1): ... for k in (0, 1): ... for l in (0, 1): ... print i, j, k, l, cmp(Property(i,j),Property(k,l)) ... 0 0 0 0 0 0 0 0 1 -1 0 0 1 0 -1 0 0 1 1 -1 0 1 0 0 1 0 1 0 1 0 0 1 1 0 -1 0 1 1 1 -1 1 0 0 0 1 1 0 0 1 1 1 0 1 0 0 1 0 1 1 -1 1 1 0 0 1 1 1 0 1 1 1 1 1 0 1 1 1 1 1 0 Steve From steven.bethard at gmail.com Fri Dec 17 04:53:52 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 17 Dec 2004 09:53:52 GMT Subject: Cool object trick In-Reply-To: References: <97B6410BE753D411894E00D0B77E6F7F0340BF53@neam2mx1.corp.emc.com> <%Oxwd.251809$HA.98890@attbi_s01> Message-ID: Alex Stapleton wrote: > you are setting the variable name in your code (b.varA), not generating > the variable name in a string (var = "varA") (dictionary key) at > run-time and fetching it from the __dict__ like i was attempting to > describe. Ahh. Well if you just want to get an attribute, I don't see why you wouldn't do it the normal way: >>> b = Bunch(varA="Hello!") >>> getattr(b, "varA") 'Hello!' That's what getattr's for. ;) No need to go poking around in __dict__. Steve From bounces at foo.org Fri Dec 17 23:07:20 2004 From: bounces at foo.org (Dan) Date: Sat, 18 Dec 2004 04:07:20 GMT Subject: BASIC vs Python In-Reply-To: References: Message-ID: Steve Holden wrote: > Which, now I remember, Digital Equipment extended to floating-point in > their FOCAL language. Never used FOCAL, or VAX Basic for that matter (was it the same thing?), but I can remember calling the VAX Basic BAS$EDIT routine from Pascal in college. BAS$EDIT had most of the basic string operations that are common today, like trimming whitespace, splitting, upper or lower casing, etc., and using it was easier than using Pascal's facilities. My wife picked up an old (c) 1978 version of DEC's Basic user's guide, and it doesn't list this function, so it must have been added between then and 1985 when I encountered it. /Dan -- dedded att verizon dott net From bob_smith_17280 at hotmail.com Wed Dec 15 13:02:32 2004 From: bob_smith_17280 at hotmail.com (bob_smith_17280 at hotmail.com) Date: 15 Dec 2004 10:02:32 -0800 Subject: Fill a Server References: <1103128682.041915.62730@c13g2000cwb.googlegroups.com> Message-ID: <1103133752.402673.76140@c13g2000cwb.googlegroups.com> I think you solved it Fredrik. The first ten folders looked like this: D:\0\1\2\3\4\5\6\7\8\9 22 Chars long. The rest looked like this: \10\11\12\13....\82\83\84 ~ 222 CHars long. Subdir 84 had one file in it named XXXXXXXXXXX.bat That file broke the 255 limit, then subdir 85 wasn't created and when the script tried to copy a file to 85, an exception was raised. Not that it matters. Interesting to know that limits still exists and that this is a NTFS issue. From stephen.thorne at gmail.com Wed Dec 22 23:13:28 2004 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 23 Dec 2004 14:13:28 +1000 Subject: Lambda going out of fashion Message-ID: <3e8ca5c8041222201332fb0b92@mail.gmail.com> Hi guys, I'm a little worried about the expected disappearance of lambda in python3000. I've had my brain badly broken by functional programming in the past, and I would hate to see things suddenly become harder than they need to be. An example of what I mean is a quick script I wrote for doing certain actions based on a regexp, which I will simlify in this instance to make the pertanant points more relevent. { 'one': lambda x:x.blat(), 'two': lambda x:x.blah(), }.get(someValue, lambda x:0)(someOtherValue) The alternatives to this, reletively simple pattern, which is a rough parallel to the 'switch' statement in C, involve creating named functions, and remove the code from the context it is to be called from (my major gripe). So, the questions I am asking are: Is this okay with everyone? Does anyone else feel that lambda is useful in this kind of context? Are there alternatives I have not considered? merrily-yr's Stephen. From aleaxit at yahoo.com Wed Dec 29 05:35:18 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 29 Dec 2004 11:35:18 +0100 Subject: what would you like to see in a 2nd edition Nutshell? Message-ID: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> I'm considering proposing to O'Reilly a 2nd edition of "Python in a Nutshell", that I'd write in 2005, essentially to cover Python 2.3 and 2.4 (the current 1st edition only covers Python up to 2.2). What I have in mind is not as complete a rewrite as for the 2nd vs 1st edition of the Cookbook -- Python hasn't changed drastically between 2.2 and 2.4, just incrementally. Language and built-ins additions I'd of course cover -- decorators, custom descriptors (already in 2.2 but not well covered in the 1st edition), importing from zipfiles, extended slicing of built-in sequences, sets, genexps, ... and also major new standard library modules such as (in no special order) optparse, tarfile, bsddb's new stuff, logging, Decimal, cookielib, datetime, email... and new capabilities of existing modules, such as thread-local storage. Outside of the standard library, I was thinking of expanding the coverage of Twisted and adding just a few things (numarray -- perhaps premature to have it _instead_ of Numeric, though; dateutils, paramiko, py2app...). Since the book's size can't change much, I'll also have to snip some stuff (the pre-email ways to deal with mail, for example; modules asyncore and asynchat, probably) to make space for all of the additions. I haven't take any real decisions about it, yet, except one: I'll keep covering Tkinter, rather than moving to, say, wxPython (no space to _add_ wx coverage while leaving Tk intact - having to choose, I still believe Tkinter coverage is going to help more readers). Just about everything else is still to be finalized in my mind... So, if there's any advice or request about a 2nd edition of the Nutshell, this is the right time for y'all to let me know. Feedback is welcome, either privately or right here. Thanks in advance -- _and_ apologies in advance because I know I just won't be able to accomodate all the requests/advice, given the constraints on book size &c. Alex From kael at alussinan.org Fri Dec 10 10:29:02 2004 From: kael at alussinan.org (kael) Date: Fri, 10 Dec 2004 16:29:02 +0100 Subject: Python + Newspipe Message-ID: <41B9C0BE.4030106@alussinan.org> Hello, I'm trying to run _Newspipe_ but Python returns an error : ----------------------------------------------------------------------- [root at kael root]# python2.3 /home/kael/newspipe/newspipe.py newspipe.py - version 1.1.1 revision 1.42, Copyright (C) 2003-2004 Ricardo M. Reyes Traceback (most recent call last): File "/home/kael/newspipe/newspipe.py", line 1484, in ? MainLoop() File "/home/kael/newspipe/newspipe.py", line 1323, in MainLoop config = LeerConfig() File "/home/kael/newspipe/newspipe.py", line 895, in LeerConfig for attr in ini.options('NewsPipe'): File "/usr/local/lib/python2.3/ConfigParser.py", line 240, in options raise NoSectionError(section) ConfigParser.NoSectionError: No section: 'NewsPipe' ----------------------------------------------------------------------- Unfortunately, I'm new to Linux (RedHat9) and to Python (2.3) and I'm not able to understand this error message. Could someone enlighten me ? O:-) Thank you very much. -- kael From jepler at unpythonic.net Mon Dec 20 12:40:58 2004 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 20 Dec 2004 11:40:58 -0600 Subject: List limits In-Reply-To: <1103561252.512434.143870@z14g2000cwz.googlegroups.com> References: <1103561252.512434.143870@z14g2000cwz.googlegroups.com> Message-ID: <20041220174057.GD30996@unpythonic.net> I'm referring to Python 2.2's C headers as I answer this question. I believe some of may have changed by 2.4. The number of elements in a "variable-sized object" (those with Py_VAR_HEAD; I believe this includes lists, tuples, and strings) is stored in a platform 'int'. On most (desktop) systems, this means the limit of any sized object is no more than 2**31-1, or about 2 billion. On those same systems, a list object of length 128 million, give or take, approximately 512 megabytes of memory will be allocated for the list object itself (4 bytes for each pointer-to-element). If each element of the list is distinct, those objects will each require additional memory---The smallest useful Python object takes around 16 bytes, IIRC, which would bring the total memory required to around 2560 megabytes if I didn't screw up my arithmetic. This is close to (or over, depending on the system) the maximum amount of physical RAM these machines can accomodate, and the maximum amount of address space available to a single program. While performing list-resizing operations, there may be a temporary need for two copies of the list object itself, bumping the memory used up to 3 gigs. Finally, the speed of some operations (l.index(item), l.pop(0), l.insert(0, item)) are related linearly to the size of the list, so your program may slow down as the lists it manipulates grow. Others, such as l[i], l.pop(), and l.append(item), are constant-time or amortized-constant- time. Jeff -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ian at kirbyfooty.com Mon Dec 20 02:41:38 2004 From: ian at kirbyfooty.com (ian at kirbyfooty.com) Date: 19 Dec 2004 23:41:38 -0800 Subject: Python To Send Emails Via Outlook Express In-Reply-To: <41C67E3D.5040205@kdart.com> References: <1103519604.987664.117400@c13g2000cwb.googlegroups.com> <1103521500.427846.238790@c13g2000cwb.googlegroups.com> <41C67E3D.5040205@kdart.com> Message-ID: <1103528498.945675.43920@z14g2000cwz.googlegroups.com> Hi Keith Thanks for your reply. I am aware of the smtplib module and it works very well! (refer script below) The problem is that I have a developed a freeware application called Kirby Alarm And Task Scheduler (see www.kirbyfooty.com). The program can pop up a note, run a program, play a sound, or send an email at whatever intervals the user wants.. When it comes to sending emails the user has the option of sending them via smtp, or via there email client (eg outlook express). I prefer the send method as this makes setting up the email parameters a lot easier for the user. As the program is used by over 16,000 people around the world I don't want to complicate things by asking them to enter the mail server properties. Because Python is so powerful I want to develop a suite of applications in Python that Kirby Alarm can run. Things like FTP, Backup, Speech etc would be excellent There has to be a way for Python to send emails via Outlook Express.... Kind regards Ian PS Here is the working script for sending emails via SMTP.. ----------------------------------------------------------------------------------------------------------------- # Import smtplib for the actual sending function import os import sys import smtplib import mimetypes from email.Encoders import encode_base64 from email.MIMEAudio import MIMEAudio from email.MIMEBase import MIMEBase from email.MIMEImage import MIMEImage from email.MIMEMultipart import MIMEMultipart from email.MIMEText import MIMEText FROM = 'i... at kirbyfooty.com' TO = 'i... at cgbs.com.au;i... at yahoo.com' SUBJECT = 'This is the subject' MSGBODY = 'This the body of the message ' ATTACHSTR = 'c:/ian.txt;c:/c55/footytip/2003finalresults.txt;c:/snap.jpg' MAILSERVER = 'insert mail server' port = 25 username = 'insert username' password = 'insert password' # trim the strings of any leading or trailing spaces FROM = FROM.strip() TO = TO.strip() SUBJECT = SUBJECT.strip() MSGBODY = MSGBODY.strip() ATTACHSTR = ATTACHSTR.strip() MAILSERVER = MAILSERVER.strip() username = username.strip() password = password.strip() # function to attach files def getAttachment(path, filename): ctype, encoding = mimetypes.guess_type(path) if ctype is None or encoding is not None: ctype = 'application/octet-stream' maintype, subtype = ctype.split('/', 1) fp = open(path, 'rb') if maintype == 'text': attach = MIMEText(fp.read(),_subtype=subtype) elif maintype == 'message': attach = email.message_from_file(fp) elif maintype == 'image': attach = MIMEImage(fp.read(),_subtype=subtype) elif maintype == 'audio': attach = MIMEAudio(fp.read(),_subtype=subtype) else: print maintype, subtype attach = MIMEBase(maintype, subtype) attach.set_payload(fp.read()) encode_base64(attach) fp.close attach.add_header('Content-Disposition', 'attachment', filename=filename) return attach #Connect to server print 'Connecting to mail server ', MAILSERVER try: s = smtplib.SMTP(MAILSERVER,port) #s.set_debuglevel(1) except: print 'ERROR: Unable to connect to mail server', MAILSERVER sys.exit(1) #login to server if password <> '': print 'Logging into mail erver' try: s.login(username,password) except: print 'ERROR: Unable to login to mail server', MAILSERVER print 'Please recheck your password' sys.exit(1) # get list of email addresses to send to ToList = TO.split(';') print 'Sending email to ', ToList # set up email parameters msg = MIMEMultipart() msg['From'] = FROM msg['To'] = TO msg['Subject'] = SUBJECT msg.attach(MIMEText(MSGBODY)) # get list of file attachments AttachList = ATTACHSTR.split(';') for file in AttachList: try: attach = getAttachment(file,os.path.basename(file)) msg.attach(attach) except: print 'Error attaching ',file pass # send email s.sendmail(FROM, ToList, msg.as_string()) s.quit() s.close() print 'done' ----------------------------------------------------------------------------------------- From titus at caltech.edu Fri Dec 17 03:29:20 2004 From: titus at caltech.edu (C. Titus Brown) Date: Fri, 17 Dec 2004 00:29:20 -0800 Subject: sgmllib problem & proposed fix. Message-ID: Hi all, while playing with PBP/mechanize/ClientForm, I ran into a problem with the way htmllib.HTMLParser was handling encoded tag attributes. Specifically, the following HTML was not being handled correctly: The 'value' attr was being given the escaped value, not the correct unescaped value, 'Small (6")'. It turns out that sgmllib.SGMLParser (on which htmllib.HTMLParser is based) does not unescape tag attributes. However, HTMLParser.HTMLParser (the newer, more XHTML-friendly class) does do so. My proposed fix is to change sgmllib to unescape tags in the same way that HTMLParser.HTMLParser does. A context diff to sgmllib.py from Python 2.4 is at the bottom of this message. I'm posting to this newsgroup before submitting the patch because I'm not too familiar with these classes and I want to make sure this behavior is correct. One question I had was this: as you can see from the code below, a simple string.replace is done to replace encoded strings with their unencoded translations. Should handle_entityref be used instead, as with standard HTML text? Another question: should this fix, if appropriate, be back-ported to older versions of Python? (I doubt sgmllib has changed much, so it should be pretty simple to do.) thanks for any advice, --titus *** /u/t/software/Python-2.4/Lib/sgmllib.py 2004-09-08 18:49:58.000000000 -0700 --- sgmllib.py 2004-12-16 23:30:51.000000000 -0800 *************** *** 272,277 **** --- 272,278 ---- elif attrvalue[:1] == '\'' == attrvalue[-1:] or \ attrvalue[:1] == '"' == attrvalue[-1:]: attrvalue = attrvalue[1:-1] + attrvalue = self.unescape(attrvalue) attrs.append((attrname.lower(), attrvalue)) k = match.end(0) if rawdata[j] == '>': *************** *** 414,419 **** --- 415,432 ---- def unknown_charref(self, ref): pass def unknown_entityref(self, ref): pass + # Internal -- helper to remove special character quoting + def unescape(self, s): + if '&' not in s: + return s + s = s.replace("<", "<") + s = s.replace(">", ">") + s = s.replace("'", "'") + s = s.replace(""", '"') + s = s.replace("&", "&") # Must be last + + return s + class TestSGMLParser(SGMLParser): From fredrik at pythonware.com Mon Dec 13 16:48:53 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 13 Dec 2004 22:48:53 +0100 Subject: do you master list comprehensions? References: <1102971085.659444.22790@z14g2000cwz.googlegroups.com> <41be044c$0$289$edfadb0f@dread12.news.tele.dk> Message-ID: Max M wrote: >> I tried funnies like [[w for w in L] for L in data], >> that is correct syntax, but you'd never guess. > > That is absolutely correct. It's not a funnie at all. If you find it odd it's only because you are > not used to list comprehensiones. well, syntactically correct or not, it doesn't do what he want... > In that case you might be more comfortable with: > > data = [['foo','bar','baz'],['my','your'],['holy','grail']] > result = [] > for l in data: > result += l how about (slightly evil): result = []; map(result.extend, data) From joewong at mango.cc Mon Dec 6 21:50:53 2004 From: joewong at mango.cc (Joe Wong) Date: Tue, 7 Dec 2004 10:50:53 +0800 Subject: httpconnection class handle 302 redirect? Message-ID: <00b401c4dc07$92253410$7f00a8c0@scl01.siliconcreation.com> Hi , it looks like that HTTPConnection class is not capable to handle 302 redirect response. Is there any sample implementation that tackle this problem? I am using python 2.3.3 on Windows platform. best regards, - Joe --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.806 / Virus Database: 548 - Release Date: 2004/12/5 -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Wed Dec 8 02:14:43 2004 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 8 Dec 2004 02:14:43 -0500 Subject: memoize factorial example (was Re: decorators ?) References: <1102458244.004fc0dc548f5536ec77f769e501ff1e@teranews> <1f7befae04120718513e297ae6@mail.gmail.com> Message-ID: "Tim Peters" wrote in message news:1f7befae04120718513e297ae6 at mail.gmail.com... > Terry, since you're talking about "the rabbit problem", are you sure > you're talking about the factorial example? It sounds like you're > talking about the Fibonacci example. Of course. 0! is 1 multiplied by nothing (not 0) which is 1, just as n**0 is 1 multiplied by n 0 times and hence 1. TJR From nick at craig-wood.com Tue Dec 14 01:47:26 2004 From: nick at craig-wood.com (Nick Craig-Wood) Date: 14 Dec 2004 06:47:26 GMT Subject: Performance (pystone) of python 2.4 lower then python 2.3 ??? References: Message-ID: Peter Hansen wrote: > For comparison, I do get a decent speedup. Machine is an > AMD Athlon XP 2500+ (1.82GHz) running Win XP Pro SP2. > > Python 2.3.4: 36393 pystones. > Python 2.4: 39400 pystones. > > ...about an 8% speedup. On my 2.6 GHz P4 running debian testing I got the following results :- $ for p in 2.1 2.2 2.3 2.4; do echo $p; python$p pystone.py 1000000 ; done 2.1 Pystone(1.1) time for 1000000 passes = 40.67 This machine benchmarks at 24588.1 pystones/second 2.2 Pystone(1.1) time for 1000000 passes = 39.64 This machine benchmarks at 25227 pystones/second 2.3 Pystone(1.1) time for 1000000 passes = 32.49 This machine benchmarks at 30778.7 pystones/second 2.4 Pystone(1.1) time for 1000000 passes = 29.88 This machine benchmarks at 33467.2 pystones/second Showing that 2.4 is the fastest so far! (And is also a good advert for AMD ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From michele.simionato at gmail.com Fri Dec 3 09:50:36 2004 From: michele.simionato at gmail.com (Michele Simionato) Date: 3 Dec 2004 06:50:36 -0800 Subject: Curses programming, threads? References: Message-ID: <4edc17eb.0412030650.68ae87d4@posting.google.com> Bartlomiej Rymarski wrote in message news:... > Bartlomiej Rymarski wrote: > > [...] > > And the loader() function would run in a loop until connect_db() is > > is finished. Is that possible in python? Or are there any other, > > better ways to do it? > > [...] > > Oh, I forgot - I'm using Linux, and curses module in Python 2.3. You don't need curses. Some time ago somebody (I forgot the name) posted this spinner class: class Spinner( threading.Thread ): # a google search should find the author DELAY = 0.1 DISPLAY = [ '|', '/', '-', '\\' ] def __init__( self, before='', after='' ): threading.Thread.__init__( self ) self.before = before self.after = after def run( self ): write, flush = sys.stdout.write, sys.stdout.flush self.running = 1 pos = -1 while self.running: pos = (pos + 1) % len(self.DISPLAY) msg = self.before + self.DISPLAY[pos] + self.after write( msg ) flush() write( '\x08' * len(msg) ) time.sleep( self.DELAY ) write( ' ' * len(msg) + '\x08' * len(msg) ) flush() def stop( self ): self.running = 0 self.join() if __name__=="__main__": spinner = Spinner('Be patient please ...') spinner.start() time.sleep(5) # doing a long operation spinner.stop() Michele Simionato From Erik.geiger at gmx.de Tue Dec 21 19:58:23 2004 From: Erik.geiger at gmx.de (Erik Geiger) Date: Wed, 22 Dec 2004 01:58:23 +0100 Subject: how to start a new process while the other ist running on Message-ID: Hi, sorry, my english ist not that got but I'll try. I have a running python script (capisuit incoming.py). This script shall start a linux shell script. If I start this script like os.system(/paht/to shellscipt.sh) the python scipt waits for the exit of the shell script and then goes on with the rest of the python script. How to start a shell script without waiting for the exit of that shell script? It shall start the shell script and immediately execute the next python command. Thanks for any hints Erik -- Jemanden wie ein rohes Ei zu behandeln kann auch bedeuten, ihn in die Pfanne zu hauen. From matt.gerrans at hp.com Wed Dec 1 15:15:49 2004 From: matt.gerrans at hp.com (Matt Gerrans) Date: Wed, 01 Dec 2004 20:15:49 GMT Subject: Converting String to Class References: Message-ID: You didn't specify exactly how the string is parsed, so this is a guess: class Thingy(object): def __init__(self,rawinfo): self.StructId, vq,self.ProcessName = rawinfo.split() self.Version,self.QName = vq.split('.') def __str__(self): return '' % (self.StructId, self.Version, self.QName, self.ProcessName) t = Thingy( "TMC 2TEST.QUEUE LV1871.MQPROCESS" ) str(t) -> '' - mfg From apardon at forel.vub.ac.be Tue Dec 21 04:47:10 2004 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 21 Dec 2004 09:47:10 GMT Subject: Why are tuples immutable? References: <41BE1644.8050906@freemail.gr> <10s1si0fb0l4pae@corp.supernews.com> <10s4a4rso24vb83@corp.supernews.com> Message-ID: Op 2004-12-18, Nick Coghlan schreef : > Antoon Pardon wrote: >> Would you have us construct two related classes each time we find >> ourselves in such a situation and copy an object from one >> class to the other depending on the circumstances? > > Python itself seems to think so, given the pairings of set/frozenset & list/tuple. > > Using genuinely immutable objects as dictionary keys is much easier than saying > "while this object is part of a dictionary, don't alter it's hash value or > comparison results". Instead, the immutable version is provided to say > "alterations are not allowed on this copy" Why then doesn't python think the same about sorted lists. When I have a sorted list and do operations on it that depend on it being sorted, I can mess things up just as easily by mutating an element in that sorted list as I can mess things up by mutating a dictionary key. > You can certainly *do* the former (using __hash__ and appropriate comparison > overrides), but it isn't particularly easy to do correctly, > and hence usually > isn't a great idea unless copies are *really* expensive (and even then, a > shallow copy approach can often suffice). The problem is you have to make copies evrywhere. You have to copy when you insert a key, you have to make a copy when you access by key, you have to copy when you want your key be used as an object. -- Antoon Pardon From steven.bethard at gmail.com Wed Dec 8 03:48:43 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 08 Dec 2004 08:48:43 GMT Subject: guarding for StopIteration (WAS: Help with generators outside of loops.) In-Reply-To: <62ztd.532216$D%.125153@attbi_s51> References: <62ztd.532216$D%.125153@attbi_s51> Message-ID: Steven Bethard wrote: > Just to clarify here, the only time code raising a StopIteration will > cause a for-loop to exit silently is if the StopIteration is raised in > an __iter__ method, e.g.: That was a little imprecise. What I should have said is "the only time code raising a StopIteration will cause a for-loop to exit silently is if the StopIteration is raised in the code that is executed under the iteration protocol." So, using the legacy iterator protocol: >>> class C: ... def __getitem__(self, index): ... if index > 3: ... raise IndexError ... if index == 1: ... raise StopIteration ... return index ... >>> for i in C(): ... print i ... 0 Or using a separate iterator object: >>> class C(object): ... def __iter__(self): ... return I() ... >>> class I(object): ... def __init__(self): ... self.count = -1 ... def next(self): ... self.count += 1 ... if self.count == 1: ... raise StopIteration ... return self.count ... >>> for i in C(): ... print i ... 0 Or using a generator to create the iterator object: >>> class C(object): ... def __iter__(self): ... for i in range(3): ... if i == 1: ... raise StopIteration ... yield i ... >>> for i in C(): ... print i ... 0 Basically, each of these raises a StopIteration in the equivalent of the .next method. If a function that raises a StopIteration is put into any of the places where my code says 'raise StopIteration', then that StopIteration will silently terminate the loop. I don't believe there should be any other places where raising a StopIteration would silently terminate a loop. Steve From aleaxit at yahoo.com Thu Dec 30 12:07:37 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 30 Dec 2004 18:07:37 +0100 Subject: Why tuples use parentheses ()'s instead of something else like <>'s? References: <1104299822.394489.161500@z14g2000cwz.googlegroups.com> <41d2ce43$0$35731$a1866201@visi.com> <10t5p4nedr06h94@news.supernews.com> Message-ID: <1gpmcad.1czfj31knykrrN%aleaxit@yahoo.com> John Roth wrote: ... > and division. We've allowed ourselves to be limited by the > ASCII character set for so long that improving that seems to be > outside of most people's boxes. APL didn't allow itself to be limited that way. Anybody who's used it can hardly be accused to keep non-ASCII characters "outside their box". And, you know what? Despite being an old APL user, I think would be a _disaster_ for Python to go that route. Yes, ASCII imposes design constraints. But constraints can be a good and helpful thing. Look for example at what classical architects and sculptors DID, within horrible technical constraints on materials and methods, and compare it with artsy modern architecture, which can use an enormously wider palette of technical approaches and materials... I think a tiny minority of today's architecture and sculpture can rightfully be compared with the masterpieces of millennia past. Similarly, highly constrained forms such as sonnet or haiku can unchain a poet's creativity in part BECAUSE of the strict constraints they impose wrt free verse or prose... Back to feet-on-ground issues, mandating a wider-than-ASCII character set would horribly limit the set of devices, as well as of software tools, usable with/for Python -- I love the fact that Python runs on cellphones, for example. Input methods for characters outside the ASCII set are always a bother, particularly to the touch-typist: even to enter Italian accented vowels, on this US keyboard, I have to go through definitely eccessive gyrations, which horribly slow down my usually very fast typing. Seeing what you're doing can sometimes be a bother too: you need to ensure the glyphs for all the characters you need are readable _and distinguishable_ in whatever font you're using. Alex From fumanchu at amor.org Sun Dec 19 19:50:22 2004 From: fumanchu at amor.org (Robert Brewer) Date: Sun, 19 Dec 2004 16:50:22 -0800 Subject: atmosphere on c.l.py (WAS: How about "pure virtual methods"?) Message-ID: <3A81C87DC164034AA4E2DDFE11D258E3398081@exchange.hqamor.amorhq.net> Fredrik Lundh wrote: > well, since I'm not in the ego-stroking business, what if I > promise never to > reply to posts by you, robert, and alex? ?? I'll take your replies anytime. You're a long way from all noise and no signal. I'm happy to learn what I can from you. Robert Brewer MIS Amor Ministries fumanchu at amor.org From ali.jan at gmail.com Mon Dec 20 10:09:54 2004 From: ali.jan at gmail.com (Ali) Date: 20 Dec 2004 07:09:54 -0800 Subject: Newbie: A very basic problem related to cgi.py In-Reply-To: References: <1103550481.686003.172960@f14g2000cwb.googlegroups.com> <1103553998.949172.254000@c13g2000cwb.googlegroups.com> Message-ID: <1103555394.211384.79830@z14g2000cwz.googlegroups.com> >1. When you tried "import cgi.py" from the interactive prompt, >was that really what you typed? Because that's not a valid >import statement for the cgi module. You should have done >"import cgi" instead. import cgi was giving me the same error, because it was importing from the cgi.pyc? >3. There's something strange about that traceback, I >think. Why does it show the doc-string for the module, >and why does it show a comment after the "line 6" line? >Did you hand-edit this before posting it? nope, i didn't edit anything... > maybe of the forehead-slapping kind. Thanks for the reply, yes it was :) From tim.golden at viacom-outdoor.co.uk Thu Dec 9 13:29:42 2004 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 9 Dec 2004 18:29:42 -0000 Subject: Users Message-ID: <9A28C052FF32734DACB0A288A3533991035926@vogbs009.gb.vo.local> [python1] | Do you know of a way to list the users on a Win2K machine? I | can't seem to find a module for this. Interpretation 1: who is in the user database of a given machine? Investigate the win32net module. Something like this: import win32net import win32netcon MACHINE_NAME = 'VOGBP200' resume = 0 while 1: (_users, total, resume) = \ win32net.NetUserEnum ( MACHINE_NAME, 1, win32netcon.FILTER_NORMAL_ACCOUNT, resume, win32netcon.MAX_PREFERRED_LENGTH ) for _user in _users: print _user['name'] if not resume: break Using active directory might also be a possibility. As with many such questions, the first question is: how do you do this in Windows generally? And then: how do you translate that to Python? Interpretation 2: who is currently logged on to the machine? This is more difficult. On XP / 2003, there are WMI classes to tell you this (Win32_LoggedOnUser) but not on 2000. Likewise, there are LsaEnumerateLogonSessions in XP+, but not on 2000. Anyone else got any ideas? TJG ________________________________________________________________________ This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk ________________________________________________________________________ From grante at visi.com Fri Dec 3 17:49:34 2004 From: grante at visi.com (Grant Edwards) Date: 03 Dec 2004 22:49:34 GMT Subject: using cmd.exe as a telnet client References: Message-ID: <41b0ed7e$0$85066$a1866201@visi.com> On 2004-12-03, Donnal Walter wrote: > Several months ago I tried using the telnet module (on Windows XP) to > communicate with a proprietary host on our network. This was > unsuccessful due to problems with "option negotiation", and I gave up on > the project for a while. I still have need for this, however, so I > recently started thinking about alternatives. I suppose I could dig deep > enough into option negotiation to use the socket module (with telnet as > a guide), but I am hoping to find a way to use fewer synapses. You don't have to start from scratch. The telnet module has hooks built-into it1 so that you can have it call your routines to handle option negotiation. I did it once to impliment some extra Telnet protocol features, and it wasn't difficult. -- Grant Edwards grante Yow! How's the wife? Is at she at home enjoying visi.com capitalism? From usenet_spam at janc.invalid Tue Dec 7 22:15:06 2004 From: usenet_spam at janc.invalid (JanC) Date: Wed, 08 Dec 2004 03:15:06 GMT Subject: Python installation breaks Outlook Express References: <1102366583.345135.36990@z14g2000cwz.googlegroups.com> Message-ID: Mike schreef: > I have the same problem. It isn't a problem with Outlook. It is with > Python. I loose my wired AND wireless connections. Removing Python > bringst them back to operational. > Mike I don't know about the wired/wireless connections above, but this: > M. Laymon wrote: >> I just installed Python 2.3.3 under Windows XP professional. After I >> did, my wife tried to access her email using Outlook Express and got >> the error messages: >> >> Your server has unexpectedly terminated the connection. Possible >> causes for >> this include server problems, network problems, or a long period of >> inactivity. >> Account: 'incoming.verizon.net', Server: 'outgoing.verizon.net', >> Protocol: SMTP, Port: 25, Secure(SSL): No, Error Number: 0x800CCC0F >> >> Your server has unexpectedly terminated the connection. Possible >> causes for this >> include server problems, network problems, or a long period of >> inactivity. >> Account: 'incoming.verizon.net', Server: 'incoming.verizon.net', >> Protocol: POP3, >> Port: 110, Secure(SSL): No, Error Number: 0x800CCC0F >> >> (No comments about Outlook, please.I have tried to get her to use a >> different email program, but she likes Outlook.) I checked the >> settings, then recreated her account in Outlook, but nothing worked. >> My Mozilla Thunderbird email client worked fine. >> >> Since the only thing I had done recently was to install Python. I >> used system restore to go back to the point before installing Python. >> After I did, Outlook started working again. Has anyone else seen >> this behavior ? ... might happen if you use a Python program to filter spam in Outlook (e.g. SpamBayes). This error is often caused by a personal firewall blocking such a filter program, and after a Python upgrade, every Python program will be considered "unknown". -- JanC "Be strict when sending and tolerant when receiving." RFC 1958 - Architectural Principles of the Internet - section 3.9 From benji at benjiyork.com Fri Dec 24 00:09:00 2004 From: benji at benjiyork.com (Benji York) Date: Thu, 23 Dec 2004 23:09:00 -0600 Subject: String backslash characters In-Reply-To: <1103863993.900799.142090@z14g2000cwz.googlegroups.com> References: <1103863993.900799.142090@z14g2000cwz.googlegroups.com> Message-ID: <41CBA46C.3050205@benjiyork.com> PD wrote: > I am new to python, but i am quite curious about the following. > > print '\378' > > which should not work because \377 is the max. then it displays two > characters (an 8 and a heart in my case...). What else does'nt quite > make sense is that if this is an octal why is an 8 accepted? It would appear that the parser reads \377 as a single character and \378 as two (\37 and the "8" character). I'm somewhat surprised you're seeing a heart and an 8. What OS/language combination are you using? If you're using English Windows you can get a heart and an "8" with "print '\38'". -- Benji York benji at benjiyork.com From km at mrna.tn.nic.in Fri Dec 3 11:44:48 2004 From: km at mrna.tn.nic.in (km) Date: Fri, 3 Dec 2004 22:14:48 +0530 Subject: exec size Message-ID: <20041203164448.GA25118@mrna.tn.nic.in> Hi all, just curious to know why /usr/bin/python2.3 is 890K and /usr/bin/python2.4 is 3.5M in linux ? tia, KM From steve at holdenweb.com Wed Dec 29 08:21:37 2004 From: steve at holdenweb.com (Steve Holden) Date: Wed, 29 Dec 2004 08:21:37 -0500 Subject: MySQLdb Windows Installer (2.4) published [was: Problems installing MySQLdb on Windows [newbie]] In-Reply-To: References: <41D1DF9D.1070105@holdenweb.com> Message-ID: <9fyAd.61850$Jk5.14232@lakeread01> Alex Meier wrote: > In article <41D1DF9D.1070105 at holdenweb.com>, steve at holdenweb.com says... > >>http://pydish.holdenweb.com/pwp/MySQL-python.exe-1.0.0.win32-py2.4.exe >> >>That's a ready-to-go no-compilation-required installer for Windows >>Python 2.4, and will get you going straight away. > > > Thanx a lot, Steve! This worked without a hitch. > Great. I don't know what Andy Dustman's situation is right now, but he's clearly not got time to maintain MySQLdb. Since it's likely other people will want this I've added it to the Holden Web public domain Python page at http://www.holdenweb.com/Python/index.html -- that way Google might pick it up, who knows. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From les_ander at yahoo.com Mon Dec 13 16:24:31 2004 From: les_ander at yahoo.com (les_ander at yahoo.com) Date: 13 Dec 2004 13:24:31 -0800 Subject: how do I "peek" into the next line? In-Reply-To: <1102964987.812024.5180@c13g2000cwb.googlegroups.com> References: <1102964987.812024.5180@c13g2000cwb.googlegroups.com> Message-ID: <1102973071.239704.167280@z14g2000cwz.googlegroups.com> OK, I am sorry , I did not explain my problem completely. I can easily break from the loop when I see the character in a line that I just read; however my problem involves putting back the line I just read since if I have seen this special character, I have read one line too many. Let me illustrate suppose the file has 3 lines line1.line1.line1 >line2.line2.line line3.line3.line3 now suppose I have read the first line already. then I read the second line and notice that there is a ">" in front (my special character) then I want the put back the second line into the file or the stdin. An easy way is if i read all the lines in to an array and then I can put back the line with the special character back into this array. However, this file I am readding is huge! and I can read it all in one swoop (not enough memory). for x in stdin: if x[0]==">": #### put back the x some how... <----- break else: print x I hope this is clear thanks From philippecmartin at sbcglobal.net Tue Dec 7 11:51:23 2004 From: philippecmartin at sbcglobal.net (Philippe C. Martin) Date: Tue, 7 Dec 2004 10:51:23 -0600 Subject: Loading a file only once into an object and being able to access it from other modules Message-ID: <200412071051.23251.philippecmartin@sbcglobal.net> Thank you all for your answers, I guess I would not have made Python 101:-) As far as I was concerned, importing a module twice would have resulted in loading the file twice. Regards, Philippe -- ********************* Philippe C. Martin SnakeCard LLC www.snakecard.com ********************* From unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom Sun Dec 26 05:24:05 2004 From: unseulmcmcmcmc at msupprimerlepoint.claveauPOINTcom (Michel Claveau - abstraction méta-galactique non triviale en fuite perpétuelle.) Date: Sun, 26 Dec 2004 11:24:05 +0100 Subject: where is ctypes.py? References: <1104055174.719604.287630@c13g2000cwb.googlegroups.com> Message-ID: <41ce9b7d$0$24541$8fcfb975@news.wanadoo.fr> Hi ! See : http://starship.python.net/crew/theller/ctypes/ From tonino.greco at gmail.com Thu Dec 23 01:03:46 2004 From: tonino.greco at gmail.com (Tonino) Date: 22 Dec 2004 22:03:46 -0800 Subject: mathmatical expressions evaluation References: <1103719856.106409.190100@z14g2000cwz.googlegroups.com> <1103749275.393821.280000@z14g2000cwz.googlegroups.com> Message-ID: <1103781826.906893.49710@c13g2000cwb.googlegroups.com> thanks all for the info - and yes - speed is not really an issue and no - it is not an implementation of a complete financial system - but rather a small subset of a investment portfolio management system developed by "another company" ... What I am trying to achieve is to parse a formula(s) and generate a result ... I will look into the pyparsing suggested and maybe even leave out numarrays for now - as it seems a bit overkill ... The formula are a bit complex and maybe even difficult to write out Thanks all - I will post my progress ;) From stephen.thorne at gmail.com Thu Dec 23 08:34:37 2004 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 23 Dec 2004 23:34:37 +1000 Subject: Lambda going out of fashion In-Reply-To: <1gp91wn.1v9e6hb1qiryc2N%aleaxit@yahoo.com> References: <1gp91wn.1v9e6hb1qiryc2N%aleaxit@yahoo.com> Message-ID: <3e8ca5c8041223053471b130f6@mail.gmail.com> On Thu, 23 Dec 2004 13:47:49 +0100, Alex Martelli wrote: > Nick Coghlan wrote: > ... > > Perhaps something like: > > > > accepts_func( (def (a, b, c) to f(a) + o(b) - o(c)) ) > > Nice, except I think 'as' would be better than 'to'. 'as' should be a > full keyword in 3.0 anyway (rather than a surprisingly-NOT-keyword like > today), and "define something as somethingelse" seems marginally more > readable to me than "define something to somethingelse" anyway. I'm sorry, but I dislike this quite a bit, 'def arglist as expression' just doesn't fit right for me. After reading the discussion, and trying to glean answers to my original questions, I realise that there's a pragmatic way of doing the things that I mentally 'require' lambda for, without using lambda at all. I might try and catalog lambda patterns and their alternatives at some point. Alex, thankyou for the feedback concerning the misuse of lambda. I consider prevention of misuse to be much more important than the denial of use. I recognise fully the frustration you must experience when you see map(lambda x:f(x). I think it is important to voice concern, and I recieved not a few 'me-too's in reply to this thread. But at the end of the day, I'm not against removing lambda in py3k. slightly-less-concerned-ly yr's Stephen Thorne. From danperl at rogers.com Thu Dec 16 20:19:04 2004 From: danperl at rogers.com (Dan Perl) Date: Thu, 16 Dec 2004 20:19:04 -0500 Subject: Python IDE References: <1103141895.620517.49860@z14g2000cwz.googlegroups.com> <1103218159.737726.241440@z14g2000cwz.googlegroups.com> <86zn0d20x8.fsf@guru.mired.org> Message-ID: <4M2dnXr5POuUqV_cRVn-iA@rogers.com> "Mike Meyer" wrote in message news:86zn0d20x8.fsf at guru.mired.org... > A: What's the most obnoxious thing on Usenet? > Q: topposting. What is "Jeopardy", Alex? You got your Q&A mixed up. So what, just because I wrote at the top of the posting you couldn't see my warning sign for the sarcasm impaired? Dan From davidb at mcs.st-and.ac.uk Tue Dec 7 17:06:50 2004 From: davidb at mcs.st-and.ac.uk (davidb at mcs.st-and.ac.uk) Date: 7 Dec 2004 14:06:50 -0800 Subject: PDF count pages References: Message-ID: <1102457210.266459.42630@c13g2000cwb.googlegroups.com> Andreas Lobinger wrote: > > Jose Benito Gonzalez Lopez wrote: > > Does anyone know how I could do in order > > to get/count the number of pages of a PDF file? > > Like this ? [...] > >>> import pdffile > >>> pf = pdffile.pdffile('../rfc1950.pdf') > >>> import pages > >>> pp = pages.pages(pf) > >>> len(pp.pagelist) [...] That's interesting. Here's my equivalent example: Python 2.3.3 (#1, May 2 2004, 15:04:07) [GCC 3.2.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from pdftools import pdffile >>> doc = pdffile.PDFDocument("PDFSPEC.pdf") >>> doc.count_pages() 518 The API shown above is from an unreleased version of pdftools (http://www.boddie.org.uk/david/Projects/Python/pdftools/). > This is an example of the usage of pdfplayground. pdfplayground > is available via sourceforge. There is no package at the > moment, but you should be able to check out via anon-cvs. I browsed the code in CVS and it looks like a pretty comprehensive implementation. Maybe we should join forces. David From steven.bethard at gmail.com Mon Dec 20 14:04:11 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 20 Dec 2004 19:04:11 GMT Subject: Silly questions about True and False In-Reply-To: References: Message-ID: drs wrote: > I just upgraded my Python install, and for the first time have True and > False rather than 1 and 0. I was playing around at the command line to test > how they work (for instance, "if 9:" and "if True:" both lead to the > conditional being executed, but True == 9 -> False, that this would be true > was not obvious to me Note that evaluating to True isn't the same as being equal to True. Would you also expect that [] == None? Both evaluate to False in a boolean context. Or an even better example, would you expect that [1] == [2]? Both of these evaluate to True in a boolean context... What you should expect is that: py> bool([]) == bool(None) == False True py> bool([1]) == bool([2]) == True True > "True is True" is True, while "9 is True" is false > even though 9 evaluates to True.) Be careful here. 'is' tests object identity. So "9 is True" would only evaluate to True if 9 is exactly the same object as True. 'is' won't convert anything to a boolean; "x is y" basically translates to "id(x) == id(y)". > why doesn't False = 0 throw the same error? Backwards compatibility. A lot of modules pre-False and True have code that looks like: True, False = 1, 0 or True, False = (1 == 1), (1 == 0) If assignment to True or False became a syntax error (which it probably should be), it would break all such code. > Also, why doesn't False = 0 make > >>>>1 == 2 > 0 > > Instead of False? You've only rebound the name False in your module's namespace. 1 == 2 executes the int code for equality, which presumably returns one of Py_False or Py_True, not your binding for the name False in your module. Steve From jeff at ccvcorp.com Tue Dec 14 13:25:03 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue, 14 Dec 2004 10:25:03 -0800 Subject: gather information from various files efficiently In-Reply-To: <3e96ebd7.0412140111.69244c7c@posting.google.com> References: <3e96ebd7.0412140111.69244c7c@posting.google.com> Message-ID: <10rubol981h2c25@corp.supernews.com> Klaus Neuner wrote: >Yet, I have got 43 such files. Together they are 4,1M >large. In the future, they will probably become much larger. >At the moment, the process takes several hours. As it is a process >that I have to run very often, I would like it to be faster. > > Others have shown how you can make your dictionary code more efficient, which should provide a big speed boost, especially if there are many keys in your dicts. However, if you're taking this long to read files each time, perhaps there's a better high-level approach than just a brute-force scan of every file every time. You don't say anything about where those files are coming from, or how they're created. Are they relatively static? (That is to say, are they (nearly) the same files being read on each run?) Do you control the process that creates the files? Given the right conditions, you may be able to store your data in a shelve, or even proper database, saving you lots of time in parsing through these files on each run. Even if it's entirely new data on each run, you may be able to find a more efficient way of transferring data from whatever the source is into your program. Jeff Shannon Technician/Programmer Credit International From ebonakDUH at hotmail.com Thu Dec 16 22:06:21 2004 From: ebonakDUH at hotmail.com (Esmail Bonakdarian) Date: Thu, 16 Dec 2004 22:06:21 -0500 Subject: Is Python good for graphics? In-Reply-To: <8KGdnUWZVJISrlzcRVn-2Q@comcast.com> References: <10s1bdaj7gbin8e@corp.supernews.com> <8KGdnUWZVJISrlzcRVn-2Q@comcast.com> Message-ID: <10s4j9e9ss1gd57@corp.supernews.com> Doug Holton wrote: > > I'll tell you know it's not going to be so easy. There isn't something > in python like flash. But here are some options: > > See pyxel for python: http://bellsouthpwp.net/p/r/prochak/pyxel.html > and pygame: http://pygame.org/ > Gato, the graph animation toolkit, is implemented in python and tkinter: > http://www.zpr.uni-koeln.de/~gato/ cool, thanks for the links, I'll take a look. > You know you can use java with python, too. It's called jython. You > could use jython to interface the open source physics toolkit, for > example: http://www.opensourcephysics.org/ > See also the Jython Environment for Students (JES). A book about it is > supposed to be published tomorrow actually. > > And you can use a python-like language for .NET called boo with the > Piccolo.NET structured graphics toolkit: http://www.cs.umd.edu/hcil/jazz/ > or these graph drawing toolkits: http://netron.sourceforge.net/ewiki/ > http://www.codeproject.com/cs/miscctrl/quickgraph.asp hmm .. more options. I guess my preference would be to stick just with Python if possible. regards, Esmail From michael at stroeder.com Fri Dec 3 18:02:58 2004 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Sat, 04 Dec 2004 00:02:58 +0100 Subject: ANN: python-ldap-2.0.6 Message-ID: Find a new release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.0.6 2004-12-03 Changes since 2.0.5: Lib/: * Added sub-module ldap.dn * Added function ldap.dn.escape_dn_chars() * Special check when implicitly setting SUP 'top' to structural object classes without SUP defined to avoid a loop in the super class chain. From and-google at doxdesk.com Mon Dec 20 15:13:10 2004 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 20 Dec 2004 12:13:10 -0800 Subject: Web forum (made by python) In-Reply-To: References: <32m5g1F3on6drU1@individual.net> Message-ID: <1103573590.469519.18910@z14g2000cwz.googlegroups.com> Choe, Cheng-Dae wrote: > example site is http://bbs.pythonworld.net:9080/pybbs.py Since this seems quite happy to accept posted
action="HierarchyControllerServlet/start/"> > This is an omission from the params you are passing to the HierarchyServlet. Although the "printParams" field is not visible to you in a browser, the browser still submits a name/value pair in its form submission. So you should also in your code, as shwon below. > Also, you are using the wrong value for the taxonomy field. You are setting a value of "bergeys", which is the ID of the field, not its value. The correct value is "rdpHome". > --------Python test code--------------- > #!/usr/bin/python > > import urllib > > options = [("strain", "type"), ("source", "both"), > ("size", "gt1200"), ("taxonomy", "bergeys"), > ("browse", "Browse")] Try this options = [ ("printParams", "no"), ("strain", "type"), ("source", "both"), ("size", "gt1200"), ("taxonomy", "rdpHome"), ("browse", "Browse"),] > > params = urllib.urlencode(options) > > rdpbrowsepage = urllib.urlopen( > "http://rdp.cme.msu.edu/hierarchy/HierarchyControllerServlet/start", > params) > > pagehtml = rdpbrowsepage.read() > > print pagehtml > ---------end Python test code---------- HTH, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From davidf at sjsoft.com Fri Dec 3 04:18:49 2004 From: davidf at sjsoft.com (David Fraser) Date: Fri, 03 Dec 2004 11:18:49 +0200 Subject: inheritance problem with 2 cooperative methods In-Reply-To: References: Message-ID: Dan Perl wrote: > Here is a problem I am having trouble with and I hope someone in this group > will suggest a solution. First, some code that works. 3 classes that are > derived from each other (A->B->C), each one implementing only 2 methods, > __init__ and setConfig. > ------------------------------------------------------- > #!/usr/bin/python > class A (object): > def __init__(self): > super(A, self).__init__() > self.x = 0 > def setConfig(self, config): > self.x += config['x'] > > class B (A): > def __init__(self): > super(B, self).__init__() > self.y = 0 > def setConfig(self, config): > super(B, self).setConfig(config) > self.y += config['y'] > > class C (B): > def __init__(self): > super(C, self).__init__() > self.z = 0 > def setConfig(self, config): > super(C, self).setConfig(config) > self.z += config['z'] > > config = {'x':1, 'y':2, 'z':3} > alpha = A() > alpha.setConfig(config) > print alpha.x > beta = B() > beta.setConfig(config) > print beta.x, beta.y > beta.setConfig(config) > print beta.x, beta.y > gamma = C() > gamma.setConfig(config) > print gamma.x, gamma.y, gamma.z > gamma.setConfig(config) > print gamma.x, gamma.y, gamma.z > -------------------------------------------------- > > The output from that code is: > 1 > 1 2 > 2 4 > 1 2 3 > 2 4 6 > > So far, so good! But let's assume that I want to change the __init__ > methods so that they take a configuration as an argument so the objects are > created and configured in one step, like this: > alpha = A(config) > > How can the code be changed to implement this? It is tempting to modify the > __init__ methods like this: > class A (object): > def __init__(self, config): > super(A, self).__init__(config) > self.x = 0 > A.setConfig(self, config) > > However, if implemented this way, the output is: > 1 > 2 2 > 3 4 > 3 4 3 > 4 6 6 > > This shows that setConfig gets called more than once because both __init__ > and setConfig are cooperative methods. > > I have been thinking about this for a day now and I cannot find a good > solution. I imagine this would be a common problem and that there would be > a recipe somewhere, but I couldn't find one (I looked in the Python > Cookbook). I've thought of creating 2 separate methods instead of > setConfig, one that does the "local" configuration and another one that > takes care of invoking super. But I don't like the idea of creating 2 > methods in each class and I haven't been able to think of a way to solve the > problem with just one change in the base class that would be inherited by > all the subclasses. > > Anyone has any ideas? Thanks. What about using an attribute in the base class to remember whether initial config has been done? This seems to work: #!/usr/bin/python class A (object): def __init__(self, config): self.x = 0 self.configinitialized = False super(A, self).__init__() if not self.configinitialized: self.setConfig(config) def setConfig(self, config): self.x += config['x'] self.configset = True class B (A): def __init__(self, config): self.y = 0 super(B, self).__init__(config) def setConfig(self, config): super(B, self).setConfig(config) self.y += config['y'] class C (B): def __init__(self, config): self.z = 0 super(C, self).__init__(config) def setConfig(self, config): super(C, self).setConfig(config) self.z += config['z'] config = {'x':1, 'y':2, 'z':3} alpha = A(config) print alpha.x beta = B(config) print beta.x, beta.y beta.setConfig(config) print beta.x, beta.y gamma = C(config) print gamma.x, gamma.y, gamma.z gamma.setConfig(config) print gamma.x, gamma.y, gamma.z From roy at panix.com Mon Dec 13 20:53:11 2004 From: roy at panix.com (Roy Smith) Date: Mon, 13 Dec 2004 20:53:11 -0500 Subject: [dictionary] how to get key by item References: Message-ID: In article , Skip Montanaro wrote: > Egor> i know how to get item by key > ... > Egor> but i wonder how to get key by item > > Assuming your dictionary defines a one-to-one mapping, just invert it: > > >>> forward = {10 : 50, 2 : 12, 4 : 43} > >>> reverse = dict([(v,k) for (k,v) in forward.iteritems()]) > >>> print forward > {10: 50, 4: 43, 2: 12} > >>> print reverse > {50: 10, 43: 4, 12: 2} > > That doubles your storage, so you'll have to trade that off against the > speed gain of not having to loop over the entire dictionary. Well, you *do* loop over the entire dictionary, but you only do it once, when you create the reverse dict. If you are only going to do a single lookup, it's no gain, but if you amortize the cost over many lookups, it's almost certainly a big win. This raises an interesting question. Let's assume that you add all the entries to the dictionary before you do any lookups, and you then need to lookup things up in both directions. Which is faster, to simultaneously build both the forward and reverse dicts, or to just build the forward one and when you're done doing that, build the reverse one in a single shot with the above list comprehension? BTW, does Python really build the intermediate list and throw it away after using it to initialize the dictionary, or is it smart enough to know that it doesn't really need to build the whole list in memory? From kjmacken at gmail.com Fri Dec 17 13:39:24 2004 From: kjmacken at gmail.com (kjm) Date: 17 Dec 2004 10:39:24 -0800 Subject: Create linear spaced vector? Message-ID: <6ca895b5.0412171039.7586077d@posting.google.com> Hi Everyone, I am trying to port some old MatLab code to python, and am stuck on how to accomplish something. I am trying to write a generalized function that will create a linearly spaced vector, given the start and end point, and the number of entries wanted. In MatLab I have this function that I wrote: [code] function out = linearspace(x1,x2,n) out = [x1+ (0:n-2)*(x2 - x1)/(floor(n)-1) x2]; return [/code] I have the numeric package, numarray installed, and I think it should be accomplished easily, but I just can't seem to get the syntax correct with python. Any tips would be greatly appreciated. Thanks From steven.bethard at gmail.com Wed Dec 22 16:42:16 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 22 Dec 2004 21:42:16 GMT Subject: list IndexError In-Reply-To: References: Message-ID: Ishwor wrote: > i am trying to remove an item 'e' from the list l I thought it might be helpful to code some of the alternatives you've been given and look at the timings to put things into perspective. The code: -------------------- remove.py -------------------- def remove_lc(x, lst): lst[:] = [item for item in lst if item != x] def remove_list(x, lst): result = [] for item in lst: if item != x: result.append(item) lst[:] = result def remove_filter(x, lst): lst[:] = filter(lambda item: item != x, lst) def remove_xrange(x, lst): for i in xrange(len(lst)-1, -1, -1): if lst[i] == x: del lst[i] def remove_remove(x, lst): while x in lst: lst.remove(x) def remove_try(x, lst): try: while True: lst.remove(x) except ValueError: pass def remove_ishwor(x, lst): for item in lst[:]: if item == x: lst.remove(x); -------------------------------------------------- First, some timings when only 1 out of every 1000 elements needs to be removed. Timings were taken with Python 2.4 on a 2.26 Ghz Windows box using: $ python -m timeit -s "import remove; lst = [x % 1000 for x in xrange(10000)]" "remove.remove_(500, lst)" remove_remove: 516 usec per loop remove_try: 604 usec per loop remove_ishwor: 1.61 msec per loop remove_xrange: 2.29 msec per loop remove_lc: 2.37 msec per loop remove_list: 5.3 msec per loop remove_filter: 5.65 msec per loop Now, some timings when 1 out of every 10 elements needs to be removed. Timings were taken using: $ python -m timeit -s "import remove; lst = [x % 10 for x in xrange(10000)]" "remove.remove_(5, lst)" remove_lc: 2.03 msec per loop remove_xrange: 2.08 msec per loop remove_list: 4.72 msec per loop remove_filter: 5.17 msec per loop remove_try: 30.7 msec per loop remove_ishwor: 31.5 msec per loop remove_remove: 60.2 msec per loop The moral of the story here is that, if the items to be removed only make up a very small percentage of the list, an approach like remove_remove or remove_try might be okay. On the other hand, if you expect the items to be removed will make up even a moderate percentage of the list (e.g. 10%), then remove_lc or remove_xrange is a vastly better alternative. Steve From gh at ghaering.de Thu Dec 30 11:02:29 2004 From: gh at ghaering.de (Gerhard Haering) Date: Thu, 30 Dec 2004 17:02:29 +0100 Subject: [OT] Azureus Java BitTorrent client - was: Re: Probleme mit der Installation der openSource Bittorrent.... python vs JAVA In-Reply-To: References: Message-ID: <20041230160229.GA4132@mylene.ghaering.de> On Thu, Dec 30, 2004 at 07:24:45AM -0800, xunling wrote: > Hallo, > > ich h?tte da mal eine Frage zum Azureus bttrn client. [...] [I'd have a question about the Azureus BitTorrent client.] While the original BitTorrent is implemented in Python, this is not the right mailing list/newsgruop for Java BitTorrent clients. The Azureus homepage has a guide on how to get it running on various operating systems. Perhaps these instructions will help you: http://azureus.sourceforge.net/howto_win.php -- Gerhard -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From ch.list at us-hampton.mail.saic.com Mon Dec 13 13:28:24 2004 From: ch.list at us-hampton.mail.saic.com (Chris) Date: Mon, 13 Dec 2004 13:28:24 -0500 Subject: Fun with Outlook and MAPI In-Reply-To: References: Message-ID: <41BDDF48.7030600@us-hampton.mail.saic.com> >>At the risk of beating a dead horse, but you really should consider >>using SMTP instead if you are really going to be sending a lot >>of messages. > The problem is that doesn't work in more complicated configurations > such as when authentication and/or SSL have to happen, not to mention > the issue of configuring servers and ports, that users have already > configured in their mail clients. Additionally when you use MAPI, > messages that you send also end up in your sent items folder. (I > also have not had any issue sending lots of messages using MAPI). > > Ultimately the utility of vanilla of pure SMTP will depend on > customer requirements and how simple the configuration is. That pretty much sums it up. Also, since everything is done over IMAP with Outlook, I don't really have access to an SMTP server. Chris From theller at python.net Fri Dec 10 07:32:59 2004 From: theller at python.net (Thomas Heller) Date: Fri, 10 Dec 2004 13:32:59 +0100 Subject: Building Windows debug distribution References: Message-ID: "Mark English" writes: > I have a Windows build of Python 2.4 core with all the extensions, both > debug and release. The release installer is built by msi.py > Is there a way to build a debug distribution other than rewriting msi.py > ? But rewriting msi.py shouldn't be hard (replace xyz.pyd by xyz_d.pyd, basically) Thomas From ebonakDUH at hotmail.com Sun Dec 12 20:43:14 2004 From: ebonakDUH at hotmail.com (Esmail Bonakdarian) Date: Sun, 12 Dec 2004 20:43:14 -0500 Subject: uptime for Win XP? In-Reply-To: <41bb78ee$0$29749$ed2e19e4@ptn-nntp-reader04.plus.net> References: <10rmr8ksbhlq341@corp.supernews.com> <41bb78ee$0$29749$ed2e19e4@ptn-nntp-reader04.plus.net> Message-ID: <10rpstj96v4rg10@corp.supernews.com> Tom Wesley wrote: > > I believe that "uptime" works from the console, but don't have a machine > to check it with... Hi Tom, no, unfortunately not. Esmail From fredrik at pythonware.com Wed Dec 15 12:13:07 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 15 Dec 2004 18:13:07 +0100 Subject: Fill a Server References: <1103128682.041915.62730@c13g2000cwb.googlegroups.com> Message-ID: >> Also, my first attempt at this did a recursive copy creating subdirs in >> dirs as it copied. It would crash everytime it went 85 subdirs deep. >> This is an NTFS filesystem. Would this limitation be in the filesystem >> or Python? > > see the "Max File Name Length" on this page (random google link) > for an explanation: > > http://www.ntfs.com/ntfs_vs_fat.htm also: print len(os.path.join("c:\\scratch", *map(str, range(85)))) From fredrik at pythonware.com Tue Dec 21 15:35:14 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 21 Dec 2004 21:35:14 +0100 Subject: A reception desk in a sort of office building References: <41C342A0.3040700@users.ch> <86sm64tzax.fsf@guru.mired.org> Message-ID: /.../ Hans: [Boo] may *look* like Python, but its inner workings are nothing like Python /.../ Pointing out the difference is not trolling. Doug: Hans Nowak and others were the ones unsuccessfully trying to control what people could talk about here. Hans: I never said that. Doug: You said that boo should not be mentioned on this newsgroup. That is a fact. Mr Vibrating: (pressing the bell on his desk) Thank you, good morning. Doug: What? Mr Vibrating: That's it. Good morning. Doug: That was never five minutes just now! Mr Vibrating: I'm afraid it was. Doug: No it wasn't. Mr Vibrating: I'm sorry, I'm not allowed to argue any more. Doug: What!? Mr Vibrating: If you want me to go on arguing, you'll have to pay for another five minutes. From jplauril at nostromo.dynalias.org Thu Dec 23 08:12:15 2004 From: jplauril at nostromo.dynalias.org (Jukka Laurila) Date: Thu, 23 Dec 2004 13:12:15 GMT Subject: Python for Series 60 update References: <41c9faae@news.highway1.com.au> Message-ID: On Thu, 23 Dec 2004 06:52:28 +0800, Tim Hoffman wrote: > I did find a problem with it on my 7610. > It works, but I had to hard code my bluetooth mac address (I assume > thats what it is called in bluetooth). The bt_discover() call > didn't seem to find my host. How did it fail? Did it simply not show your computer in the list or did it hang indefinitely when connecting to it? Bluetooth discovery has always been problematic, but connecting to a host directly using the mac address has worked perfectly for months now. (I am one of the developers in this project.) Try doing the discovery again. Sometimes the phone just magically discovers hosts it did not see ten seconds earlier. The discovery will also fail if there already is a Bluetooth connection open, for example the PC Suite can leave connections open that mess up the discovery. You can force all connections to be terminated by turning bluetooth on and off from the phone menu. > from the console I could immediatly do xml-rpc calls > to my favourite Zope/CMF instance over GPRS and it just worked. > > This is cool. Yes, very :) From peter at engcorp.com Mon Dec 20 13:20:38 2004 From: peter at engcorp.com (Peter Hansen) Date: Mon, 20 Dec 2004 13:20:38 -0500 Subject: Silly questions about True and False In-Reply-To: References: Message-ID: drs wrote: > I just upgraded my Python install, and for the first time have True and > False rather than 1 and 0. I was playing around at the command line to test > how they work (for instance, "if 9:" and "if True:" both lead to the > conditional being executed, but True == 9 -> False, that this would be true > was not obvious to me -- "True is True" is True, while "9 is True" is false > even though 9 evaluates to True.) What do you mean by "9 evalutes to True"? That's not the case. bool(9) does evaluate to True, and that's effectively what "if 9:" is doing... Anyhow, in doing my tests, I accidentally > typed > > >>>>False = 0 > rather than > >>>>False == 0 > > and I lost the False statement. To get it back, you should do "del False". Remarkably, this actually just removes the local name False that you created which was "shadowing" the builtin name, allowing the builtin name (which you didn't change) to be seen again. Note that this name you are creating is actually *local* to the module you are in, which at the interactive prompt is called __main__. Thus you are not changing False from the point of view of any other module, or of the Python internals. They are (for the most part) still getting it from the builtin module. > which seems to put False back to False, but this seems weird. >>>>1 = 0 > > throws an error (can't assign to literal), why doesn't False = 0 throw the > same error? False is not a constant, it's merely a name. 1 and 0 are constants. You can't change a constant, but you *can* "rebind" a name (that is, attach it to something else). That's all you're doing here. > Also, why doesn't False = 0 make >>>>1 == 2 > 0 > Instead of False? Because such comparisons are all effectively doing a bool() which continues to return the builtin False. -Peter From theller at python.net Tue Dec 21 10:00:34 2004 From: theller at python.net (Thomas Heller) Date: Tue, 21 Dec 2004 16:00:34 +0100 Subject: Problem with msvcrt60 vs. msvcr71 vs. strdup/free References: Message-ID: Gerhard Haering writes: > Hello, > > I used to build Python extension modules with mingw. Now, Python has > switched to the MSVCR71 runtime with version 2.4, and I thought mingw > has support for this. But I get problems with symbols being referenced > from the wrong DLLs. > > You can see the problem by compiling this: > > ################## > #include > > int main() > { > char* s; > int i; > > > for (i = 0; i < 10; i++) { > s = strdup("foo"); > free(s); > } > > return 0; > } > ################## > > with gcc x.c -lmsvcr71 > > Then if you run a.exe it crashes. > > If you use depends.exe on it, you see that it resolves strdup() via > msvcrt, but the rest with msvcr71.dll. That's why strdup() is using > the one malloc, but free() a different free() from the other DLL, > which is undoubtedly the reason for the crash. > > Is there any way I can force mingw to not link in msvcr for things > like strdup? Only guesswork, but replacing this section in the lib\gcc-lib\mingw32\3.2.3\specs file (I can only guess wht this file does) *libgcc: %{mthreads:-lmingwthrd} -lmingw32 -lgcc -lmoldname -lmingwex -lmsvcrt with this one: *libgcc: %{mthreads:-lmingwthrd} -lmingw32 -lgcc -lmoldname -lmingwex -lmsvcr71 seemed to do the trick. Thomas From tim.tadh at gmail.com Mon Dec 13 23:40:36 2004 From: tim.tadh at gmail.com (Tim Henderson) Date: Mon, 13 Dec 2004 23:40:36 -0500 Subject: A problem with list Message-ID: <41BE6EC4.30601@gmail.com> Hi There are many different ways to solve the problem that you are having. The easiest if you are planning on only dealing with strings or a predictable data structure would be to do something like this: Code: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #Pre: Pass in a string and the character you want it tokenized by #Post: Returns a list of all the tokens def tokenizer(str, chr=' '): #heres a useful tool just like StringTokenizer feature in Java if chr != '': chr = chr[0] else: chr = ' ' x = "" tokens = [""] z = 0 for x in str: if x != chr: tokens[z] = tokens[z] + x else: z = z + 1 tokens.append("") return tokens list = ['abc', 'def', 'xyz'] str = '' for x in list: str+=list+'.' #note this is a delimiter could be anything, if you wanted to you could re-implement the above function to work with delimiters of any length not just length 1 #save the str #load str a loadedStr loadedList = tokenizer(loadedStr, '.') #loadedList = ['abc', 'def', 'xyz'] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ that is one way too solve your problem another is to use some sort of real database structure, for simplicity, you could use XML example xml structure: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ float 3.14 0 int 3 1 string Hi i am a string 2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The first way to solve your problem is quick dirty and efficient. The XML version is highly scalable but requires a lot more code to implement. As mentioned before there are a number of other solutions to the same problem --- Cheers Tim Henderson original message: ---- >The following code >############## >import string >MyList=['abc','def'] >for i in MyList: >print i >############### > >works as I expect that is I get >abc >def > >but when I have Mylist in a file and I read it from the file it does >not work as I expect. >######### >import string >ff=open('C:\\Robotp\\MyFile.txt','r') # read MyList from a file >MyList=ff.read() >for i in MyList: >print i >########### >I will get >[ >' >a >b >c >' >, >' >d >e >f >' >] > >where my MyFile.txt looks like this: >['abc','def'] > >Where is a problem? >Thanks for help >Lad > From fredrik at pythonware.com Tue Dec 14 03:27:40 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Dec 2004 09:27:40 +0100 Subject: PEP 338: Executing modules inside packages with '-m' References: <1102833987.622846.64230@z14g2000cwz.googlegroups.com> <41BD78AC.7060302@iinet.net.au> Message-ID: Just wrote: >> as for the rest of your arguments, I have to assume that you were joking. >> (or >> that you have no experience whatsoever of distribution of Python programs in >> Unix and Windows environments). > > Whatever. You suggestion does not work in many cases. How about a > program that starts threads? Can't do that as a side effect of import. my suggestion was to make sure that the user can type "bar arg" to start a Python program called "bar" with the argument "arg". that's trivial, on all major platforms, despite what Nick says -- and yes, you can start threads from a program named "bar". try it. From ask at etamp.net Sun Dec 5 17:16:02 2004 From: ask at etamp.net (etamp) Date: Mon, 6 Dec 2004 07:16:02 +0900 (KST) Subject: What's New on the Web : Today Message-ID: What's New on the Web : Today http://www.etamp.net/ =========================================================== Etamp(etamp.net) provides latest news of web sites around the globe. You can inform free of charge what is happening in your web site. To submit your releases, you must first become a member. It's free, fast and easy. ============================================================ ====== [ url2image.com Offers New Service to Help Web site Designers and Webmasters Discover Problems with Lack of Browser Compatibility ] url2image.com Offers New Service to Help Web site Designers and Webmasters Discover Problems with Lack of Browser Compatibility A new service of?? http://www.etamp.net/beta/?etamp=check_dir/news.html?&part=ws&number=1049 [ ICQ joins webmail battles with new service ] ICQ joins webmail battles with new service By Juan Carlos Perez The increasingly competitive webmail market has a new player: Instant messaging?? http://www.etamp.net/beta/?etamp=check_dir/news.html?&part=ws&number=1048 [ Voiceglo Issues Call for Beta Users for GloConnect IM Application ] Voiceglo Issues Call for Beta Users for GloConnect IM Application December 2004 ?Voiceglo, a global communications and networking company, to?? http://www.etamp.net/beta/?etamp=check_dir/news.html?&part=ws&number=1047 [ OmniOutliner 3.0 announced, public beta available ] OmniOutliner 3.0 announced, public beta available The Omni Group today announced a major new upgrade to its outlining and organizational applicati?? http://www.etamp.net/beta/?etamp=check_dir/news.html?&part=ws&number=1046 From osv at javad.ru Thu Dec 2 08:41:56 2004 From: osv at javad.ru (Sergei Organov) Date: 02 Dec 2004 16:41:56 +0300 Subject: Semaphore or what should I use? References: <41aef9ea$0$18874$636a15ce@news.free.fr> Message-ID: Pierre Barbier de Reuille writes: > Ville Vainio a ?crit : > >>>>>>"Bastian" == Bastian Hammer writes: > > Bastian> Now I have to make sure, that both threads are > > > Bastian> synchronal, 1 thread edits something and the other is > > Bastian> blocked until the first thread is ready. > > Bastian> Isn?t it a good idea to do this with a semaphore? > > > Semaphore will do, but this is a classical use case for > > threading.Lock. > > > > There should be lots of stuff regarding locks (or more googleably, > > "mutexes") on the net. > > > > > I don't agree. Mutexes (or locks) are best suited for critical sections (ie. > sections that cannot be run by many thread at the same time). Please don't add even more confusion to the issue. Mutex conceptually is designed to be used for MUTual EXclusion of access to a resource (e.g., a peace of data). While critical section could be implemented using mutex, the mutex itself is more general concept. Besides, the rule of thumb using mutexes is: "protect data, not program code." My answer to OP's question is: use either lock (mutex) or semaphore. I'd probably use semaphore as mutexes are usually optimized for the case when contention probability is low (i.e., they usually shouldn't be locked for a long time). -- Sergei. From jb_perin at yahoo.fr Tue Dec 21 04:33:52 2004 From: jb_perin at yahoo.fr (Jean-Baptiste PERIN) Date: Tue, 21 Dec 2004 10:33:52 +0100 Subject: extending python with a C-written dll In-Reply-To: References: <41c6e784$0$16084$a1866201@visi.com> <41c6f353$0$16095$a1866201@visi.com> <1xdldj1h.fsf@python.net> Message-ID: Steve Holden a ?crit : > Jean-Baptiste PERIN wrote: > >> >>> >>>> >> error: Python was built with version 6 of Visual Studio, and >>>> extensions need to >>>> be built with the same version of the compiler, but it isn't installed. >>> >>> >>> >>> >>> How do you expect to be able to write your own extension if you don't >>> have >>> the environment to do so in the first place? that error has nothing >>> to do >>> with python itself, but with you not having installed the right >>> compiler. >>> THe same problem will arise building your own extension. >> >> >> >> I know it has nothing to do with python .. >> It just makes me sad to see that python cannot get rid of Visual >> Studoi to be extended . It's just amazing !! >> >> Python is free >> The compiler I use is free >> The code I plan to produce will be free >> >> Where can I find a free version of Visual Studio ? >> >> the only thing I use that is not free is the operating system and it's >> because I had no choice .. my company decided for it >> >>> Others suggested trying the ctypes binary installer. Do so. >> >> >> >> Yes .. that's what I'm going to do .. but I find it frustrating .. > > > Perhaps you aren't aware that Microsoft make a free tool chain available > that can be used to create binary extensions? There has been some > discussion of this recently, and I managed to compile MySQLdb and a > couple of the mx extensions, so it's eminently doable [the PIL is > proving a little less tractable due to dependencies on other libraries > that I have yet to resolve]. > > The downloads are quite large, but if you want to try it, take a look at > > http://www.vrplumber.com/programming/mstoolkit/ > > regards > Steve If nothing else works .. I'll try that way .. So far, I've tried to keep as far as possible from MS things .. thank you for your help ... From roland.heiber at web.de Thu Dec 16 05:27:57 2004 From: roland.heiber at web.de (Roland Heiber) Date: Thu, 16 Dec 2004 11:27:57 +0100 Subject: KeyError In-Reply-To: References: Message-ID: Doran_Dermot at emc.com wrote: > Hi "R", > > The only explanation I can give is that the environment varialbe REMOTE_ADDR > does not exist! Wrap your high-level code with try and except. Example: > try: > tablesDirectory = tablesDirectoryPrefix + os.environ['REMOTE_ADDR'] > except KeyError: > # Code to handle the fact tht REMOT_ADDR does not exist. ... or just replace os.environ['REMOTE_ADDR'] with os.environ.get('REMOTE_ADDR', 'enter_default_here') to use a default in case of missing REMOTE_ADDR ... HtH, Roland From jcarlson at uci.edu Thu Dec 2 21:12:26 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Thu, 02 Dec 2004 18:12:26 -0800 Subject: A way to wait Python event In-Reply-To: <89cc6e1f.0411301357.6f306893@posting.google.com> References: <89cc6e1f.0411301357.6f306893@posting.google.com> Message-ID: <20041202181154.FAA6.JCARLSON@uci.edu> changli_to at hotmail.com (Chang LI) wrote: > > I tried to launch "python.exe test.py" in another program. After the > launch the console was showed and exited on Windows. I want the > console stay there. Is there a Python statement to wait an event loop > like Tcl's "after forever"? I'm a fan of... _ = raw_input('press enter to continue...') - Josiah From jrrywise at yahoo.com Thu Dec 30 15:33:26 2004 From: jrrywise at yahoo.com (jerry wise) Date: Thu, 30 Dec 2004 12:33:26 -0800 (PST) Subject: project Message-ID: <20041230203326.92206.qmail@web80910.mail.scd.yahoo.com> I need some help on a project. I've never used python, and basically what I want to do is have a program where I can bang small wav or mp3 files together end to end. I want to be able to select say 10 files and have the program come up with all the possible combinations of those ten to be saved on my computer so I can play them back to myself. That's the gist of it, but I can go into a little more depth if needed. I would really, really, really appreciate it if someone could help me out. Thanks a lot. --------------------------------- Do you Yahoo!? Dress up your holiday email, Hollywood style. Learn more. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jcarlson at uci.edu Sun Dec 5 15:09:22 2004 From: jcarlson at uci.edu (Josiah Carlson) Date: Sun, 05 Dec 2004 12:09:22 -0800 Subject: string slicing In-Reply-To: <34534aed04120511124d236c0d@mail.gmail.com> References: <20041205100937.ECCF.JCARLSON@uci.edu> <34534aed04120511124d236c0d@mail.gmail.com> Message-ID: <20041205112212.ECD2.JCARLSON@uci.edu> Ishwor wrote: > > On Sun, 05 Dec 2004 10:31:12 -0800, Josiah Carlson wrote: > > > > "Fredrik Lundh" wrote: > > > > a suggestion: if you really want to be productive in python, forget about > > > "is" for a while. > > I know what Fredrik means here (Thanx Frederick :) ) but IMHO if the > pattern of forgetting something is taken everytime someone tries to > scratch under the hood, then seriously it'll take ages before someone > seriously learns a language! > > > The above two tips are in my "top-10 things to tell newbs" list. > > You should consider having your own *nice* nifty things to say about > newbs (like me) rather than try to point at someone else's > intellectual property. If you are running out of ideas consider > reading one of those "Complete Idiot's guide to xxxx" :) Goodness, you got right snippy with the 'intellectual property' thing. I'm sorry if it sounded as if I had meant "I came up with this before", I did not mean it that way. What I meant was "good advice", "I've seen this advice before", and "I've previously taken note of it". As an aside, I also believe that if Fredrik were concerned about my supposed theft of his 'advice IP', he would mention it Confusions about 'is' are quite common. Perhaps every week a new thread in regards to object identity is offered, usually asking about integer, string or list identity. I'm not having much luck with the google incantation right now, but my email archive is spitting back a thread on "interning strings" from early November, which discusses strings and identity. Really, everyone who is thinking of using 'is' should ask themselves whether or not it is truely important to have the same object. In some cases it matters, and in others cases it doesn't matter. The more experience one has with Python and the implementations of algorithms, the more obvious such choices will become. A perfect example of a case when using 'is' is proper is by Barry Warsaw (http://mail.python.org/pipermail/python-dev/2004-March/043224.html): missing = object() if d.get('somekey', missing) is missing: # it ain't there In the case of it not mattering, there was a series of threads in March of this year in python-dev, discussing replacing the 'is' operator strictly comparing object identity with a 'can be replaced by' operator, spelled 'is'. See the threads entitled "redefining is" here: http://mail.python.org/pipermail/python-dev/2004-March/thread.html Of course it came out that it didn't happen ('is' is much faster, and doesn't require objects to define a mechanism to get at their contents, etc.), but it is not uncommon for people who think they want 'is' to really want 'can be replaced by', especially in the case of tuples: >>> a = tuple(list('hello')) >>> b = tuple(list('hello')) >>> a == b True >>> a is b False >>> CanBeReplacedBy(a, b) True >>> (of course you need a proper implementation of CanBeReplacedBy, of which a few are offered in the previously mentioned 'replacing is' threads). Now, whether or not knowing what 'is' does, or whether knowing the internals in regards to how object identity works, is necessary for learning the language, I don't know. It's been a few years since I was a newb, but considering all of the questions regarding 'is' usually resulting with python-list saying "you want '=='", I'd offer, 'it is not necessary'. - Josiah From titi2027 at NOSPAM.netplus.ch Tue Dec 7 13:55:09 2004 From: titi2027 at NOSPAM.netplus.ch (titouille) Date: Tue, 07 Dec 2004 19:55:09 +0100 Subject: ming for python Message-ID: <41b5fc8d$1@news.vsnet.ch> Hello everybody !! anyone has try to build ming0.3beta1 for python 2.3.3 under windows ?? Since three days, I try to build it with mingw32, and finally, I am stopped with C declarations error in src/actioncompiler/swf4compiler.y If anyone has build with success ming (mingc.pyd) for python 2.3.3, can he please send me this file, or explain what I do to build it successfully ?? I have downloaded all software who are needed (bison, flex, mingw developer Studio to have make, dlltool, etc...) But finally, I'm not sure that I can compile theses sources with mingw... I have followed instructions on - http://www.u-blog.net/corailnumerique/2003/12/17 (in french, it's my mother tongue...) and - https://sourceforge.net/tracker/index.php?func=detail&aid=921431&group_id=18365&atid=118365 but no results... If anyone has a solution, please help me :) Thierry From mwm at mired.org Sun Dec 19 15:15:55 2004 From: mwm at mired.org (Mike Meyer) Date: Sun, 19 Dec 2004 14:15:55 -0600 Subject: A completely silly question References: Message-ID: <86y8fu11tw.fsf@guru.mired.org> Craig Ringer writes: > On Sat, 2004-12-18 at 00:40, Amir Dekel wrote: >> This must be the silliest question ever: >> >> What about user input in Python? (like stdin) >> Where can I find it? I can't find any references to it in the documentation. > > Under UNIX, I generally either use curses, or just put the terminal into > raw mode: > > .>>> def sane(): > .... os.system("stty sane") > .... > .>>> def raw(): > .... os.system("stty raw") The termios gives module gives you the tools to manipulate the tty directly, without invoking stty. The tty module gives you an easier interface to those routines. However, it's missing a setsane functions. Hmm. I think it's time for another PEP. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From carribeiro at gmail.com Mon Dec 20 08:37:23 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Mon, 20 Dec 2004 11:37:23 -0200 Subject: Best GUI for small-scale accounting app? In-Reply-To: References: <7xmzw9cf8l.fsf@ruckus.brouhaha.com> Message-ID: <864d370904122005374cd6729a@mail.gmail.com> On Mon, 20 Dec 2004 14:20:43 +0100, Bulba! wrote: > On 20 Dec 2004 04:43:06 -0800, Paul Rubin > >I'd try to make it web based unless > >there's a good reason not to. > > Reason 1: It would be somewhat complex to develop it using > PHP (I have done some recon in that area) and using GUI > on Windows is actually faster way of entering and editing data > than via the Web browser I think. > > Reason 2: I don't want to learn yet another language > just for this app and want to avoid integration problems > as we plan to develop yet another application for other workers > that would connect to the common DB and sent the data directly > for that accounting app. Two good reasons indeed. There are some types of data entry tasks that don't map well to the browser. Rich grid style data entry just comes to mind, it requires a ton of Javascript code, not to mention XMLRPC, if you want it to be dynamic and responsive. But if the data entry forms are simple, I recommend you to check some lightweight approaches for Web development in Python. I personally used CherryPy (www.cherrypy.org); you can also check Quixote or Snakelets. All three are much lighter than Zope. CherryPy in particular is extremely light and easy to work with, and includes a reasonably powerful embedded Python-based webserver; it's not Apache, but it's much easier to set up. And all three options are free. -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From insert at spam.here Mon Dec 20 01:15:38 2004 From: insert at spam.here (Doug Holton) Date: Mon, 20 Dec 2004 00:15:38 -0600 Subject: atmosphere on c.l.py (WAS: How about "pure virtual methods"?) In-Reply-To: References: <1gp06r8.10q8off1j9v6nvN%aleaxit@yahoo.com><1103448439.953120.209950@c13g2000cwb.googlegroups.com><1gp1415.10zjxtu1cfp9cxN%aleaxit@yahoo.com><1gp1afn.udxyw81p5gajqN%aleaxit@yahoo.com><1gp1m3i.1e39lko1nsv2z8N%aleaxit@yahoo.com> Message-ID: Steven Bethard wrote: > Doug Holton wrote: > >> Fredrik Lundh wrote: >> >>> well, since I'm not in the ego-stroking business, what if I promise >>> never to reply to posts by you, robert, and alex? >> >> >> That's not fair to the rest of us though :) > > > That's not even fair to the non-rest of us. =) As I noted, "his answers > ... are often very insightful" -- it would be a pity to lose them. He was only acknowledging the problem to those 3 people who complained about it. I was making the point that others do not like being trolled either. From lutherrevisited at aol.com Sun Dec 26 06:14:35 2004 From: lutherrevisited at aol.com (LutherRevisited) Date: 26 Dec 2004 11:14:35 GMT Subject: WxListCtrl Message-ID: <20041226061435.11425.00002510@mb-m29.aol.com> Is there any way I can disable just the horizontal scroll bar for a listctrl? When enough items have been added for it to scroll vertically a horizontal bar also appears, even though you don't need it at all. I've played around with sizing individual columns and haven't seemed to come up with anything satisfactory. From stuart at bmsi.com Wed Dec 8 18:38:14 2004 From: stuart at bmsi.com (Stuart D. Gathman) Date: Wed, 08 Dec 2004 18:38:14 -0500 Subject: Help beautify ugly heuristic code References: Message-ID: On Wed, 08 Dec 2004 18:00:06 -0500, Mitja wrote: > On Wed, 08 Dec 2004 16:09:43 -0500, Stuart D. Gathman > wrote: > >> I have a function that recognizes PTR records for dynamic IPs.... Here >> is the very ugly code so far. >> ... >> # examples we don't yet recognize: >> ... > > This doesn't help much; post example of all the possible patterns you > have to match (kind of like the docstring at the beginning, only more > elaborate), otherwise it's hard to know what kind of code you're trying > to implement. This is a heuristic, so there is no exhaustive list or hard rule. However, I have posted 23K+ examples at http://bmsi.com/python/dynip.samp with DYN appended for examples which the current algorithm classifies as dynamic. Here are the last 20 (which my subjective judgement says are correct): 65.112.76.15 usfshlxmx01.myreg.net 201.128.108.41 dsl-201-128-108-41.prod-infinitum.com.mx DYN 206.221.177.128 mail128.tanthillyingyang.com 68.234.254.147 68-234-254-147.stmnca.adelphia.net DYN 63.110.30.30 mx81.goingwiththe-flow.info 62.178.226.189 chello062178226189.14.15.vie.surfer.at DYN 80.179.107.85 80.179.107.85.ispeednet.net DYN 200.204.68.52 200-204-68-52.dsl.telesp.net.br DYN 12.203.156.234 12-203-156-234.client.insightBB.com DYN 200.83.68.217 CM-lconC1-68-217.cm.vtr.net DYN 81.57.115.43 pauguste-3-81-57-115-43.fbx.proxad.net DYN 64.151.91.225 sv2a.entertainmentnewsclips.com 64.62.197.31 teenfreeway.sparklist.com 201.9.136.235 201009136235.user.veloxzone.com.br DYN 66.63.187.91 91.asandox.com 83.69.188.198 st11h07.ptambre.com 66.192.199.217 66-192-199-217.pyramidcollection.org DYN 69.40.166.49 h49.166.40.69.ip.alltel.net DYN 203.89.206.62 smtp.immigrationexpert.ca 80.143.79.97 p508F4F61.dip0.t-ipconnect.de DYN From binux.lists at gmail.com Wed Dec 15 22:43:08 2004 From: binux.lists at gmail.com (Binu K S) Date: Thu, 16 Dec 2004 09:13:08 +0530 Subject: ftp In-Reply-To: <1103154571.204203.182710@c13g2000cwb.googlegroups.com> References: <1103154571.204203.182710@c13g2000cwb.googlegroups.com> Message-ID: <2b7d8b4204121519437a19e529@mail.gmail.com> Try retrbinary instead of retrlines in the original script (the one without write('\n')). retrlines fetches the file in ASCII mode and that must be altering the line terminations. On 15 Dec 2004 15:49:31 -0800, hawkmoon269 wrote: > I would like to write a small ftp script that I could use in place of > DOS. So far I have this -- > > from ftplib import FTP > > server = 'xxx' > username = 'xxx' > password = 'xxx' > file = 'xxx' > > ftp = FTP(server) > ftp.login(username, password) > ftp.retrlines('RETR ' + file, open('C:\My Documents\' + file, > 'w').write > > but this just writes the source files contents into a giant string in > the output file. The source file is comma-delimited with a > fixed-length of 80 chars per line. I need the same format for the > output file. I've tried this -- > > ftp.retrlines('RETR ' + file, open('C:\My Documents\' + file, > 'w').write('\n') > > and that gives the correct output format...but it writes the output to > the IDE interpreter command line and not the file. What am I doing > wrong? > > hawk > > -- > http://mail.python.org/mailman/listinfo/python-list > From bwobbones at gmail.com Sun Dec 12 09:35:36 2004 From: bwobbones at gmail.com (bwobbones) Date: Sun, 12 Dec 2004 22:35:36 +0800 Subject: usage of __import__ across two files Message-ID: <41BC5738.1040906@gmail.com> Hi, I'm having trouble making __import__ work with the two classes attached. The PrintHello() method can't be seen in the BMTest2 class - what am I doing wrong here? **************************** class one - BMTest - in BMTest.py: **************************** import wx from traceback import print_exc class ImportTest(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "ImportTest", size = (666,480), style = wx.DEFAULT_FRAME_STYLE) #tb = BMToolBar(self) # works just fine! tb = __import__('BMTest2') tb2.PrintHello() class MyApp(wx.App): def __init__(self, flag): wx.App.__init__(self, flag) def OnInit(self): frame = ImportTest() self.SetTopWindow(frame) return True if __name__ == '__main__': try: app = MyApp(False) app.MainLoop() except: print print_exc() ************************** class 2 BMTest2 - in BMTest2.py: ************************** import wx class BMToolBar(wx.ToolBar): def __init__(self, parentFrame): wx.ToolBar.__init__(self, parentFrame, -1, style=wx.TB_HORIZONTAL|wx.NO_BORDER|wx.TB_FLAT|wx.TB_TEXT) print "*** gday ***" self.Realize() def PrintHello(self): print "Hello" Any help will be much appreciated! Bones From ebolonev at mail.ru Wed Dec 8 05:29:27 2004 From: ebolonev at mail.ru (Egor Bolonev) Date: Wed, 08 Dec 2004 20:29:27 +1000 Subject: os.path.islink() References: Message-ID: On Wed, 08 Dec 2004 10:23:13 +0100, Peter Maas wrote: > Egor Bolonev schrieb: >> far file manager said 'C:\Documents and Settings\????\My >> Documents\Scripts\Antiloop\' is link >> how to detect ntfs links? > > There are no ntfs links. What appears as a link on GUI level is > nothing but a plain file with special content, so that > os.path.islink() tells the truth. Windows "links" are a special > Windows feature (shortcuts) and must be detected via Win32 api > calls or by searching for content characteristics of shortcuts. gui folder link is a .lnk file From max at alcyone.com Fri Dec 17 04:37:33 2004 From: max at alcyone.com (Erik Max Francis) Date: Fri, 17 Dec 2004 01:37:33 -0800 Subject: Python RSS aggregator? Message-ID: <4_udncp_Fs1ANV_cRVn-3w@speakeasy.net> Back in 2000 I made a news aggregation site (REALpolitik, http://www.realpolitik.com/) since I didn't find anything that fit my needs. (REALpolitik is unfortunately made in Perl; it was my last significant project before I started using Python for most of my work.) At the time, RSS had not reached the near-universality that it has now, so RP itself uses a combination of custom scraping and whatever XML-type feeds that were available. I've checked and all the feeds _I_ care about :-) are available in RSS now, so it would make sense to move to an RSS aggregator if it has the same features. I've looked around at some that are available, both in Python and not, and haven't found anything that had the feature set I want. One in Python would obviously be a huge benefit. I'm not looking for anything all that fancy, but there are a combination of some seemingly basic features I just can't seem to find in other aggregators. They are: - one-page display: It's awkward going back and forth between multiple feeds in a hierarchical format, and so it's much nicer if they're all presented on one page available for perusal. - filtering news items: Preferably for filtering out as well as highlighting, and also being able to selectively pass on, say, the first item in an RSS feed, since some popular feeds use that slot as an advertisement. - caching news items: I read news sporadically throughout the day, so one feature I really like is the ability to queue up new items over time, as distinguished by unique GUID. For example, if an RSS feed only provided one (unique) item at all in its feed and that was updated once a day, letting the system run for several days would collect them all, each stored uniquely and available. - recent items: When you check for news, it only shows you the news items in each category that are new since you last caught up (catching up is the equivalent of a "mark all as read" feature). That way, new news accumulates, and it's only news you haven't seen before. Somewhat surprisingly to me, I can't seem to find an aggregator that supports all these features (using Mozilla). Is it possible it's time for another Yet Another-type project? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis If love be good, from whence cometh my woe? -- Chaucer From johnpote at blueyonder.co.uk Thu Dec 16 06:59:53 2004 From: johnpote at blueyonder.co.uk (John Pote) Date: Thu, 16 Dec 2004 11:59:53 GMT Subject: Multithreading tkinter question References: Message-ID: "Mark English" wrote in message news:mailman.7804.1103134911.5135.python-list at python.org... Is there a safe way to run tkinter in a multithreaded app where the mainloop runs in a background thread ? Mark, I tried your code snippet with Python 2.3.4. Worked fine. Only problem was that the program fell off the end and terminated before the second thread could open the Tkinter window. So I added these lines at the end to make the main thread wait:- from msvcrt import kbhit, getch print "\n\nPress key to end" while not kbhit(): pass getch() Both your Hello and Quit buttons worked. However, I have found that tkinter crashes if any components, labels text box etc, are accessed directly from another thread. Below is a posting I did some time ago. My solution to the problem. I'm still interested to know if this is a good/best way to solve this problem. It is not optimal in that 'otherThread' runs continuously even when the label is not being updated. What a waste of cpu cycles! This shows up in that other windows apps slow right down. What is needed is a comms method between threads that causes a thread to block while it's waiting for data rather than my continuous polling approach. Would a Queue help here? John Pote "Martin Franklin" wrote in message news:mailman.6201.1100071949.5135.python-list at python.org... > On Tue, 09 Nov 2004 17:41:56 GMT, John Pote > wrote: > >> Running my programme in Python 2.3.4 I received the following msg in the >> consol :- >> (Pent III running W2K prof) >> >> """ >> Exception in Tkinter callback >> Traceback (most recent call last): >> File "c:\apps\python\234\lib\lib-tk\Tkinter.py", line 1345, in __call__ >> return self.func(*args) >> File "c:\apps\python\234\lib\lib-tk\Tkinter.py", line 459, in callit >> self.deletecommand(tmp[0]) >> AttributeError: 'str' object has no attribute 'deletecommand' >> UpdateStringProc should not be invoked for type option >> >> abnormal program termination >> """ >> There was no other traceback information. >> >> Could this be related to lines of the ilk:- >> self.infoSpd.config(text="%d.%01d"%spd) >> where infoSpd is a Tkinter Label object placed using the grid manager. >> >> Thousands of these updates were performed so the labels displayed >> progress >> through a memory dump of a system accessed through a serial port. >> >> I had trouble before with Python versions 2.2.1 and 2.2.3 where >> commenting >> out these Label updates stopped the system crashing and it was happy to >> run >> for hours performing tests on the external hardware. (an embedded data >> logger I'm developing) >> >> Anyone any thoughts? >> >> John > > > Only one (thought that is) Are you updating thses Label widgets from > other > threads? and could you possibly post an example? > > Martin Ahhhh -- Experience had already taught me that lesson about tkinter. On checking my code guess what I found I'd done - called the widget.config method from the other thread. So I put in a list to queue the label updates from the other thread to the tkinter thread and it's now been running for several hours without problem. Thanks for the reminder. BTW the program structure I've been using is:- def otherThread(): while TRUE: if updatelabel: labelQ = "new label text" def guiLoop(): if labelQ: myLabel.config(text=labelQ) labelQ = None #re-register this fn to run again rootWin.after(10, guiLoop) #strangely .after_idle(guiLoop) is slower! . . rootWin = Tk(className=" tester") #rest of GUI set up. then:- thread.start_new( otherThread, () ) rootWin.after(50, guiLoop) rootWin.mainloop() It works but is it the best way to do this sort of thing? The point is that I need moderately fast serial comms, which I do in 'otherThread' and found the 'after' and 'after_idle' call backs were too slow. The timing I did on py2.2.1 indicated that 'after_idle' could not do better than ~70ms and 'after(10, ....)' was faster, 30-40 ms, but still too slow for my app. Any more thoughts appreciated. John From snail at objmedia.demon.co.uk Tue Dec 21 17:22:41 2004 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Tue, 21 Dec 2004 22:22:41 +0000 Subject: memory leak References: Message-ID: <6iuh1DBxIKyBFwKH@objmedia.demon.co.uk> In message , Daniel Wheeler writes >I'm on a linux platform and looking in proc/pid/status. Using top shows >the same problem. OK, If you were on Windows I could give you some detailed advice - but for Linux, better that somebody else does it. Linux is not my main thing these days (it was in '94 :-). Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk RSI Information: http://www.objmedia.demon.co.uk/rsi.html From yan at NsOeSiPnAeMr.com Thu Dec 2 15:04:31 2004 From: yan at NsOeSiPnAeMr.com (Kamus of Kadizhar) Date: Thu, 02 Dec 2004 15:04:31 -0500 Subject: RotatingFileHandler Message-ID: I'm having a problem with logging. I have an older app that used the RotatingFileHandler before it became part of the main distribution (I guess in 2.3). It worked fine then. Now I get: [yan at hermes bin]# ./mplayer.py file://test.avi //test.avi Traceback (most recent call last): File "./mplayer.py", line 40, in ? logFile.emit(movieName) File "/usr/src/build/394694-i386/install/usr/lib/python2.3/logging/handlers.py", line 102, in emit File "/usr/src/build/394694-i386/install/usr/lib/python2.3/logging/__init__.py", line 567, in format File "/usr/src/build/394694-i386/install/usr/lib/python2.3/logging/__init__.py", line 362, in format AttributeError: 'str' object has no attribute 'getMessage' The offending snippet of code is: logFile = logging.handlers.RotatingFileHandler('/var/log/user/movies2.log','a',2000,4) logFile.emit(movieName) I don't see anything wrong with this, but I'm a relative python bonehead. movieName contains the string 'test.avi' at the time of the crash. What's going on? Anything I need to look at? --Kamus -- o | o__ >[] | A roadie who doesn't ride a mountain bike has no soul. ,>/'_ /\ | But then a mountain biker who doesn't ride a road bike has no legs... (_)\(_) \ \ | -Doug Taylor, alt.mountain-bike From klapotec at chello.at Fri Dec 31 09:25:30 2004 From: klapotec at chello.at (Christopher Koppler) Date: Fri, 31 Dec 2004 14:25:30 GMT Subject: The Industry choice References: <1104425916.615972.97530@z14g2000cwz.googlegroups.com> <7xmzvu1ycn.fsf@ruckus.brouhaha.com> <7xd5wqd14y.fsf@ruckus.brouhaha.com> Message-ID: On Fri, 31 Dec 2004 05:54:05 -0800, Paul Rubin wrote: > Bulba! writes: >> OK, so what projects and why would you consider Python: >> >> 1. "clearly unsuitable" > > An OS kernel, a high-performance signal processing application like a > video encoder, or maybe a compact embedded application for an 8-bit > microcontroller. Of course, but those are not areas where I'd consider any high-level language appropriate. C, Forth and Assembler rule where every last bit counts, and they will continue to do so. Exceptions like Lisp Machines are however something to hope for. Note that you could do the microcontroller project > with JavaCard. (Yeah, you could maybe write the outer shell of the > high-performance app in Python, but I mean the part doing the real work.) Hmm, didn't know about JavaCard, but I'd guess without bothering to look that, like Java's Micro Edition, this features a restricted subset of Java... Python definitely cannot do that now, but the PyPy future may (hopefully) change that. And at least Python's beginning to try to encroach in the very heavily Java-dominated mobile phone software market... > >> 2. "plausible but there are sound technical reasons to be wary" > > A security-critical financial application. Why, specifically? Would you need to eval user input? > >> BTW, I don't think I agree with your statement elsewhere about unit >> tests - if you write a prototype (in any language), why bother with >> unit tests, and if you write security-critical app, maybe the tests >> should be written anyway (again, whatever is the language chosen for >> a project). > > You should write unit tests either way, but in Python you're relying > on the tests to find stuff that the compiler finds for you with Java. > > I'm also not too impressed with Python's bundled debugging features, > as compared with gcc/gdb. People have said nice things about some of > the commercial Python environments but I haven't used those. I haven't used those either (well, I looked at some, but I generally feel better at home in Emacs or even Idle than some glitzy IDE), but I find Python's debugging facilities completely sufficient, especially since I nearly never use them ;-) The interactive environment and unit testing are just great for whatever I've needed so far. But then I haven't used Python in a really *large* project yet, either. -- Christopher In theory, I'm in love with Lisp, but I hop into bed with Python every chance I get. From hwlgw at hotmail.com Mon Dec 13 15:51:25 2004 From: hwlgw at hotmail.com (Will Stuyvesant) Date: 13 Dec 2004 12:51:25 -0800 Subject: do you master list comprehensions? Message-ID: <1102971085.659444.22790@z14g2000cwz.googlegroups.com> Here is a question about list comprehensions [lc]. The question is dumb because I can do without [lc]; but I am posing the question because I am curious. This: >>> data = [['foo','bar','baz'],['my','your'],['holy','grail']] >>> result = [] >>> for d in data: ... for w in d: ... result.append(w) >>> print result ['foo', 'bar', 'baz', 'my', 'your', 'holy', 'grail'] puts all the words in a list, like I want. How to do this with [lc] instead of for-loops? I tried funnies like [[w for w in L] for L in data], that is correct syntax, but you'd never guess. I know, silly! No need for [lc]! So there's my question. I am sure a one-liner using [lc] will be very enlightening. Like studying LISP. -- I wish there was a knob on the TV to turn up the intelligence. There's a knob called `brightness', but it doesn't work. -- Gallagher From eddie at replicon.com Fri Dec 10 15:34:05 2004 From: eddie at replicon.com (Eddie Parker) Date: Fri, 10 Dec 2004 13:34:05 -0700 Subject: Clarification of two concepts (or maybe one?) Message-ID: <20041210203327.A4C591E4008@bag.python.org> Sorry, I?ve tried to search the web on this, but I?m still a little fuzzy. I was hoping a quick e-mail might clear this up. What I?m looking for, is a way to turn a python ?application?, into a ?stand-alone? application. i.e., you don?t need the Python interpreter, libraries, etc, installed on your hard drive. (I?m OK with .py files existing ? I just don?t want to have to bother the user to install more then just my app). One alternative is to embed the Python interpreter in a C++ app, and then just call the entry point... But I?m curious if there?s a better way? On the unrelated (or maybe related) concept, the words ?python freezing? keeps buzzing around my subconscious. I?m not sure if this item can help me in any such way, but I can?t find any good articles on what this phenomenon *is*. Can anyone point me to a definitive web page that describe this, or indicate if it *is* in fact what I?m looking for? (I?m probably way off base on this one). Anyhow, your help is most appreciated! Thank you! -e- --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.788 / Virus Database: 533 - Release Date: 01/11/2004 -------------- next part -------------- An HTML attachment was scrubbed... URL: From binux.lists at gmail.com Wed Dec 22 00:17:33 2004 From: binux.lists at gmail.com (Binu K S) Date: Wed, 22 Dec 2004 10:47:33 +0530 Subject: word to digit module In-Reply-To: <2b7d8b4204122121117d58d01c@mail.gmail.com> References: <2b7d8b4204122121117d58d01c@mail.gmail.com> Message-ID: <2b7d8b42041221211751aff193@mail.gmail.com> Oops! That just does the opposite of what you want. I guess you can tinker it a bit to do the reverse conversion unless someone suggests a better module. On Wed, 22 Dec 2004 10:41:46 +0530, Binu K S wrote: > You'll find a script here: > http://www.python.org/pycon/dc2004/papers/42/ex1-C/ > Found it in the miscellany section at http://www.vex.net/parnassus/ (num2eng) > > On Wed, 22 Dec 2004 10:27:16 +0530, Gurpreet Sachdeva > wrote: > > Is there any module available that converts word like 'one', 'two', > > 'three' to corresponding digits 1, 2, 3?? > > > > Thanks and Regards, > > GSS > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > From schu0999 at gmail.com Wed Dec 8 14:11:22 2004 From: schu0999 at gmail.com (stefan) Date: 8 Dec 2004 11:11:22 -0800 Subject: after embedding and extending python (using swig) problem importing (non-core) modules In-Reply-To: References: <1102479704.220397.59070@c13g2000cwb.googlegroups.com> Message-ID: <1102533082.362542.190100@c13g2000cwb.googlegroups.com> thanks a lot for the quick answer. I had to provide the debug-versions, since I was in debug mode, like you already expected! thanks a lot again! -stefan From maitj at vianet.ca Mon Dec 13 14:36:48 2004 From: maitj at vianet.ca (Jeffrey Maitland) Date: Mon, 13 Dec 2004 14:36:48 -0500 Subject: how do I "peek" into the next line? In-Reply-To: <20041213193250.29126.qmail@mail.vianet.ca> References: <1102964987.812024.5180@c13g2000cwb.googlegroups.com> <20041213193250.29126.qmail@mail.vianet.ca> Message-ID: <20041213193648.7207.qmail@mail.vianet.ca> Jeffrey Maitland writes: > les_ander at yahoo.com writes: > >> Hi, >> suppose I am reading lines from a file or stdin. >> I want to just "peek" in to the next line, and if it starts >> with a special character I want to break out of a for loop, >> other wise I want to do readline(). >> >> Is there a way to do this? >> for example: >> while 1: >> line=stdin.peek_nextline() >> if not line: break >> if line[0]=="|": >> break: >> else: >> x=stdin.nextline() >> # do something with x >> >> thanks >> >> -- >> http://mail.python.org/mailman/listinfo/python-list > > Well what you can do is read the line regardless into a testing variable. > > here is some sample code (writting this off the topof my head so syntax > might be off some) > > import re > > file = open("test.txt", 'r') > > variablestr = '' #this would be your object.. in my example using a string > for the file data > > file.seek(0,2) > eof = file.tell() #what this is the position of the end of the file. > file.seek(0,0) > > while file.tell() != eof: > testline = file.readline() > if re.match("#", testline) == True: > break > else: > variablestr += testline > > file.close() > > now if I was concerned with being at the beging of the testline that it > read in what you can do is in the if is something like: > file.seek((file.tell() - len(testline)), 0) > and that will move you back to the beginging of that line which is where > the readline from the previous call left you before the "peek". > > hope that helps some.. > > Jeff > -- > http://mail.python.org/mailman/listinfo/python-list I noticed something in my code. re.match("#", testline) == True isn't possible it would be more like. re.match("#", testline) != None From tanghaibao at gmail.com Sat Dec 25 22:55:03 2004 From: tanghaibao at gmail.com (Haibao Tang) Date: 25 Dec 2004 19:55:03 -0800 Subject: Jython & IronPython Under Active Development? Message-ID: <1104033303.754319.269650@c13g2000cwb.googlegroups.com> This question may be a bit weird but I really want to know if these two hybrid projects are still active. From db3l at fitlinxx.com Fri Dec 31 14:15:59 2004 From: db3l at fitlinxx.com (David Bolen) Date: 31 Dec 2004 14:15:59 -0500 Subject: Securing a future for anonymous functions in Python References: <10t84q9icqjnie7@news.supernews.com> <41d596bd$1@nntp0.pdx.net> Message-ID: Scott David Daniels writes: > David Bolen wrote: > > So for example, an asynchronous sequence of operations might be like: > > d = some_deferred_function() > > d.addCallback(lambda x: next_function()) > > d.addCallback(lambda blah: third_function(otherargs, blah)) > > d.addCallback(lambda x: last_function()) > > which to me is more readable (in terms of seeing the sequence of > > operations being performed in their proper order), then something like: > > def cb_next(x): > > return next_function() > > def cb_third(blah, otherargs): > > return third_function(otherargs, blah) > > def cb_last(x): > > return last_function() > > d = some_deferred_function() > > d.addCallback(cb_next) > > d.addCallback(cb_third, otherargs) > > d.addCallback(cb_next) > > which has an extra layer of naming (the callback functions), > > and > > requires more effort to follow the flow of what is really just a simple > > sequence of three functions being called. > > But this sequence contains an error of the same form as the "fat": "this" being which of the two scenarios you quote above? > while test() != False: > ...code... I'm not sure I follow the "error" in this snippet... > The right sequence using lambda is: > d = some_deferred_function() > d.addCallback(next_function) > d.addCallback(lambda blah: third_function(otherargs, blah)) > d.addCallback(last_function) By what metric are you judging "right"? In my scenario, the functions next_function and last_function are not written to expect any arguments, so they can't be passed straight into addCallback because any deferred callback will automatically receive the result of the prior deferred callback in the chain (this is how Twisted handles asynchronous callbacks for pending operations). Someone has to absorb that argument (either the lambda, or next_function itself, which if it is an existing function, needs to be handled by a wrapper, ala my second example). Your "right" sequence simply isn't equivalent to what I wrote. Whether or not next_function is fixable to be used this way is a separate point, but then you're discussing two different scenarios, and not two ways to write one scenario. -- David From caleb1 at telkomsa.net Wed Dec 1 23:55:07 2004 From: caleb1 at telkomsa.net (Caleb Hattingh) Date: Wed, 01 Dec 2004 23:55:07 -0500 Subject: Regular Expression Problem... References: Message-ID: Obviously, Peter and Jorge are hardcore, but below is what a beginner like me hacked up: My point, I guess, is that it is possible to quickly get a solution to a specific problem like this without being a total expert. The code below was typed out once, and with only one minor correction before it produced the required behaviour. Sure, it is not the general solution, but *this is WHY I use python* - You get a lot of mileage out of the basics. Plus, I can still read and understand the sub-optimal code, and probably will be able to several years from now :) Regular expressions are real powerful, and I am learning through using ViM - but it takes time and practice. (err, I didn't include your example with quotes, but you should get the general idea) *** '>>> stngs = [r'This Is An $EXAMPLE String', r'This Is An $EXAMPLE.String', r'This Is An $EXAMPLE',r'This Is An \$EXAMPLE\String'] '>>> stngs ['This Is An $EXAMPLE String', 'This Is An $EXAMPLE.String', 'This Is An $EXAMPLE', 'This Is An \\$EXAMPLE\\String'] '>>> for i in stngs: wdlist = i.split(' ') for j in wdlist: if j.find(r'$') > -1: dwd = j.split('.')[0] if dwd.find('\\') > -1: dwd = dwd.split('\\')[1] print dwd $EXAMPLE $EXAMPLE $EXAMPLE $EXAMPLE '>>> *** On Wed, 01 Dec 2004 13:40:17 +0100, Peter Otten <__peter__ at web.de> wrote: > andrea.gavana at agip.it wrote: > >> identifying/extracting a substring from another string. What I have to >> do >> is to extract all the strings that begins with a "$" character, but >> excluding characters like "." (point) and "'" (single quote) and "\" "/" >> (slashes). For example I have: >> >> 1) This Is An $EXAMPLE String >> 2) This Is An $EXAMPLE.String >> 3) 'This Is An $EXAMPLE' >> 4) This Is An \$EXAMPLE\String; >> >> I would like to extract only the "keyword" $EXAMPLE and what I'm using >> at > > Is that what you want? > >>>> import re >>>> r = re.compile("[$]\w+") >>>> r.findall(""" > ... 1) This Is An $EXAMPLE String > ... 2) This Is An $EXAMPLE.String > ... 3) 'This Is An $EXAMPLE' > ... 4) This Is An \$EXAMPLE\String; > ... """) > ['$EXAMPLE', '$EXAMPLE', '$EXAMPLE', '$EXAMPLE'] > > Peter > From steve at holdenweb.com Mon Dec 27 09:55:20 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 27 Dec 2004 09:55:20 -0500 Subject: Jython & IronPython Under Active Development? In-Reply-To: <41d01ac2_1@newspeer2.tds.net> References: <1104033303.754319.269650@c13g2000cwb.googlegroups.com> <1104039182.718016.78800@f14g2000cwb.googlegroups.com> <7q03a2-uev.ln1@lairds.us> <41d01ac2_1@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > Steve Holden wrote: > >> Just a little further background. The Python Software Foundation >> recently awarded a grant to help to bring Jython into line with the >> current CPython release. > > > Is information publicly available about this and other PSF grants? I > don't see any announcement on the PSF web site or in the grants-discuss > mail list. > > Thanks, > Kent I know an announcement is to be made, but I can't tell you when to expect it. Certainly the intention is to be as open as possible about the grants process. hoping-i-haven't-jumped-the-gun-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From fredrik at pythonware.com Thu Dec 23 12:52:16 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 23 Dec 2004 18:52:16 +0100 Subject: Lambda going out of fashion References: <1103787058.7586.34.camel@albert.localnet><1103821176.262563.123820@z14g2000cwz.googlegroups.com> <1103822877.985636.101580@f14g2000cwb.googlegroups.com> Message-ID: tanghaibao at gmail.com wrote: > o Why don't you just say all python can be written in equivalent java, your argumentation skills are awesome. From adekel at ort.org.il Sat Dec 18 17:28:38 2004 From: adekel at ort.org.il (Amir Dekel) Date: Sun, 19 Dec 2004 00:28:38 +0200 Subject: A beginner's problem... In-Reply-To: <86y8fv2qtr.fsf@guru.mired.org> References: <86y8fv2qtr.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > > Doing a second import will find the module in sys.modules and not > bother looking in the file system. The solution is to reload(module) > instead of import module. > > Message-ID: <3Gkwd.43287$6q2.35409@newssvr14.news.prodigy.com> "abisofile" wrote in message news:mailman.7879.1103222183.5135.python-list at python.org... > > hi > > I'm new to programming.I've try a little BASIC so I want ask since > Python is also interpreted lang if it's similar to BASIC. > > > Is a Ferrari similar to a horse-wagon? Yes, they both have 4 wheels. :=) From ncoghlan at iinet.net.au Thu Dec 30 08:58:09 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 30 Dec 2004 23:58:09 +1000 Subject: Tkinter vs wxPython In-Reply-To: <41D402B1.7070307@holdenweb.com> References: <33hq6aF41vbm5U1@individual.net> <41D402B1.7070307@holdenweb.com> Message-ID: <41D40971.8000305@iinet.net.au> Steve Holden wrote: > Bernd Schmidt wrote: > >> Sure, but on my Linux, I use KDE, never Gnome, other people use >> Windowmaker or something else. wxPython with KDE-Look? What is the >> native look with wxPython and KDE? I don't think there is something >> like this, and the problem is that there isn't a free QT on Windows. >> >> Bernd > > > Well, of course, the problem with X Window has always been when you ran > an application built using one toolkit under a window manager built > using another. *Then* the ugliness is due to the fact that different > parts of the window are decorated by different toolkits. That's always > going to be ugly. Not always - the KDE and Gnome folks are doing a fair bit of work to make apps written with each others' framework blends in with the currently running window manager. To answer Bernd's question, a wx-based app will looks as good on KDE as any other GTK app does. For most distros, the app should look fine, since the vendor generally sets up the Gnome and KDE themes to be virtually identical. As I understand it, there are a couple of cross-theming engines that allow you to set GTK to 'use the KDE theme' and vice-versa so that apps written with the 'other' toolkit track any changes you make to the theme used by your window manager. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From peter at engcorp.com Thu Dec 30 16:59:44 2004 From: peter at engcorp.com (Peter Hansen) Date: Thu, 30 Dec 2004 16:59:44 -0500 Subject: Problem in threading In-Reply-To: <867jmzsbnn.fsf@guru.mired.org> References: <861xd9t06p.fsf@guru.mired.org> <867jmzsbnn.fsf@guru.mired.org> Message-ID: Mike Meyer wrote: > See which > clearly has the words "New in 2.4" on it. It also says that the > threading module is loosely based on the Java model. I may have > misinterpreted what the "New in 2.4" applies to, which means that the > comment about the Java model being new in 2.4 would be wrong. You have misinterpreted that. The "New in 2.4" part is not so much "on" that page as it is "in" it, and specifically it is right in the section on the new-to-2.4 class "local". The rest of the threading module is basically unchanged since a number of versions ago, but thanks for your clarification. :-) -Peter From stephen.thorne at gmail.com Thu Dec 23 05:47:29 2004 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Thu, 23 Dec 2004 20:47:29 +1000 Subject: Lambda going out of fashion In-Reply-To: <7xpt114cre.fsf@ruckus.brouhaha.com> References: <1Rtyd.549053$wV.296842@attbi_s54> <1103786497.565595.85070@z14g2000cwz.googlegroups.com> <7xpt114cre.fsf@ruckus.brouhaha.com> Message-ID: <3e8ca5c804122302476836a20a@mail.gmail.com> On 23 Dec 2004 00:52:53 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Alan Gauld writes: > > readability. Pythonic lambdas are just syntactic sugar in > > practice, > > Actually it's the other way around: it's named functions that are the > syntactic sugar. Not true, you can't re-write def f(): raise ValueError, "Don't call f" as a lambda. Lambdas contain only a single expression. Even the py3k wiki page ignores this critical difference. A single expression means no statements of any kind can be included. Assignment, if/elif/else, while, for, try/except, etc are not catered for in lambdas. There has been a case in the past for a lambda that contains statements, but they have been stomped on due to problems with syntax. I don't like lambdas that have more than a single expression myself (if it's more complex than "lambda x:baz(x.foo(y))", I would prefer to write a named function). ultimate-ly yr's. Stephen Thorne. From roccomoretti at hotpop.com Thu Dec 30 16:07:21 2004 From: roccomoretti at hotpop.com (Rocco Moretti) Date: Thu, 30 Dec 2004 15:07:21 -0600 Subject: Compiled bytecode In-Reply-To: References: <20041229185714.06154.00001753@mb-m21.aol.com> Message-ID: Peter Hansen wrote: > The main script is generally not compiled, but all imported > scripts are generally compiled automatically, the first time > they are imported, and never again unless the source changes. Someone please correct me if I'm wrong, but I'm under the impression that the main script *is* compiled, but the byte-code compiled file is kept in memory, and not written to disk. That's what makes this work: ------ file1.py ----- import dis def f(): a = 1 print a dis.dis(f) --------------------- > python file1.py 4 0 LOAD_CONST 1 (1) 3 STORE_FAST 0 (a) 5 6 LOAD_FAST 0 (a) 9 PRINT_ITEM 10 PRINT_NEWLINE 11 LOAD_CONST 0 (None) 14 RETURN_VALUE > ---------------------- From ncoghlan at iinet.net.au Thu Dec 23 02:39:59 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 23 Dec 2004 17:39:59 +1000 Subject: Newbie namespace question In-Reply-To: <1103748472.850500.171000@f14g2000cwb.googlegroups.com> References: <1103726535.898895.207410@c13g2000cwb.googlegroups.com> <1103732151.258284.270620@c13g2000cwb.googlegroups.com> <0NKdndLw_o3QR1TcRVn-sQ@powergate.ca> <1103748472.850500.171000@f14g2000cwb.googlegroups.com> Message-ID: <41CA764F.3030303@iinet.net.au> Brandon wrote: > Peter, > > You're correct about the bug. I did need a 'self' parm... I was just > winging the example because the actual code is pretty large. I'm using > google groups for my posting and it didn't carry spaces through (I did > use spaces and not tabs). > > The "fix" or workaround was to import __builtin__ and add the > AdminConfig reference there in configure_server_foo.py as follows: > > import __builtin__ > __builtin__.AdminConfig = AdminConfig > > As for the indentations, substitute ~ with a space. > > Hopefully, a bug free and "indented" version. :) > > #jdbc.py > class DataSource: > ~~~def __init__(self, servername): > ~~~~~~self.servername = servername > > ~~~def create(self, name, connectionInfo, etc): > ~~~~~~#Call the IBM supplied WebSphere config object > ~~~~~~AdminConfig.create('DataSource') > Is there any particular reason DataSource can't be modified to accept a reference to the AdminConfig as a constructor argument? Or as a class attribute? Alternatively, here's another trick to 'nicely' set a module global from outside a module: #jdbc.py def setAdminConfig(adm_cfg): global AdminConfig AdminConfig = adm_cfg However, if you would prefer not to alter jdbc.py, consider trying: import jdbc jdbc.AdminConfig = AdminConfig Global variables are bad karma to start with, and monkeying with __builtin__ is even worse :) Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From aleaxit at yahoo.com Wed Dec 29 17:31:40 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Wed, 29 Dec 2004 23:31:40 +0100 Subject: what would you like to see in a 2nd edition Nutshell? References: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> Message-ID: <1gpkwwt.8jyy2a1us66q4N%aleaxit@yahoo.com> Fernando Perez wrote: > Alex Martelli wrote: > > > the coverage of Twisted and adding just a few things (numarray -- > > perhaps premature to have it _instead_ of Numeric, though; dateutils, > > You might want to keep in touch with the scipy/numarray gang on this > particular topic. An effort is currently under way to make scipy work > with numarray, and matplotlib already works with numarray out of the box. > These two facts will, I think, greatly accelerate the adoption of numarray > and the transition away from Numeric. There are a few people (like me, > unfortunately), who can simply not use numarray because of the small array > instatiation overhead. But that subcommunity tends to know enough to be > able to deal with the problems by itself. Since numarray is indeed the > long-term array core for Python, I think the book would be better off by > covering it. Numarray is actively developed, and vastly better documented > than Numeric. Well, I _am_ going to cover or at least "mention" numarray -- my question was on whether I can _drop_ Numeric in favour of numarray. In good part _because_ numarray has good docs, it may be less crucial for me to cover it thoroughly, than I felt it was for Numeric. Three years ago, numarray was barely a blip on the radar, if that; three years from now, the same may be true of Numeric; but right now, I get some sense that we're "in transition" -- that numarray needs and deserves coverage or at least extended mention, BUT nevertheless it might be premature to drop the coverage of Numeric... > A mention of the particular problems with numarray might be a good idea, so > that readers are aware of Numeric and where it may still be preferable to > numarray, but with the understanding that it's a (shrinking) niche. Hopefully > one day that niche will shrink to zero, but that is going to take time and > work. Right -- and if I can get the 2nd ed of the Nutshell out within 2005, it may be too early to say that Numeric has shrunk to the vanishing point... so I may still need to have both in... > Finally, I think in this section a mention of the overall scipy project would > be a good idea. Scipy is the central meeting point for most scientific > computing projects in python, and therefore a natural reference for most users > of numarray/numeric. Amongst other useful things at the scipy site, there's a > community maintained wiki of links to python-based projects of scientific > interest: > > http://www.scipy.org/wikis/topical_software/TopicalSoftware Most definitely a good idea, thanks. Indeed, the lack of mention of scipy _is_ a wart in the 1st ed -- as my excuse I can only explain that I was _so_ focused on being focused... I ended up excising even all mentions of my own baby, gmpy...!-) But yes, scipy _will_ most definitely get a mention this time around -- thanks for reminding me!-) Alex From kent3737 at yahoo.com Fri Dec 3 06:06:11 2004 From: kent3737 at yahoo.com (Kent Johnson) Date: Fri, 03 Dec 2004 06:06:11 -0500 Subject: PySQLLite Speed In-Reply-To: References: Message-ID: <41b0472d$1_3@newspeer2.tds.net> Kevin wrote: > Hello All, > > I wanted to thank Roger Binn for his email. He had > the answer to my issue with writing speed. It's > actual made an incredible change in the preformace. I > didn't have to go all the way to implementing the > synchronous mode(for my app). Previously, I was > insert one record at a time. The key was to write > them all at one time. I moved up to a 13 meg file and > wrote it to the db in secs. Now the issue is the 120 > meg of RAM consumed by PyParse to read in a 13 meg > file. If anyone has thoughts on that, it would be > great. Otherwise, I will repost under a more specific > email. If your data is (or can be) created by an iterator, you can use this recipe to group the data into batches of whatever size you choose and write the individual batches to the db. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303279 Kent > > Thanks, > Kevin > > > > db.execute("begin") > > while i < TriNum > db.execute("""insert into TABLE(V1_x) > values(%f),""" (data[i])) > i = i + 1 > > db.execute("commit") > > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - You care about security. So do we. > http://promotions.yahoo.com/new_mail From ncoghlan at email.com Fri Dec 3 18:48:26 2004 From: ncoghlan at email.com (Nick Coghlan) Date: Sat, 04 Dec 2004 09:48:26 +1000 Subject: assymetry between a == b and a.__eq__(b) In-Reply-To: <986sd.605940$mD.582402@attbi_s02> References: <9YNsBls/K7gH089yn@the-wire.com> <986sd.605940$mD.582402@attbi_s02> Message-ID: <41b0fb4a$0$25761$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Steven Bethard wrote: > Mel Wilson wrote: > >> In article , >> Steven Bethard wrote: >> >>> I believe what Peter Otten was pointing out is that calling __eq__ is >>> not the same as using ==, presumably because the code for == checks the >>> types of the two objects and returns False if they're different before >>> the __eq__ code ever gets called. >> >> >> >> Doesn't seem to: > > [snip] > > Check his example: > > http://mail.python.org/pipermail/python-list/2004-November/252660.html I suspect that example is due to the rule that "A op B" can be passed to any of the following, depending on the operator and the types of A and B: A.__op__(B) B.__op__(A) B.__rop__(A) The latter two get invoked when B is a proper subclass of A (using 'op' for commutative operations, and 'rop' for potentially non-commutative ones). This is so that subclasses can interact with parent classes correctly. So, in Steven's original code, B.__eq__(A) was invoked, and returned False (since A was the parent class of B, not a subclass). Cheers, Nick. From bturczyn at gmail.com Wed Dec 15 15:42:25 2004 From: bturczyn at gmail.com (Bill Turczyn) Date: 15 Dec 2004 12:42:25 -0800 Subject: Module question Message-ID: <1103143345.721887.80940@c13g2000cwb.googlegroups.com> Does python have a module similiar to the perl Spreadsheet::WriteExcel Thanks, Bill From steve at holdenweb.com Thu Dec 23 09:51:24 2004 From: steve at holdenweb.com (Steve Holden) Date: Thu, 23 Dec 2004 09:51:24 -0500 Subject: Best GUI for small-scale accounting app? In-Reply-To: <41CA03CA.7040808@swiftdsl.com.au> References: <7xmzw9cf8l.fsf@ruckus.brouhaha.com> <7x8y7t5c3l.fsf@ruckus.brouhaha.com> <41CA03CA.7040808@swiftdsl.com.au> Message-ID: huy wrote: > Dave Cook wrote: > >> On 2004-12-20, Paul Rubin wrote: >> >> >>> I think I can put together a useable (but not visually stunning) web >>> interface faster than I can put together any pure client-side >>> interface. >> >> >> >> Web browser "widgets" seem pretty limited to me, though. You don't even >> have something as simple as a combo box (i.e. an editable entry with a >> drop >> down), let alone the rich set of widgets something like wxwidgets offers. >> Also web development doesn't seem as coherent to me as development with a >> good GUI framework. > > > I think it depends on your target audience. Many people love simplicity. > Many people hate multiple tabs, tree structures, deep nested menus etc > etc. If you wanted to make a web program as complex as a rich client > program then it's probably a bad idea to do as a web program. But If you > wanted to keep it simple, then I'd go with a web program any day. Indeed the best advice to many programmers is to spend A LOT of time considering the user interface, since that's what will often have the major impact on user experience, and hence ultimately on acceptance. I still moan about having to use EIGHT mouse clicks in Mozilla 1.7 to change my default SMTP host to the other one on a list of two. Which remionds me, time to check out the latest release ... regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From fuzzyman at gmail.com Fri Dec 17 08:08:46 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: 17 Dec 2004 05:08:46 -0800 Subject: setup.py - just what is it for ? In-Reply-To: References: Message-ID: <1103288926.455488.202620@z14g2000cwz.googlegroups.com> You could *try* writing a cgi which did something like os.spawnv('python', ['setup.py', 'install']) (or whatever would be right without looking up the docs)... You sometimes don't need admin rights to run setup.py I would be interested in the results. Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From steve at holdenweb.com Fri Dec 24 09:33:06 2004 From: steve at holdenweb.com (Steve Holden) Date: Fri, 24 Dec 2004 09:33:06 -0500 Subject: How about "pure virtual methods"? In-Reply-To: <1gp9wjb.18uqvfi1ibk5wxN%aleaxit@yahoo.com> References: <10shetjeo2cbpfa@corp.supernews.com> <1gp9wjb.18uqvfi1ibk5wxN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: [...] > Sorry for the toy-ness of the > example, but I don't want to post for hundreds of lines. [...] Can we take it this is some kind of early New Year's resolution? happy-christmas-ly y'rs - steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From aahz at pythoncraft.com Tue Dec 28 23:06:47 2004 From: aahz at pythoncraft.com (Aahz) Date: 28 Dec 2004 23:06:47 -0500 Subject: getattr() woes References: <87hdm5hnet.fsf@thomas.local> Message-ID: In article <87hdm5hnet.fsf at thomas.local>, Thomas Rast wrote: > >I've found out about a fundamental problem of attribute lookup, the >hard way. Maybe. >asyncore.py uses the following code: > >class dispatcher: > # ... > def __getattr__(self, attr): > return getattr(self.socket, attr) > >Now suppose that I'm asking for some attribute not provided by >dispatcher: The lookup mechanism will apparently try to find it >directly and fail, generating an AttributeError; next it will call >__getattr__ to find the attribute. So far, no problems. > >But I used a property much like this: > >>>> import asyncore >>>> class Peer(asyncore.dispatcher): >... def _get_foo(self): >... # caused by a bug, several stack levels deeper >... raise AttributeError('hidden!') >... foo = property(_get_foo) >... You're not supposed to use properties with classic classes. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From theller at python.net Tue Dec 7 15:50:29 2004 From: theller at python.net (Thomas Heller) Date: Tue, 07 Dec 2004 21:50:29 +0100 Subject: error on crude test of embedding python in c++ HELP PLEASE References: Message-ID: "Donnie Leen" writes: > I wrote a program to test calling c function from python code embedding in c > as following, it cause error after running a while(about 398 circle). I > test it in msvc6, python2.3, windows 2k, could anyone tell me why this > happened since i just work according to the document? Thanks first. > > Donnie Leen > > > source code: > > > #include > > static PyObject* pymyfun( PyObject* self, PyObject* args ) > { > return Py_None; // do nothing You forgot an Py_INCREF here: Py_INCREF(Py_None); return Py_None; // do nothing > } > static PyMethodDef emb_methods[] = { > { "fun", pymyfun, METH_VARARGS, "doc." }, > {NULL, NULL, 0, NULL} > }; > > void main( ) > { > Py_Initialize( ); > > PyObject* r = Py_InitModule( "mymodule", emb_methods ); > PyRun_SimpleString( "import mymodule" ); > while ( 1 ) > { > // error occur after 398 loops here > PyRun_SimpleString( "mymodule.fun( 'testest' )" ); > } > > Py_Finalize(); > } From ncoghlan at iinet.net.au Mon Dec 6 06:11:05 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Mon, 06 Dec 2004 21:11:05 +1000 Subject: Recursive list comprehension In-Reply-To: References: Message-ID: <41b43e49$0$25772$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Peter Nuttall wrote: > I think you do it with a generator like this: > > def flatten(nested): > for sublist in nested: > for element in sublist: > yield element > > n=[['N', 'F'], ['E'], ['D']] > output=[] > > for value in flatten(n): > output.append(value) > > print output I highly recommend learning about the stdlib module "itertools" (I only really looked into it recently). The above can be done in 3 lines (counting imports): from itertools import chain n = [['N', 'F'], ['E'], ['D']] print [chain(*n)] Documentation: http://www.python.org/doc/2.3.4/lib/itertools-functions.html Cheers, Nick. From benhopkins at mindspring.com Mon Dec 13 18:09:48 2004 From: benhopkins at mindspring.com (ben) Date: 13 Dec 2004 15:09:48 -0800 Subject: system requirements for python 2.4 References: <1102969092.705783.204000@z14g2000cwz.googlegroups.com> <131220041501444655%mrjean1ATcomcastDOTnet@no.spam.net> Message-ID: <1102979388.802011.17970@c13g2000cwb.googlegroups.com> Ah, I figured I would have to resort to that. Thanks. From steven.bethard at gmail.com Fri Dec 17 15:30:36 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 17 Dec 2004 20:30:36 GMT Subject: better lambda support in the future? In-Reply-To: References: Message-ID: Jason Zheng wrote: > I'm wondering why python still has limited lambda support. What's > stopping the developers of python to support more lisp-like lambda > function? This comes up every few weeks on the list. If you haven't already, check the archives in Google for 'anonymous def' or 'anonymous function'. The usual response to this question is something along the lines of "if it's good enough to create a function for, it's good enough to name". One of the other big reasons for this type of proposal never making it far is that, so far, no one has found a syntax that everyone (or even most people) like. You end up with things like: x = func or lambda x, y: # body of lambda func # indented here or x = func or lambda x, y: # body of lambda func # indented here or x = func or lambda x, y { # body of lamda func indented # however you want... } or any thousand other varieties. Even if you could settle the syntax issue, once you've decided that you really do need a true block in an anonymous function, you're not really saving much space by not declaring it: def f(*args): # body line 1 # body line 2 # ... # body line N x = func or f v.s. x = func or lambda *args: # body line 1 # body line 2 # ... # body line N so, you save a single line, which is only 1 Nth of the size of your function (where N is the number of lines in your function body). For a single or double line function, these savings may be more substantial, but chances are if your function is only one or two lines, it can be written as an expression anyway (e.g. using LCs or GEs)... Do check the archives -- there are a lot of discussions on this topic, but hopefully the brief commentary above will give you something of an overview. Steve From dalke at dalkescientific.com Fri Dec 31 14:01:33 2004 From: dalke at dalkescientific.com (Andrew Dalke) Date: Fri, 31 Dec 2004 19:01:33 GMT Subject: Parsing a search string References: Message-ID: "It's me" wrote: > Here's a NDFA for your text: > > b 0 1-9 a-Z , . + - ' " \n > S0: S0 E E S1 E E E S3 E S2 E > S1: T1 E E S1 E E E E E E T1 > S2: S2 E E S2 E E E E E T2 E > S3: T3 E E S3 E E E E E E T3 Now if I only had an NDFA for parsing that syntax... :) Andrew dalke at dalkescientific.com From tim.peters at gmail.com Mon Dec 6 10:30:06 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 6 Dec 2004 10:30:06 -0500 Subject: [BUG] IMO, but no opinions? Uncle Tim? was: int(float(sys.maxint)) buglet ? In-Reply-To: <41b3f08f.105027181@news.oz.net> References: <41b3f08f.105027181@news.oz.net> Message-ID: <1f7befae04120607301d9107c4@mail.gmail.com> [Bengt Richter] > Peculiar boundary cases: > > >>> 2.0**31-1.0 > 2147483647.0 > >>> int(2147483647.0) > 2147483647L > >>> int(2147483647L ) > 2147483647 > >>> > >>> -2.0**31 > -2147483648.0 > >>> int(-2147483648.0) > -2147483648L > >>> int(-2147483648L ) > -2147483648 > > some kind of one-off error? It would help if you were explicit about what you think "the error" is. I see a correct result in all cases there. Is it just that sometimes int(a_float) returns a Python long when int(a_long_with_the_same_value_as_that_float) returns a Python int? If so, that's not a bug -- there's no promise anywhere, e.g., that Python will return an int whenever it's physically possible to do so. Python used to return a (short) int in all cases above, but that lead to problems on some oddball systems. See the comments for float_int() in floatobject.c for more detail. Slowing float_int() to avoid those problems while returning a short int whenever physically possible is a tradeoff I would oppose. From pythongnome at hotmail.com Mon Dec 20 08:18:06 2004 From: pythongnome at hotmail.com (Lucas Raab) Date: Mon, 20 Dec 2004 13:18:06 GMT Subject: Funny story about python In-Reply-To: <1103504255.706194.41410@z14g2000cwz.googlegroups.com> References: <1103504255.706194.41410@z14g2000cwz.googlegroups.com> Message-ID: [snip] > eScrew > eScrew will keep writing this shit because eScrew enjoys to masturbate > your spiritual sense of self eScrew > Awww, it was such a good story until now. From deetsNOSPAM at web.de Thu Dec 2 06:18:15 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Thu, 02 Dec 2004 12:18:15 +0100 Subject: installing wxPython on Linux and Windows References: Message-ID: > Same task on Win2k: download wxPython-setup.exe, double-click, done. > Took me approx. 1 minute. This strikes me. Why are some tasks so hard > on Linux and so easy on Windows? After all wxPython/Win and wxPython/Lin > are made by the same developers. My guess: the software deployment > infrastructure on Linux needs to be improved. On debian, it apt-get install wxPython2.5.3 So it clearly depends on you distribution. That this is unfortunate is of course true... I think there are several reasons for windows having easier installation: - on unix, progams usually are linked to libraries available on the machine, so missing dependencies make the installation fail. On windows, the installer installs all the dependencies - and possibly overwrites system dlls (CorelDraw 7 killed Exchange by that, back in 1998) - there is more commercially available installers for windows - maybe because free software developers on UNIXes are less keen to pay for such tools, or the admins of such systems can be trusted to be more apt dealing with configure and the like. - the variety of hardware _and_ software unix systems run on is much larger, so compiling is the only way to go if you don't want to support a plethorea of binaries (and have hardware available for these). On windows, you can compile at home and install it on the big iron at work. All the points are of course only an explanation, no excuse - there _could_ be better installers. As I showed, in parts that's already available, e.g. for debian which handles dependencies usually much better and is easier to use for online updates. I think we have to wait until consistent dependency checking and so on are established - maybe LSB helps us there. -- Regards, Diez B. Roggisch From mrjean1ATcomcastDOTnet at no.spam.net Tue Dec 21 16:02:02 2004 From: mrjean1ATcomcastDOTnet at no.spam.net (Jean Brouwers) Date: Tue, 21 Dec 2004 21:02:02 GMT Subject: memory leak References: Message-ID: <211220041302301632%mrjean1ATcomcastDOTnet@no.spam.net> Since you are on Linux, one thing which could be helpful is to lower the virtual memory limit. Before running your program, use the Csh limit command to set the upper limit for vmemory. If there is a leak in your program or in any of the extensions, it will run out of memory earlier. But setting the limit does not help finding the root cause of a leak. That requires additional effort and/or dignostic tools. /Jean Brouwers In article , Daniel Wheeler wrote: > I'm on a linux platform and looking in proc/pid/status. Using top shows > the same problem. > > I've actually just found the c routine where the memory is leaking by > the painstaking process of > taking the difference between memory consumption before and after each > python routine. I guess > that memory leaks that are not associated with python dangling > references are nearly always in the > underlying c code. > > Also, does anyone know of some good memory diagnostic tools for python, > maybe even a GUI. > I am currently using some pulled from various webpages: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286222 > http://www.nightmare.com/medusa/memory-leaks.html > > > On Dec 21, 2004, at 12:18 PM, Stephen Kellett wrote: > > > In message , > > Daniel Wheeler writes > >> However, I would like to understand first if pure python can leak > >> without the reference count increasing? > > > > How are you determining that used memory is increasing? > > > > Stephen > > -- > > Stephen Kellett > > Object Media Limited http://www.objmedia.demon.co.uk > > RSI Information: http://www.objmedia.demon.co.uk/rsi.html > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > ------------------------------------- > Daniel Wheeler > Telephone: (301) 975-8358 > From aahz at pythoncraft.com Tue Dec 21 10:34:35 2004 From: aahz at pythoncraft.com (Aahz) Date: 21 Dec 2004 10:34:35 -0500 Subject: atmosphere on c.l.py (WAS: How about "pure virtual methods"?) References: Message-ID: In article , Doug Holton wrote: > >Unfortunately, I may have jumped the gun on that one. He does not even >acknowledge his behavior outside of the three instances he referred to. >From my POV, your use of a munged e-mail address makes you far more antisocial than Fredrik. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From burnettmn at ornl.gov Thu Dec 2 15:27:30 2004 From: burnettmn at ornl.gov (Mike) Date: 2 Dec 2004 12:27:30 -0800 Subject: help running python in a limited interpreted environment Message-ID: <1102019250.812710.249120@c13g2000cwb.googlegroups.com> We have a large c++ program that runs under Windows NT Embedded to control an instrument. That program has been written to run external python scripts. The computer where this code runs does not and cannot have a full python installation. It ONLY has the pythonNN.dll file that comes with a full python installation. For simple scripts that do not import external modules, this works just fine. For more complex scripts that require imported external modules, the called modules (.py) have been placed on the computer in the same folder as the calling script. However, when the calling scripts run, we get the error message: AttributeError: 'module' object has no attribute 'xxx' We know the calling script finds the necessary modules, and the attribute clearly appears in the module's .py file. Can anyone tell me what the problem is or if what we're trying to do is not possible? Is there something in addition to the .dll that needs to be present? Thanks. From mdraghi at prosud.com Thu Dec 30 14:37:57 2004 From: mdraghi at prosud.com (Mariano Draghi) Date: Thu, 30 Dec 2004 16:37:57 -0300 Subject: what would you like to see in a 2nd edition Nutshell? In-Reply-To: References: <1gpjz0o.umrpws1pjdekyN%aleaxit@yahoo.com> <1gpkxzx.fu7ild1r7602uN%aleaxit@yahoo.com> <200412301319.10987.drlinux@columbus.rr.com> Message-ID: Alex Martelli escribi?: > > Yes, good point... I _do_ plan another book after I'm done with the 2nd > ed Nutshell, though ti will mostly be about Design Patterns and > development methods so may not meet your exact desires... Now I'm anxious! *that* is the book I'm waiting for :) I think the Python community really needs such a book; you have plenty of books and articles and papers and resources on-line with (almost) all the bits & pieces. But I really miss a book that focuses in the "Pythonic way" of project management, design patterns, development cycles, QA... something targeted to the enterprise. I think that somehow Python's "J2EE" equivalent is already out there (sort of...), if you have time to look for the bits, and if you manage to glue them together. A good book with a higher level approach, focused in design, would be an invaluable help in that proccess. -- Mariano From steven.bethard at gmail.com Thu Dec 23 11:58:51 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 23 Dec 2004 16:58:51 GMT Subject: list Integer indexing dies?? In-Reply-To: References: Message-ID: Ishwor wrote: > On Thu, 23 Dec 2004 13:33:16 -0300, Batista, Facundo > wrote: > >> >>[Ishwor] >> >>#- > What should 035[0] cough up? Be carefull it should >>#- >>#- >>>035[0] >>#- 3 # my own opinion. >>#- >>#- > cough up the same as 29[0]. >>#- >>#- >>>29[0] >>#- 2 #again my own opinion >> >>Be aware that: >> >> >>>>>035 == 29 >> >>True >> > > Yup. Octal variation of 29. But that wasn't my point. Yes, but worse yet: py> 035 is 29 True So 035 and 29 refer to exactly the same object. They're just syntactic variants. So how's Python to know which syntactic variant you want the index taken from? AFAIK that information is not stored in a Python int or you wouldn't get results like: py> 035 29 Steve From guettli at thomas-guettler.de Tue Dec 21 11:04:43 2004 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 21 Dec 2004 17:04:43 +0100 Subject: getting env variable from bourne shell script References: Message-ID: Am Tue, 21 Dec 2004 07:51:53 -0800 schrieb biner: > Hello, > > I have file called PARAMETRES that is used in bourne shell script to > define variable. In order to do so I put a ". PARAMETRES" line and the > script has acces to all the variable defined in the PARAMETRES file. Hi, you can run ". PARAMETERS; set" with popen. Then read stdin and parse the lines: The lines from stdin look like this: ACLOCAL_PATH=/opt/gnome/share/aclocal BASH=/bin/bash BASH_VERSINFO=([0]="2" [1]="05b" [2]="0" [3]="1" [4]="release" [5]="i586-suse-linux") BASH_VERSION='2.05b.0(1)-release' COLORTERM=1 COLUMNS=143 CPU=i686 CVSROOT=:ext:tguettler at homeserver:/raid/develop CVS_RSH=ssh .... you could use '^(.*?)=(.*)$' as regex to parse each line group(1) is the variable name group(2) the value. HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ From itsme at yahoo.com Tue Dec 28 14:34:36 2004 From: itsme at yahoo.com (It's me) Date: Tue, 28 Dec 2004 19:34:36 GMT Subject: A scoping question Message-ID: This must be another newbie gotchas. Consider the following silly code, let say I have the following in file1.py: #============= import file2 global myBaseClass myBaseClass = file2.BaseClass() myBaseClass.AddChild(file2.NextClass()) #============= and in file2.py, I have: #============= global myBaseClass class BaseClass: def __init__(self): self.MyChilds = [] ... def AddChild(NewChild): self.MyChilds.append(NewChild) ... class NextClass: def __init__(self): for eachChild in myBaseClass.MyChilds: # <- ERROR ... #============= When I run this, Python complains that myBaseClass is undefined in the last line above. What am I doing wrong? (Yes, I know I am thinking too much in C). I thought the global declaration would have been sufficient but it's obviously not. Thanks, From almondb at gmail.com Fri Dec 31 16:57:53 2004 From: almondb at gmail.com (Brian) Date: 31 Dec 2004 13:57:53 -0800 Subject: PyQT installation References: <1104370062.562575.88620@f14g2000cwb.googlegroups.com> <1104417268.153983.71970@z14g2000cwz.googlegroups.com> <8SVAd.64014$Jk5.26087@lakeread01> <1gpo9ow.7zqmxi1rwc564N%aleaxit@yahoo.com> Message-ID: <1104530273.389128.136830@z14g2000cwz.googlegroups.com> For those curious about Trolltech's stance on Windows, here's what Trolltech's "License FAQ - Open Source Edition" ( http://www.trolltech.com/developer/faqs/license_gpl.html ) has to say: " Why is there no Open Source (GNU GPL) version of Qt on Windows ? We have regrettably not found a way of making GPL versions for Windows available without risking the very business model we depend upon to be able to further develop and support Qt. Please note that if you make the source code for your project available and your license allows it, any holder of a commercial Qt Windows license can create binaries for your project. " From steven.bethard at gmail.com Fri Dec 17 17:38:56 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 17 Dec 2004 22:38:56 GMT Subject: better lambda support in the future? In-Reply-To: References: Message-ID: <4eJwd.777315$8_6.26539@attbi_s04> Fredrik Lundh wrote: > Steven Bethard wrote: > >>I've seen at least one reasonable example of this kind of thing: >> >>http://mail.python.org/pipermail/python-list/2004-October/245432.html > > the code he's referring to doesn't seem to use that construct anymore, so > it's not obvious what "dejavu.icontains" etc really is, but assuming they're > strings, the following is a reasonable lambda-free alternative: > > class xforms: > def icontains(self, x, y): return x + " Like '%" + y[1:-1] + "%'" > def icontainedby(self, x, y): > # icontainedby body goes here instead of in a separate function > def istartswith(self, x, y): return x + " Like '" + y[1:-1] + "%'" > def iendswith(self, x, y): return x + " Like '%" + y[1:-1] + "'" > def ieq(self, x, y): return x + " = " + y > def now(self): return "Now()" > def today(self): return "DateValue(Now())", > def year(self, x): return "Year(" + x + ")" > def dispatch(self, tag, *args): > return getattr(self, tag)(*args) This doesn't work if the strings aren't valid Python identifiers (e.g. "!CONTAINS!"). On the other hand, if they are (and you can be guaranteed that they will continue to be), then your solution above is nice, though if you want to fully reproduce the behavior, you probably also want the method def __getitem__(self, item): return getattr(self, item) Steve From has.temp2 at virgin.net Mon Dec 20 09:26:30 2004 From: has.temp2 at virgin.net (has) Date: 20 Dec 2004 06:26:30 -0800 Subject: Funny story about python In-Reply-To: <1103552548.198820.210950@z14g2000cwz.googlegroups.com> References: <1103504255.706194.41410@z14g2000cwz.googlegroups.com> <1103552548.198820.210950@z14g2000cwz.googlegroups.com> Message-ID: <1103552790.431591.176570@c13g2000cwb.googlegroups.com> has wrote: > Not sure which is less Turing-complete: eScrew, or eScrew's author... Oops, I meant 'AI-complete'. From fperez528 at yahoo.com Tue Dec 28 18:18:03 2004 From: fperez528 at yahoo.com (Fernando Perez) Date: Tue, 28 Dec 2004 16:18:03 -0700 Subject: emulating python shell References: Message-ID: Uwe Mayer wrote: > Hi, > > in an application I want to provide direct access to the python interpreter > of the running program. > I use rawinput() and exec() to read an input string and a self-made function > to check wether the inputed block is closed and then execute it. > > When running python interactively the result of the previous statement is > assigned to the variable "_" and commands like dir() just output their > results to stdout. > However, executions of the sort: > > exec("_ = "+command) > > don't work. > > Any ideas how to mimick python -i 's behaviour? You can look at the code.py module in the python standard lib. It implements a pure-python interactive interpreter from scratch, so there's no need for you to reinvent that particular wheel. Since it's in the standard lib, you can rely on it for deployment to external sites. If you want something more sophisticated, and ready-made for this kind of embedding, look at ipython: http://ipython.scipy.org. IPython is itself based on code.InteractiveConsole, but at this point it has overridden almost all of the methods in the base class. Embedding it is as easy as: from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed() ipshell() # this call anywhere in your program will start IPython You can have multiple embedded instances, and they can be initialized to use anythingb You can find further details about embedding ipython here: http://ipython.scipy.org/doc/manual/node9.html HTH, f From mrjean1ATcomcastDOTnet at no.spam.net Wed Dec 1 10:49:39 2004 From: mrjean1ATcomcastDOTnet at no.spam.net (Jean Brouwers) Date: Wed, 01 Dec 2004 15:49:39 GMT Subject: Syntax for extracting multiple items from a dictionary References: <313tc8F34ln9sU1@uni-berlin.de> <7OednTjJLOltfDDcRVn-og@rcn.net> Message-ID: <011220040751208520%mrjean1ATcomcastDOTnet@no.spam.net> The correct syntax is: dict([(key, row[key]) for key in cols]) i.e. the list must be enclosed in [...]. /Jean Brouwers In article <7OednTjJLOltfDDcRVn-og at rcn.net>, Dave Merrill wrote: > "anton muhin" wrote: > > Stefan Behnel wrote: > > > > > > > > > shark schrieb: > > > > > >> row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken", > > >> "state" : > > >> "Alaska"} > > >> cols = ("city", "state") > > >> > > >> Is there a best-practices way to ask for an object containing only the > > >> keys > > >> named in cols out of row? In other words, to get this: > > >> {"city" : "Hoboken", "state" : "Alaska"} > > > > > > > > > Untested: > > > > > > dict( (key,value) for (key,value) in row.iteritems() if key in cols ) > > > > > > Works in Py2.4 > > > > > > Stefan > > > > Or dict((key, row[key]) for key in cols). > > > > regards, > > anton. > > I'm on Py 2.3.3, and neither of these appear to work. Can someone confirm? I > can't see anything in the 2.4 release notes that point to where this would > have changed. > > Thanks, > > shark > > From mefjr75 at hotmail.com Tue Dec 28 00:56:48 2004 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 27 Dec 2004 21:56:48 -0800 Subject: Confusion About Classes In-Reply-To: <1104194131.792545.140560@z14g2000cwz.googlegroups.com> References: <1104194131.792545.140560@z14g2000cwz.googlegroups.com> Message-ID: <1104213408.450534.205270@z14g2000cwz.googlegroups.com> flamesrock wrote: [snip] > 3) Can I create a configParser object and just call self.parser.set() > inside the function without passing it as a parameter, or do I pass it > as a parameter and call it as parser.set (without the 'self' > statement.) > > Basically..I'm confused on the proper use of 'self' in this type of > situation, even after going through all these different tutorials. Any > ideas? > > -thanks in advance\ Ok you have several problems that I see. First you are having namespace difficulties. I am not sure you 'get it' yet , but if you stay around long enough you will ;) http://docs.python.org/tut/node11.html The proper use of 'self' in a class is its namespace. You *have* to pass 'self' to all member functions of a class sp the all can have a reference to the namespace. It makes it easy to pass data back and forth between functions in a class. Below is an example of functions calling functions within a class and setting attributes, maybe this will clear it up some example: py>class bla: ... def __init__(self): ... self.data=0 ... def setData(self, data): ... self.data = data ... def getData(self): ... return self.data ... def nullData(self): ... self.setData(None) Namespace is one of those crucial concepts you *must* master in python. Do a search on google for python namespace, and read, and code, till you get it. Master namespace if you have not already. Break out an interpreter and hack away. Use dir() around your classes and functions and 'see' for yourself what is in them. Do a search on this newsgroup for namespace. This has been explained much better than I can. Second if you haven't done it yet read up on configparser. http://docs.python.org/lib/module-ConfigParser.html before implementing a universalconfigwriter/reader you need to know how to find previously written sections and options , and add error checking etc.. Especially note this page. (Hint this will save you from many long boring hours reinventing all this junk and avoiding some eval hack to get the stuff back to the right type.) If you think I am kidding note others in this newsgroup have been there done that, not me of course, I never need documentation ;) Hth, M.E.Farmer From eino at iki.fi Fri Dec 10 05:10:10 2004 From: eino at iki.fi (=?ISO-8859-1?Q?Eino_M=E4kitalo?=) Date: Fri, 10 Dec 2004 12:10:10 +0200 Subject: samba/windows shares (with python?) In-Reply-To: References: Message-ID: <41b97602$0$16584$39db0f71@news.song.fi> I.V. Aprameya Rao wrote: > hi > > does anybody know how to access samba/windows shares on a network? is > there any module that does this? > > i am running linux and i thought of using the mount command to mount that > remote share and then access it, but i was wondering whether that is the > right way? > > Aprameya > With python, CIFS client for python? If not, try smbclient Eino From ncoghlan at iinet.net.au Wed Dec 22 08:12:17 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Wed, 22 Dec 2004 23:12:17 +1000 Subject: Lazy argument evaluation (was Re: expression form of one-to-many dict?) In-Reply-To: References: <863by22gqs.fsf@guru.mired.org> Message-ID: <41C972B1.5060705@iinet.net.au> Steven Bethard wrote: >> There must be something wrong with this idea that I'm missing. . . > > > Well, it does cost you some conciceness, as your examples show[1]: > > lazy(mul, x, y) v.s. :x * y > lazy(itemgetter(i), x) v.s. :x[i] > lazy(attrgetter("a"), x) v.s. :x.a > lazycall(lazy(attrgetter("a"), x)) v.s. :x.a() > > Not sure how I feel about this yet. I don't personally need lazy > argument evaluation often enough to be able to decide which syntax would > really be clearer... I think you've hit the downside on the head, though. Any time you have to use the operator module, you take a big hit in verbosity (particularly since noone ever came up with better names for attrgetter and itemgetter. . .) There's a reason people like list comprehensions :) Ah well, I'll let it bake for a while - I'm still not entirely sure about it myself, since I'm in a similar boat to you w.r.t. lazy evaluation (I usually just define functions that do what I want and pass them around). Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From steven.bethard at gmail.com Tue Dec 28 12:47:01 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 28 Dec 2004 17:47:01 GMT Subject: Keyword arguments - strange behaviour? In-Reply-To: <1104233889.130130.213780@z14g2000cwz.googlegroups.com> References: <1103622331.247762.161750@f14g2000cwb.googlegroups.com> <1103637176.450940.243500@c13g2000cwb.googlegroups.com> <1103802539.705471.122640@f14g2000cwb.googlegroups.com> <1103816686.956825.226880@z14g2000cwz.googlegroups.com> <7gCyd.245287$V41.152597@attbi_s52> <1103842710.927642.265090@c13g2000cwb.googlegroups.com> <9thzd.631929$D%.175524@attbi_s51> <1104233889.130130.213780@z14g2000cwz.googlegroups.com> Message-ID: Fuzzyman wrote: > I see. I may be wrong on this... *but* I thought the only time when a > variable defined in the same scope as a function wouldn't be available > in the same namespace is when the function is a global but the variable > isn't ? Sorta depends on what you mean by "available in the same namespace": py> class C(object): ... def f(matcher=re.compile(r'...')): ... pass ... py> class D(object): ... matcher = re.compile(r'...') ... def f(): ... pass ... py> class E(object): ... class f(object): ... matcher = re.compile(r'...') ... def __new__(cls): ... pass ... py> c = C() py> c.matcher Traceback (most recent call last): File "", line 1, in ? AttributeError: 'C' object has no attribute 'matcher' py> d = D() py> d.matcher <_sre.SRE_Pattern object at 0x01142F20> py> e = E() py> e.matcher Traceback (most recent call last): File "", line 1, in ? AttributeError: 'E' object has no attribute 'matcher' Now in all three classes, the callable 'f' can access matcher -- it's either in f's namespace or within an enclosing namespace. However, moving the 'matcher' declaration up one level (as in class D) adds matcher to the enclosing class's namespace. The current code (class C) and my proposed code (class E) do not add 'matcher' to the enclosing class's namespace -- they keep it within f's namespace. This is what I considered to be 'polluting the namespace' -- adding extra things that aren't used by other parts of the class to the class's namespace. (Of course, this only holds if, as in my code, matcher is only needed within f.) Does that make my problem clearer? Steve From aleaxit at yahoo.com Fri Dec 24 08:40:04 2004 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 24 Dec 2004 14:40:04 +0100 Subject: Optional Static Typing - Haskell? References: <1103795375.843649.286620@c13g2000cwb.googlegroups.com> Message-ID: <1gpaypu.hp5icf1tvg99cN%aleaxit@yahoo.com> Neal D. Becker wrote: > I've just started learning about Haskell. I suggest looking at this for an > example. > > A good intro: http://www.haskell.org/tutorial Haskell's a great language, but beware: its static typing is NOT optional -- it's rigorous. It can INFER types for you (just like, say, boo), that's a different issue. It also allows bounded genericity at compile time (like, say, C++'s templates without the hassles), and that's yet another (typeclasses are a great mechanism, btw). Languages with really optional static typing can be found; I think the premier example is still Dylan -- a kind of commonlisp without infix notation, unfortunately very out of fashion nowadays but still available (some good books, too). I love the explanations of Van Roy and Haridi, p. 104-106 of their book, though I may or may not agree with their conclusions (which are basically that the intrinsic difference is tiny -- they point to Oz and Alice as interoperable languages without and with static typing, respectively), all the points they make are good. Most importantly, I believe, the way dynamic typing allows real modularity (harder with static typing, since type discipline must be enforced across module boundaries), and "exploratory computing in a computation model that integrates several programming paradigms". "Dynamic typing is recommended", they conclude, "when programs must be as flexible as possible". I recommend reading the Agile Manifesto to understand why maximal flexibility is crucial in most real-world application programming -- and therefore why, in said real world rather than in the more academic circles Dr. Van Roy and Dr. Hadidi move in, dynamic typing is generally preferable, and not such a tiny issue as they make the difference to be. Still, they at least show more awareness of the issues, in devoting 3 excellent pages of discussion about it, pros and cons, than almost any other book I've seen -- most books have clearly delineated and preformed precedence one way or the other, so the discussion is rarely as balanced as that;). Alex From ncoghlan at iinet.net.au Thu Dec 30 02:39:09 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Thu, 30 Dec 2004 17:39:09 +1000 Subject: objects as mutable dictionary keys In-Reply-To: References: <41BE1644.8050906@freemail.gr> <33bdosF3qm2j6U1@individual.net><33e3k7F3ulad0U1@individual.net> <41D2AB53.1030903@iinet.net.au> Message-ID: <41D3B09D.1050604@iinet.net.au> Terry Reedy wrote: > "Nick Coghlan" wrote in message > news:41D2AB53.1030903 at iinet.net.au... > >>This *is* a bug (since Guido called it such), but one not yet fixed as >>the obvious solution (removing object.__hash__) causes problems for >>Jython, >>and a non-obvious solution has not been identified. > > > Since object was added in 2.2 and the most recently released Jython I know > about is 2.1, are you referring to a newer version in development? Huh, I didn't think of that. I guess Samuele must have been talking about the in-development version. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From christian.ergh at gmail.com Sun Dec 12 14:29:59 2004 From: christian.ergh at gmail.com (Christian Ergh) Date: Sun, 12 Dec 2004 20:29:59 +0100 Subject: character encoding conversion In-Reply-To: <41bc7719$0$2069$9b622d9e@news.freenet.de> References: <41bc7719$0$2069$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: > Dylan wrote: > >> Things I have tried include encode()/decode() > > > This should work. If you somehow manage to guess the encoding, > e.g. guess it as cp1252, then > > htmlstring.decode("cp1252").encode("us-ascii", "xmlcharrefreplace") > > will give you a file that contains only ASCII characters, and > character references for everything else. > > Now, how should you guess the encoding? Here is a strategy: > 1. use the encoding that was sent through the HTTP header. Be > absolutely certain to not ignore this encoding. > 2. use the encoding in the XML declaration (if any). > 3. use the encoding in the http-equiv meta element (if any) > 4. use UTF-8 > 5. use Latin-1, and check that there are no characters in the > range(128,160) > 6. use cp1252 > 7. use Latin-1 > > In the order from 1 to 6, check whether you manage to decode > the input. Notice that in step 5, you will definitely get successful > decoding; consider this a failure if you have get any control > characters (from range(128, 160)); then try in step 7 latin-1 > again. > > When you find the first encoding that decodes correctly, encode > it with ascii and xmlcharrefreplace, and you won't need to worry > about the encoding, anymore. > > Regards, > Martin I have a similar problem, with characters like ???A??? and so on. I am extracting some content out of webpages, and they deliver whatever, sometimes not even giving any encoding information in the header. But your solution sounds quite good, i just do not know if - it works with the characters i mentioned - what encoding do you have in the end - and how exactly are you doing all this? All with somestring.decode() or... Can you please give an example for these 7 steps? Thanx in advance for the help Chris From daniel.wheeler at nist.gov Tue Dec 21 11:57:44 2004 From: daniel.wheeler at nist.gov (Daniel Wheeler) Date: Tue, 21 Dec 2004 11:57:44 -0500 Subject: memory leak In-Reply-To: References: Message-ID: <6F26BA3C-5371-11D9-88D4-000A95B1DE08@nist.gov> It's using a number of extension modules: scipy Numeric pysparse These are all c extensions and could all be leaking memory independently of course. However, I would like to understand first if pure python can leak without the reference count increasing? On Dec 21, 2004, at 11:41 AM, Fredrik Lundh wrote: > Daniel Wheeler wrote: > >> Can python leak memory even if the reference count for all the >> objects is not increasing? > > sure. > >> For example: >> >> for i in range(N): >> print ref_count_all_objects() >> do_something() >> >> and every iteration the ref count is constant but the memory usage is >> increasing. What are the >> likely problems? > > leaking extension modules? it's pretty much impossible to say, without > knowing more about "do_something". what does it do? what kind of > Python modules is it using? what extension modules are involved? > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > > > ------------------------------------- Daniel Wheeler Telephone: (301) 975-8358 From reinhold-birkenfeld-nospam at wolke7.net Wed Dec 29 15:53:52 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Wed, 29 Dec 2004 21:53:52 +0100 Subject: Why tuples use parentheses ()'s instead of something else like <>'s? In-Reply-To: <41d314c6$0$30032$a1866201@visi.com> References: <1104299822.394489.161500@z14g2000cwz.googlegroups.com> <41d2ce43$0$35731$a1866201@visi.com> <10t5p4nedr06h94@news.supernews.com> <33gg57F3uh3hnU1@individual.net> <41d314c6$0$30032$a1866201@visi.com> Message-ID: <33gjr1F3siliuU1@individual.net> Grant Edwards wrote: > On 2004-12-29, Reinhold Birkenfeld wrote: > >> Perl6 experiments with the use of guillemots as part of the syntax. > > As if Perl didn't look like bird-tracks already... > > http://www.seabird.org/education/animals/guillemot.html > http://www.birdguides.com/html/vidlib/species/Uria_aalge.htm Well, (1,1,2,3,5) ?+? (1,2,3,5,8); # results in (2,3,5,8,13) (>>+<< being an operator) just isn't something I would like to read in my code... Reinhold From fuzzyman at gmail.com Mon Dec 13 11:17:32 2004 From: fuzzyman at gmail.com (Fuzzyman) Date: 13 Dec 2004 08:17:32 -0800 Subject: PIL for Windows for Python 2.4 In-Reply-To: <41BDBE66.8070200@holdenweb.com> References: <1102587036.703951.63690@z14g2000cwz.googlegroups.com> <1102604285.448599.33660@f14g2000cwb.googlegroups.com> <%Hrud.10528$Jk5.3022@lakeread01> <1102926162.831462.9520@z14g2000cwz.googlegroups.com> <1102942887.320044.190280@c13g2000cwb.googlegroups.com> <41BDBE66.8070200@holdenweb.com> Message-ID: <1102954652.921487.200720@z14g2000cwz.googlegroups.com> Yep - when it finally works it's nice to see distutils do it's stuff ! Regards, Fuzzy http://www.voidspace.org.uk/atlantibots/pythonutils.html From jelle.feringa at ezct.net Sun Dec 19 11:49:04 2004 From: jelle.feringa at ezct.net (Jelle Feringa // EZCT / Paris) Date: Sun, 19 Dec 2004 17:49:04 +0100 Subject: python & nurbs In-Reply-To: <%Xhxd.4049$Z47.2492@newsread2.news.atl.earthlink.net> Message-ID: <20041219164514.375EF2400114@mwinf0909.wanadoo.fr> > Have you looked at Blender (http://www.blender3d.com)?? Blender seems very promising, its python support is exactly what I'm looking for, but it lacks the cad/parametric capabilities I'm looking for. From duncan-news at grisby.org Thu Dec 9 05:20:57 2004 From: duncan-news at grisby.org (Duncan Grisby) Date: Thu, 09 Dec 2004 11:20:57 +0100 Subject: ANNOUNCE: Ice 2.0 released References: <1102542673.956058.27570@c13g2000cwb.googlegroups.com> Message-ID: <7016c$41b82709$51604868$28467@nf1.news-service.com> In article , Michi Henning wrote: [...] >Instead of compiling the definition, you can write: > > Ice.loadSlice("Color.ice") > import M > > print "My favourite color is ", M.Color.blue Just like this then? omniORB.importIDL("Color.idl") import M print "My favourite color is ", M.blue Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From martin at v.loewis.de Wed Dec 29 19:04:27 2004 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 30 Dec 2004 01:04:27 +0100 Subject: Compiled bytecode In-Reply-To: <20041229185714.06154.00001753@mb-m21.aol.com> References: <20041229185714.06154.00001753@mb-m21.aol.com> Message-ID: <41d34609$0$13082$9b622d9e@news.freenet.de> LutherRevisited wrote: > This may be a dumb question, but are there any practical advantages of > compiling a python application to *.pyo, or *.pyc? I haven't noticed any > difference in the performance of text *.py or a bytecompiled file. For a large application, the startup cost may be noticable, as it first compiles all files to bytecode. So it is a good idea to keep the bytecode files around. As to what difference -O makes: in 2.4, it only - sets __debug__ to be false, at compile time, - removes assert statements - removes __doc__ strings from the bytecode Regards, Martin From adam at cognitcorp.com Mon Dec 13 19:11:32 2004 From: adam at cognitcorp.com (Adam DePrince) Date: Mon, 13 Dec 2004 19:11:32 -0500 Subject: Python mascot proposal In-Reply-To: <200412131150.08184.jstroud@mbi.ucla.edu> References: <200412131150.08184.jstroud@mbi.ucla.edu> Message-ID: <1102983092.4867.466.camel@localhost.localdomain> On Mon, 2004-12-13 at 14:50, James Stroud wrote: > As far as python.png below is concerned, I am reminded of the structure of the > HIV virus: http://www.avert.org/pictures/hivstructure.htm > > Pleasing to virologists and drug companies, but as a single, computer-type > guy, it makes my skin crawl in more ways than one. > > On Sunday 12 December 2004 07:40 pm, Brian Beck wrote: > > Here are a couple of images/logos (quite a bit > > different from a mascot) I've been working on... > > > > http://exogen.cwru.edu/python.png > > http://exogen.cwru.edu/python2.png > > > > If anyone can think of a way to break free of the reptile-oriented > > thought process but maintain clear, symbolic imagery, I'd love to see > > more suggestions or renditions! The notion of python as a meme, a mental virus, something ubiquitous, invasive and unavoidable like the common cold or a half time ad isn't bad. A rebellion against the accusations made by some that open source code is viral would be nice. But I agree, python.png is a bit harsh. It screams "rigid, militaristic, violent." It is also dangerous; if I saw that on the bumper of an overturned car I wouldn't stop to help -- I'd run like hell. We don't want Python aficionados to die from lack of medical care while hazmat teams look up arcane symbols on underpowered field hardened laptops while wearing inch thick gloves. When I think of Python in emotional terms. A plush toy like Tux is more appealing. As for python2.png ... does the snake get all smushed up in the gear if it turns? Adam DePrince From insert at spam.here Mon Dec 6 00:32:53 2004 From: insert at spam.here (Doug Holton) Date: Sun, 05 Dec 2004 23:32:53 -0600 Subject: Time for : comp.lang.python.newbies ?? In-Reply-To: <41B3E483.6080009@swiftdsl.com.au> References: <41B3E483.6080009@swiftdsl.com.au> Message-ID: gmduncan wrote: > Maybe a time for a new discussion group along that suggested > by the Subject line ? http://mail.python.org/mailman/listinfo/tutor > Or is their increasing presence here a price we must pay for their > belated recognition of this wonderful language ? Don't forget the price we pay for not having a comp.lang.python.cynicaloldfarts From firstname.lastname at iki.fi-spam Sun Dec 19 16:29:42 2004 From: firstname.lastname at iki.fi-spam (Simo Melenius) Date: 19 Dec 2004 23:29:42 +0200 Subject: Is this a good use for lambda References: Message-ID: "Fredrik Lundh" writes: > Walter S. Leipold wrote: > > I think that Charlie's point is that, when you use "def ", > > you have polluting your namespace. The whole program > > becomes harder to understand because you can't ignore > > anywhere, even if it was only ever intended to be used in one > > place. > Ahem. If you name the function, you can reuse the name (or just > forget about it) as soon as you've used the function object. Sure, but mental pollution counts too IMO. What you write and what you read must go through your brain, including dummy variables. And next you start thinking how to "hide" it from your own mind (e.g. naming it "_my_local_func" or something as ugly as the leading underscores in it). And I think that it does, in fact, touch the innermost symbol table too, even if the case is optimized out by the compiler -- is it? Why do something for the sake of not actually having to do it? *** Anyway, personally, this namespace cluttering most often happens because lambda is only a single expression. If one could write a true function block into a lambda, there would be less cases where lambda doesn't suffice, really. Now, if lambda was more than an expr, dumping "lambda" keyword would be a convenient idea -- unnecessary keywords can make the language less clear in some cases. One could do with Python's plain and simple "def", like this: filter (def (x): x*2, myseq) (Disclaimer: Without thinking further I'm not sure whether the above syntax would be unique enough, Python grammar-wise.) br, S From carribeiro at gmail.com Fri Dec 3 08:39:57 2004 From: carribeiro at gmail.com (Carlos Ribeiro) Date: Fri, 3 Dec 2004 11:39:57 -0200 Subject: pre-PEP generic objects In-Reply-To: References: <7xsm6ojhqi.fsf@ruckus.brouhaha.com> Message-ID: <864d370904120305393cfd7fa@mail.gmail.com> On Fri, 03 Dec 2004 07:41:59 -0500, Steve Holden wrote: > Next question: bunch is a cute name, but not very suggestive of purpose. > Who can think of a better one? "Better"is highly subjective in this context. There are several alternatives: Bunch Generic Record DataRecord I use "DataRecord" in my own code, because it's readable and makes it clear that it's not a full fledged class, but a data-only structure. Given my Pascal roots, I'm also fond of "Record". But given that many people actually loathe Pascal (probably for reasons deeply rooted in a bad academic experience :-), that may be a big "turn off". -- Carlos Ribeiro Consultoria em Projetos blog: http://rascunhosrotos.blogspot.com blog: http://pythonnotes.blogspot.com mail: carribeiro at gmail.com mail: carribeiro at yahoo.com From g.brandl at gmx.net Sun Dec 26 01:44:08 2004 From: g.brandl at gmx.net (Georg Brandl) Date: Sun, 26 Dec 2004 07:44:08 +0100 Subject: Features for a Python package manager? In-Reply-To: References: <3351ouF3rt1lgU1@individual.net> <868y7l93o4.fsf@guru.mired.org> Message-ID: <3378f2F3pknhgU1@individual.net> Robert Kern wrote: > Mike Meyer wrote: >> Nick Coghlan writes: >> >> >>>I don't know enough about Portage to answer that question. I do know >>>any package manager which made it into the standard distribution would >>>need to work for at least the big three platforms (Windows/Mac/*nix) :) >> >> >> Being written in python - and hopefully integrated into Distutils - >> why shouldn't it work on any platform that Python worked on? > > Assumptions about directory structures, and the like. That is already taken care by the distutils. The various PEPs already describe a simple method how to store package metadata, and I will try to follow these standards as close as possible. Of course, the PyPI would have to be adapted for that. > IIRC, Portage was > written for the Gentoo project, so it could assume that it was > installing stuff to a Gentoo system. Package management systems have a > distressing habit of infecting their *architecture* with these > assumptions. It makes adapting them difficult. > Also, Portage needs to execute subprocesses, something which is > notoriously platform dependent. 2.4's subprocess module should probably > be used here, but I don't think Portage does, yet. OTOH, it's Gentoo, so > it wouldn't surprise me, either. :-) That's right, but I would just draw the line at Python's standard library. What is possible with it, is done, what not, is left out. regards, Georg From jeff at ccvcorp.com Thu Dec 30 18:15:51 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu, 30 Dec 2004 15:15:51 -0800 Subject: Securing a future for anonymous functions in Python In-Reply-To: References: <10t84q9icqjnie7@news.supernews.com> Message-ID: <10t92ofkstn7if9@corp.supernews.com> David Bolen wrote: >>I think this specific use case -- defining callbacks -- should be >>addressed, rather than proposing a solution to something that isn't >>necessary. (...) >> >> > >I'd be interested in this approach too, especially if it made it simpler >to handle simple manipulation of callback arguments (e.g., since I often >ignore a successful prior result in a callback in order to just move on >to the next function in sequence). > > It seems to me that what most people *actually* want, when asking for lambdas, is a quicker and more convenient way to get closures. (At least, that's what the vast majority of examples of lambda use seem to be for.) Perhaps one could get a bit more traction by looking for improved closure syntax instead of focusing on the anonymous function aspect. All of the suggestions for anonymous multiline functions (with embedded indentation) seem to me to miss what seems to me to be the only significant benefit of lambda -- its ability to be used in-line without creating a huge ugly tangle. (I'd argue that lambdas create a *small* ugly tangle, but apparently that's just me. ;) ) Lambdas do have some value in defining callbacks, but that value derives almost exclusively from the fact that they are in-line (rather than a few lines above). Mimicking function-def indentation inside of another function's arglist strikes me as an abomination just waiting to happen; in comparison, the need to type a name twice seems trivial. As a result, it seems to me that, rather than generalize lambdas into "full" anonymous functions (with most of the negatives and few of the positives of lambda), it would be much better to specialize them further into inline-closure-creators, where they can serve a valuable purpose without quite as much risk of code pollution. Jeff Shannon Technician/Programmer Credit International From deetsNOSPAM at web.de Sun Dec 12 18:56:10 2004 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Mon, 13 Dec 2004 00:56:10 +0100 Subject: Python mascot proposal References: Message-ID: Nice drawing! -- Regards, Diez B. Roggisch From steven.bethard at gmail.com Tue Dec 21 15:50:19 2004 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 21 Dec 2004 20:50:19 GMT Subject: Lazy argument evaluation (was Re: expression form of one-to-many dict?) In-Reply-To: References: <863by22gqs.fsf@guru.mired.org> Message-ID: Nick Coghlan wrote: > > def lazy(x, *args, **kwds): > """Executes x(*args, **kwds) when called""" > if args or kwds: > return lambda : x(*args, **kwds) > else: > return x # No arguments, so x must be callable by itself > > [snip] > > Huh. I think I like the idea of lazy() much better than I like the > current PEP 312. Well, 'lazy' is definitely much easier to read, reference in the documentation, etc. than ':' would be. > There must be something wrong with this idea that I'm > missing. . . Well, it does cost you some conciceness, as your examples show[1]: lazy(mul, x, y) v.s. :x * y lazy(itemgetter(i), x) v.s. :x[i] lazy(attrgetter("a"), x) v.s. :x.a lazycall(lazy(attrgetter("a"), x)) v.s. :x.a() Not sure how I feel about this yet. I don't personally need lazy argument evaluation often enough to be able to decide which syntax would really be clearer... Steve [1] To try to make things as fair as possible, I'm assuming that you've done from operator import mul, itemgetter, attrgetter at the top of the module. From modus.tollens at gmail.com Wed Dec 8 17:20:36 2004 From: modus.tollens at gmail.com (Aaron Leung) Date: 8 Dec 2004 14:20:36 -0800 Subject: How to implement autonomous timer (for FRP)? Message-ID: <1102544436.840374.80500@z14g2000cwz.googlegroups.com> Hi everyone, I want to take a shot at implementing a simple framework for functional reactive programming in Python. (It will be loosely based on a paper I read about a system called FrTime for DrScheme.) However, I'm not sure how to go about implementing certain components. One basic component will be an object representing the current time (preferably down to, say, 10 ms). This time object should update itself autonomously. Other objects which somehow depend on the time object will be kept in a dependency graph, and automatically updated as the time object updates itself. I'm not sure what's the best way to implement this time object. I'm guessing it should run in its own thread, and whenever it updates, it should update the graph of its dependents in another thread. But naturally I'd like the timer to be efficient and precise (again, down to ~10 ms), and I'm not sure what my options are. I'd appreciate any suggestions. Thanks and regards, Aaron From ch.list at us-hampton.mail.saic.com Tue Dec 14 11:36:34 2004 From: ch.list at us-hampton.mail.saic.com (Chris) Date: Tue, 14 Dec 2004 11:36:34 -0500 Subject: Python IDE Message-ID: <41BF1692.6000103@us-hampton.mail.saic.com> What IDE's do y'all recommend for Python? I'm using PythonWin atm, but I'd like something with more functionality. Chris From markdevine at eircom.net Fri Dec 17 04:52:54 2004 From: markdevine at eircom.net (Mark Devine) Date: Fri, 17 Dec 2004 09:52:54 +0000 Subject: create lowercase strings in lists - was: (No subject) Message-ID: <20041217095255.0A9AA1E4009@bag.python.org> Thanks. This version is the version that comes with cygwin. They must be behind. Steven Bethard wrote: > > Mark Devine wrote: > > the trouble is it throws up the following error for set: > > > > $ ./test.py > > Traceback (most recent call last): > > File "./test.py", line 23, in ? > > reflist = [normalize(element) for element in list1] > > File "./test.py", line 20, in normalize > > return set(text.split()) > > NameError: global name 'set' is not defined > > > > The set type became a builtin in Python 2.4. I would suggest upgrading, > but if this is not an option, you can put this at the top of the file, > and it should get rid of the NameError: > > from sets import Set as set > > Steve > -- > http://mail.python.org/mailman/listinfo/python-list > _________________________________________________________________ Sign up for eircom broadband now and get a free two month trial.* Phone 1850 73 00 73 or visit http://home.eircom.net/broadbandoffer From fumanchu at amor.org Fri Dec 17 15:50:57 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 17 Dec 2004 12:50:57 -0800 Subject: Troubleshooting: re.finditer() creates object even when nomatch found Message-ID: <3A81C87DC164034AA4E2DDFE11D258E339807B@exchange.hqamor.amorhq.net> Chris Lasher wrote: > That's odd that there's no built-in method to do this. It seems like > it would be a common task. Is there any way to request a feature like > this from the RE module keepers, whomever they may be? The best way to request such a feature would be to write a patch. ;) FuManChu From bvdp at uniserve.com Wed Dec 22 11:39:35 2004 From: bvdp at uniserve.com (Bob van der Poel) Date: Wed, 22 Dec 2004 09:39:35 -0700 Subject: MIDI (was - Re: BASIC vs Python) In-Reply-To: References: <8vibs05kuov4qppsk356h5557772c6d3un@4ax.com> Message-ID: <10sj8q6potitta2@corp.supernews.com> Jan Dries wrote: > Andrew Dalke wrote: > >> Jan Dries >> >>> If you just want to play notes, you could look at MIDI. >> >> > [snip] > >> >> It's hard to compare that to the current era. Sound >> clips are much more common, it's easy to record audio, >> keyboards and other specialized devices are cheap, and >> there's plenty of mixer and recording software. Were >> I to have started now I would have taken a different >> course and perhaps one of these newer things would have >> interested me more. > > > The funny thing is, for me, MIDI is dead old. One of my first computers, > back in 1986, was an Atari ST. It came equiped with a MIDI port. And the > MIDI file format was created in those days, on Atari. The Atari also had > a Yamaha YM2149 sound chip on it that one could mess with in the way you > describe, and I did play with that too. But the cool thing about MIDI > was that it came with additional stuff, such as multiple voices, and > different timbres for different instruments. And I didn't have to bother > with the attack-decay-sustain-release envelope in order to make my notes > sound like notes instead of beeps. Playing with the sound chip was like > assembler, while playing with MIDI was more like a higher level > language. At the time I was a teenager and couldn't afford my own > keyboard though, and the Atari didn't have a sufficiently sophisticated > audio system for playback of MIDI files. > > Back in 1995 my then girlfriend wrote a thesis on AI where she did an > analysis of Rachmaninov's Ampico rolls in an attemt to try to extract > characteristics from that that could be applied to any piece of music to > make it sound more "human" than when played by a computer. > I helped her out by writing a "notes to MIDI" converter, to make the > results of her work audible. > I seem to remember that even then we still had to rely on a keyboard or > so to do the playback. > > But nowadays even the cheapest PC comes with "multi-media" sound > hardware, and playback of MIDI files is easy. And the nice thing for me > to find out is that the good old file format from back in the days on > Atari is still out there, and well supported by programs like Windows > Media Player. > Frankly I share your sentiment and "these newer things" like sound > clips, mixers, recording software and so have never managed to > interested me either. But MIDI is not among those, at least not for me. > Because of my particular background, MIDI has for about 20 years now > been the "serious" way to playing notes. And in fact, to the best of my > knowledge it is still the easiest way to get decent notes out of my PC. > A while ago I bought a few software packages that enable one to enter > notes and play them back. After trying out half a dozen of these, I > ended rolling my own solution in just 400 lines of Python, plus a Python > module to read/write MIDI files. > > Regards, > Jan Just as a side note, I remember reading somewhere that the Casio WK3000 Keyboard uses Python. Not sure if that's internal or just for Casio's own development. -- Bob van der Poel ** Wynndel, British Columbia, CANADA ** EMAIL: bvdp at uniserve.com WWW: http://mypage.uniserve.com/~bvdp From mwm at mired.org Thu Dec 16 19:22:45 2004 From: mwm at mired.org (Mike Meyer) Date: Thu, 16 Dec 2004 18:22:45 -0600 Subject: BASIC vs Python References: Message-ID: <86r7lp3h9m.fsf@guru.mired.org> "Thomas Bartkus" writes: > The "interpreted" nature of the existing Python language has little to do > with how it compares to other languages. Most languages, including BASIC, > are available in either flavor - interpreted or compiled. And either way, > it's still the same language. That being said, one would expect an > interpreted language (like Python!) to be a bit more approachable for > beginners. The mechanics of producing a working program are just simpler > when the language is interpreted, no matter what that language might be. On what basis do you think the mechanics of producing a working language are easier because the language is interpreted? My experience is that interpreted C (yes, I really did work with a C interpreter - and it was the only interpreter I've ever used that had no compilation phase whatsoever) is no easier to deal with than compiled C. Ditto for the various flavors of LISP I've worked with. Now, having an interactive environment with a REPL makes learning the language and checking things a lot easier. Those tend to be rare for compiled languages. But interpreted languages don't necessarily have them, as witnessed by Java and Perl. You have to get your REPL as a third party package for those languages. http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. From fumanchu at amor.org Fri Dec 10 22:05:35 2004 From: fumanchu at amor.org (Robert Brewer) Date: Fri, 10 Dec 2004 19:05:35 -0800 Subject: Tibia 0.1 DOM-based website editor Message-ID: <3A81C87DC164034AA4E2DDFE11D258E32453BE@exchange.hqamor.amorhq.net> Gabriel Cooper wrote: > Robert Brewer wrote: > > >I assume you're using the demo? My copy of Firefox has an > error browser > >under Tools->Javascript Console. Does the double-click > report any error > >there? Make sure you clear the list before trying, since > errors from all > >other webpages gt dumped in the same list. > > > > > I was using the demo on your site as Admin, but it looks like your > server is overloaded now as the pages no longer load... Ah well. ;) Sorry about that; I think it was entirely unrelated. Please try again if you have the time. NOTICE: I've been convinced to follow convention and have renamed the file back to tibia.py. So if you download it again, or try the demo, use that extension instead of .tba Thanks to Oleg Broytmann, I've also fixed the CGI bug when __file__ is not defined (it now uses sys.argv[0]). This should fix any error messages anyone was getting about relative paths or "ascending the tree". Download: http://www.aminus.org/rbre/tibia/tibia.py Demo: http://www.aminus.org/rbre/tibia/demo/tibia.py SVN: svn://casadeamor.com/tibia/trunk revision 37 Bugs: http://www.casadeamor.com/FogBugz Thanks to all who have tried it out! Robert Brewer MIS Amor Ministries fumanchu at amor.org From steve at holdenweb.com Mon Dec 20 16:18:05 2004 From: steve at holdenweb.com (Steve Holden) Date: Mon, 20 Dec 2004 16:18:05 -0500 Subject: Oddity in 2.4 with eval('None') In-Reply-To: <32oss0F3kedr2U1@individual.net> References: <32opprF3pgrieU1@individual.net> <32oss0F3kedr2U1@individual.net> Message-ID: Leif K-Brooks wrote: > Steve Holden wrote: > >> Yes. "print eval('None')" is printing the value of None as defined in >> your module's global namespace: > > > Right, but why? The expression "None" doesn't worry about the global > namespace when used in normal code; why does it when used in eval()ed code? I have no idea why. Given that >>> eval("globals()['__builtins__'].globals().keys()") ['None', '__builtins__', '__file__', 'sys', '__name__', '__doc__'] it's beginning to smell a bit like a buglet. regards Steve -- Steve Holden http://www.holdenweb.com/ Python Web Programming http://pydish.holdenweb.com/ Holden Web LLC +1 703 861 4237 +1 800 494 3119 From just at xs4all.nl Thu Dec 23 13:40:17 2004 From: just at xs4all.nl (Just) Date: Thu, 23 Dec 2004 19:40:17 +0100 Subject: Unicode entries on sys.path References: <41CB0D7A.3080107@v.loewis.de> Message-ID: In article <41CB0D7A.3080107 at v.loewis.de>, "Martin v. Lowis" wrote: > > Hm, maybe more a windows question than a python question... > > The real question here is: why does Python not support arbitrary > Unicode strings on sys.path? It could, in principle, atleast on > Windows NT+ (and also on OSX). Patches are welcome. Works for me on OSX 10.3.6, as it should: prior to using the sys.path entry, a unicode string is encoded with Py_FileSystemDefaultEncoding. I'm not sure how well it works together with zipimport, though. Just From aahz at pythoncraft.com Sun Dec 26 11:09:56 2004 From: aahz at pythoncraft.com (Aahz) Date: 26 Dec 2004 11:09:56 -0500 Subject: Improving Python (was: Lambda going out of fashion) References: Message-ID: In article , Fredrik Lundh wrote: > >func(*arg) instead of apply() is a step back -- it hides the fact >that functions are objects, and it confuses the heck out of both >C/C++ programmers and Python programmers that understand the "def >func(*arg)" form, because it looks like something it isn't (there's a >false symmetry between the call-form and the def-form). For me, it works the other way around, but I can see how you perceive it that way. >and I still do enough 1.5.2-programming to use "x = x + y"; when I find >myself in a situation where my code would benefit a lot from being able >to write "x += y" instead, I go back and fix the design. Okay, it wasn't clear in your original post that you're still stuck with 1.5.2. That makes a huge difference in the convenience of newer features. >string methods are nice, but nothing groundbreaking, and their niceness >is almost entirely offset by the horrid "".join(seq) construct that >keeps popping up when people take the "the string module is deprecated" >yada yada too seriously. and what do the python-devers do? they add a >"sum" built-in, but no "join"? hello? While I'm in complete agreement about the "".join() construct on the basis of looks, I have come to appreciate the fact that I *never* mess up the order of arguments any more. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "19. A language that doesn't affect the way you think about programming, is not worth knowing." --Alan Perlis From remy.blank_asps at pobox.com Tue Dec 7 10:50:27 2004 From: remy.blank_asps at pobox.com (Remy Blank) Date: Tue, 07 Dec 2004 16:50:27 +0100 Subject: Loading a file only once into an object and being able to access it from other modules In-Reply-To: <200412070925.57343.philippecmartin@sbcglobal.net> References: <200412070925.57343.philippecmartin@sbcglobal.net> Message-ID: Philippe C. Martin wrote: > I have a very large XML file that I load into dictionnaries defined in a class > located in a module that is imported in many places. > > Since the loading process is very slow, I would like the file not to be loaded > on import or class instantiation, but only once (on first import or class > instantiation). What about: class MyClass: hugeDict = loadHugeDic("filename.xml") def __init__(self): """hugeDict can be accessed by self.hugeDict""" ... The function loadHugeDict() will only be called once, when importing the module for the first time. If you wanted to load it on the first *instantiation*, you could do: class MyClass: hugeDict = None def __init__(self): if MyClass.hugeDict is None: MyClass.hugeDict = loadHugeDic("filename.xml") ... HTH. -- Remy Remove underscore and suffix in reply address for a timely response. From ramen at lackingtalent.com Sun Dec 19 21:16:01 2004 From: ramen at lackingtalent.com (Dave Benjamin) Date: Mon, 20 Dec 2004 02:16:01 -0000 Subject: A rational proposal References: <864qik472n.fsf@guru.mired.org> Message-ID: Hi Mike - Thanks for taking the time to put this together. In article <864qik472n.fsf at guru.mired.org>, Mike Meyer wrote: > - max(*args): return the largest of a list of numbers and self. > - min(*args): return the smallest of a list of numbers and self. I would strongly prefer either adapting the already built-in min/max functions to support this type or creating functions in a module rather than using the method approach. My reason is the assymetry; I would much prefer: rational.max(rat1, rat2, rat3) over: rat1.max(rat2, rat3) for the simple reason that the latter looks unbalanced and empbasizes "rat1" when there is really no reason to do so. > Rationals will mix with all other numeric types. When combined with an > integer type, that integer will be converted to a rational before the > operation. When combined with a floating type - either complex or > float - the rational will be converted to a floating approximation > before the operation, and a float or complex will be returned. The > reason for this is that floating point numbers - including complex - > are already imprecise. To convert them to rational would give an > incorrect impression that the results of the operation are > precise. Decimals will be converted to rationals before the > operation. [Open question: is this the right thing to do?] Sounds right to me. Cheers, Dave -- .:[ dave benjamin: ramen/[sp00] -:- spoomusic.com -:- ramenfest.com ]:. "talking about music is like dancing about architecture." From chrispatton at gmail.com Wed Dec 8 17:38:59 2004 From: chrispatton at gmail.com (chris) Date: 8 Dec 2004 14:38:59 -0800 Subject: a newbie question Message-ID: <1102545539.234273.279270@c13g2000cwb.googlegroups.com> In what directory are the preinstalled python libraries located on a Linux RH9 machine? From claird at lairds.us Tue Dec 14 12:08:03 2004 From: claird at lairds.us (Cameron Laird) Date: Tue, 14 Dec 2004 17:08:03 GMT Subject: Html or Pdf to Rtf (Linux) with Python References: Message-ID: In article , Axel Straschil wrote: >Hello! > >Sorry Cameron, I was replying, now my folloup ;-): > >> Are you trying to convert one document in particular, or automate the >> process of conveting arbitrary HTML documents? > >I have an small CMS System where the customer has the posibility to view >certain Html-Pages as Pdf, the CMS ist Python based. I also thought >about >passing the Url to an external converter Script, but found nothing ;-( > > >> What computing host is available to you--Win*? Linux? MacOS? >> Solaris!? > >Linux > >> Is Word installed? > >No. > >> OpenOffice? > >Yes. > >> Why have you specified Python? > >Becouse I like Python ;-) >The System behind generating the HTML-Code is written in Python. . . . That's a fine reason to use Python. It helps me to know, though. I do a lot of this sort of thing--automation of conversion between different Web display-formats. I don't have a one-line answer for the particular one you describe, but it's certainly feasible. I'm willing to bet there's an HTML-to-RTF converter available for Linux, but I've never needed (more accurately: I have written my own for special purposes--for my situations, it hasn't been diffi- cult) one, so I can't say for sure. My first step would be to look for such an application. Failing that, I'd script OpenOffice (with Python!) to read the HTML, and SaveAs RTF. I list a few PDF-to-RTF converters in . Again, I think there are more, but haven't yet made the time to hunt them all down. From sjmachin at lexicon.net Tue Dec 21 14:31:16 2004 From: sjmachin at lexicon.net (John Machin) Date: 21 Dec 2004 11:31:16 -0800 Subject: input record sepArator (equivalent of "$|" of perl) References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com> Message-ID: <1103657476.495700.191020@f14g2000cwb.googlegroups.com> Nick Coghlan wrote: [snip] > delimeter. Hey, Terry, another varmint over here! From programmer.py at gmail.com Wed Dec 1 15:22:15 2004 From: programmer.py at gmail.com (Jaime Wyant) Date: Wed, 1 Dec 2004 14:22:15 -0600 Subject: Python xmlrpc servers? In-Reply-To: References: <16814.6877.874118.289718@montanaro.dyndns.org> Message-ID: Check these out -> http://server3.sleekcom.com/~jaime/webservice.html (syntax highlighted version) http://server3.sleekcom.com/~jaime/webservice.txt (savable text version) HTH, jw On Wed, 01 Dec 2004 20:04:46 GMT, ted holden wrote: > Jaime Wyant wrote: > > > Mark Pilgrim wrote a really neat piece of python code that did XML-RPC > > over CGI. It seems to have disappeared from his website, though > > (http://diveintomark.org/public/webservices.txt). > > > > If you can't dig it up, I have a working copy that I use. I'll post > > it / email it if you want. > > > > Thanks, couldn't hurt anything to post it. Again the real problem seems to > be the cnostant state of flux of open software and the attempts to have > machines and software write documentation don't really seem to help much. > > > Ted > > > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Tue Dec 14 08:19:35 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 14 Dec 2004 14:19:35 +0100 Subject: RegEx: find all occurances of a single character in a string References: Message-ID: Franz Steinhaeusler wrote: > given a string: > > st="abcdatraataza" > ^ ^ ^ ^ (these should be found) > I want to get the positions of all single 'a' characters. for m in re.finditer("a+", st): if len(m.group()) == 1: print m.start() or, perhaps: indexes = [m.start() for m in re.finditer("a+", st) if len(m.group()) == 1] From ncoghlan at iinet.net.au Tue Dec 21 05:19:30 2004 From: ncoghlan at iinet.net.au (Nick Coghlan) Date: Tue, 21 Dec 2004 20:19:30 +1000 Subject: A rational proposal In-Reply-To: <86oego1sbg.fsf@guru.mired.org> References: <864qik472n.fsf@guru.mired.org> <86oego1sbg.fsf@guru.mired.org> Message-ID: <41C7F8B2.2060605@iinet.net.au> Mike Meyer wrote: > I'm willing to do the work to get > decimals working properly with it. Facundo's post reminded me of some of the discussion about the interaction between floats and Decimal that went on when he was developing the module that eventually made it into the standard library. Perhaps Rational should have the same "arm's length" interaction with floats that Decimal does - require the user to set the precision they want by turning the float into a string that is then fed to the Rational constructor. My argument is that the following behaviour might be a little disconcerting: Py> x = 1.1 Py> Rational(x) Rational("11000000000000001 / 10000000000000000") as opposed to: Py> x = 1.1 Py> Rational("%.2f" % x) Rational("11 / 10") (A direct Decimal->Rational conversion should be OK, however, since it should match standard expections regarding the behaviour of the fractional portion) The other point is that, since converting a Rational to float() or Decimal() may lose information, this is something that Python shouldn't really do automatically. As Facundo suggested, a string representation is a suitable intermediate format that makes explicit the degree of precision used in the conversion. Cheers, Nick. -- Nick Coghlan | ncoghlan at email.com | Brisbane, Australia --------------------------------------------------------------- http://boredomandlaziness.skystorm.net From redhog at takeit.se Fri Dec 10 12:33:51 2004 From: redhog at takeit.se (redhog at takeit.se) Date: 10 Dec 2004 09:33:51 -0800 Subject: Wrapper objects In-Reply-To: <41b9021b.209351251@news.oz.net> References: <41b9021b.209351251@news.oz.net> Message-ID: <1102700031.276079.36580@f14g2000cwb.googlegroups.com> Bengt Richter wrote: > On 9 Dec 2004 06:11:41 -0800, redhog at takeit.se (Egil M?ller) wrote: > > >Is there any way to create transparent wrapper objects in Python? > > > >I thought implementing __getattribute__ on either the wrapper class or > >its metaclass would do the trick, but it does not work for the built > >in operators: > > > >class Foo(object): > > class __metaclass__(type): > > def __getattribute__(self, name): > > print "Klass", name > > return type.__getattribute__(self, name) > > def __getattribute__(self, name): > > print "Objekt", name > > return object.__getattribute__(self, name) > > > > > >>>> Foo() + 1 > >Traceback (most recent call last): > > File "", line 1, in ? > >TypeError: unsupported operand type(s) for +: 'Foo' and 'int' > >>>> Foo().__add__(1) > >Objekt __add__ > >Traceback (most recent call last): > > File "", line 1, in ? > > File "", line 8, in __getattribute__ > >AttributeError: 'Foo' object has no attribute '__add__' > > > > > >Thus, note that a + b does not do > > > >try: > > return a.__add__(b) > >except: > > return b.__radd__(a) > > > >and neither, as I first thought > > > >try: > > return type(a).__add__(a, b) > >... > > > >but something along the lines of > > > >try: > > return type.__getattribute__(type(a), '__add__')(a, b) > >... > > > > > >So my naive implementation of a wrapper class, > > > > > >class wrapper(object): > > def __init__(self, value, otherdata): > > self.value = value > > self.otherdata = otherdata > > def __getattribute__(self, name): > > return getattr(self.value, name) > > > > > >does not work. Any ideas for a solution? > > This seems to go some way towards it: > > >>> class MethodDesc(object): > ... def __get__(self, inst, cls=None): > ... if inst is None: return self > ... func = self.__dict__['func'] > ... if func: return func.__get__(self.thing, type(self.thing)) > ... else: return getattr(self.thing, self.name) > ... def __init__(self, name, thing, func): > ... self.name = name > ... self.thing = thing > ... self.func = func > ... def __call__(self, *args, **kw): print 'called %s: %r %r'%(self.name, args, kw) > ... > >>> def wrapit(thing, *otherdata): > ... class Wrapper(object): > ... def __metaclass__(cname, cbases, cdict): > ... for name, func in type(thing).__dict__.items(): > ... if callable(func): > ... if name not in [ > ... '__getattr__', '__getattribute__', '__setattr__', > ... '__new__', '__init__']: > ... cdict[name] = MethodDesc(name, thing, func) > ... else: > ... cdict[name] = MethodDesc(name, thing, None) > ... return type(cname, cbases, cdict) > ... def __init__(self, *otherdata): > ... if otherdata: self.otherdata = otherdata > ... def __getattr__(self, name): > ... raise AttributeError('Wrapped %r object has no attribute %r'% (type(self).__name__, name)) > ... Wrapper.__name__ = 'Wrapped_'+type(thing).__name__ > ... return Wrapper(*otherdata) > ... > >>> class Demo(object): > ... a = 'eigh' > ... two = 2 > ... def foo(self): return 'Demo foo' > ... def bar(self, *args, **kw): print 'Demo bar %r %r'%(args, kw) > ... > >>> o2 = wrapit( Demo(), 'stuff') > >>> o2.foo > > > >>> o2.foo() > 'Demo foo' > >>> o2.bar(1,2,3,x=111,y=222) > Demo bar (1, 2, 3) {'y': 222, 'x': 111} > >>> o2.a > 'eigh' > >>> o2.two > 2 > >>> o2.z > Traceback (most recent call last): > File "", line 1, in ? > File "", line 16, in __getattr__ > AttributeError: Wrapped 'Wrapped_Demo' object has no attribute 'z' > >>> o2.z = 'zee' > >>> o2.z > 'zee' > >>> o2 > > >>> o2.a = 'not eigh' > >>> o2.a > 'not eigh' > >>> del o2.a > >>> o2.a > 'eigh' > >>> o3 = wrapit('strange', 'stuff') > >>> o3 > 'strange' > >>> o3.otherdata > ('stuff',) > >>> o3[2:] > 'range' > >>> > >>> o3.z > Traceback (most recent call last): > File "", line 1, in ? > File "", line 16, in __getattr__ > AttributeError: Wrapped 'Wrapped_str' object has no attribute 'z' > > Not tested beyond what you see ;-) This doesn't wrap setting attributes on the wrapped object, > so setting attributes sets them on the wrapper itself, but that could be fixed. > > Now what was it you wanted to use a wrapper for? ;-) > Note: > > >>> o3 += 'fail' > >>> o3 > 'strangefail' > >>> type(o3) > > > So if you want new wrapped instances as results from various ops, we need some more code ;-) > Another time ... (cf. a recent post of mine re wrapping complex as a point type). > > Regards, > Bengt Richter Ah, thanks. I didn't think of the possibility of creating a list of methods that needed wrapping, and wrapping them uppon creation of the wrapper object. Mainly I think, becaus it seems to me as such an uggly workaround for a misdesign in Python. Also, if the wrapped object gets some extra methods/callable member variables added "after the fact", those will not get wrapped (this is however not a common thing to happen, it just annoys me that it won't work). However, I do have some questions about your implementation: If "if inst is None: return self" to protect for infinite recursion when looking up self.__dict__? What is the reason to give func to the MethodDesc property object, why does its __get__ method have to do if func: return func.__get__(self.thing, type(self.thing)) ? What is the reason to neither wrap, nor just copy, any of __getattr__, __getattribute__, __setattr__, '__new__' or '__init__'? Especially __getattr__, __getattribute__ and __setattr__ seems to need at least some type of wrapping (but perheaps some special one)? Regards, Egil M?ller From fredrik at pythonware.com Sun Dec 19 12:58:40 2004 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 19 Dec 2004 18:58:40 +0100 Subject: How about "pure virtual methods"? References: <1gp06r8.10q8off1j9v6nvN%aleaxit@yahoo.com><1103448439.953120.209950@c13g2000cwb.googlegroups.com><1gp1415.10zjxtu1cfp9cxN%aleaxit@yahoo.com> <1gp1afn.udxyw81p5gajqN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: >> Traceback (most recent call last): >> File "mymodule.py", line 9, in somefunction >> someobj.bar() >> ... zero or more lines ... >> File "somelibrary.py", line 3, in bar >> raise NotImplementedError("must implement abstract method bar") >> NotImplementedError: must implement abstract method bar >> >> you have to look at the last line of a traceback to find the error >> message, and the offending module/method is two lines above that. > > The offending module is the one which instantiates a class it shouldn't > instantiate -- a class which isn't made concrete by overriding all > methods which need to be. What is that module? in real life, it's mymodule.py or mylib.py, in code that you wrote very recently. > The error is generally not the calling of 'bar' on someobj: someobj > arrives as a argument to somefunction from somewhere -- the caller of > somefunction is quite often innocent, in turn -- who BUILT someobj, by > instantiating which class? I think `minutes' is a very fair (not at all > pessimistic) assessment of the time it will generally take to find out. you can blather for years if you want to, but your arguments are just another variant of the "you cannot use whitespace for indentation" stuff we've all seen from time to time; it's trivial to come up with a large number of theoretical problems with any given approach, but in real life, for real-life programmers, using real-life libraries designed by real-life developers, it's simply not the problem you want it to be. but not that I'm going to convince you, now that you've spent 15,000 characters on this topic... From reinhold-birkenfeld-nospam at wolke7.net Tue Dec 21 12:38:23 2004 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Tue, 21 Dec 2004 18:38:23 +0100 Subject: input record sepArator (not sepErator) In-Reply-To: References: <1103491569.609341.240000@c13g2000cwb.googlegroups.com><1103501833.632076.74050@f14g2000cwb.googlegroups.com><1103504587.796518.245030@f14g2000cwb.googlegroups.com><41c6386e$1@nntp0.pdx.net> <32nmqtF3ninrdU1@individual.net> <41c6fe6b$1@nntp0.pdx.net> Message-ID: <32r5cfF3m90glU1@individual.net> Peter Otten wrote: > Terry Reedy wrote: > >> 'separate' (se-parate == take a-part) and its derivatives are perhaps the >> most frequently misspelled English word on clp. Seems to be 'par' for the >> course. It has 2 e's bracketing 2 a's. It derives from the Latin >> 'parare', as does pare, so 'par' is the essential root of the word. >> >> My gripe for the day, just to let non-native writers know what not to >> imitate. > > I hereby suggest seperate/(separate+seperate) as the hamburger standard (see > http://www.oanda.com/products/bigmac/bigmac.shtml) for technical > communities. Some data points, adjectives only, s.e.e.o.: > > the web: 4% > python: 9% > slashdot: 26% > perl: 29% * How did you get these data points? Reinhold -- [Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs- mitteln inkompatibel. -- Florian Diesch in dcoulm From danb_83 at yahoo.com Sun Dec 26 06:47:29 2004 From: danb_83 at yahoo.com (Dan Bishop) Date: 26 Dec 2004 03:47:29 -0800 Subject: A Revised Rational Proposal References: <86llbl7kvv.fsf@guru.mired.org> Message-ID: <1104061649.243801.12940@c13g2000cwb.googlegroups.com> Mike Meyer wrote: > This version includes the input from various and sundry people. Thanks > to everyone who contributed. > > > PEP: XXX > Title: A rational number module for Python ... > Implicit Construction > --------------------- > > When combined with a floating type - either complex or float - or a > decimal type, the result will be a TypeError. The reason for this is > that floating point numbers - including complex - and decimals are > already imprecise. To convert them to rational would give an > incorrect impression that the results of the operation are > precise. The proper way to add a rational to one of these types is to > convert the rational to that type explicitly before doing the > operation. I disagree with raising a TypeError here. If, in mixed-type expressions, we treat ints as a special case of rationals, it's inconsistent for rationals to raise TypeErrors in situations where int doesn't. >>> 2 + 0.5 2.5 >>> Rational(2) + 0.5 TypeError: unsupported operand types for +: 'Rational' and 'float' From jerf at jerf.org Mon Dec 6 22:04:38 2004 From: jerf at jerf.org (Jeremy Bowers) Date: Mon, 06 Dec 2004 22:04:38 -0500 Subject: why python is slower than java? References: <418b166f$1@news.unimelb.edu.au> <418b27a1$1@news.unimelb.edu.au> <418C0DB6.1040007@zephyrfalcon.org> <1102363266.420440.46150@z14g2000cwz.googlegroups.com> Message-ID: On Mon, 06 Dec 2004 13:01:47 -0800, fuzzylollipop wrote: > yeah, but a lie unanswered by the truth becomes the truth. You know, it's bad enough that somebody starts this thread anew about every two months anyhow, do you really have to try to resurrect dead ones? Be patient and I'm sure you'll have many more opportunities to post this general thought in a more timely fashion in the all-too-near future. From caroundw5h at yahoo.com Sun Dec 19 20:34:08 2004 From: caroundw5h at yahoo.com (bitshadow) Date: Sun, 19 Dec 2004 20:34:08 -0500 Subject: Web forum (made by python) References: <32m5g1F3on6drU1@individual.net> Message-ID: I have to say i'm really impressed at that fledgling progject choe, the only problem i could see is that it seemed to have problems connecting to the database everytime. I think pybbs is a wonderful idea and a great think to give back to the commnity. I will keep checking on your sites for future development. good luck and good work. -- bitshadow ------------------------------------------------------------------------ bitshadow's Profile: http://lampforums.org/member.php?userid=14 View this thread: http://lampforums.org/showthread.php?t=94358 From noamr at remove.the.dot.myrea.lbox.com Sat Dec 25 17:57:56 2004 From: noamr at remove.the.dot.myrea.lbox.com (Noam Raphael) Date: Sun, 26 Dec 2004 00:57:56 +0200 Subject: How about "pure virtual methods"? In-Reply-To: <1gp9wjb.18uqvfi1ibk5wxN%aleaxit@yahoo.com> References: <10shetjeo2cbpfa@corp.supernews.com> <1gp9wjb.18uqvfi1ibk5wxN%aleaxit@yahoo.com> Message-ID: Thank you very much for this answer! I learned from you about unit tests, and you convinced me that "testing oriented programming" is a great way to program. You made me understand that indeed, proper unit testing solves my practical problem - how to make sure that all the methods which should be implemented were implemented. However, I'm still convinced that this feature should be added to Python, for what may be called "aesthetic reasons" - I came to think that it fills a gap in Python's "logic", and is not really an additional, optional feature. And, of course, there are practical advantages to adding it. The reason why this feature is missing, is that Python supports building a class hierarchy. And, even in this dynamically-typed language, the fact that B is a subclass of A means that B is supposed to implement the interface of A. If you want to arrange in a class hierarchy a set of classes, which all implement the same interface but don't have a common concrete class, you reach the concept of an "abstract class", which can't be instantiated. And the basestring class is exactly that. The current Python doesn't really support this concept. You can write in the __new__ of such a class something like "if cls == MyAbstractClass: raise TypeError", but I consider this as a patch - for example, if you have a subclass of this class which is abstract too, you'll have to write this exception code again. Before introducing another problem, let me quote Alex: > ... If you WANT the method in the ABC, for documentation > purposes, well then, that's not duplication of code, it's documentation, > which IS fine (just like it's quite OK to have some of the same info in > a Tutorial document, in a Reference one, AND in a class's docstring!). > > If you don't want to have the duplication your unit tests become easier: > you just getattr from the class (don't even have to bother instantiating > it, ain't it great!), and check the result with inspect. That's actually right - listing a method which should be implemented by subclasses, in the class definition is mainly a matter of *documentation*. I like the idea that good documentation can be derived from my documented code automatically, and even if I provide an external documentation, the idea that the code should explain itself is a good one. The problem is, that the current convention is not a good documentation: def frambozzle(self): ''' must make the instance frambozzled ''' raise NotImplementedError The basic problem is that, if you take this basic structure, it already means another thing: This is a method, which takes no arguments and raises a NotImplementedError. This may mean, by convention, that this method must be implemented by subclasses, but it may also mean that this method *may* be implemented by subclasses. I claim that a declaration that a method must be implemented by subclass is simply not a method, and since Python's "logic" does lead to this kind of thing, it should supply this object (I think it should be the class "abstract"). Two of Python's principles are "explicit is better than implicit", and "there should be (only?) one obvious way to do it". Well, I think that this: @abstract def frambozzle(self): """Must make the instance frambozzled""" pass is better than the previous example, and from def frambozzle(self): raise NotImplementedError, "You must implemented this method, and it must make the instance frambozzled" and from def frambozzle(self): """Must make the instance frambozzled. PURE VIRTUAL """ pass and from maybe other possible conventions. Note also that making this explicit will help you write your tests, even if Python would allow instantiation of classes which contain abstract methods - you will be able to simple test "assert not isinstance(MyClass.frambozzle, abstract)". (I don't like the solution of not mentioning the method at all, which makes the test equally simple, because it doesn't document what the method should do in the class definition, and I do like in-code documentation.) To summarize, I think that this feature should be added to Python because currently, there's no proper way to write some code which fits the "Python way". As a bonus, it will help you find errors even when your unit tests are not sufficient. I plan to raise this issue in python-dev. If you have any additional comments, please post them here. (I will probably be able to reply only by the weekend.) Have a good day, Noam From elbertlev at hotmail.com Thu Dec 2 04:27:58 2004 From: elbertlev at hotmail.com (elbertlev at hotmail.com) Date: 2 Dec 2004 01:27:58 -0800 Subject: M2Crypto for 2.4 In-Reply-To: References: <9418be08.0412011228.6ac054f4@posting.google.com> Message-ID: <1101979678.963285.97160@z14g2000cwz.googlegroups.com> //I will do it in the next day or two. Me too! Remember, this is a programmer and a manager telling you his plan. :) But, if I do not, nobody in my department will :( From kdahlhaus at yahoo.com Thu Dec 16 15:44:41 2004 From: kdahlhaus at yahoo.com (kdahlhaus at yahoo.com) Date: 16 Dec 2004 12:44:41 -0800 Subject: Python mascot proposal In-Reply-To: References: Message-ID: <1103229881.737860.19950@f14g2000cwb.googlegroups.com> > http://exogen.cwru.edu/python2.png Wow, that's sharp! From chris.lasher at gmail.com Fri Dec 3 12:05:15 2004 From: chris.lasher at gmail.com (Chris Lasher) Date: 3 Dec 2004 09:05:15 -0800 Subject: Difficulties POSTing to RDP Hierarchy Browse Page Message-ID: <128a885f.0412030905.85d08cc@posting.google.com> Hello, I'm trying to write a tool to scrape through some of the Ribosomal Database Project II's (http://rdp.cme.msu.edu/) pages, specifically, through the Hierarchy Browser. (http://rdp.cme.msu.edu/hierarchy/) The Hierarchy Browser is accessed first through a page with a form. There are four fields with several options to be chosen from (Strain, Source, Size, and Taxonomy) and then a submit button labeled "Browse". The HTML of the form is as follows (note, I am also including the Javascript code, as it is called by the submit button): --------excerpted HTML----------------

Hierarchy Browser - Start

 

Strain:    
Source:
Size:
Taxonomy: