May June PSF Board meeting minutes available
Minutes of Regular Meetings of the Board of Directors of the Python Software Foundation, * May 12, 2008: http://www.python.org/psf/records/board/minutes/2008-05-12 * June 16, 2008: http://www.python.org/psf/records/board/minutes/2008-06-16 David Goodger, PSF Secretary -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
ANN: Urwid 0.9.8.3 - Console UI Library
Announcing Urwid 0.9.8.3 Urwid home page: http://excess.org/urwid/ Tarball: http://excess.org/urwid/urwid-0.9.8.3.tar.gz RSS: http://excess.org/feeds/tag/urwid/ About this release: === This is a maintenance release that fixes a memory leak and a canvas bug affecting Urwid 0.9.8, 0.9.8.1 and 0.9.8.2. New in this release: * Fixed a canvas cache memory leak affecting 0.9.8, 0.9.8.1 and 0.9.8.2 (found by John Goodfellow) * Fixed a canvas fill_attr() bug (found by Joern Koerner) About Urwid === Urwid is a console UI library for Python. It features fluid interface resizing, UTF-8 support, multiple text layouts, simple attribute markup, powerful scrolling list boxes and flexible interface design. Urwid is released under the GNU LGPL. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
[ANN} Daily pyogp coders meeting (PYthon Open Grid Protocols for virtual worlds)
pyogp is a Python-based virtual worlds test harness and client library being developed by Linden Lab, makers of Second Life, and members of the SL Architecture Working Group, in order to test the Open Grid Protocols that were used in the recent proof of concept demo by IBM and Linden Lab, that allowed avatars to teleport from one virtual world (Second Life) to another (Open Simulator) using standardized interoperability protocols. http://www.informationweek.com/news/personal_tech/virtualworlds/showArticle.jhtml?articleID=208803274 A daily meeting within Second LIfe has been setup for pyogp coders and designers to meet, as described in the announcement below. This is the transcript of the first meeting: http://wiki.secondlife.com/wiki/Pyogp/Chat_Logs/Daily_Meeting/14_jul_2008 The pyogp meetings are open to any resident of Second Life, and anyone with a desire to contribute to the process (especially coding) is certainly welcome. In World Meetings We're going to start having daily meetings at infinity is full of stars in the Levenhall simulator in Second Life at 9:30AM SLT (Pacific Coast Time) each day. These meetings are for the PyOGP coders to meet and discuss design, process and status. In the near term, these are likely to be somewhat beefy meetings where design issues are discussed and differences hammered out. In the longer term, these will hopefully be more Agile Stand-Up style meetings where we discuss: a. what we've done in the last 24 hours, b. what we're going to do in the next 24 and c. what we're blocked on. what PyOGP Coders Meeting who PyOGP l33t C0d3rZ whereinfinity is full of stars @ http://slurl.com/secondlife/Levenhall/91/208/22 when 9:30AM SLT / 12:30PM Eastern Time / 5:30PM GMT / 6:30PM Central European Time why for PyOGP contributors to hash out architecture, design, test and deploy issues IRC: irc://irc.freenode.com/#pyogp Mailing list: https://lists.secondlife.com/cgi-bin/mailman/listinfo/pyogp wiki: http://wiki.secondlife.com/wiki/Pyogp -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Jython 2.5 Alpha Released!
On behalf of the Jython development team, I'm pleased to announce that Jython 2.5a0+ is available here http://downloads.sourceforge.net/jython/jython_installer-2.5a0.jar for download. See http://jython.org/Project/installation.html for installation instructions. This is the first alpha release of Jython 2.5 and contains many new features. In fact, because we have skipped 2.3 and 2.4, there are too many to even summarize. A few of the features are: * generator expressions * with statement * exceptions as new-style classes * unicode support more in line with CPython * decorators Under the hood Jython 2.5 has a new parser based on ANTLR 3.1 and the compiler has been refactored to use ASM. There are so many more changes that I have missed more than I have listed. This is an alpha release, so there are known and unknown bugs, so be careful. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
[pygtk] ANNOUNCE: PyGObject 2.15.1
I am pleased to announce version 2.15.1 of the Python bindings for GObject. The new release is available from ftp.gnome.org as and its mirrors as soon as its synced correctly: http://download.gnome.org/sources/pygobject/2.15/ There are two new significant features in this release series, initial bindings for GIO. Note that these are not complete, please report missing API in Bugzilla so we know what people are missing. Codegen has been moved from PyGTK and can now be used without depending on GTK+, which should be useful for GObject based libraries. What's new since PyGObject 2.15.1? - Rename pygtk-codegen-2.0 to pygobject-codegen-2.0 to avoid conflicting with PyGTK (Paul Pogonyshev) Blurb: GObject is a object system library used by GTK+ and GStreamer. PyGObject provides a convenient wrapper for the GObject+ library for use in Python programs, and takes care of many of the boring details such as managing memory and type casting. When combined with PyGTK, PyORBit and gnome-python, it can be used to write full featured Gnome applications. Like the GObject library itself PyGObject is licensed under the GNU LGPL, so is suitable for use in both free software and proprietary applications. It is already in use in many applications ranging from small single purpose scripts up to large full featured applications. PyGObject requires glib = 2.8.0 and Python = 2.3.5 to build. GIO bindings require glib = 2.16.0. -- Johan Dahlin [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
[ANN] netaddr for Python
This is a post to announce the creation of a brand new library for Python called NetAddr. It is a network address manipulation library released under the BSD license. It supports several of the most common address formats (IPv4, IPv6 and MAC and IEEE EUI) as well as several aggregate notations such as CIDR. An effort has been made to provide an API that is as Pythonic as possible. NetAddr is now in beta (latest release is 0.3.1) and is currently being actively developed. Developers and testers are needed to assist in improving the quality and availability of network library support for Python which is distinctly lacking when compared with other popular interpreted languages such as Ruby and Perl. NetAddr is an attempt to redress this imbalance to some extent. Home page: http://netaddr.googlecode.com/ Features include :- - Flexible support for the representation of multiple address types using the a common set of network address classes - Address objects emulate standard Python types dependent on context. They behave as strings, integers, lists, compare and sort numerically, etc - Efficient representation of large address spaces via several aggregate types. Also supports arbitrary network address ranges that don't necessarily fall on strict bit boundaries - Generators are used throughout for efficient iteration, indexing and slicing of network address spaces and ranges - Testing on both big and little endian architectures has carried out throughout the initial development of this library - A lot more features are planned over coming releases Requirements :- - Python 2.3 or higher (doesn't support Python 3.0 ... yet) For more information, downloads and examples, please visit :- http://netaddr.googlecode.com/ Share and enjoy, David Moss -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Simplify Code
header_sizes = (36, 26, 22, 18, 14, 12) if x not in header_sizes: raise Exception() else: h36, h26, h22, h18, h14, h12 = tuple( line if x == size else '' for x in header_sizes) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to figure out if the platform is 32bit or 64bit?
I need to know if I'm running on 32bit or 64bit ... so far I haven't come up with how to get this info via python. sys.platform returns what python was built on ... but not what the current system is. I thought platform.uname() or just platform.processor() would have done it, but python returns an empty string on windows. Any ideas? import sys hex(sys.maxint) '0x7fff' I don't think that will satisfy the OP. Apparently, he wants to find out that the system is running on 64bit even when the interpreter is a 32-bit build executable (what python was built on). I don't think Python supports querying that information in general (i.e. is the microprocessor supporting a 64-bit address space, even if the current process, and perhaps the current operating system only uses a 32-bit address space?) It is possible to answer that question with Python in a platform-specific manner, but the answer is more difficult than a single yes/no: - is the processor capable of executing 64-bit code? - is the operating system kernel operating the processor in 64-bit mode? - does the operating system support 64-bit user-space applications? (in some OSX and Solaris releases, the answer to this question was no, even though the answer to the previous question was yes, IIRC) - does the Python binary support 64-bit mode? - is the Python binary running in 64-bit mode? (again, this may vary from the previous question, in case of fat (universal) binaries) Whether any of these questions are of interest, and which of them the OP wanted to ask, I don't know. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Redirecting stdout to another script
Hopefully, this explanation will sufficiently clear despite the lack of code. I wrote a python script that takes data via stdin, does stuff with the data, and outputs the result to stdout. A friend wrote a perl script that opens a pipe to my script, feeds it data, and then accepts the result. The problem here is that the python script's outputting the result to stdout via print statements isn't doing what we expected: my friend's perl script isn't getting the result back via the pipe. Is there is simple solution for this problem? Whose script needs to be modified? Thanks, Richard Simões -- http://mail.python.org/mailman/listinfo/python-list
Re: new itertools functions in Python 2.6
On Jul 15, 1:44 am, Raymond Hettinger [EMAIL PROTECTED] wrote: On Jul 14, 1:26 pm, Mensanator [EMAIL PROTECTED] wrote: ## Combinations with replacement ## - ## aaa aab aac aad aae abb abc abd abe acc acd ace ## add ade aee bbb bbc bbd bbe bcc bcd bce bdd bde ## bee ccc ccd cce cdd cde cee ddd dde dee eee ## ## actual words: 35(m+n-1)!/(n!(m-1)!) words: 35 Although it works, it's somewhat slow as we have to iterate over the entire Cartesian Product and the filter list(x)==sorted(x) has got to be expensive (it's slower than the nested loop algorithm). Is there a better way to get Combinations With Replacement using itertools? There may a technique to start with the combinations without replacement and then grow the result by repeating elements: Great idea, I had only considered making a sub=set. It never occured to me to try and make a super=set. Thanks for the suggestions, they've given me some ideas to try. result = set(combinations('abcde', 3)) # transform 'ab ac ad ae bc bd be cd ce de' into 'aab abb aac acc ...' for c in combinations('abcde', 2): # transform 'ab' -- 'aab abb' for i in range(2): result.add(c[:i] + c[i]*1 + c[i:]) for c in combinations('abcde', 1): for i in range(1): # 'a' -- 'aaa' result.add(c[:i] + c[i]*2 + c[i:]) If you generalize the above, it may solve the problem using itertools as a starting point. Alternatively, it's not too hard to transform the pure python version given in the docs to one that supports combinations with replacement: I was trying to avoid that kind of solution. ifilter(product()) is exactly the kind of thing I'm looking for, just wondering if there's a better way, using a different combination of functions. def combinations_with_replacement(iterable, r): pool = tuple(iterable) n = len(pool) indices = [0] * r yield tuple(pool[i] for i in indices) while 1: for i in reversed(range(r)): if indices[i] != n - 1: break else: return indices[i] += 1 for j in range(i+1, r): indices[j] = indices[j-1] yield tuple(pool[i] for i in indices) Raymond -- http://mail.python.org/mailman/listinfo/python-list
Re: Moving to functional programming
Ben Finney wrote: Paul Rubin http://[EMAIL PROTECTED] writes: I don't like square-bracket listcomps because they leak the index variables to the outside. According to PEP 289 URL:http://www.python.org/dev/peps/pep-0289, this is an acknowledged wart that will be fixed in Python 3.0. Has been. IDLE 3.0b1 a=[i for i in range(5)] i Traceback (most recent call last): File pyshell#1, line 1, in module i NameError: name 'i' is not defined -- http://mail.python.org/mailman/listinfo/python-list
Re: Python internals
Ben Finney wrote: Larry Bates [EMAIL PROTECTED] writes: The term pointer carries much extra baggage for a programmer thinking of C (as the original poster is)... Thanks everyone! Just a quick correction - as the original poster is is a bit of a jump that does not reflect my original question. I DO understand how C and other programming languages handle variables internally (the bits of actual memory reserved, etc. etc.) and that's why I asked the question in the first place. If Python doesn't do it like C and the others then what mechanism does it use - it's the sort of issue that helps me understand how the language is interacting with the underlying operating system/hardware. By way of background, in my ancient working days I looked after mainframe systems written in COBOL and Natural (and some assembler which I never had to support personally but my staff did). I found that most programmers write bad code because they don't understand what the machine is doing with their code. Probably doesn't matter any more but old habits die hard! ;-) Regards, Peter -- Peter Anderson There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things -- Niccolo Machiavelli, The Prince, ch. 6 -- http://mail.python.org/mailman/listinfo/python-list
Re: Python internals question
Helmut Jarausch wrote: Please have a look at ... http://rg03.wordpress.com/2007/04/21/semantics-of-python-variable-names-from-a-c-perspective/ Helmut, I found the second reference (the one above) very useful thank you. Most other respondents to my original question did not seem to understand what I was asking or didn't read the question and simply proceeded to re-state what I had quoted from Beazley - well I understood what he was saying, I simply wanted to find out how Python did it at a lower level. Your reference answered the question ;-) Thanks, Peter -- Peter Anderson There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things -- Niccolo Machiavelli, The Prince, ch. 6 -- http://mail.python.org/mailman/listinfo/python-list
Re: reading one byte from stdin
Mark McDuff schrieb: I'm trying to read one byte from stdin, without the newline. If I try something like: import os, sys os.read(sys.stdin.fileno(),1) I can input a character, but then I have to press enter, which leaves a newline character in the stdin buffer and requires two keypresses. Is there any way to read only one keypress in a simple manner (i.e. no curses)? Depending on your OS, yes. Under *nix, you need to set the terminal to RAW-mode. This recipe claims to be OS-agnostinc: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892 Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Redirecting stdout to another script
Richard Simões schrieb: Hopefully, this explanation will sufficiently clear despite the lack of code. I wrote a python script that takes data via stdin, does stuff with the data, and outputs the result to stdout. A friend wrote a perl script that opens a pipe to my script, feeds it data, and then accepts the result. The problem here is that the python script's outputting the result to stdout via print statements isn't doing what we expected: my friend's perl script isn't getting the result back via the pipe. Is there is simple solution for this problem? Whose script needs to be modified? That of your friend, if he is the one invoking you. Because the invoking script is the one responsible for connecting the pipes properly. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Is re.findall guaranteed to be in order?
Joshua Kugler wrote: Experimenting has shown me that re.findall() will return a list with the matches in the order it found them. in the order it found them doesn't really say much, does it? ;-) findall and finditer both scans the string from left to right, and will return matches in that order. (the documentation is a bit vague, so if you have the time, please add a request for clarification to the bug tracker) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: About wmi
patrol wrote: http://timgolden.me.uk/wmi-project/wmi.py It cannot work either. Oh well. It was only a quick fix! I'll try to get some kind of non-ASCII edition of Windows to test against. As I understand it, the situation is that some WMI exception (ie coming from the underlying WMI/COM subsystem) results in an error message which contains non-ASCII characters. Just so I'm not chasing red herrings, could you paste the output from the following code, please? code import wmi # use the version linked above c = wmi.WMI (non-existent computer) # # Should give a traceback here for the DCOM # error, not a UnicodeDecodeError. # /code Thanks TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Python internals
Peter Anderson [EMAIL PROTECTED] writes: If Python doesn't do it like C and the others then what mechanism does it use You've already been pointed to it, but here it is again: URL:http://effbot.org/zone/python-objects.htm -- \ “I may disagree with what you say, but I will defend to the | `\death your right to mis-attribute this quote to Voltaire.” | _o__) —Avram Grumer, rec.arts.sf.written, May 2000 | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Is this correct behavior for default parameters?
Bruce Pearson wrote: The first call to test has the file_list empty but on the second call to test the file_list is no longer empty but contains the values appended in the first call. Is this correct behavior? I'm using python 2.5 yes: http://docs.python.org/ref/function.html Default parameter values are evaluated when the function definition is executed. (in bold, even) it's also explained in the tutorial (section 4.7.1) and in the FAQ. (it's always a good idea to double-check the documentation or google a little before convincing yourself that you may have found a bug in a commonly used part of a system that's over 15 years old and has been used by hundred of thousands of programmers). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there any library that can extract titles from PDFs?
ZelluX wrote: I want to write a script which will rename PDFs according to their titles. I want to know if there is any library that can extract titles(the first line of the PDF) from PDFs. Mathieu Fenniak's PyPdf should be able to do this: http://pybrary.net/pyPdf/ (but note that the first line of the PDF may not be the first thing that's rendered on the page, so don't expect such an approach to work for all files) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: bad recursion, still works
On Jul 16, 2:21 am, Michael Torrie [EMAIL PROTECTED] wrote: iu2 wrote: I still don't understand: In each recursive call to flatten, acc should be bound to a new [], shouldn't it? Why does the binding happen only on the first call to flatten? Nope. In each new call it's (re)bound to the same original list, which you've added to as your function continues--it's mutable. Default variables that are bound to mutable objects are one of the big caveats that is mentioned in the FAQ. Thanks guys, it's clear now -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging to different addressees
Hi Vinay, thank you for being so patient. On 16 Jul., 01:21, Vinay Sajip [EMAIL PROTECTED] wrote: On Jul 15, 5:17 pm, McA [EMAIL PROTECTED] wrote: If you added the admin sink handler to the root logger, you're done. Isn't that the first thing above? What do you mean? I gave you a choice - to add the handler to the admin_logger OR the root logger. So I am saying here that if you added to the root logger (and not common_logger, assuming they're different), then there's nothing more to do... Reading the rest of your mail let me understand what you meant. # simple.py import logging admin_logger = logging.getLogger() # The root logger addressee_logger = logging.getLogger(addressee) admin_sink = logging.FileHandler(admin.log, w) addressee_sink = logging.FileHandler(addressee.log, w) admin_logger.addHandler(admin_sink) addressee_logger.addHandler(addressee_sink) admin_logger.setLevel(logging.DEBUG) admin_logger.debug(This message appears in admin sink only.) addressee_logger.debug(This message appears in both admin sink and addressee sink. Thank you for that snippet. That means, that the root-logger does inherit EVERY message (if it fits to the level and isn't filtered) and the inheritage chain is build by the chosen logger names, e.g. messages to logging.getLogger('tree.leave') would also show up in logging.getLogger('tree') automatically? If this is true, how can I avoid this bubbling up if I would like to? (You see, that's a new question, but I want to take the chance to get the answers from you personally ;-) Hope not to bother. Best regards Andreas Mock -- http://mail.python.org/mailman/listinfo/python-list
Re: snippet to update local (bazaar, mercurial, svn) versioned source
On Jul 16, 8:34 am, Alia Khouri [EMAIL PROTECTED] wrote: Here's a very simple snippet I use to automatically keep my versioned sources fresh.. Posted here in case it may be of use to anybody... code #!/usr/local/bin/python import os, sys src = '/Users/ak/Code/src' # utility functions join, isdir, listdir = os.path.join, os.path.isdir def run(cmd): print cmd os.system(cmd) ops = { '.bzr': ['bzr pull', 'bzr update'], '.hg': ['hg pull', 'hg update'], '.svn': ['svn update'] } for folder in os.listdir(src): target = os.path.join(src,folder) if os.path.isdir(target): internal = os.listdir(target) for f in internal: if f in ops: print os.chdir(target) cmds = ops[f] print print target, '--', for cmd in cmds: run(cmd) /code My bad, here's the one that actually (-: code #!/usr/local/bin/python import os, sys src = '/Users/sa/Code/src' # utility functions join, isdir = os.path.join, os.path.isdir def run(cmd): print cmd os.system(cmd) ops = { '.bzr': ['bzr pull', 'bzr update'], '.hg': ['hg pull', 'hg update'], '.svn': ['svn update'] } for folder in os.listdir(src): target = join(src,folder) if isdir(target): internal = os.listdir(target) for f in internal: if f in ops: print # print f, target os.chdir(target) cmds = ops[f] print print target, '--', for cmd in cmds: run(cmd) /code -- http://mail.python.org/mailman/listinfo/python-list
How can i use a variable without define it ?
How can i use a variable without define it ? I have thought about the __import__ function, but the docs says the __import__() function does not set the local variable named eggs。 -- http://mail.python.org/mailman/listinfo/python-list
Re: Amazon: Practical Django Projects by James Bennett (June 2008)
Dave U. Random [EMAIL PROTECTED] wrote: http://snipr.com/PracticalDjango June 2008 is a bit too early. Django isn't ready. -- Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How can i use a variable without define it ?
zhw [EMAIL PROTECTED] writes: How can i use a variable without define it ? What do you mean by use? That's so vague I can think of many possible interpretations. What do you mean by variable? That term carries a lot of baggage that doesn't apply in Python. Can you give a small, complete example that demonstrates the issue you're trying to solve? -- \ “The face of a child can say it all, especially the mouth part | `\of the face.” —Jack Handey | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: reading one byte from stdin
Mark McDuff wrote: I'm trying to read one byte from stdin, without the newline. If I try something like: import os, sys os.read(sys.stdin.fileno(),1) I can input a character, but then I have to press enter, which leaves a newline character in the stdin buffer and requires two keypresses. Is there any way to read only one keypress in a simple manner (i.e. no curses)? in addition to the cookbook article Diez posted, there's also a FAQ entry about this: http://effbot.org/pyfaq/how-do-i-get-a-single-keypress-at-a-time.htm /F -- http://mail.python.org/mailman/listinfo/python-list
RE: isPrime works but UnBoundLocalError when mapping on list
Terry Reedy wrote: Wrong. Thank you. For loop variables continue after the loop exits. This is intentional. I never knew that and I can't find reference to it in the docs. Can you help me with the reasons for it? Drea -- http://mail.python.org/mailman/listinfo/python-list
Re: Amazon: Practical Django Projects by James Bennett (June 2008)
Stefan Scholl wrote: Django isn't ready. That's a remarkably ignorant statement. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: How can i use a variable without define it ?
On 7月16日, 下午4时47分, Ben Finney [EMAIL PROTECTED] wrote: zhw [EMAIL PROTECTED] writes: How can i use a variable without define it ? What do you mean by use? That's so vague I can think of many possible interpretations. What do you mean by variable? That term carries a lot of baggage that doesn't apply in Python. Can you give a small, complete example that demonstrates the issue you're trying to solve? -- \ “The face of a child can say it all, especially the mouth part | `\of the face.” ―Jack Handey | _o__) | Ben Finney Thank you! Sorry for my poor english! Here is a example that I want to complete: import sys, new context={name:david, sex:male} sys.modules[foo] = new.module(foo) import foo for attr in context: setattr(foo, attr, context[attr]) def bar(): # here is a error # import * only allowed at module level from foo import * print name, sex bar() -- http://mail.python.org/mailman/listinfo/python-list
Re: isPrime works but UnBoundLocalError when mapping on list
Andreas Tawn wrote: I never knew that and I can't find reference to it in the docs. the for-in loop does ordinary assignments in the current scope: http://docs.python.org/ref/for.html Each item in turn is assigned to the target list using the standard rules for assignments, and then the suite is executed. somewhat simplified, for vars in expression: code is equivalent to inlining: _ = iter(expression) while 1: try: vars = _.next() except StopIteration: break else: body where _ is an internal variable. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: How can i use a variable without define it ?
zhw [EMAIL PROTECTED] writes: Here is a example that I want to complete: import sys, new context={name:david, sex:male} Here you have a set of values addressible by name. sys.modules[foo] = new.module(foo) Why do you believe you need to create a module object? import foo for attr in context: setattr(foo, attr, context[attr]) This doesn't appear to get you anything that isn't already available with the 'context' mapping. def bar(): # here is a error # import * only allowed at module level from foo import * print name, sex You can simply do: context = {'name': david, 'sex': male} def bar(): ... print context['name'], context['sex'] ... bar() david male Or, more flexible and more explicit: foo = {'name': david, 'sex': male} def bar(context): ... print context['name'], context['sex'] ... bar(foo) david male What problem are you trying to solve? -- \ “The best mind-altering drug is truth.” —Jane Wagner, via Lily | `\Tomlin | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: How can i use a variable without define it ?
On 7月16日, 下午5时35分, Ben Finney [EMAIL PROTECTED] wrote: zhw [EMAIL PROTECTED] writes: Here is a example that I want to complete: import sys, new context={name:david, sex:male} Here you have a set of values addressible by name. sys.modules[foo] = new.module(foo) Why do you believe you need to create a module object? import foo for attr in context: setattr(foo, attr, context[attr]) This doesn't appear to get you anything that isn't already available with the 'context' mapping. def bar(): # here is a error # import * only allowed at module level from foo import * print name, sex You can simply do: context = {'name': david, 'sex': male} def bar(): ... print context['name'], context['sex'] ... bar() david male Or, more flexible and more explicit: foo = {'name': david, 'sex': male} def bar(context): ... print context['name'], context['sex'] ... bar(foo) david male What problem are you trying to solve? I an sorry, I can't tell you. If you can't give a solution, just ignore it! -- http://mail.python.org/mailman/listinfo/python-list
Re: new itertools functions in Python 2.6
On Jul 16, 7:20 am, Mensanator [EMAIL PROTECTED] wrote: ## Combinations with replacement ## - ## aaa aab aac aad aae abb abc abd abe acc acd ace ## add ade aee bbb bbc bbd bbe bcc bcd bce bdd bde ## bee ccc ccd cce cdd cde cee ddd dde dee eee ## ## actual words: 35 (m+n-1)!/(n!(m-1)!) words: 35 for x in combinations(range(7), 4): ... x = [-1] + list(x) + [7] ... print ''.join(c*(x[i+1]-x[i]-1) for i, c in enumerate('abcde')) ... eee dee dde ddd cee cde cdd cce ccd ccc bee bde bdd bce bcd bcc bbe bbd bbc bbb aee ade add ace acd acc abe abd abc abb aae aad aac aab aaa Generalization left as an exercise for the reader. Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: How can i use a variable without define it ?
Hello. 2008/7/16 zhw [EMAIL PROTECTED]: On 7月16日, 下午5时35分, Ben Finney [EMAIL PROTECTED] wrote: zhw [EMAIL PROTECTED] writes: Here is a example that I want to complete: import sys, new context={name:david, sex:male} Here you have a set of values addressible by name. sys.modules[foo] = new.module(foo) Why do you believe you need to create a module object? import foo for attr in context: setattr(foo, attr, context[attr]) Forgetting these considerations (I agree with Ben, though), your error is trying to use an 'import *' inside a function. You should take it outside the function, and try to run it again. def bar(): # here is a error # import * only allowed at module level from foo import * print name, sex There are different import statements you can use in Python. I recommend you to take a look at the tutorial to learn about the differences between them: http://docs.python.org/tut/node8.html Good luck. -- http://mail.python.org/mailman/listinfo/python-list
Re: Modify a string's value
On Jul 15, 11:55 pm, Ben Finney [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] writes: I just came across this unusual situation where I'd like to modify a string passed to a function Again: Why? The normal way to do this is to create a new string and return that. snip Yes, usually, but that won't work in this case (look at my previous post around the 'cin line' line). This is what I came up with: class StreamLineBuffer: def __init__(self): self.buf = def __rrshift__(self, stream): self.buf = stream.readline() def __str__(self): return self.buf cin = sys.stdin buf = StreamLineBuffer() cin buf line = str(buf) Works like a charm :) -- http://mail.python.org/mailman/listinfo/python-list
Re: isPrime works but UnBoundLocalError when mapping on list
Andreas Tawn wrote: Terry Reedy wrote: Wrong. Thank you. For loop variables continue after the loop exits. This is intentional. I never knew that and I can't find reference to it in the docs. Interesting starting point. It never occurred to me that they might not. (So I didn't look for anything in the docs when they did :) ). TJG -- http://mail.python.org/mailman/listinfo/python-list
Get current class namespace.
Guys, What's the simplest way to access a classes namespace from within itself. I want to use it in a custom __repr__() method so it prints the current namespace for the class like package.module.class. Suggestions? I'm sure there is a simple enough method built in to help me here, I've just not seen it before. Cheers, Robert -- http://mail.python.org/mailman/listinfo/python-list
Re: bad recursion, still works
On Jul 15, 7:21 pm, Michael Torrie [EMAIL PROTECTED] wrote: iu2 wrote: I still don't understand: In each recursive call to flatten, acc should be bound to a new [], shouldn't it? Why does the binding happen only on the first call to flatten? Nope. In each new call it's (re)bound to the same original list, which you've added to as your function continues--it's mutable. Default variables that are bound to mutable objects are one of the big caveats that is mentioned in the FAQ. Is this avoidable by using a call to list() in the definition instead? -- http://mail.python.org/mailman/listinfo/python-list
Re: How can i use a variable without define it ?
zhw [EMAIL PROTECTED] writes: On 7月16日, 下午5时35分, Ben Finney [EMAIL PROTECTED] wrote: What problem are you trying to solve? I an sorry, I can't tell you. Perhaps I'm not being clear: What *programming* problem are you trying to solve? I ask because it seems you are focussed to much on some specific method, when it is very likely that your problem is better solved using different methods. If you can't give a solution, just ignore it! I *did* give a solution. If that doesn't work for you, please tell us more about the problem so we can provide better solutions. -- \ “Say what you will about the Ten Commandments, you must always | `\ come back to the pleasant fact that there are only ten of | _o__) them.” —Henry L. Mencken | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
RE: isPrime works but UnBoundLocalError when mapping on list
Andreas Tawn wrote: Terry Reedy wrote: Wrong. Thank you. For loop variables continue after the loop exits. This is intentional. I never knew that and I can't find reference to it in the docs. Interesting starting point. It never occurred to me that they might not. (So I didn't look for anything in the docs when they did :) ). TJG I don't have experience of too many other languages, but in C++ (and I guess C)... for (int i=0; i10; ++i) { doStuff(i); } doStuff(i); // Error int i; for (i=0; i10;++i) { doStuff(i); } doStuff(i); // No error That's the behaviour I was expecting. Is the Python behaviour just a happy side effect of the target list assignment or specific design decision? Cheers, Drea -- http://mail.python.org/mailman/listinfo/python-list
Re: About wmi
On 7月16日, 下午3时29分, Tim Golden [EMAIL PROTECTED] wrote: patrol wrote: http://timgolden.me.uk/wmi-project/wmi.py It cannot work either. Oh well. It was only a quick fix! I'll try to get some kind of non-ASCII edition of Windows to test against. As I understand it, the situation is that some WMI exception (ie coming from the underlying WMI/COM subsystem) results in an error message which contains non-ASCII characters. Just so I'm not chasing red herrings, could you paste the output from the following code, please? code import wmi # use the version linked above c = wmi.WMI (non-existent computer) # # Should give a traceback here for the DCOM # error, not a UnicodeDecodeError. # /code Thanks TJG The errors are in the following: Traceback (most recent call last): File D:\My Documents\code\python\wmi\test.py, line 5, in module c = wmi.WMI (non-existent computer) File C:\Python25\lib\wmi.py, line 1199, in connect handle_com_error (error_info) File C:\Python25\lib\wmi.py, line 184, in handle_com_error exception_string = [u%s - %s % (hex (hresult_code), hresult_name)] UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 4: ordinal not in range(128) Patrol -- http://mail.python.org/mailman/listinfo/python-list
Re: Python internals
Peter Anderson wrote: Thanks everyone! Just a quick correction - as the original poster is is a bit of a jump that does not reflect my original question. I DO understand how C and other programming languages handle variables internally (the bits of actual memory reserved, etc. etc.) and that's why I asked the question in the first place. If Python doesn't do it like C and the others then what mechanism does it use - it's the sort of issue that helps me understand how the language is interacting with the underlying operating system/hardware. The easiest way to think of this is that Python uses mostly dictionaries dictionaries for namespaces, and a few places it uses other techniques if there are over-riding considerations that make the dictionaries impractical in particular cases. Python performance would be crippled if their dictionary implementation(s) slowed down, much as C performance would suffer is access to RAM slowed down. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Why is this blowing the stack, thought it was tail-recursive...
On Jul 13, 8:44 pm, Fuzzyman [EMAIL PROTECTED] wrote: On Jul 13, 7:56 am, Steven D'Aprano [EMAIL PROTECTED] cybersource.com.au wrote: On Sat, 12 Jul 2008 19:25:18 -0400, Terry Reedy wrote: ssecorp wrote: def fib(n): def fibt(a, b, n): if n = 1: return b else: return fibt(b, a + b, n - 1) if n == 0: return 0 else: return fibt(0, 1, n); and can memoization speed up this even more? tesintg with memoization doesnt really say anything because it is so fast it is instant anyway. Except for the fact that a+b gets slower as a and b get bigger, this would already be linear time in n. Memoization (here by means of a linear list) only helps if the list is preserved and one makes repeated requests for various fib values. I am just curious what input you tried that blew the stack? It had to be pretty large. No, not really. Try it for yourself: on my system, I get RuntimeError: maximum recursion depth exceeded with fib(999). fib(999) is a large number, with 208 digits, but not that large: 268638100244853593861467272021429239676166093189869523401 231759976179817002478816893383696544833565641918278561614 433563129766736422103503246348504103776803673341511728991 69723197082763985615764450078474174626L -- Steven The default CPython recursion limit is 1000 - so hitting it with an input of 999 is not that surprising... You can set a higher limit with sys.setrecursionlimit(...) Though that would be a kludge, not a fix. Using iteration or generator expression is better. -- http://mail.python.org/mailman/listinfo/python-list
Re: Need Python Programmer (preferentially in Los Angeles)
robnhood00 wrote: I need a python programmer that can integrate graphics into an existing python application. The application is a basic application and the job should be pretty easy for an experienced Python programmer. Los Angeles programmer is preferred but this can obviously be done from anywhere. Please contact me at [EMAIL PROTECTED] is you can help me. Thank you. I get worried when I hear people tell me that a job they don't know how to do should be pretty easy, but at least it is better than should only take a week. What I'd rather hear is, seems like it is a simple job. Beware of customers who know something will take little effort without being able to characterize that effort. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: isPrime works but UnBoundLocalError when mapping on list
Andreas Tawn wrote: I don't have experience of too many other languages, but in C++ (and I guess C)... That's invalid C (you cannot declare variables in the for statement itself, at least not in C89). And back in the old days, some C++ compilers did in fact leak declarations from for loops, and others didn't... Is the Python behaviour just a happy side effect of the target list assignment or specific design decision? I'd say it all follows from the fact that Python doesn't have variable declarations; if you want to stick to the principle that variables can introduced simply by assigning to them, you cannot introduce new blocks nilly-willy. So none of the basic structural elements do that; variables introduced inside an if statement or a for-in statement are no different from variables introduced outside them. And intro- ducing a new block only for the loop variables would be confusing and rather impractical, given how fundamental looping over sequences and iterables are in Python. (the discussions about loop variables in list comprehensions and generator expressions are a bit different; they're expressions, not statements, and shouldn't really do assignments as a side effect, any more than function calls should leak parameter names into the calling scope...) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: bad recursion, still works
Jeff wrote: Is this avoidable by using a call to list() in the definition instead? No. Default values are *always* evaluated when, and only when, the def statement is executed; see: http://docs.python.org/ref/function.html Also note that def is an executable statement in Python, and that default arguments are evaluated in the def statement's environment. If you execute def multiple times, it'll create a new function object (with freshly calculated default values) each time. ::: The workaround is, as others have mentioned, to use a placeholder value instead of modifying the default value. None is a common value: def myfunc(value=None): if value is None: value = default() # go on an modify value If you need to handle arbitrary objects (including None), you can use a sentinel object: sentinel = object() def myfunc(value=sentinel): if value is sentinel: value = default() (in older code, written before object was introduced, you sometimes see things like sentinel = ['placeholder'] used to create a non-false object with a unique identity; [] creates a new list every time it is evaluated.) ::: Finally, it should be noted that more advanced Python code often uses this mechanism to its advantage; for example, if you create a bunch of UI buttons in a loop, you might try something like: for i in range(10): def callback(): print clicked button, i UI.Button(button %s % i, callback) only to find that all callbacks print the same value (most likely 9, in this case). The reason for this is that Python's nested scopes bind to variables, not object values, so all callback instances will see the current (=last) value of the i variable. To fix this, use explicit binding: for i in range(10): def callback(i=i): print clicked button, i UI.Button(button %s % i, callback) The i=i part binds a local variable i to the *current* value of the outer variable i. Two other uses are local caches/memoization; e.g. def calculate(a, b, c, memo={}): try: value = memo[a, b, c] # return already calculated value except KeyError: value = do calculation on a, b, c memo[a, b, c] = value # update the memo dictionary return value (this is especially nice for certain kinds of recursive algorithms) and, for highly optimized code, local rebinding of global names: def this_one_must_be_fast(x, sin=math.sin, cos=math.cos): ... Hope this helps more than it confuses. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: How to figure out if the platform is 32bit or 64bit?
Thanks .. but I want to find out if the system is running on 64bit even when the interpreter is a 32-bit build executable (what python was built on). platform.architecture() and platform() in general seems to only be looking at the build executable and what it was built for on windows (sorry, I don't have a unix box available at the moment). platform.architecture() returns 32bit when on a windows 64bit box. Another recommendation was: import sys hex(sys.maxint) x = sys.maxint n = 1 while x: n += 1 x = 1 print n Unfortunately this too appears to be looking at the build executable ... on Windows 64 it returns '32'. Thanks for the suggestions, hopefully we'll come up with a winner. Ken On Tue, Jul 15, 2008 at 1:39 PM, Benjamin Kaplan [EMAIL PROTECTED] wrote: On Tue, Jul 15, 2008 at 4:10 PM, [EMAIL PROTECTED] wrote: I need to know if I'm running on 32bit or 64bit ... so far I haven't come up with how to get this info via python. sys.platform returns what python was built on ... but not what the current system is. I thought platform.uname() or just platform.processor() would have done it, but python returns an empty string on windows. Any ideas? Thanks, Ken -- platform.architecture() should have it. -- http://mail.python.org/mailman/listinfo/python-list
Securing mobile Python code
Hi guys and girls. I am currently developing an execution environment for mobile Python code. To that end I have developed a system called Scavenger based on Stackless Python. The biggest problem when working with mobile code is of course security - especially when working with a language such as Python that has no security modes. I have therefore used a validation/blacklisting approach towards code security, i.e., before the mobile code is executed it is validated and if it uses illegal operations it is rejected (apart from that I have also monkey-patched some functionality so that my own versions of built-in functions are invoked). Using such a blacklist approach is of course problematic because one has to know about every possible way to circumvent the system to be sure of its validity... This is where you come in: To test the security of my system I have placed a Scavenger host on the Internet that will perform any Python code you throw at it. I would like to invite anybody with an interest in Python and security to participate in this Hack-Attack on my Scavenger host :-) For more information see: http://www.daimi.au.dk/~madsk/?cat=15 Thanks for your time! Best regards, Mads Kristensen -- http://mail.python.org/mailman/listinfo/python-list
python's YENC.DECODE - weird output
I save posts from a midi music newsgroup, some are encoded with yenc encoding. This gave me an opportunity to try out the decoders in Python. The UU decoder works okay, but my YENC effort gives results unexpected: import yenc, sys fd1=open(sys.argv[1],'r') #yenc.encode(sys.argv[1],outfile.yenc,bytes=0) yenc.decode(sys.argv[1],outfile.mid,bytes=0,crc_in='') I confirmed that yenc.decode exactly reverses yenc.encode, BUT the encoding itself seems to differ from the USENET standard. That is, when I decode USENET files the result isn't a valid music file. (I did try both with and w/o the headers.) Maybe it uses a different character set? I can't quite put my finger on what might be happening. What I can say is that the yenc coding from the newsgroup article, when viewed with Linux 'more', displays roughly 10% of its characters as a question mark, whereas when I give Python's yenc.encode a binary music file and view its output using 'more', it displays about 90% of the output as a question mark. Any ideas? -- John Savage(my news address is not valid for email) -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging to different addressees
On Jul 16, 8:55 am, McA [EMAIL PROTECTED] wrote: Thank you for that snippet. That means, that the root-logger does inherit EVERY message (if it fits to the level and isn't filtered) and the inheritage chain is build by the chosen logger names, e.g. messages tologging.getLogger('tree.leave') would also show up inlogging.getLogger('tree') automatically? Yes. If this is true, how can I avoid this bubbling up if I would like to? (You see, that's a new question, but I want to take the chance to get the answers from you personally ;-) Hope not to bother. Use the propagate flag, which is mentioned in the documentation. In fact, please make sure you've reviewed all the documentation before posting, as the documentation is intended to answer the more straightforward and common questions which come up. Best regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
Re: How to figure out if the platform is 32bit or 64bit?
Ken Hartling wrote: Thanks .. but I want to find out if the system is running on 64bit even when the interpreter is a 32-bit build executable (what python was built on). platform.architecture() and platform() in general seems to only be looking at the build executable You can pass in an arbitrary binary to architecture(), so I guess you could use this on some suitable thing under /bin on a Unix box. This doesn't work on Windows, though. In this message, http://mail.python.org/pipermail/python-list/2005-June/326158.html Thomas Heller suggests using ctypes to call the Windows API directly; so something like this could work: import ctypes, sys i = ctypes.c_int() kernel32 = ctypes.windll.kernel32 process = kernel32.GetCurrentProcess() kernel32.IsWow64Process(process, ctypes.byref(i)) 1 is64bit = (i.value != 0) is64bit False (IsWow64Process returns a non-zero value if it manages to check the status, and sets the variable to a non-zero value if the process is running under WOW64. I only have 32-bit boxes here, so it's only partially tested). And yes, looks like official support for this might appear in 2.6: http://mail.python.org/pipermail/python-dev/2008-May/079022.html (in that thread, Mark Hammond suggests '64 bit' in sys.version as a workaround, but warns for false negatives). /F -- http://mail.python.org/mailman/listinfo/python-list
Playing stereo wav files in Python
-Hello all, I am trying to play stereo wavefiles in python with no success. I can play mono wavefiles, using either pygames mixer library, python's winsound library or wxPython's wx.Sound library, but i cannot get stereo wavefiles to play in any of these. Normally i wouldn't care and covert the files to mono, but the phase difference between the two ears in important for this application. Does anyone know of a way that i have missed? I am using a LynxONE soundcard if that is important. -AM -- http://mail.python.org/mailman/listinfo/python-list
Re: How to figure out if the platform is 32bit or 64bit?
Fredrik Lundh wrote: Ken Hartling wrote: Thanks .. but I want to find out if the system is running on 64bit even when the interpreter is a 32-bit build executable (what python was built on). platform.architecture() and platform() in general seems to only be looking at the build executable You can pass in an arbitrary binary to architecture(), so I guess you could use this on some suitable thing under /bin on a Unix box. This doesn't work on Windows, though. In this message, http://mail.python.org/pipermail/python-list/2005-June/326158.html Thomas Heller suggests using ctypes to call the Windows API directly; so something like this could work: import ctypes, sys i = ctypes.c_int() kernel32 = ctypes.windll.kernel32 process = kernel32.GetCurrentProcess() kernel32.IsWow64Process(process, ctypes.byref(i)) 1 is64bit = (i.value != 0) is64bit False This is included in the latest pywin32-211 as well: code import win32process print win32process.IsWow64Process () /code TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: How to figure out if the platform is 32bit or 64bit?
Tim Golden wrote: This is included in the latest pywin32-211 as well: code import win32process print win32process.IsWow64Process () /code on the other hand, ctypes is only an import away if you have a current Python... /F -- http://mail.python.org/mailman/listinfo/python-list
Regular expression
Hi all, How do I write a regular expression for this kind of sequences gi|158028609|gb|ABW08583.1| CG8385-PF, isoform F [Drosophila melanogaster] MGNVFANLFKGLFGKKEMRILMVGLDAAGKTTILYKLKLGEIVTTIPTIGFNVETVE thanks -- Beema Shafreen -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular expression
Beema shafreen wrote: How do I write a regular expression for this kind of sequences gi|158028609|gb|ABW08583.1| CG8385-PF, isoform F [Drosophila melanogaster] MGNVFANLFKGLFGKKEMRILMVGLDAAGKTTILYKLKLGEIVTTIPTIGFNVETVE line.split(|) ? it's a bit hard to come up with a working RE with only a single sample; what are the constraints for the different fields? is the last part free form text or something else, etc. have you googled for existing implementations of the format you're using? /F -- http://mail.python.org/mailman/listinfo/python-list
Best Python packages?
Although the standard library in Python is great, there are undoubtedly some great packages available from 3rd parties, and I've encountered a few almost by accident. However, I don't know how a user would become aware of many of these. http://pypi.python.org/pypi/ presumably lists most of the decent ones, but there's a lot there and little indication as to quality or popularity - great if you know exactly what you need, but not so great for just browsing. I'd love to have some way of finding out what hidden gems are out there in the Python world which could make my development a lot easier. Any suggestions? -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging to different addressees
On 16 Jul., 15:38, Vinay Sajip [EMAIL PROTECTED] wrote: On Jul 16, 8:55 am, McA [EMAIL PROTECTED] wrote: messages tologging.getLogger('tree.leave') would also show up inlogging.getLogger('tree') automatically? Yes. Ok. Hope not to bother. Use the propagate flag, which is mentioned in the documentation. That's the right hint. In fact, please make sure you've reviewed all the documentation before posting, as the documentation is intended to answer the more straightforward and common questions which come up. I did it and I'll do it again. :-) You know, sometimes a piece of text/documentation starts to become information for the reader when he exactly hits the problem. Anyway, thank you for your help and for that module. Best regards, Vinay Sajip Best regards Andreas Mock -- http://mail.python.org/mailman/listinfo/python-list
Re: Best Python packages?
Ben Sizer wrote: make my development a lot easier. Knowing what kind of development you do might help, of course. Some libraries are excellent in some contexts and suck badly in others... Looking at things that larger projects and distributions use can also be a good idea. For example, if you're doing scientific stuff, go directly to enthought.com. If you're doing web stuff, look at the libraries big Django applications use. Etc. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: About wmi
patrol wrote: The errors are in the following: Traceback (most recent call last): File D:\My Documents\code\python\wmi\test.py, line 5, in module c = wmi.WMI (non-existent computer) File C:\Python25\lib\wmi.py, line 1199, in connect handle_com_error (error_info) File C:\Python25\lib\wmi.py, line 184, in handle_com_error exception_string = [u%s - %s % (hex (hresult_code), hresult_name)] UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 4: ordinal not in range(128) OK, I'm trying to set up a Virtual PC so I can install a non-English XP. But would you mind running the following code for me, please, so I can get a handle on what's coming back: code import pythoncom import win32com.client try: win32com.client.GetObject (winmgmts://blahblah) except pythoncom.com_error, info: for i in info: print repr (i) /code Thanks TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Logging in __del__()
On Wed, 16 Jul 2008 12:38:50 +0100, Robert Rawlins wrote: So, am I right to assume that python will still handle its garbage disposal if I implement __del__(), it just handles circular references in a slightly different way, but to the same effect. Right? No. Circular references in objects with a `__del__()` implementation are not collected! Why are you using `__del__()` anyway? Are you aware of the promises that are *not* made! It's not guaranteed when the method is called nor if it is called at all! Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Angle brackets in command-line arguments?
Hi all, I am using someone else's script which expects input in the form of: ./script.py arg1 arg2 I was wondering if the angle-brackets here have a special meaning? It seems like they specify an input and output stream to use in place of the console. I could not find anything in the python manual or Python in a Nut-shell though. Anyone know? Thanks, Keith -- http://mail.python.org/mailman/listinfo/python-list
Custom 'Float' class. Am I right here?
import sys class Float(float): Custom float datatype with addtional attributes. def __new__(self, value=0.0, #default value name='', # string range=(0.0, 1.0) # tuple ) try: self.name = name self.range = range self.pos = (1, 1) return float.__new__(self, value) except: print ('Invalid value : Float = %s %s' % (str(value), sys.exc_info()[:2])) def setpos(self, value): self.pos = value def getpos(self): return self.pos*2.0 p = property(getpos, setpos) myFloat = Float(0.23) print myFloat.pos I am trying to create a custom 'float' datatype by subtyping default 'float'. There are few things I would like to know here: 1. How to make 'name' 'range' only readable attributes. 2. The property 'p' is not working as it has to. What's wrong here? 3. I would be heavily instancing this class, and I won't be creating any new attribute on instance. Is there any way to optimize? __slots__? Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Angle brackets in command-line arguments?
On Wed, 16 Jul 2008 07:53:56 -0700, Keith Hughitt wrote: I am using someone else's script which expects input in the form of: ./script.py arg1 arg2 I was wondering if the angle-brackets here have a special meaning? It seems like they specify an input and output stream to use in place of the console. I could not find anything in the python manual or Python in a Nut-shell though. Anyone know? That's not Python's business but the command shell's. Those characters are used for redirecting input and ouput from/to files in shells, so it should be covered in the documentation of the shell you are using. Including ways to protect the characters, so they reach the called program in arguments. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: Angle brackets in command-line arguments?
Keith Hughitt wrote: I am using someone else's script which expects input in the form of: ./script.py arg1 arg2 arg is a common notation for replace with argument value, so it could be that they're just expecting you to type: ./script.py arg1 arg2 Alternatively, they meant ./script.py arg1 arg2 in which case arg1 and arg2 are filenames. This is most commonly used with tools that process textfiles in some way. In the latter case, you can try the script simply by running: ./script.py and then typing the input to the terminal (use control-D on Unix or control-Z on Windows to terminate). Do the instructions use more meaningful names than arg1 and arg2? /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Angle brackets in command-line arguments?
Keith Hughitt wrote: Hi all, I am using someone else's script which expects input in the form of: ./script.py arg1 arg2 I was wondering if the angle-brackets here have a special meaning? It seems like they specify an input and output stream to use in place of the console. I could not find anything in the python manual or Python in a Nut-shell though. Anyone know? Thanks, Keith -- http://mail.python.org/mailman/listinfo/python-list In most Unix/Linux and related OS shells, the angled brackets *do* specify input and output streams as you surmise. However, they are *not* seen by the script as command line arguments. (And they are *not* brackets, and do not need to be matched. ) For any command, cmd file redirects the contents of file to cmd's standard input, which in Python is accessed by reading from sys.stdin (use input or raw_input or sys.stdin.read...) Also for any command, cmd file redirects the output of cmd to the named file. In Python this can be accessed using print, sys.stdout.write, ... Anything written to sys.stderr will not be caught by the redirection, ans so will probably end up on the screen instead of in file. Also various shells will provide similar functionality using a variety of similar syntaxes: , , , and |, and so on. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list
poplib 100% cpu usage
Hi all I wrote a multithreaded script that polls mails from several pop/imap accounts. To fetch the messages I'm using the getmail classes ( http://pyropus.ca/software/getmail/ ) , those classes use the poplib for the real pop transaction. When I run my script for a few hours cpu usage goes up to 100%, sometimes even 104% according to 'top' :-) This made our test machine freeze once. First I thought I maybe didn't stop my threads correctly after polling an account but I attached a remote debugger and it showed that threads are stopped ok and that the cpu gets eaten in poplib in the function _getline which states in the description: ---snip--- # Internal: return one line from the server, stripping CRLF. # This is where all the CPU time of this module is consumed. # Raise error_proto('-ERR EOF') if the connection is closed. def _getline(self): ---snip--- So for testing purposes I changed this function and added: time.sleep(0.0001) (googling about similar problems with cpu usage yields this time.sleep() trick) It now looks ok, cpu usage is at about 30% with a few spikes to 80-90%. Of course I don't feel cozy about changing a standard library as the changes will be overwritten by python upgrades. Did someone else from the list hit a similar problem and maybe has a better solution? Thanks for your hints. Best regards, Oli Schacher -- http://mail.python.org/mailman/listinfo/python-list
Re: Angle brackets in command-line arguments?
On Jul 16, 11:16 am, Gary Herron [EMAIL PROTECTED] wrote: Keith Hughitt wrote: Hi all, I am using someone else's script which expects input in the form of: ./script.py arg1 arg2 I was wondering if the angle-brackets here have a special meaning? It seems like they specify an input and output stream to use in place of the console. I could not find anything in the python manual or Python in a Nut-shell though. Anyone know? Thanks, Keith -- http://mail.python.org/mailman/listinfo/python-list In most Unix/Linux and related OS shells, the angled brackets *do* specify input and output streams as you surmise. However, they are *not* seen by the script as command line arguments. (And they are *not* brackets, and do not need to be matched. ) For any command, cmd file redirects the contents of file to cmd's standard input, which in Python is accessed by reading from sys.stdin (use input or raw_input or sys.stdin.read...) Also for any command, cmd file redirects the output of cmd to the named file. In Python this can be accessed using print, sys.stdout.write, ... Anything written to sys.stderr will not be caught by the redirection, ans so will probably end up on the screen instead of in file. Also various shells will provide similar functionality using a variety of similar syntaxes: , , , and |, and so on. Gary Herron Thanks all for the quick response. I should have known it was shell- related. I haven't ever had to use this kind of redirection before, mostly just the single-bracket version to feed the contents of a file into some command. The reason it was causing me concern in the first place was that I was trying to execute a python script from Apache Ant, and it was failing. It turned out that when I escaped the angle brackets in Ant, they were there-after treated as normal command-line arguments, so when the script was then executed, it just had some additional values in sys.argv. I ended up getting around the issue by creating a small bash-script which simply wraps input in angle brackets and then executes the python script itself. That way I didn't have to escape anything in in Ant, and things worked well. Thanks everyone for taking the time to explain things to me. I really appreciate the help :) Take care, Keith -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQL Insert
Thanks to all for your time and patience with this! The insert is working fine based on the suggestions in this thread. I now have another problem that should be resolved with a regular expression to remove currency formatting before inserting into the db. -- http://mail.python.org/mailman/listinfo/python-list
Setting Message Importance using SMTP Mail
Hi all, I'm trying to create a message using SMTP Mail through Python with a message Importance of either 0 (Low) or 2 (High). If I do outer.Add_header('Importance', '0') it is ignored. If I do uter.Replace_header('Importance', '0') I get the error below. Traceback (most recent call last): File #, line 840, in module outer.Replace_header('Importance', '0') AttributeError: MIMEMultipart instance has no attribute 'Replace_header' Can anyone provide any clues on the correct way of updating the Msg Importance header? Thanks in advance Ed -- http://mail.python.org/mailman/listinfo/python-list
Re: About wmi
On 7月16日, 下午10时39分, Tim Golden [EMAIL PROTECTED] wrote: patrol wrote: The errors are in the following: Traceback (most recent call last): File D:\My Documents\code\python\wmi\test.py, line 5, in module c = wmi.WMI (non-existent computer) File C:\Python25\lib\wmi.py, line 1199, in connect handle_com_error (error_info) File C:\Python25\lib\wmi.py, line 184, in handle_com_error exception_string = [u%s - %s % (hex (hresult_code), hresult_name)] UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 4: ordinal not in range(128) OK, I'm trying to set up a Virtual PC so I can install a non-English XP. But would you mind running the following code for me, please, so I can get a handle on what's coming back: code import pythoncom import win32com.client try: win32com.client.GetObject (winmgmts://blahblah) except pythoncom.com_error, info: for i in info: print repr (i) /code Thanks TJG -2147023174 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3' None None -- import pythoncom import win32com.client try: win32com.client.GetObject (winmgmts://blahblah) except pythoncom.com_error, info: for i in info: print i -2147023174 RPC 服务器不可用。 None None - a=RPC 服务器不可用。 a 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3' - Patrol -- http://mail.python.org/mailman/listinfo/python-list
Re: About wmi
patrol wrote: -2147023174 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3' None None -- import pythoncom import win32com.client try: win32com.client.GetObject (winmgmts://blahblah) except pythoncom.com_error, info: for i in info: print i -2147023174 RPC 服务器不可用。 None None - a=RPC 服务器不可用。 a 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3' - Patrol Brilliant. Thanks, Patrol. So the error message comes back encoded. Can you confirm what your console encoding is, please? The following script should confirm: code import os, sys print sys.stdout.encoding os.system (chcp) /code TJG -- http://mail.python.org/mailman/listinfo/python-list
Is there any interest in working on an application?
Hello, I have an python application which I've been developing for several years (off and on, mostly off for lack of time) which I'm considering putting up to open source if I can find other developers interested in contributing. The application is a web publisher/information outliner. (See an example of a beta here: http://members.cox.net/ronpro/welcome.html where I test my ability to generate an interactive tree for the data in an outline.) The application is 100% Python. The gui is written using Tkinter and Tix -- I'm definitely open to other libraries for the GUI. The app supports unicode in the outlines. There's a spell-checker plugin (complements of the pyenchant project). The application is written on top of an application framework and plugin framework both of which I developed myself. Much of the application is actually plugins so it's very modular. For screen shots of the app so far see: http://members.cox.net/ronpro/scrnCap1.JPG and http://members.cox.net/ronpro/scrnCap2.JPG The development would probably be done through SourceForge. I'm in the process of documenting the current design in UML class diagrams using the free version of Visual Paradigm (if another tool is suggested we could switch). My motive: I'm a research scientist. My prefered method to record, review, edit and organize my notes is within an outline (rather than a flat notebook format used by most researchers). The ability to consider new ideas can be as easy as moving items around in the outline. I've used many commercial programs in the past but all have had some limitation or another. Most don't support unicode (I need unicode characters to record mathematical and logical formulae). Those that do produce html don't produce the side-by-side view of an interactive tree (able to expand or collapse nodes) beside the actual on-screen notes. The interactive tree is a necessity for me with over 2000 entries in my largest outline and growing fast. Design Philosophy: I've attempted to keep to the following design philosophy (prioritized by order). - User Experience -- everything should be easy for the user. - OO, Maximize modularity, minimize cross dependence. (e.g. The Application framework, plugin framework and word processor know nothing about the problem domain and nothing about the other modules in the application). - KISS, I prefer simple straightforward code over speedy tricks. If it's hard to read or understand I'll probably hate it. - Minimize 3rd party modules in the core application. I know 3rd party libs can make it easier to develop and this would seem to violate KISS. However, with User Experience being higher priority, the less there is for a user to install the easier. Best case, the user installs Python and s/he's ready to go. I don't mind requiring 3rd party libs for most plugins. My take on this is here: - If it's part of the core distribution (the core application or a plugin that's part of the main distribution), do everything possible to avoid 3rd party libs. - For plugins distributed separately from the application installer, the plugin must check for the required libs upon loading and exit gracefully if the lib is not present (at most display a dialog stating that the required lib is not installed.) - If at all possible, provide unit test with each module (including plugins) Future Direction: - Some of the features in the menus and on the toolbars are not yet implemented. (e.g. find, search/replace, bulletized and numbered lists, tables) - The content of any tree entry is displayed in the content pane to the right of the outline. Right now the only supported content is formatted text in a word processor (actually a glorified Text widget). The Text widget is part of the core app. I want this widget to be turned into a plugin so that other kinds of content are possible with other content editor plugins. The main app would then select and display the appropriate content editor for a given kind of data. - Currently, cutting and pasting is possible, however cutting and pasing formatted text is only possible within the application. Want to support cutting and pasing stylized text with the system clipboard and other applications (word, star office, etc.) - Import export other formats (importers and exporters are already plugins). We just need to write more of them. - Support multiple views of a single outline so we can view different parts of the outline simultaneously. - Support cutting and pasting, dragging and dropping across different outlines. - Customizable appearance for HTML output. - Anything else the development group or users can think of. If you're interested in more information or trying out this app (note that it's very immature and probably only worthy of being called an alpa) please don't hesitate to contact me. Thanks for reading, Ron-- http://mail.python.org/mailman/listinfo/python-list
Re: Regular expression
On Jul 16, 4:14 pm, Fredrik Lundh [EMAIL PROTECTED] wrote: Beema shafreen wrote: How do I write a regular expression for this kind of sequences gi|158028609|gb|ABW08583.1| CG8385-PF, isoform F [Drosophila melanogaster] MGNVFANLFKGLFGKKEMRILMVGLDAAGKTTILYKLKLGEIVTTIPTIGFNVETVE line.split(|) ? it's a bit hard to come up with a working RE with only a single sample; what are the constraints for the different fields? is the last part free form text or something else, etc. have you googled for existing implementations of the format you're using? That'a a fasta file, so for the header line this is enough: [part.strip() for part in line.split(|)] But better is to use the biopython libs that already perform all such things better. Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
Re: About wmi
Assuming that the error comes back in the sys.stdout encoding, the following version *should* work ok. I still haven't got a non-English set up to test it on, but it certainly does return a Unicode error message. http://timgolden.me.uk/wmi-project/wmi.py The usual test case, if you wouldn't mind: code import wmi wmi.WMI (non-existent computer) /code should give a (language-specific) error message, not an UnicodeDecodeError TJG -- http://mail.python.org/mailman/listinfo/python-list
Eclipse, Pydev, question
I have a small project for further development in eclipse, using the pyDev plug-in. I am working on foo.py and bar.pyc is also in the directory. bar.py is not in the directory; it is someone else's (confidential) file, and I don't get the python source. Can I run bar.pyc from eclipse ? -- http://mail.python.org/mailman/listinfo/python-list
Re: how to match whole word
On Jul 15, 10:29 pm, Gary Herron [EMAIL PROTECTED] wrote: Peng Yu wrote: Hi, The following code snippet is from /usr/bin/rpl. I would like the it to match a word, for example, abc in :abc:. But the current one would not match abc in :abc:. I tried to modify it myself. Would you please let me know what is the corrected way to do it? Thanks, Peng if opts.whole_words: regex = re.compile(r(?:(?=\s)|^) + re.escape(old_str) + r(?=\s| $), opts.ignore_case and re.I or 0) -- http://mail.python.org/mailman/listinfo/python-list The regular expression \w+ will match (what might be your definition of) a word, and in particular will match abc in :abc:. Regular expressions have lots of other special \-sequences that might be worth your while to read about: http://docs.python.org/lib/re-syntax.html Gary Herron I didn't read the docs and tried the following code. regex = re.compile(r\A + re.escape(old_str) + r\Z, opts.ignore_case and re.I or 0) But I'm not sure why it is not working. Thanks, Peng -- http://mail.python.org/mailman/listinfo/python-list
Framework recommendations for web service?
We're looking at the next phase of development for our webapp, and the main focus will be to move the core from the app to a web service so other systems can use the data we've gathered (we're thinking along the lines of the XML API of Highrise from 37Signals). Its possible that we'll extend the service to allow access via vanilla XML, JSON, and YAML at some point, however we've decided to use Facebook's Thrift for connectivity initially to support as many techs as possible and also because our web interface for the app is written in PHP. As we're extracting the core we'll be translating it to Python to make use of the wealth of well-structured libraries and hopefully make the project shorter. However, we've hit a snag in choosing a framework around which to rebuild the service. It seems the more popular frameworks (django, turbogears) are all focused on providing web content. Since our core will be using thrift to communicate, we don't need templating, feeds, admin pages (django), or ajax (turbogears). What we *do* need is a lightweight, simple framework that will allow us to create a RESTful interface and throw code together fast. We'll probably go with SQLObject (unless we can extract the ORM from django - lazy evaluation would be very useful), and we're just looking for something fast and light to sit between that and the thrift interfaces we'll create. So, can anyone suggest a lightweight python framework which just does the essentials? -- http://mail.python.org/mailman/listinfo/python-list
Re: how to match whole word
Peng Yu wrote: I didn't read the docs and tried the following code. regex = re.compile(r\A + re.escape(old_str) + r\Z, opts.ignore_case and re.I or 0) But I'm not sure why it is not working. as the documentation says, \A and \Z matches at the beginning/end of a *string*, not a word. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: About wmi
On 7月16日, 下午11时59分, Tim Golden [EMAIL PROTECTED] wrote: patrol wrote: -2147023174 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3' None None -- import pythoncom import win32com.client try: win32com.client.GetObject (winmgmts://blahblah) except pythoncom.com_error, info: for i in info: print i -2147023174 RPC 服务器不可用。 None None - a=RPC 服务器不可用。 a 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3' - Patrol Brilliant. Thanks, Patrol. So the error message comes back encoded. Can you confirm what your console encoding is, please? The following script should confirm: code import os, sys print sys.stdout.encoding os.system (chcp) /code TJG- 隐藏被引用文字 - - 显示引用的文字 - import os,sys print sys.stdout.encoding cp936 os.system(chcp) 活动的代码页: 936 0 sys.getdefaultencoding() 'ascii' -- http://mail.python.org/mailman/listinfo/python-list
Re: About wmi
On 7月17日, 上午12时16分, Tim Golden [EMAIL PROTECTED] wrote: Assuming that the error comes back in the sys.stdout encoding, the following version *should* work ok. I still haven't got a non-English set up to test it on, but it certainly does return a Unicode error message. http://timgolden.me.uk/wmi-project/wmi.py The usual test case, if you wouldn't mind: code import wmi wmi.WMI (non-existent computer) /code should give a (language-specific) error message, not an UnicodeDecodeError TJG -- import wmi wmi.WMI('non-existent computer') Traceback (most recent call last): File stdin, line 1, in module File C:\Python25\lib\wmi.py, line 1199, in connect handle_com_error (error_info) File C:\Python25\lib\wmi.py, line 184, in handle_com_error exception_string = [u%s - %s % (hex (hresult_code), hresult_name)] UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 4: ordinal not in range(128) -- yup,error_info contains the Chinese encoded string. All of the Simple Chinese Windows use the CP936.Every Chinese word utilizes two bytes.Maybe you can fix this bug by modifying handle_com_error. Patrol -- http://mail.python.org/mailman/listinfo/python-list
Re: Best Python packages?
Ben Sizer wrote: I'd love to have some way of finding out what hidden gems are out there in the Python world If they were easy to find, they wouldn't be hidden gems. :-) Dennis Cote -- http://mail.python.org/mailman/listinfo/python-list
Re: How to figure out if the platform is 32bit or 64bit?
I need to know if I'm running on 32bit or 64bit ... so far I haven't come up with how to get this info via python. sys.platform returns what python was built on ... but not what the current system is. I thought platform.uname() or just platform.processor() would have done it, but python returns an empty string on windows. Any ideas? Thanks, Ken === From what I'm reading I think the answer lies in being able to see Microsoft's OS 'About' statement. One of the Python guru's should be able to supply the code. On Linux you should be able to uname -m and get a pretty good idea. See man uname. something like: #contents of t.py #--- import os zstatflg= os.system(uname -m) #--- EOF --- then: python t.py i686 (I'm running a stock Python 2.5.2) If the Python itself was compiled 32 bit and installed on a 64 bit machine that runs 32 bit code (like most all do during transition times) then all attempts with Python to check itself will return 32 bit responses. Using math and/or 'kibitz' (cheater text) will be useless. Hope this helps; Steve [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: how can i save my command prompt screen?
Ty hensons wrote: how can i save my command prompt screen? == That by itself leaves lots of questions. Taken literally to be the box then: In Microsoft use the Print Screen followed by mspaint and Edit/paste (Or SHIFT-PrintScreen if whole screen showed up, I forget which it is. One does just the box that is hot while the other gets all) In Unix use xwd. See man xwd and xwud. Also man convert with box open and text you want for show'n'tell visible xwdscreen_1.xwd (click in box of choice) to view results: xwudscreen_1.xwd (click picture to make it go away) To turn .xwd into jpeg: convert screen_1.xwd JPEG:screen_1.jpg With Python running something in one box and a simple script in another you can create lots of pics for the documentation. If you invert the colors the pics will have black letters on a white background and save tons of ink. Steve [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: how can i save my command prompt screen?
On Jul 16, 12:28 pm, norseman [EMAIL PROTECTED] wrote: Ty hensons wrote: how can i save my command prompt screen? == That by itself leaves lots of questions. Taken literally to be the box then: In Microsoft use the Print Screen followed by mspaint and Edit/paste (Or SHIFT-PrintScreen if whole screen showed up, I forget which it is. One does just the box that is hot while the other gets all) In Windows you can right-click, choose Mark and then select the text. Hit enter to copy it to the clipboard. Then you can paste it into any text editor you like. Steve [EMAIL PROTECTED] Mike -- http://mail.python.org/mailman/listinfo/python-list
For_loops hurt my brain.
This script uses a simple for loop to zip some files. However I am repeating code that cries out for a nested loop. My two lists of files_to_be_zipped (spare and seekfacts) are of uneven length so I can't seem to decipher the for_logic. I would appreciate any help. Thanks, Bill import zipfile import os zips = [ 'c:/spare.zip', 'c:/seekfacts.zip' ] spare = [ 'c:/spare/huge.fm3', 'c:/spare/huge.wk3' ] seekfacts = [ 'c:/seekfacts/bookmark.html', 'c:/seekfacts/index.htm', 'c:/seekfacts/seek.css', 'c:/seekfacts/seek.js' ] zFile = zipfile.ZipFile(zips[0], 'w') for files in spare: zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED) zFile.close() zFile = zipfile.ZipFile(zips[1], 'w') for files in seekfacts: zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED) zFile.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: About wmi
patrol wrote: import wmi wmi.WMI('non-existent computer') Traceback (most recent call last): File stdin, line 1, in module File C:\Python25\lib\wmi.py, line 1199, in connect handle_com_error (error_info) File C:\Python25\lib\wmi.py, line 184, in handle_com_error exception_string = [u%s - %s % (hex (hresult_code), hresult_name)] UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position 4: ordinal not in range(128) -- yup,error_info contains the Chinese encoded string. All of the Simple Chinese Windows use the CP936.Every Chinese word utilizes two bytes.Maybe you can fix this bug by modifying handle_com_error. Well, that's what I've done in that latest version. Only I naively assumed that I could use sys.stdout.encoding to determine the encoding. I'll have to try harder. TJG -- http://mail.python.org/mailman/listinfo/python-list
Is there any component-oriented (non-MVC) web framework available for Python?
Hi Is there any component-oriented (non-MVC) web framework available for Python? That is something like Apache Wicket, Tapestry or JSF, but I need it to be in Python. Regards, Ali -- http://mail.python.org/mailman/listinfo/python-list
Uploading an image using PUT
Hi All, Let me start by saying that's I'm relatively new to Python, so please be gentle! I need to up upload a file to a Tomcat web app using httplib. The web app requires the following: Files need to be split into 100kb (102400b) and each file segment loaded using the PUT request. It is also a requirement that the following headers be sent: For simplicity I've used an image (jpg) smaller than 100kb, so it doesn't need to be chunked headers = { Accept: text/xml, Authorization: testAuthHeader, Content-Length: 50172, Content-Range: bytes 0-50172/50172, Content-Type: image/jpeg, If-Match: 1, User-Agent: (en-IE; Grinder), } I make the following connection: conn = httplib.HTTPConnection(url) conn.request(method, uriStr, body, additionalHeaders) where: method = PUT uriStr is the web app specific URI body is the raw data (bytes) from the jpg image additionalHeaders are the headers above For some reason I keep getting a Status 400 error from the web server. Is it possible to PUT (or POST?) data in this fashion using httplib? Many thanks for your help Noelob -- http://mail.python.org/mailman/listinfo/python-list
Re: For_loops hurt my brain.
On Jul 16, 1:42 pm, [EMAIL PROTECTED] wrote: This script uses a simple for loop to zip some files. However I am repeating code that cries out for a nested loop. My two lists of files_to_be_zipped (spare and seekfacts) are of uneven length so I can't seem to decipher the for_logic. I would appreciate any help. Thanks, Bill import zipfile import os zips = [ 'c:/spare.zip', 'c:/seekfacts.zip' ] spare = [ 'c:/spare/huge.fm3', 'c:/spare/huge.wk3' ] seekfacts = [ 'c:/seekfacts/bookmark.html', 'c:/seekfacts/index.htm', 'c:/seekfacts/seek.css', 'c:/seekfacts/seek.js' ] zFile = zipfile.ZipFile(zips[0], 'w') for files in spare: zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED) zFile.close() zFile = zipfile.ZipFile(zips[1], 'w') for files in seekfacts: zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED) zFile.close() I would do something like this: # UNTESTED import zipfile import os zip_dict = { 'spare' : ['c:/spare.zip', 'c:/seekfacts.zip'], 'seekfacts' : [ 'c:/seekfacts/bookmark.html', 'c:/seekfacts/index.htm', 'c:/seekfacts/seek.css', 'c:/seekfacts/seek.js' ] } for key,value in zip_dict.items(): zFile = zipfile.ZipFile(c:/%s.zip % key, 'w') for fname in value: zFile.write(fname, os.path.basename(files), zipfile.ZIP_DEFLATED) zFile.close() # End untested code. This implicitly maps thing with the key foo to the zip file c:/ foo.zip, but if you want to be more general, I would suggest thinking about making a class. -Dan -- http://mail.python.org/mailman/listinfo/python-list
Re: Converting from local - UTC
Thanks Gabriel! That helps clear things up for me. The above method works very well. I only have one remaining question: How can I pass a datetime object to MySQL?' So far, what I've been doing is building the query as a string, for example: query = INSERT INTO image VALUES(%d, %d, %s, '%s') % (id, meas, date, 'jpg') cursor.execute(query) This works fine for regular datetime objects, which are passed as strings similar to: 2003-10-01 00:00:00. When incorporating a timezone, however, the resulting string is of the form 2003-10-01 00:00:00+00:00. Unfortunately, MySQL does not recognize the offset. I know you said you don't use MySQL, but how would you do something execute a similar query on the database you normally interface with? Thanks, Keith On Jul 15, 12:04 am, Gabriel Genellina [EMAIL PROTECTED] wrote: En Mon, 14 Jul 2008 12:06:30 -0300,KeithHughitt [EMAIL PROTECTED] escribió: On Jul 12, 12:52 am, Gabriel Genellina [EMAIL PROTECTED] wrote: En Fri, 11 Jul 2008 15:42:37 -0300,KeithHughitt [EMAIL PROTECTED] escribió: I am having a little trouble figuring out how to convert a python datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would like to create a UTC date so that when I send it to MySQL (which treats all dates at local dates by default), it will already have incorporated the proper UTC offset. I've tried looking through the docshttp://python.active-venture.com/lib/datetime-datetime.html), but have not had any luck. You have to use a timezone aware datetime object. If all you want is to store an UTC date, the tzinfo demo classes that you can find in the Python docs at http://docs.python.org/lib/datetime-tzinfo.html may be enough. Thanks for advice Gabriel. I downloaded the tzinfo demo class, saved it as UTC.py and imported it. I'm still not exactly sure how to use it though. It looks like the file already creates an instance of the UTC tzinfo class (line 20: utc = UTC()), however, when I try to test it out in the interpreter, it cannot be found. I'm new to python, and there is probably something obvious I'm missing, but do you have any ideas? The import statement in Python doesn't behave the same way as similar statements in other languages - and it may be confusing you. I'll try to explain it using this example. You have: - a *file* UTC.py, containing the source code for the *module* UTC. It contains: - a *class* definition (UTC) and - an *instance* of that class, utc. --- begin UTC.py ---If you pass a timezone aware datetime object as a SQL parameter class UTC(tzinfo): ... utc = UTC() ... --- end UTC.py --- Here is what I'm attempting: output begin = Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type help, copyright, credits or license for more information. import datetime, UTC Here you have imported the *module* UTC. That is, the name UTC now refers to a newly created module just loaded from the UTC.py file. t = datetime.datetime(2008, 7, 14, 00, 00, 00, UTC()) Traceback (most recent call last): File stdin, line 1, in module TypeError: 'module' object is not callable The error comes from UTC(): UTC is a module, UTC() is attempting to call it, and since modules are not callable objects, we get a TypeError. utc Traceback (most recent call last): File stdin, line 1, in module NameError: name 'utc' is not defined The *only* name we have imported so far is UTC - the module. Lowercase utc isn't defined. utc = UTC() Traceback (most recent call last): File stdin, line 1, in module TypeError: 'module' object is not callable Same as above... Ok, how to solve it? We know that UTC refers to the *module* with the same name. To get the *class* inside that module, use UTC.UTC - try again in the interpreter. To create a new instance of that class, you can use UTC.UTC(). To obtain the instance already created in the UTC module, use UTC.utc **OR** Import those names explicitely: py from UTC import UTC In this case the name UTC refers to the *class* inside the module. In this particular example it may be confusing - both have the same name. Another example from the standard library: the poplib module contains a POP3 class, so after executing this line: py from poplib import POP3 the name POP3 refers to that class. The poplib module itself isn't directly available. Back to the UTC module, you could use: py from UTC import utc and now utc refers to the *instance* already created inside the module. This last form may be the most convenient in your case: py import datetime py from UTC import utc py print datetime.datetime(2008, 7, 14, 20, 30, 0, 0, utc) 2008-07-14 20:30:00+00:00 -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Is there any component-oriented (non-MVC) web framework available for Python?
On Jul 16, 6:48 pm, Alis [EMAIL PROTECTED] wrote: Hi Is there any component-oriented (non-MVC) web framework available for Python? That is something like Apache Wicket, Tapestry or JSF, but I need it to be in Python. Regards, Ali Have you looked at kamaelia? http://kamaelia.sourceforge.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: bad recursion, still works
On Wed, 16 Jul 2008 15:20:23 +0200, Fredrik Lundh wrote: [snip] Hope this helps more than it confuses. Absolutely. It is wonderfully enlightening. Many thanks. -- To email me, substitute nowhere-spamcop, invalid-net. -- http://mail.python.org/mailman/listinfo/python-list
Re: Testing for connection to a website
Fredrik Lundh wrote: Alexnb wrote: e = '' try: ... except HTTPError, e: print e.code except URLError, e: print e.reason if e == '': print good to go footnote: here's a better way to test if an exception was raised or not: try: ... except HTTPError, e: print e.code except URLError, e: print e.reason else: print good to go /F -- http://mail.python.org/mailman/listinfo/python-list Thanks! can't believe I didn't think of that. -- View this message in context: http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p18493785.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Is re.findall guaranteed to be in order?
Fredrik Lundh wrote: Joshua Kugler wrote: Experimenting has shown me that re.findall() will return a list with the matches in the order it found them. in the order it found them doesn't really say much, does it? ;-) findall and finditer both scans the string from left to right, and will return matches in that order. (the documentation is a bit vague, so if you have the time, please add a request for clarification to the bug tracker) Done. http://bugs.python.org/issue3384 j -- http://mail.python.org/mailman/listinfo/python-list
py2exe issues with pictures and icons
Hello I am sure most of you are familiar with py2exe. I am having a bit of a problem. See the program has a few pictures involved and the .ico it uses for the windows. However, the pictures are stored in the same directory as the source, something like: C:\Docs and settings\me\My docs\python\program. When I run the program for the interpreter, just as a .py, everything works just as it should. However, when I compile the main source as an .exe, and say let a friend try the program. It fails because it is missing the .ico. The catch, is I don't want to have it have to installed, at least at this point, I want it to be able to just run. So how can I make it just run from any computer with the files not being in the immediate directory. If that is not possible, how can I put them in the immediate directory and still make it work. Because that directory may change a lot so the path will change. Just a few questions. I hope someone out there can help me out! -- View this message in context: http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp18493908p18493908.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: Framework recommendations for web service?
Phillip B Oldham wrote: So, can anyone suggest a lightweight python framework which just does the essentials? web.py is pretty slim (not to be confused with web2py). Pylons isn't very large, depending on what you call essential. j -- http://mail.python.org/mailman/listinfo/python-list
Re: Framework recommendations for web service?
What we *do* need is a lightweight, simple framework that will allow us to create a RESTful interface and throw code together fast. We'll probably go with SQLObject (unless we can extract the ORM from django - lazy evaluation would be very useful), and we're just looking for something fast and light to sit between that and the thrift interfaces we'll create. So, can anyone suggest a lightweight python framework which just does the essentials? Have you looked at CherryPy? It's very simple to get up and running and can be changed to go through Apache if you need it to be fast. I don't think RESTful interfaces are built in but I know people have succesfully built RESTful apps on top of CherryPy. Also plans for REST in CherryPy 3 look promising. Here is a post I ran across from one of the contributers. Hey there, CherryPy 3 is currently under brainstorming before being first draft. There some feature we do want such as the ability to change the URL dispatching at will depending on what is required for a given application. One dispatching rule I do want is the one based on HTTP verbs. So it might take a few months to get there but eventually it will be a built-in :) - Sylvain -- Ivan Ven Osdel Senior Software Engineer http://datasyncsuite.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Framework recommendations for web service?
I don't think RESTful interfaces are built in but I know people have succesfully built RESTful apps on top of CherryPy. Also plans for REST in CherryPy 3 look promising. Here is a post I ran across from one of the contributers. Hey there, CherryPy 3 is currently under brainstorming before being first draft. There some feature we do want such as the ability to change the URL dispatching at will depending on what is required for a given application. One dispatching rule I do want is the one based on HTTP verbs. So it might take a few months to get there but eventually it will be a built-in :) - Sylvain My apologies, it appears that post was from 2006! -- Ivan Ven Osdel Senior Software Engineer http://datasyncsuite.com -- http://mail.python.org/mailman/listinfo/python-list