ANN: PyIMSL Studio 1.5 now available at no charge for non-commercial use
Visual Numerics, a Rogue Wave Software Company, is making PyIMSL Studio 1.5 available for download at no charge for non-commercial use or for commercial evaluation. Learn more about PyIMSL Studio and download at: http://www.vni.com/campaigns/pyimslstudioeval PyIMSL Studio contains both open source and proprietary components that create a fully supported and documented platform for analytic prototyping and production development. - For prototyping, a number of open source tools including Python, NumPy, Eclipse, matplotlib and commercial components from Visual Numerics, Inc. are available for Python, including Python wrappers to the mathematics and statistics algorithms in the IMSL Numerical Library which are incorporated in the distribution. This combination of tools provides a rich environment for prototype development. - For production deployment, commercial users of PyIMSL Studio also have access to the IMSL C Library to allow the development of native C implementations of algorithms for high performance production code. Using the IMSL C Library provides parity between prototype and production code. The IMSL Numerical Libraries have been the cornerstone of high-performance and desktop computing as well as predictive analytics applications in science, technical and business environments for well over three decades. Functional areas include: Mathematics * Matrix Operations * Linear Algebra * Eigensystems * Interpolation Approximation * Numerical Quadrature * Differential Equations * Transforms * Nonlinear Equations * Optimization * Special Functions * Finance Bond Calculations Statistics * Basic Statistics * Time Series Forecasting * Multivariate Analysis * Nonparametric Tests * Correlation Covariance * Regression * Analysis of Variance and Designed Experiments * Categorical and Discrete Data Analysis * Survival and Reliability Analysis * Goodness of Fit * Distribution Functions * Random Number Generation * Neural Networks * Genetic Algorithm * Naïve Bayes -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
ANN: Urwid 0.9.9 - Console UI Library
Announcing Urwid 0.9.9 -- Urwid home page: http://excess.org/urwid/ Updated screen shots: http://excess.org/urwid/examples.html Tarball: http://excess.org/urwid/urwid-0.9.9.tar.gz RSS: http://excess.org/feeds/tag/urwid/ About this release: === This release includes many new features developed since the last major release. Urwid now supports 256 and 88 color terminals. A new MainLoop class has been introduced to tie together widgets, user input, screen display and an event loop. Twisted and GLib-based event loops are now supported directly. A new AttrMap class now allows mapping any attribute to any other attribute. Most of the code base has been cleaned up and now has better documentation and testing. Lots of other improvements are listed below. New in this release: * New support for 256 and 88 color terminals with raw_display and html_fragment display modules * New palette_test example program to demonstrate high color modes * New AttrSpec class for specifying specific colors instead of using attributes defined in the screen's palette * New MainLoop class ties together widgets, user input, screen display and one of a number of new event loops, removing the need for tedious, error-prone boilerplate code * New GLibEventLoop allows running Urwid applications with GLib (makes D-Bus integration easier) * New TwistedEventLoop allows running Urwid with a Twisted reactor * Added new docstrings and doctests to many widget classes * New AttrMap widget supports mapping any attribute to any other attribute, replaces AttrWrap widget * New WidgetDecoration base class for AttrMap, BoxAdapter, Padding, Filler and LineBox widgets creates a common method for accessing and updating their contained widgets * New left and right values may be specified in Padding widgets * New command_map for specifying which keys cause actions such as clicking Button widgets and scrolling ListBox widgets * New tty_signal_keys() method of raw_display.Screen and curses_display.Screen allows changing or disabling the keys used to send signals to the application * Added helpful __repr__ for many widget classes * Updated all example programs to use MainLoop class * Updated tutorial with MainLoop usage and improved examples * Renamed WidgetWrap.w to _w, indicating its intended use as a way to implement a widget with other widgets, not necessarily as a container for other widgets * Replaced all tabs with 4 spaces, code is now more aerodynamic (and PEP 8 compliant) * Added saving of stdin and stdout in raw_display module allowing the originals to be redirected * Updated BigText widget's HalfBlock5x4Font * Fixed graph example CPU usage when animation is stopped * Fixed a memory leak related to objects listening for signals * Fixed a Popen3 deprecation warning 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/
Pydev 1.5.1 Released
Hi All, Pydev 1.5.1 has been released Details on Pydev: http://pydev.org Details on its development: http://pydev.blogspot.com Release Highlights: --- * Improvements in the AST rewriter * Improvements on the refactoring engine: o No longer using BRM o Merged with the latest PEPTIC o Inline local available o Extract method bug-fixes o Extract local on multi-line o Generating properties using coding style defined in preferences o Add after current method option added to extract method o A bunch of other corner-case situations were fixed * Bug-fixes: o Minor editor improvements o Adding default forced builtins on all platforms (e.g.: time, math, etc) which wouldn't be on sys.builtin_module_names on some python installations o Adding 'numpy' and 'Image' to the forced builtins always o Ctrl+1: Generate docstring minor fixes o Ctrl+1: Assign to local now follows coding style preferences properly o Exponential with uppercase E working on code-formatting o When a set/get method is found in code-completion for a java class an NPE is no longer thrown o Backspace properly treated in block mode o Setting IRONPYTHONPATH when dealing with Iron Python (projects could not be referenced) o No longer giving spurious 'statement has no effect' inside of lambda and decorators o Fixed new exec in python 3k o Fixed NPE when breakpoint is related to a resource in a removed project o Fixed import problem on regexp that could lead to a recursion. o No longer giving NPE when debugging with the register view open o List access be treated as __getitem__() in the list -- patch from Tassilo Barth o Fix for invalid auto-self added when typing What is PyDev? --- PyDev is a plugin that enables users to use Eclipse for Python, Jython and Iron Python development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny -- Software Developer Aptana http://aptana.com/python Pydev - Python Development Environment for Eclipse http://pydev.org http://pydev.blogspot.com -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
IMDbPY 4.3
IMDbPY 4.3 is available (tgz, rpm, exe) from: http://imdbpy.sourceforge.net/ IMDbPY is a Python package useful to retrieve and manage the data of the IMDb movie database about movies, people, characters and companies. With this release, a lot of bugs were fixed, and some minor new features introduced. Platform-independent and written in pure Python (and few C lines), IMDbPY can retrieve data from both the IMDb's web server and a local copy of the whole database. IMDbPY package can be very easily used by programmers and developers to provide access to the IMDb's data to their programs. Some simple example scripts are included in the package; other IMDbPY-based programs are available from the home page. -- Davide Alberani albera...@libero.it [GPG KeyID: 0x465BFD47] http://erlug.linux.it/~da/ -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
announcing Caribou: python migrations for sqlite databases
check it out: http://github.com/clutchski/caribou feedback is much appreciated. thanks for reading. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
ANN: a mini-language for encapsulating deep-copy operations on Python data structures
During the last few days I have written code in support of a small DDL language that encapsulates a concise representation of the manipulations needed to make a deep subcopy of a Python-like data structure. It is inspired by syntax from mainstream modern languages, including, of course, Python. The DDL can be converted to an AST. That AST can be walked to either generate Python code that expresses the mapping or to generate Python objects that can execute the mapping. Either of the prior outputs can then subsequently be applied to real world inputs to create new Python data structures from old ones, using the mechanisms specified in the original DDL for attribute access, dictionary lookup, iteration, method invocation, etc. Here is an example of the DDL (and I hate the terminology DDL, just cannot think of anything better): { 'show_table_of_contents', 'author' { .person 'name', .person 'location' as city, .favorite_books()[ .title, .cost() as expense ] as books} } There are more details here: http://showellonprogramming.blogspot.com/2009/11/more-on-python-deep-copy-schema.html Apart from shamelessly plugging my blog, I am hoping to generate ideas, constructive criticism, etc. Feel free to comment here or on the blog. So far there are three entries on the blog, all pertaining to Python. The implementation of the idea is quite new, but it is a topic that I have been pondering for a long time--no matter how expressive your programming language of choice might be, there are certain programming tasks that just seem needlessly tedious. The mini-language above proposes to solve one problem but solve it well. I am particularly interested to find out whether somebody has tried something like this before. -- http://mail.python.org/mailman/listinfo/python-list
Re: IOError: [Errno 28] No space left on device
Lie Ryan schrieb: hong zhang wrote: --- On Tue, 11/17/09, Tim Chase python.l...@tim.thechases.com wrote: From: Tim Chase python.l...@tim.thechases.com Subject: Re: IOError: [Errno 28] No space left on device To: Lie Ryan lie.1...@gmail.com Cc: python-list@python.org Date: Tuesday, November 17, 2009, 7:47 PM for i in glob.glob('/sys/kernel/debug/ieee80211/phy*/iwlagn/data/continuous_tx'): with open(i, 'w') as f: print f, cont_tx work perfectly. But following get error like: print f, cont_tx IOError: [Errno 28] No space left on device Apparently the harddisk where you stored the file is full? Likely a misinterpretation of the error. I'm guessing either one needs to be root to write to this [likely virtual] file, or a member of an associated group.. It would help to have the output of bash$ whoami bash$ id and bash$ ls -lsF /sys/kernel/debug/ieee80211/phy*/iwlagn/data/continuous_tx It is root. see following. File ../henry-cont-tx, line 186, in do_cont_tx print f, cont_tx IOError: [Errno 28] No space left on device r...@tester-laptop:/home/tester/Desktop/sv-project/scripts/scripts# whoami root r...@tester-laptop:/home/tester/Desktop/sv-project/scripts/scripts# id uid=0(root) gid=0(root) groups=0(root) r...@tester-laptop:/home/tester/Desktop/sv-project/scripts/scripts# ls -lsF /sys/kernel/debug/ieee80211/phy*/iwlagn/data/continuous_tx 0 -rw--- 1 root root 0 2009-11-17 17:51 /sys/kernel/debug/ieee80211/phy2/iwlagn/data/continuous_tx Where is the output file? Could it possibly be located in a device that is impossible to write even for root (e.g. filesystem mounted as read-only or CD or floppy with the readonly switch active or NTFS partition without ntfs-3g driver)? Can you write to this file from outside python (try echo-ing to the file)? What's the permission of the folder? The output of your 'df' shows that you only have one partition (for root) and nothing else; it is quite uncommon for linux/unix to be setup with only one partition, you didn't trim anything right? /sys is not a block-device, it's similar to /proc (or replaces it, I forgot). It displays system-information and device-trees and whatnot, and some of those files can be written to change settings. I think the error the OP sees is a mis-interpretion or unlucky re-map of an error-code the kernel gives when things go wrong, I can only guess but maybe he writes to fast to the files, or to often. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: XML root node attributes
Thanks But this doesn't work. I've ended using something like this: import xml.etree.ElementTree as ET root = ET.Element(root, dict(a='v', b='v2', c='v3')) n = ET.SubElement(root,'d') tree = ET.ElementTree(root) import sys tree.write(sys.stdout) On 17 Lis, 15:36, Stefan Behnel stefan...@behnel.de wrote: Slafs, 17.11.2009 15:19: I'm little confused about adding attributes to the root node when creating an XML document. Can I do this using minidom or something else. Yes, you /can/, but you /should/ use something else. I can't find anything that would fit my needs. i would like to have something like this: ?xml ... ? root a=v b=v2 c=v3 d ... /d /root Use ElementTree: import xml.etree.ElementTree as ET root = ET.Element(root, dict(a='v', b='v2', c='v3')) root.SubElement('d') print ET.tostring(root) Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Language mavens: Is there a programming with if then else ENDIF syntax?
On the topic of switch statements and even-more-concise-then-we-have- already if/elif/else/end constructs, I have to say that Python does occasionally force you to write code like the code below. Maybe force is too strong a word, but Python lends itself to if/elif blocks like below, which get the job done just fine, but which are not syntactically pretty, due to the (el){0,1}if kind == duplication. There are often cases where if/elif statements are just a smell that you do not know how to do dictionary lookups, but if you converted the below code to use dictionary lookups, you would complicate the code almost as much as you abstracted the code, if not more, unless I am just being very naive. Anonymous methods would help to a certain degree. I am not saying I want either anonymous methods or switch statements, but the lack of either in a language leads to very procedural looking code when you use number-of-lines-of-code as a (possibly dubious) metric. Maybe this excerpt can be golfed down to something simpler, I would love to see it! if kind == 'dict': return dictionary_schema(ast) elif kind == 'list': method = dictionary_schema(ast) return lambda lst: map(method, lst) elif kind == 'attr': return ((lambda obj: getattr(obj, ast.field)), ast.field) elif kind == 'key': return (lambda obj: obj.get(ast.field), ast.field) elif kind == 'as': method, old_name = schema(ast.parent) return (method, ast.synonym) elif kind == 'call': method, old_name = schema(ast.parent) def call(obj): return method(obj)() return (call, old_name) elif kind == 'recurse': expr = ast.expr kind = expr.kind method, field_name = schema(ast.parent) if kind in ['attr', 'key']: new_method, new_field_name = schema(expr) field_name = new_field_name elif kind in ['dict', 'list']: new_method = schema(expr) else: raise Exception('unknown kind!') def recurse(obj): obj = method(obj) return new_method(obj) return (recurse, field_name) else: raise Exception('unknown kind!') -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the difference between 'except IOError as e:' and 'except IOError, e:'
See also http://docs.python.org/dev/3.0/whatsnew/2.6.html#pep-3110-exception-handling-changes -- http://mail.python.org/mailman/listinfo/python-list
Re: Language mavens: Is there a programming with if then else ENDIF syntax?
On Wed, Nov 18, 2009 at 1:15 AM, Steve Howell showel...@yahoo.com wrote: On the topic of switch statements and even-more-concise-then-we-have- already if/elif/else/end constructs, I have to say that Python does occasionally force you to write code like the code below. Maybe force is too strong a word, but Python lends itself to if/elif blocks like below, which get the job done just fine, but which are not syntactically pretty, due to the (el){0,1}if kind == duplication. There are often cases where if/elif statements are just a smell that you do not know how to do dictionary lookups, but if you converted the below code to use dictionary lookups, you would complicate the code almost as much as you abstracted the code, if not more, unless I am just being very naive. I'm gonna have to disagree and say using the dictionary dispatch technique would clean it up a good bit. Yes, it would entail creating several functions, but those functions could then be documented (vs. the currently opaque code blocks); and due to their separation and smaller length, they would be easier to understand and test than the given code. Additionally, the sheer length of the given code segment probably constitutes a code smell in and of itself for the function containing that code. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
pygtk - icons?
Hi, please bear in mind that I'm an absolute newcomer to (py)gtk. I'm trying to install the nice synchronization tool http://live.gnome.org/Conduit which is written in Python and use pyGTK. This installed several icons e.g. /usr/share/icons/hicolor/16x16/apps/conduit.png When run, Conduit fails to find its icons. For testing purposes I've tried import gtk info=gtk.icon_theme_get_default().lookup_icon(conduit,16,0) which produces the error message GtkWarning: Could not find the icon 'conduit'. The 'hicolor' theme was not found either, perhaps you need to install it. You can get a copy from: http://icon-theme.freedesktop.org/releases On my Gentoo system lots of packages have placed icons under /usr/share/icons/hicolor So, what am I missing. Many thanks for a hint, Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Re: Language mavens: Is there a programming with if then else ENDIF syntax?
On Nov 18, 1:32 am, Chris Rebert c...@rebertia.com wrote: On Wed, Nov 18, 2009 at 1:15 AM, Steve Howell showel...@yahoo.com wrote: On the topic of switch statements and even-more-concise-then-we-have- already if/elif/else/end constructs, I have to say that Python does occasionally force you to write code like the code below. Maybe force is too strong a word, but Python lends itself to if/elif blocks like below, which get the job done just fine, but which are not syntactically pretty, due to the (el){0,1}if kind == duplication. There are often cases where if/elif statements are just a smell that you do not know how to do dictionary lookups, but if you converted the below code to use dictionary lookups, you would complicate the code almost as much as you abstracted the code, if not more, unless I am just being very naive. I'm gonna have to disagree and say using the dictionary dispatch technique would clean it up a good bit. Yes, it would entail creating several functions, but those functions could then be documented (vs. the currently opaque code blocks); and due to their separation and smaller length, they would be easier to understand and test than the given code. Additionally, the sheer length of the given code segment probably constitutes a code smell in and of itself for the function containing that code. If you introduce seven tiny little methods, aren't you increasing the length of the module by seven lines and introducing more complexity with the dispatch mechanism? (Actually, it's 14 lines more if you put a line of whitespace between your methods, and then you are also blurring an important cue that each of the seven code blocks all perform within the same context.) I do agree with your point that separate methods lead to easier unit testing. I'm a little more skeptical about the documentation/understanding argument, since code is often best understood within the context of surrounding code. I am also a bit skeptical of any coding technique that leads to lexical duplication like {'attr': process_attr, 'key': process_key, 'call': process_call}(ast); that is just replacing one smell with another. Of course, you could do something like __modules__ [kind](ast) too, but that gets a bit overly abstract for a simple dispatch. Having said all that, I'm gonna take your suggestion...thanks for the response! -- http://mail.python.org/mailman/listinfo/python-list
Re: A different take on finding primes
1) google list of prime numbers 2) see Prime numbers list in the results (number 3 in the results) 3) click link that leads towww.prime-numbers.org I found 455042511 prime numbers in approx 15 seconds. Not bad at all. How about using http://www.sagemath.org/ (written in Python). sage: time primes_first_n(10^7); CPU times: user 4.36 s, sys: 2.43 s, total: 6.79 s Wall time: 6.88 s That used 3G of RAM, you could certainly go higher if you have more memory. aht -- http://mail.python.org/mailman/listinfo/python-list
Re: TODO and FIXME tags
Scott David Daniels wrote: Martin P. Hellwig wrote: Ben Finney wrote: Chris Rebert c...@rebertia.com writes: 2009/11/16 Yasser Almeida Hernández pedro...@fenhi.uh.cu: How is the sintaxis for set the TODO and FIXME tags...? ... There's no widely-followed “syntax” for this convention, though. Except for _not_ doing what is suggested in those comments, which appears to be the biggest convention :-) Perhaps: The comments are a directive to delete the comment if you happen do this. --Scott David Daniels scott.dani...@acm.org I guess the world is split in two categories, those how come back to fix the TODO, and those how don't. I for myself belong to the second, that is why I never write TODO comments, I either do the stuff or consider this is not important enough to waste time on it. In other words I mostly agree with Martin, and envy people belonging to the first category. JM -- http://mail.python.org/mailman/listinfo/python-list
Re: Language mavens: Is there a programming with if then else ENDIF syntax?
On Nov 18, 1:32 am, Chris Rebert c...@rebertia.com wrote: On Wed, Nov 18, 2009 at 1:15 AM, Steve Howell showel...@yahoo.com wrote: On the topic of switch statements and even-more-concise-then-we-have- already if/elif/else/end constructs, I have to say that Python does occasionally force you to write code like the code below. Maybe force is too strong a word, but Python lends itself to if/elif blocks like below, which get the job done just fine, but which are not syntactically pretty, due to the (el){0,1}if kind == duplication. There are often cases where if/elif statements are just a smell that you do not know how to do dictionary lookups, but if you converted the below code to use dictionary lookups, you would complicate the code almost as much as you abstracted the code, if not more, unless I am just being very naive. I'm gonna have to disagree and say using the dictionary dispatch technique would clean it up a good bit. Yes, it would entail creating several functions, but those functions could then be documented (vs. the currently opaque code blocks); and due to their separation and smaller length, they would be easier to understand and test than the given code. Additionally, the sheer length of the given code segment probably constitutes a code smell in and of itself for the function containing that code. Here's the rewrite. The indirection from the definition of _dict to the first use of _dict is a little painful (36 lines away), but apart from that I am pleased with how the new code looks, so your points are well taken: kind = ast.kind def _dict(ast): return dictionary(ast, metavar) def _list(ast): ignore, code = dictionary(ast, 'item') code = '[%s for item in %s]' % (code, metavar) return label, code def _attr(ast): return ast.field, '%s.%s' % (metavar, ast.field) def _key(ast): return ast.field, '%s[%s]' % (metavar, repr(ast.field)) def _as(ast): ignore, parent = _code_generate(ast.parent, metavar) return ast.synonym, parent def _call(ast): parent_name, parent = _code_generate(ast.parent, metavar) parent += '()' return parent_name, parent def _recurse(ast): parent = ast.parent expr = ast.expr parent_name, parent = _code_generate(parent, metavar) kind = expr.kind if kind in ['attr', 'key', 'list']: parent_name, parent = _code_generate(expr, parent, parent_name) else: subparent_name, subparent = _code_generate(expr, parent_name) parent = '(lambda %s:\n' % parent_name + indent_block (subparent+')(%s)' % parent) return parent_name, parent dispatches = { 'dict': _dict, 'list': _list, 'attr': _attr, 'key': _key, 'as': _as, 'call': _call, 'recurse': _recurse, } if kind in dispatches: return dispatches[kind](ast) else: raise Exception('unknown kind!') Thanks! P.S. The underscores before the method names might look a little funny for inner methods, but it's the nature of the code..._dict and _list would lead to confusion with builtins, if not actual conflict. -- http://mail.python.org/mailman/listinfo/python-list
Re: Stagnant Frame Data?
On Nov 15, 1:36 pm, Terry Reedy tjre...@udel.edu wrote: Peter Otten wrote: Mike wrote: I'll apologize first for this somewhat lengthy example. It does however recreate the problem I've run into. This is stripped-down code from a much more meaningful system. I have two example classes, AutoChecker and Snapshot that evaluate variables in their caller's namespace using the frame stack. As written, the output is not what is expected: the variables evaluate to stagnant values. However, if the one indicated line is uncommented, then the result is as expected. So my questions are: Is this a bug in Python? No. The existence and use of sys._getframe -- notice the leading underscore -- is a CPython implementation artifact. Use at your own risk. Is this an invalid use of frame data? Up to you to decide. Why does the single line sys._getframe(1).f_locals fix the behavior? It updates the dictionary. A simplified demonstration of your problem: def f(update): ... a = locals() ... x = 42 ... if update: locals() ... print a ... f(False) {'update': False} f(True) {'a': {...}, 'x': 42, 'update': True} The local namespace is not a dictionary, and the locals()/f_locals dictionary contains a snapshot of the local namespace. Accessing the f_locals attribute is one way to trigger an update of that snapshot. What's puzzling is that the same dictionary is reused. Efficiency? Consistency? The doc for locals says locals() Update and return a dictionary representing the current local symbol table. In class statements, where (currently) the local namespace *is* a dict, no update is needed and locals() simply returns the dict, the same one each time. Terry Jan Reedy Thanks for the replies. If Peter's concise and much-appreciated example were to be modified as such: def f(update): .: a = inspect.stack()[0][0].f_locals .: x = 42 .: if update: .: inspect.stack()[0][0].f_locals .: print a .: f(False) {'update': False} f(True) {'a': {...}, 'x': 42, 'update': True} Now there's no use of locals() to perform its documented Update, but just a simple access of a dictionary. This behavior is curious. Further modification by accessing 'a' instead of '...f_locals' upon update produces: f(False) {'update': False} f(True) {'update': True} Checking the id() of 'a' and '...f_locals' shows the same address. How is it that '...f_locals' gets updated in this example? Is it done in stack()? Where exactly is the frame data stored prior to updating the dictionary and can I get to it? Thanks, Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Stagnant Frame Data?
On Nov 15, 1:36 pm, Terry Reedy tjre...@udel.edu wrote: Peter Otten wrote: Mike wrote: I'll apologize first for this somewhat lengthy example. It does however recreate the problem I've run into. This is stripped-down code from a much more meaningful system. I have two example classes, AutoChecker and Snapshot that evaluate variables in their caller's namespace using the frame stack. As written, the output is not what is expected: the variables evaluate to stagnant values. However, if the one indicated line is uncommented, then the result is as expected. So my questions are: Is this a bug in Python? No. The existence and use of sys._getframe -- notice the leading underscore -- is a CPython implementation artifact. Use at your own risk. Is this an invalid use of frame data? Up to you to decide. Why does the single line sys._getframe(1).f_locals fix the behavior? It updates the dictionary. A simplified demonstration of your problem: def f(update): ... a = locals() ... x = 42 ... if update: locals() ... print a ... f(False) {'update': False} f(True) {'a': {...}, 'x': 42, 'update': True} The local namespace is not a dictionary, and the locals()/f_locals dictionary contains a snapshot of the local namespace. Accessing the f_locals attribute is one way to trigger an update of that snapshot. What's puzzling is that the same dictionary is reused. Efficiency? Consistency? The doc for locals says locals() Update and return a dictionary representing the current local symbol table. In class statements, where (currently) the local namespace *is* a dict, no update is needed and locals() simply returns the dict, the same one each time. Terry Jan Reedy Thanks for the replies. If Peter's concise and much-appreciated example were to be modified as such: def f(update): .: a = inspect.stack()[0][0].f_locals .: x = 42 .: if update: .: inspect.stack()[0][0].f_locals .: print a .: f(False) {'update': False} f(True) {'a': {...}, 'x': 42, 'update': True} Now there's no use of locals() to perform its documented Update, but just a simple access of a dictionary. This behavior is curious. Further modification by accessing 'a' instead of '...f_locals' upon update produces: f(False) {'update': False} f(True) {'update': True} Checking the id() of 'a' and '...f_locals' shows the same address. How is it that '...f_locals' gets updated in this example? Is it done in stack()? Where exactly is the frame data stored prior to updating the dictionary and can I get to it? Thanks, Mike -- http://mail.python.org/mailman/listinfo/python-list
PyQt4 4.4.4 : a bug with highlightBlock ?
Hello everybody, I've been trying to do some syntax highlighting using PyQt4. I ported the example given in the documentation of Qt4 to Python. It works fine on my computer at work (which has PyQt4 version 4.3.3) but doesn't on my home computer (which has version 4.4.4) : it gets stuck in an infinite loop. Here is the code : class MyHighlighter(QtGui.QSyntaxHighlighter): def __init__(self, edit): QtGui.QSyntaxHighlighter.__init__(self,edit) def highlightBlock(self, text): myClassFormat = QtGui.QTextCharFormat() myClassFormat.setFontWeight(QtGui.QFont.Bold) myClassFormat.setForeground(QtCore.Qt.darkMagenta) pattern = \\b[A-Z_]+\\b expression = QtCore.QRegExp(pattern) index = text.indexOf(expression); while (index = 0): length = expression.matchedLength() self.setFormat(index, length, myClassFormat) index = text.indexOf(expression, index + length) What am I missing ? Is this a known bug of version 4.4.4 ? Thank you, Alexis. -- http://mail.python.org/mailman/listinfo/python-list
getting properly one subprocess output
Hi python fellows, I'm currently inspecting my Linux process list, trying to parse it in order to get one particular process (and kill it). I ran into an annoying issue: The stdout display is somehow truncated (maybe a terminal length issue, I don't know), breaking my parsing. import subprocess commandLine = ['ps', '-eo %p %U %P %y %t %C %c %a'] process = subprocess.Popen(commandLine, stdout=subprocess.PIPE, stderr=subprocess.PIPE) processList, stderrdata = process.communicate() Here is a sample of what I get in processList.split('\n'): ' 25487 1122 4344 ? 7-17:48:32 2.5 firefox-bin /usr/lib/iceweasel/firefox-', ' 25492 1122 4892 pts/6 00:08 57.2 ipython /usr/bin/python /usr/bin/ip', As you can see, to complete process command line is truncated. Any clue on how to get the full version ? JM (python 2.5) -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Urwid 0.9.9 - Console UI Library
How did you make the html 'screenshots'? I guess you have some kind of urwid2html tool or some such or is it plain ncurses? It's all handled in the demo code. This is from tour.py: if urwid.web_display.is_web_request(): screen = urwid.web_display.Screen() else: screen = urwid.raw_display.Screen() Thanks, I missed that. Urwid is really cool! No argument there :) None, indeed. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
Re: Accessing a Web server --- how?
This is what the History and Compare URL translates to: http://service.nordea.com/nordea-openpages/six.action?target=/nordea.public/bond/nordeabond.pagemagic=(cc+(detail+(tsid+310746)+(view+hist))) Some questions.. Do you have an idea on what the tsid is? It looks like it's a unique identifier for the chart and the only thing you'll need to change. Are you only interested in this chart or others? How would you like to extract the data? Is saving the chart enough or would you like to extract values from the chart? On Mon, Nov 16, 2009 at 11:14:26AM +0100, Virgil Stokes wrote: If one goes to the following URL: http://www.nordea.se/Privat/Spara%2boch%2bplacera/Strukturerade%2bprodukter/Aktieobligation%2bNr%2b99%2bEuropa%2bAlfa/973822.html it contains a link (click on Current courses NBD AT99 3113A) to: http://service.nordea.com/nordea-openpages/six.action?target=/nordea.public/bond/nordeabond.pagemagic=%28cc+%28detail+%28tsid+310746%29%29%29; and if you now click on the tab labeled history and compare this will take you to: http://service.nordea.com/nordea-openpages/six.action?target=/nordea.public/bond/nordeabond.pagemagic=%28cc+%28detail+%28tsid+310746%29+%28view+hist%29%29%29; Finally...This is where I would like to connect to the data on a daily basis or to gather data over different time intervals. I believe that if I can get some help on this, then I will be able to customize the code as needed for my own purposes. It should be clear that this is financial data on a fond managed by Nordea Bank AB. Nordea is one of the largest banks in Scandinavia. Note, that I do have some experience with Python (2.6 mainly), and find it a very useful and powerful language. However, I have no experience with it in the area of Web services. Any suggestions/comments on how to set up this financial data service project would be greatly appreciated, and I would be glad to share this project with any interested parties. Note, I posted a similar message to the list pywebsvcs; but, received no responses. -- V. Stokes -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: A different take on finding primes
On Tue, 17 Nov 2009 05:21, Tobiah wrote in comp.lang.python okgmm.17283$et3.3...@newsfe17.iad: Let me be clear, given 2min, how many primes can you find, they need not be in order or consecutive. Do they have to go from low to high? :( ) 1) google list of prime numbers 2) see Prime numbers list in the results (number 3 in the results) 3) click link that leads to www.prime-numbers.org I found 455042511 prime numbers in approx 15 seconds. Is that what you wanted? -- Nigel Rowe A pox upon the spammers that make me write my address like.. rho (snail) fisheggs (stop) name -- http://mail.python.org/mailman/listinfo/python-list
Re: Language mavens: Is there a programming with if then else ENDIFsyntax?
Dotan Cohen wrote: 2009/11/16 Steve Ferg steve.ferg.bitbuc...@gmail.com: I've often thought that a language with this kind of block-free syntax would be nice and intuitive: if condition then do stuff elif condition then do stuff else do stuff endif Note that you do not need block delimiters. Does anybody know a language with this kind of syntax for ifThenElseEndif? PHP has exactly this: if (condition) { // stuff } elseif (otherContition) { // otherStuff } elseif (yetAnotherCondition) { // yetOtherStuff } The OP explicitly said no block delimiters. Your example uses {..}, and doesn't have endif. -- Bartc -- http://mail.python.org/mailman/listinfo/python-list
Re: python simply not scaleable enough for google?
On 18 Nov, 00:31, Terry Reedy tjre...@udel.edu wrote: The problem for the future is the switch to multiple cores for further speedups. The GIL is not a big problem for scientists. Scientists are not so dependent on threads as the Java/webdeveloper crowd: - We are used to running multiple processes with MPI. - Numerical libraries running C/Fortran/Assembler will often release the GIL. Python threads are ok for multicores then. - Numerical libraries can be written or compiles for multicores e.g. using OpenMP or special compilers. If FFTW is compiled for multiple cores it does not matter that Python has a GIL. LAPACK will use multiple cores if you use MKL or GotoBLAS, regardless of the GIL. Etc. - A scientist used to MATLAB will think MEX function (i.e. C or Fortran) if something is too slow. A web developer used to Java will think multithreading. -- http://mail.python.org/mailman/listinfo/python-list
Re: python simply not scaleable enough for google?
On 18 Nov, 00:24, greg g...@cosc.canterbury.ac.nz wrote: NumPy, for example, is *extremely* flexible. Someone put in the effort, once, to write it and make it fast -- and now an endless variety of programs can be written very easily in Python to make use of it. I'm quite sure David Cournapeau knows about NumPy... By the way, NumPy is not particularly fast because of the way it is written. It's performance is hampered by the creation of temporary arrays. But NumPy provides a flexible way of managing memory in scientific programs. -- http://mail.python.org/mailman/listinfo/python-list
break LABEL vs. exceptions + PROPOSAL
I've found this email, back from 10 years ago: http://mail.python.org/pipermail/python-list/1999-September/009983.html I guess it went unnoticed, because that proposal looks really intresting. • break labels have been refused into python • we can do it anyway using exceptions • this is a proposal for something better, resembling the exception way and much more powerful and python-like than break labels -- http://mail.python.org/mailman/listinfo/python-list
Re: Language mavens: Is there a programming with if then else ENDIF syntax?
2009/11/17 sjm sjms...@gmail.com: On Nov 16, 12:54 pm, Steve Ferg steve.ferg.bitbuc...@gmail.com wrote: snip Does anybody know a language with this kind of syntax for ifThenElseEndif? Modern-day COBOL: IF some-condition do-something ELSE do-something-else END-IF. RPG/400's SELEC statement: http://bit.ly/2LDegk Thing of beauty. Cheers, Simon B. -- http://mail.python.org/mailman/listinfo/python-list
Re: break LABEL vs. exceptions + PROPOSAL
On Wed, Nov 18, 2009 at 4:05 AM, Lo'oris loo...@gmail.com wrote: I've found this email, back from 10 years ago: http://mail.python.org/pipermail/python-list/1999-September/009983.html I guess it went unnoticed, because that proposal looks really intresting. • break labels have been refused into python • we can do it anyway using exceptions • this is a proposal for something better, resembling the exception way and much more powerful and python-like than break labels You're gonna have to wait 18-24 months: http://www.python.org/dev/peps/pep-3003/ Also, the python-ideas list might be a better forum for discussing this than the general-interest list: http://mail.python.org/mailman/listinfo/python-ideas Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: a mini-language for encapsulating deep-copy operations on Python data structures
Steve Howell wrote: During the last few days I have written code in support of a small DDL language that encapsulates a concise representation of the manipulations needed to make a deep subcopy of a Python-like data structure. It is inspired by syntax from mainstream modern languages, including, of course, Python. The DDL can be converted to an AST. That AST can be walked to either generate Python code that expresses the mapping or to generate Python objects that can execute the mapping. Either of the prior outputs can then subsequently be applied to real world inputs to create new Python data structures from old ones, using the mechanisms specified in the original DDL for attribute access, dictionary lookup, iteration, method invocation, etc. Here is an example of the DDL (and I hate the terminology DDL, just cannot think of anything better): { 'show_table_of_contents', 'author' { .person 'name', .person 'location' as city, .favorite_books()[ .title, .cost() as expense ] as books} } There are more details here: http://showellonprogramming.blogspot.com/2009/11/more-on-python-deep-copy-schema.html Personally, I find the explicit approach more intuitive, since you immediately see what you are going to get: show_table_of_contents = context['show_table_of_contents'] author = context['author'] d = { 'show_table_of_contents': show_table_of_contents, 'author': { 'name': author.person['name'], 'city': author.person['location'], 'books': [{ 'title': item.title, 'expense': item.cost(), } for item in author.favorite_books()], }, } I particularly find this part non-intuitive: .favorite_books()[ .title, .cost() as expense ] as books} and would leave in the square brackets for __getitem__ lookups on these: .person 'name', .person 'location' as city, For additional inspiration, you might want to look at XSLT which provides similar transformations on XML data structures. There are also a number of other transformation languages: http://en.wikipedia.org/wiki/Model_Transformation_Language http://en.wikipedia.org/wiki/Data_transformation Regarding the term DDL: that's normally used for data definition language and doesn't really have all that much to do with transforming data. You normally define data structures using DDL - without actually putting data into those structures. Why not PyDTL Python data transformation language ?! -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Nov 18 2009) Python/Zope Consulting and Support ...http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ -- http://mail.python.org/mailman/listinfo/python-list
Minimally intrusive XML editing using Python
I wonder what Python XML library is best for writing a program that makes small modifications to an XML file in a minimally intrusive way. By that I mean that information the program doesn't recognize is kept, as are comments and whitespace, the order of attributes and even whitespace around attributes. In short, I want to be able to change an XML file while producing minimal textual diffs. Most libraries don't allow controlling the order of and the whitespace around attributes, so what's generally left to do is store snippets of original text along with the model objects and re-use that for writing the edited XML if the model wasn't modified by the program. Does a library exist that helps with this? Does any XML library at all allow structured access to the text representation of a tag with its attributes? Thank you very much. -- Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: Redirect stdout to a buffer [Errno 9]
On Nov 17, 6:51 am, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: The code below now reads from the pipe everything that has been written -- except from Python :( Thanks a lot for the fine code! So far I don't know why it fails to print from Python - I'll post here any news I get... -- http://mail.python.org/mailman/listinfo/python-list
Re: Minimally intrusive XML editing using Python
Thomas Lotze, 18.11.2009 13:55: I wonder what Python XML library is best for writing a program that makes small modifications to an XML file in a minimally intrusive way. By that I mean that information the program doesn't recognize is kept, as are comments and whitespace, the order of attributes and even whitespace around attributes. In short, I want to be able to change an XML file while producing minimal textual diffs. Take a look at canonical XML (C14N). In short, that's the only way to get a predictable XML serialisation that can be used for textual diffs. It's supported by lxml. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Minimally intrusive XML editing using Python
On Wed, Nov 18, 2009 at 4:55 AM, Thomas Lotze tho...@thomas-lotze.de wrote: I wonder what Python XML library is best for writing a program that makes small modifications to an XML file in a minimally intrusive way. By that I mean that information the program doesn't recognize is kept, as are comments and whitespace, the order of attributes and even whitespace around attributes. In short, I want to be able to change an XML file while producing minimal textual diffs. Most libraries don't allow controlling the order of and the whitespace around attributes, so what's generally left to do is store snippets of original text along with the model objects and re-use that for writing the edited XML if the model wasn't modified by the program. Does a library exist that helps with this? Does any XML library at all allow structured access to the text representation of a tag with its attributes? Have you considered using an XML-specific diff tool such as: * One off this list: http://www.manageability.org/blog/stuff/open-source-xml-diff-in-java * xmldiff (it's in Python even): http://www.logilab.org/859 * diffxml: http://diffxml.sourceforge.net/ [Note: I haven't actually used any of these.] Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Minimally intrusive XML editing using Python
Stefan Behnel wrote: Take a look at canonical XML (C14N). In short, that's the only way to get a predictable XML serialisation that can be used for textual diffs. It's supported by lxml. Thank you for the pointer. IIUC, c14n is about changing an XML document so that its textual representation is reproducible. While this representation would certainly solve my problem if I were to deal with input that's already in c14n form, it doesn't help me handling arbitrarily formatted XML in a minimally intrusive way. IOW, I don't want the XML document to obey the rules of a process, but instead I want a process that respects the textual form my input happens to have. -- Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: Minimally intrusive XML editing using Python
Chris Rebert wrote: Have you considered using an XML-specific diff tool such as: I'm afraid I'll have to fall back to using such a thing if I don't find a solution to what I actually want to do. I do realize that XML isn't primarily about its textual representation, so I guess I shouldn't be surprised if what I'm looking for doesn't exist. Still, it would be nice if it did... -- Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: ast manipulation
Terry, Thank you for responding. I actually figured out how to do this shortly after posting the message. Sorry I wasn't quite clear enough in my post, I will try to be a little more explict in the future. Just to mention it I want to go to each node in the ast including child nodes and change the values. I am making a limited mutation analysis program. If it looks generally useful as I get further along I will release the code. I did an early prototype that worked on the text of the code itself but I thought that using the ast for this would be better and maybe a little faster. Regards, Thomas -- http://mail.python.org/mailman/listinfo/python-list
Inserting Unicode text with MySQLdb in Python 2.4-2.5?
Hi all, I ran into a problem recently when trying to add support for earlier versions of Python (2.4 and 2.5) to some database related code which uses MySQLdb, and was wondering if anyone has any suggestions. With later versions of Python (2.6), inserting Unicode is very simple, e.g.: # -*- coding: utf-8 -*- ... cursor.execute('''INSERT INTO `table` VALUES (0, 'Ångström'),...''') When the same code is run on earlier versions, however, the results is either garbled text (e.g. Ã or ? instead of Å in Python 2.5), or an exception being thrown (Python 2.4): UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 60: ordinal not in range(128) So far I've tried a number of different things, including: 1. Using Unicode strings (e.g. u\u212B) 2. Manually specifying the encoding using sys.setdefaultencoding ('utf-8') 3. Manually enabling Unicode support in MySQLdb (use_unicode=False, charset = utf8) ...but no combination of any of the above resulted in proper database content. To be certain that the issue was related to Python/MySQLdb and not MySQL itself, I manually inserted the text and it worked just fine. Furthermore, when working in a Python console, both print Å and print u\u212B display the correct output. Any ideas? The versions of the MySQLdb adapter tested were 1.2.1 (Python 2.4), and 1.2.2-10 (Python 2.5). Thanks! Keith -- http://mail.python.org/mailman/listinfo/python-list
Re: Inserting Unicode text with MySQLdb in Python 2.4-2.5?
Keith Hughitt wrote: Hi all, I ran into a problem recently when trying to add support for earlier versions of Python (2.4 and 2.5) to some database related code which uses MySQLdb, and was wondering if anyone has any suggestions. With later versions of Python (2.6), inserting Unicode is very simple, e.g.: # -*- coding: utf-8 -*- ... cursor.execute('''INSERT INTO `table` VALUES (0, 'Ångström'),...''') You are aware that the coding-declaration only affects unicode-literals (the ones like ui'm unicode)? So the above insert-statement is *not* unicode, it's a byte-string in whatever encoding your editor happens to save the file in. And that's point two: make sure your editor reads and writes the file in the same encoding you specified in the comment in the beginning. When the same code is run on earlier versions, however, the results is either garbled text (e.g. Ã or ? instead of Å in Python 2.5), or an exception being thrown (Python 2.4): UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 60: ordinal not in range(128) Makes sense if the execute tries to encode to unicode first - as you didn't give it a unicode-object. So far I've tried a number of different things, including: 1. Using Unicode strings (e.g. u\u212B) 2. Manually specifying the encoding using sys.setdefaultencoding ('utf-8') 3. Manually enabling Unicode support in MySQLdb (use_unicode=False, charset = utf8) You *disabled* unicode here! Unicode is NOT utf-8!!! http://www.joelonsoftware.com/articles/Unicode.html ...but no combination of any of the above resulted in proper database content. To be certain that the issue was related to Python/MySQLdb and not MySQL itself, I manually inserted the text and it worked just fine. Furthermore, when working in a Python console, both print Å and print u\u212B display the correct output. Any ideas? The versions of the MySQLdb adapter tested were 1.2.1 (Python 2.4), and 1.2.2-10 (Python 2.5). Try the above, and better yet provide self-contained examples that show the behavior. Diez -- http://mail.python.org/mailman/listinfo/python-list
base64MIME problem, Or Just New Email Client
Hi; I'm using SimpleMail, available from SF, that used to work fine for me but now I can't build it on my new server. I get this error: [Tue Nov 17 09:53:13 2009] [error] [client 208.84.198.58] import smtplib, referer: http://globalsolutionsgroup.vi/display_spreadsheet.py [Tue Nov 17 09:53:13 2009] [error] [client 208.84.198.58] File /usr/lib64/python2.4/smtplib. py, line 49, in ?, referer: http://globalsolutionsgroup.vi/display_spreadsheet.py [Tue Nov 17 09:53:13 2009] [error] [client 208.84.198.58] from email.base64MIME import encode as encode_base64, referer: http://globalsolutionsgroup.vi/display_spreadsheet.py [Tue Nov 17 09:53:13 2009] [error] [client 208.84.198.58] ImportError: No module named base64MIME, referer: http://globalsolutionsgroup.vi/display_spreadsheet.py [Tue Nov 17 09:53:13 2009] [error] [client 208.84.198.58] Premature end of script headers: mail.py, referer: http://globalsolutionsgroup.vi/display_spreadsheet.py So, let's try this: [r...@13gems simplemail]# find . |xargs grep 'base64MIME' [r...@13gems simplemail]# What gives? Well, if there ain't no solving this one, can someone recommend a good client for easily generating emails from forms to inject into qmail? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: open source linux - windows database connectivity?
Woo-hoo! Forget ODBC. Got this working with Jython and JDBC drivers! On Nov 13, 1:03 am, M.-A. Lemburg m...@egenix.com wrote: TonySchmidtwrote: Note: The client part of this product is free. You only need to get a license for the server part. Yeah, but don't I need the server part to make the connection? Sure, but you don't need to get a license per client, unlike for e.g. the combination mxODBC + EasySoft OOB. Regards, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Nov 13 2009) Python/Zope Consulting and Support ... http://www.egenix.com/ mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ::: Try our new mxODBC.Connect Python Database Interface for free ! eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ -- http://mail.python.org/mailman/listinfo/python-list
best performance for storage of server information for python CGI web app?
I am wondering what will give me the best performance for storing information about the servers in our environment. currently i store all info about all servers in a single shelve file, but i have concerns. 1) as the size of the shelve file increases, will performance suffer ? 2) what about if 2 updates occur at the same time to the shelve file? when a shelve file is opened, is the whole file read into memory? if either scenario (1 or 2) is true, then should i think about creating a shelve file per server? i was also thinking about using SQL Lite with one DB to store all the info. with this option, i would not have to worry about concurrent updates, but as the file size increases, i could expect performance to suffer again? I am running Python 2.6 CGI scripts on Apache web server on windows platform. they interact with the current shelve file to pull info or request info from a python service which will go collect the info and put it into the shelve file. -- http://mail.python.org/mailman/listinfo/python-list
Re: IOError: [Errno 28] No space left on device
On 2009-11-18, hong zhang henryzhan...@yahoo.com wrote: Apparently the harddisk where you stored the file is full? It's not a real file, and takes up no space. I have plenty space see: $ df -l Filesystem 1K-blocks Used Available Use% Mounted on /dev/sda1 74027808 4910016 65357380 7% / That doesn't matter. /sys doesn't contain real files. It's an API to access kernel internals. but following is good. cont_tx = 1 for i in glob.glob('/sys/kernel/debug/ieee80211/phy*/iwlagn/data/continuous_tx'): with open(i, 'w') as f: print f, cont_tx Well, if that works, then what's your problem? -- Grant Edwards grante Yow! I wonder if I ought at to tell them about my visi.comPREVIOUS LIFE as a COMPLETE STRANGER? -- http://mail.python.org/mailman/listinfo/python-list
non-copy slices
Hi, I was looking for a facility similar to slices in python library that would avoid the implicit creation of a new list and copy of elements that is the default behaviour. Instead I'd rather have a lazy iteratable object on the original sequence. Well, in the end I wrote it myself but I was wondering if I missed sth in the library. If I didn't is there a particular reason there isn't sth like that? I find it hard to believe that all slice needs have strictly copy semantics. Cheers, Themis -- http://mail.python.org/mailman/listinfo/python-list
Re: non-copy slices
tbour...@doc.ic.ac.uk wrote: Hi, I was looking for a facility similar to slices in python library that would avoid the implicit creation of a new list and copy of elements that is the default behaviour. Instead I'd rather have a lazy iteratable object on the original sequence. Well, in the end I wrote it myself but I was wondering if I missed sth in the library. If I didn't is there a particular reason there isn't sth like that? I find it hard to believe that all slice needs have strictly copy semantics. I suspect that itertools is your friend, specifically itertools.islice TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: non-copy slices
Ahhh yes! that's exactly it. Thanks for pointing out! Themis On Wed, Nov 18, 2009 at 3:44 PM, Tim Golden m...@timgolden.me.uk wrote: tbour...@doc.ic.ac.uk wrote: Hi, I was looking for a facility similar to slices in python library that would avoid the implicit creation of a new list and copy of elements that is the default behaviour. Instead I'd rather have a lazy iteratable object on the original sequence. Well, in the end I wrote it myself but I was wondering if I missed sth in the library. If I didn't is there a particular reason there isn't sth like that? I find it hard to believe that all slice needs have strictly copy semantics. I suspect that itertools is your friend, specifically itertools.islice TJG -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: getting properly one subprocess output
On Nov 18, 11:25 am, Jean-Michel Pichavant jeanmic...@sequans.com wrote: Hi python fellows, I'm currently inspecting my Linux process list, trying to parse it in order to get one particular process (and kill it). I ran into an annoying issue: The stdout display is somehow truncated (maybe a terminal length issue, I don't know), breaking my parsing. import subprocess commandLine = ['ps', '-eo %p %U %P %y %t %C %c %a'] process = subprocess.Popen(commandLine, stdout=subprocess.PIPE, stderr=subprocess.PIPE) processList, stderrdata = process.communicate() Here is a sample of what I get in processList.split('\n'): ' 25487 1122 4344 ? 7-17:48:32 2.5 firefox-bin /usr/lib/iceweasel/firefox-', ' 25492 1122 4892 pts/6 00:08 57.2 ipython /usr/bin/python /usr/bin/ip', As you can see, to complete process command line is truncated. Any clue on how to get the full version ? JM (python 2.5) What about ps -eo pid,tty,cmd ? Sample: 12680 ?geany /usr/share/gramps/ReportBase/ _CommandLineReport.py 12682 ?gnome-pty-helper 12683 pts/0/bin/bash 13038 ?gnome-terminal 13039 ?gnome-pty-helper 13040 pts/1bash 13755 pts/1ps -eo pid,tty,cmd ...etc... hth, Jon. -- http://mail.python.org/mailman/listinfo/python-list
Re: getting properly one subprocess output
On Nov 18, 4:14 pm, Jon Clements jon...@googlemail.com wrote: On Nov 18, 11:25 am, Jean-Michel Pichavant jeanmic...@sequans.com wrote: Hi python fellows, I'm currently inspecting my Linux process list, trying to parse it in order to get one particular process (and kill it). I ran into an annoying issue: The stdout display is somehow truncated (maybe a terminal length issue, I don't know), breaking my parsing. import subprocess commandLine = ['ps', '-eo %p %U %P %y %t %C %c %a'] process = subprocess.Popen(commandLine, stdout=subprocess.PIPE, stderr=subprocess.PIPE) processList, stderrdata = process.communicate() Here is a sample of what I get in processList.split('\n'): ' 25487 1122 4344 ? 7-17:48:32 2.5 firefox-bin /usr/lib/iceweasel/firefox-', ' 25492 1122 4892 pts/6 00:08 57.2 ipython /usr/bin/python /usr/bin/ip', As you can see, to complete process command line is truncated. Any clue on how to get the full version ? JM (python 2.5) What about ps -eo pid,tty,cmd ? Sample: 12680 ? geany /usr/share/gramps/ReportBase/ _CommandLineReport.py 12682 ? gnome-pty-helper 12683 pts/0 /bin/bash 13038 ? gnome-terminal 13039 ? gnome-pty-helper 13040 pts/1 bash 13755 pts/1 ps -eo pid,tty,cmd ...etc... hth, Jon. Another thought: if you're only wanting to find and kill a process, what about pkill? Saves you having to filter the list in Python and then issue a kill command. Jon. -- http://mail.python.org/mailman/listinfo/python-list
using struct module on a file
Hia! I need to read a file containing packed binary data. For that, I find the struct module pretty convenient. What I always need to do is reading a chunk of data from the file (either using calcsize() or a struct.Struct instance) and then parsing it with unpack(). For that, I repeatedly write utility functions that help me do just that, but I can't imagine that there is no better way for that. Questions: 0. Am I approaching this from the wrong direction? I'm not a programming noob, but rather new to Python still. 1. The struct module has pack_into() or unpack_from(), could I somehow combine that with a file? 2. Is there some easier way to read files? I know about array and xdrlib, but neither really fit my desires. 3. Failing all that, would you consider this a useful addition to the struct module, i.e. should I write a feature request? Thanks! Uli -- http://mail.python.org/mailman/listinfo/python-list
question about tree in python
How should I write a tree using diconary. I have used a dictonary to make a tree. tree={best:collections.defaultdict(lambda:default)} in a id3 tree. Is there a way to multple values and when then only return on type of values. I tried this apporach but it did not work. class Tree: def __init__(self): pass def ini(self,default_tree,d_attr): self.tree={d_attr:collections.defaultdict(lambda:default_tree)} self.tree_A={d_attr:collections.defaultdict(lambda:default_tree)} self.tree_I={d_attr:collections.defaultdict(lambda:default_tree)} self.tree_p={d_attr:collections.defaultdict(lambda:default_tree)} self.tree_n={d_attr:collections.defaultdict(lambda:default_tree)} return self.tree def __call__(self,best,val,subtree): self.tree[best][val]=subtree def input_tree(self,best,val,subtree,postive,negative,attribute_value,info_gain): tree=self.tree print best print val tree[best][val]=subtree print self.tree self.tree_A[best][val]= attribute_value self.tree_I[best][val]= info_gain self.tree_p[best][val]= postive self.tree_n=negative tree=self.tree return tree -- http://mail.python.org/mailman/listinfo/python-list
Re: Beautifulsoup code that is not running
On Tue, 17 Nov 2009 14:38:55 -0800 (PST), Zeynel azeyn...@gmail.com wrote: [snip] from BeautifulSoup import BeautifulSoup soup = BeautifulSoup (file(test.html).read()) title = soup.find('title') titleString = title.string open('extract.text', 'w').write(titleString) This runs without an error, but nothing is written into the extract.text file. test.html has title/title tags in it. Hmm. Works for me, but of course I don't have your test.html. Why don't you try examining title and titleString? Perhaps title/title has resulted in titleString being the empty string. -- To email me, substitute nowhere-spamcop, invalid-net. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: a mini-language for encapsulating deep-copy operations on Python data structures
On Nov 18, 4:34 am, M.-A. Lemburg m...@egenix.com wrote: Steve Howell wrote: [...] Here is an example of the DDL (and I hate the terminology DDL, just cannot think of anything better): { 'show_table_of_contents', 'author' { .person 'name', .person 'location' as city, .favorite_books()[ .title, .cost() as expense ] as books} } There are more details here: http://showellonprogramming.blogspot.com/2009/11/more-on-python-deep-... Thanks for your feedback, Marc-Andre! Comments inline... Personally, I find the explicit approach more intuitive, since you immediately see what you are going to get: show_table_of_contents = context['show_table_of_contents'] author = context['author'] d = { 'show_table_of_contents': show_table_of_contents, 'author': { 'name': author.person['name'], 'city': author.person['location'], 'books': [{ 'title': item.title, 'expense': item.cost(), } for item in author.favorite_books()], }, } I understand what you mean about the explicit approach. When you go for brevity, you sacrifice some explicitness. One of the things I'm actually looking to do next is to be able to generate code like what you've written above. You could make the generated code even more procedural in terms of how it walks the structure--for example, replace the list comprehension with a for loop. This could be useful for inserting tracing code, for example. I particularly find this part non-intuitive: .favorite_books()[ .title, .cost() as expense ] as books} Yep, I think what I really want is this: .favorite_books()[{ .title, .cost() as expense }] as books} I am not sure the curlies make the transformation completely intuitive, but they are more suggestive that you are generating a list of dictionaries. and would leave in the square brackets for __getitem__ lookups on these: .person 'name', .person 'location' as city, Yep, I agree. The square brackets were not a deliberate omission. They were just slightly more tricky to implement because of '[' having double syntactical meaning. For additional inspiration, you might want to look at XSLT which provides similar transformations on XML data structures. There are also a number of other transformation languages: http://en.wikipedia.org/wiki/Model_Transformation_Languagehttp://en.wikipedia.org/wiki/Data_transformation Thanks for the links! Regarding the term DDL: that's normally used for data definition language and doesn't really have all that much to do with transforming data. You normally define data structures using DDL - without actually putting data into those structures. Why not PyDTL Python data transformation language ?! Yep, I like that suggestion. The language does indeed describe a transformation. In some ways I was wanting to think of it more broadly, in terms that the transformation also acts as a schema for any input objects. For example, you could use '{.title, .publisher, {.name} }' as a schema to validate that an object behaves like a book. I suppose that's still a transformation in an abstract sense, where the output is just True, False, or maybe even the slice of the transformation that can/cannot be executed. -- http://mail.python.org/mailman/listinfo/python-list
Re: using struct module on a file
On Nov 18, 4:42 pm, Ulrich Eckhardt dooms...@knuut.de wrote: Hia! I need to read a file containing packed binary data. For that, I find the struct module pretty convenient. What I always need to do is reading a chunk of data from the file (either using calcsize() or a struct.Struct instance) and then parsing it with unpack(). For that, I repeatedly write utility functions that help me do just that, but I can't imagine that there is no better way for that. Questions: 0. Am I approaching this from the wrong direction? I'm not a programming noob, but rather new to Python still. 1. The struct module has pack_into() or unpack_from(), could I somehow combine that with a file? 2. Is there some easier way to read files? I know about array and xdrlib, but neither really fit my desires. 3. Failing all that, would you consider this a useful addition to the struct module, i.e. should I write a feature request? Thanks! Uli First time I've seen zero based indexing for paragraph markers :) unpack_from() will work on anything that supports the buffer interface. To work with files you can use something like: my4chars = struct.Struct('4c') def struct_read(s, f): return s.unpack_from(f.read(s.size)) Which isn't hideously painful. Jon. -- http://mail.python.org/mailman/listinfo/python-list
Re: _winreg error on open key (64bit) - proper usage of _winreg.DisableReflectionKey
On Tue, Nov 17, 2009 at 19:59, Mark Hammond skippy.hamm...@gmail.comwrote: On 18/11/2009 6:29 AM, Randall Walls wrote: I don't believe so, but it seems like I'm in a catch 22, where I need to _winreg.OpenKey the key first before I can pass it to _winreg.DisableReflectionKey, but it doesn't exist, so I can't open it. I did find out that I can open the key using: hKey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, rSOFTWARE\ODBC\ODBC.INI\ DRSQL2000_mu0100\\, 0, _winreg.KEY_READ | _winreg.KEY_WOW64_64KEY) The 'trick' was adding _winreg.KEY_WOW64_64KEY, which apparently tells the system to look in the 64bit key area, and not under the Wow6432Node. That brings up problem #2, though... I can't seem to CREATE a key in the above path, and _winreg.CreateKey doesn't accept _winreg.KEY_WOW64_64KEY (in fact it doesn't accept any options other than key, sub_key). _winreg.CreateKey does work, it just puts the key in SOFTWARE\Wow6432Node\ODBC\ODBC.INI. So I'm in a quandry... I'd like to use one or the other, and not have to account for both. It looks like _winreg needs to be enhanced to make the RegCreateKeyEx API function available. It can be called via the win32api module of pywin32, or could also be called via ctypes. HTH, Mark Created http://bugs.python.org/issue7347 and added a patch which I think will solve the problem moving forward. -- http://mail.python.org/mailman/listinfo/python-list
Re: IOError: [Errno 28] No space left on device
--- On Wed, 11/18/09, Grant Edwards inva...@invalid.invalid wrote: From: Grant Edwards inva...@invalid.invalid Subject: Re: IOError: [Errno 28] No space left on device To: python-list@python.org Date: Wednesday, November 18, 2009, 9:22 AM On 2009-11-18, hong zhang henryzhan...@yahoo.com wrote: Apparently the harddisk where you stored the file is full? It's not a real file, and takes up no space. I have plenty space see: $ df -l Filesystem 1K-blocks Used Available Use% Mounted on /dev/sda1 74027808 4910016 65357380 7% / That doesn't matter. /sys doesn't contain real files. It's an API to access kernel internals. but following is good. cont_tx = 1 for i in glob.glob('/sys/kernel/debug/ieee80211/phy*/iwlagn/data/continuous_tx'): with open(i, 'w') as f: print f, cont_tx Well, if that works, then what's your problem? But error comes from following, above is good. That is point here. def do_cont_tx( is_start): global cont_tx_started, stdscr if is_start == START and not cont_tx_started: cont_tx = 1 for i in glob.glob('/sys/kernel/debug/ieee80211/phy*/iwlagn/data/continuous_tx'): with open(i, 'w') as f: print f, cont_tx -- visi.com PREVIOUS LIFE as a COMPLETE STRANGER? -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
DOM related question and problem
Hello, these day im making python script related with DOM. problem is these day many website structure is very complicate . what is best method to check DOM structure and path.. i mean...following is some example. what is best method to check can extract such like following info quickly? before i was spent much time to extract such info . and yes im also new to python and DOM. IE.Document.Frames(1).Document.forms('comment').value = 'hello' if i use DOM inspector, can i extract such info quickly ? if so would you show me some sample? here is some site . i want to extract some dom info. today i was spent all day long to extract what is dom info. but failed http://www.segye.com/Articles/News/Politics/Article.asp?aid=20091118001261ctg1=06ctg2=00subctg1=06subctg2=00cid=010101060 at the end of this page,can find some comment input box. i want to know what kind of dom element should have to use, such like IE.Document.Frames(1).Document.forms('comment').value = 'hello' anyhelp much appreciate thanks -- View this message in context: http://old.nabble.com/DOM-related-question-and-problem-tp26412730p26412730.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Urwid 0.9.9 - Console UI Library
I noticed that when run on a 256-color capable xterm, upon exiting the demo programs the colors in the bash shell are modified - e.g the bash prompt, the output of colored ls commands. For instance, due to my fiddling with dircolors, a file with executable flags on is normally displayed in light green and it now appears in bright green, presumably #00ff00. CJ -- http://mail.python.org/mailman/listinfo/python-list
Re: DOM related question and problem
On Wed, Nov 18, 2009 at 10:04 AM, elca high...@gmail.com wrote: Hello, these day im making python script related with DOM. problem is these day many website structure is very complicate . what is best method to check DOM structure and path.. i mean...following is some example. what is best method to check can extract such like following info quickly? before i was spent much time to extract such info . and yes im also new to python and DOM. IE.Document.Frames(1).Document.forms('comment').value = 'hello' if i use DOM inspector, can i extract such info quickly ? if so would you show me some sample? here is some site . i want to extract some dom info. today i was spent all day long to extract what is dom info. but failed http://www.segye.com/Articles/News/Politics/Article.asp?aid=20091118001261ctg1=06ctg2=00subctg1=06subctg2=00cid=010101060 at the end of this page,can find some comment input box. i want to know what kind of dom element should have to use, such like IE.Document.Frames(1).Document.forms('comment').value = 'hello' anyhelp much appreciate thanks This sounds suspiciously like a spambot. Why do you want to submit comments in an automated fashion exactly? Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: break LABEL vs. exceptions + PROPOSAL
Chris Rebert wrote: On Wed, Nov 18, 2009 at 4:05 AM, Lo'oris loo...@gmail.com wrote: I've found this email, back from 10 years ago: http://mail.python.org/pipermail/python-list/1999-September/009983.html I guess it went unnoticed, because that proposal looks really intresting. I think it went unnoticed because it is not very good, once looked at. • break labels have been refused into python • we can do it anyway using exceptions So the proposal is not needed • this is a proposal for something better, resembling the exception way and much more powerful and python-like than break labels It amounts to duplicating raise x...exception x as break xcontinue x in the name of aesthetics and supposed efficiency. There would be no new functionality nor any abbreviation of code. The semantics of break/continue as specific loop subcommands would be changed to 'use anyplace'. The OP gives as a reason the possibility of a typo creating a raise x ... except y mis-match. But a break x ... continue y mismatch is equally likely. Anyway, I think the example given would be better written with immediate assignment followed by simple break, rather than the proposed delayed assignment. The exception example as given would have to be rewritten to work in 3.x. You're gonna have to wait 18-24 months: http://www.python.org/dev/peps/pep-3003/ Also, the python-ideas list might be a better forum for discussing this than the general-interest list: http://mail.python.org/mailman/listinfo/python-ideas This is a fine place to discuss it. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: IOError: [Errno 28] No space left on device
hong zhang wrote: --- On Wed, 11/18/09, Grant Edwards inva...@invalid.invalid wrote: From: Grant Edwards inva...@invalid.invalid Subject: Re: IOError: [Errno 28] No space left on device To: python-list@python.org Date: Wednesday, November 18, 2009, 9:22 AM On 2009-11-18, hong zhang henryzhan...@yahoo.com wrote: Apparently the harddisk where you stored the file is full? It's not a real file, and takes up no space. I have plenty space see: $ df -l Filesystem 1K-blocks Used Available Use% Mounted on /dev/sda1 74027808 4910016 65357380 7% / That doesn't matter. /sys doesn't contain real files. It's an API to access kernel internals. but following is good. cont_tx = 1 for i in glob.glob('/sys/kernel/debug/ieee80211/phy*/iwlagn/data/continuous_tx'): with open(i, 'w') as f: print f, cont_tx Well, if that works, then what's your problem? But error comes from following, above is good. That is point here. def do_cont_tx( is_start): global cont_tx_started, stdscr if is_start == START and not cont_tx_started: cont_tx = 1 for i in glob.glob('/sys/kernel/debug/ieee80211/phy*/iwlagn/data/continuous_tx'): with open(i, 'w') as f: print f, cont_tx -- cont_x -- doesn't work. So the above can't be the actual code. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Minimally intrusive XML editing using Python
Thomas Lotze wrote: Chris Rebert wrote: Have you considered using an XML-specific diff tool such as: I'm afraid I'll have to fall back to using such a thing if I don't find a solution to what I actually want to do. I do realize that XML isn't primarily about its textual representation, so I guess I shouldn't be surprised if what I'm looking for doesn't exist. Still, it would be nice if it did... Thomas, I just might have what you are looking for. But I want to be sure I understand your problem. So, please show a small sample and explain how you want it modified. Frederic -- http://mail.python.org/mailman/listinfo/python-list
Re: Command line arguments??
On Tue, 17 Nov 2009 23:57:55 +, Rhodri James wrote: Quote the filenames or escape the spaces: C:\Python26\Python.exe C:\echo.py C:\New Folder\text.txt We've been living with this pain ever since windowed GUIs encouraged users to put spaces in their file names (Apple, I'm looking at you!). Fundamentally, if people want the pretty they have to live with the consequences. We've been living with much worse ever since Unix allowed users to put not only spaces but even newlines in their filenames. You'll notice I said encouraged, not allowed. You'll notice I said allowed, not encouraged. Code which can't handle spaces in filenames is broken from the outset; it doesn't suddenly break the first time that someone passes a filename containing spaces. I have a suspicion that Win95 put spaces in two of the most important directory names specifically to force developers to deal with this. Nowadays, any Windows program which cannot handle spaces in pathnames is usually a port of a Unix program (and a shoddy one at that). OTOH, I'm surprised at how much Windows software still cannot handle filenames outside of the system codepage (i.e. it's using the byte-oriented API rather than the Unicode API). -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling Python functions from Excel
On 18 lis, 03:09, Mark Tolonen metolone+gm...@gmail.com wrote: Chris Withers ch...@simplistix.co.uk wrote in message news:4b02d1e3.6080...@simplistix.co.uk... Mark Tolonen wrote: Please I need Calling Python functions from Excel and receive result back in Excel. Can me somebody advise simplest solution please? I am more VBA programmer than Python. Tryhttp://code.google.com/p/pyinex/ The book Python: Programming on Win32 has a whole chapter on COM, and a section on COM servers. ...and it's generally accepted that COM sucks rocks through straws, so explore alternatives when they're available ;-) Chris True, but as usual Python makes it pretty darn easy (requires PyWin32): - ex.py --- class Example(object): _public_methods_ = ['Add','Mul'] _reg_progid_ = 'MyPython.Example' _reg_clsid_ = '{insert_GUID_here}' def Add(self,a,b): return a+b def Mul(self,a,b): return a*b if __name__ == '__main__': import win32com.server.register win32com.server.register.UseCommandLine(Example) - -- Excel Macro -- Sub Testit() Set ex = CreateObject(MyPython.Example) Range(A1) = ex.Add(1, 2) Range(A2) = ex.Mul(3, 4) End Sub Just run the script to register the server. ex.py --unregister will remove it. -Mark Thanks very much. It works perfectly!!! :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: getting properly one subprocess output
On Wed, 18 Nov 2009 12:25:14 +0100, Jean-Michel Pichavant wrote: I'm currently inspecting my Linux process list, trying to parse it in order to get one particular process (and kill it). I ran into an annoying issue: The stdout display is somehow truncated (maybe a terminal length issue, I don't know), breaking my parsing. As you can see, to complete process command line is truncated. Any clue on how to get the full version ? If you only need it to work on Linux, you can just enumerate /proc/[1-9]*/exe or /proc/[1-9]*/cmdline. Or you can add -ww to ps to avoid truncating the output. Note that the /proc/*/exe report the actual executable. The command line reported by ps (from /proc/*/cmdline) can be modified by the program, so it doesn't necessarily reflect the program being run. -- http://mail.python.org/mailman/listinfo/python-list
Re: non-copy slices
tbour...@doc.ic.ac.uk wrote: Hi, I was looking for a facility similar to slices in python library that would avoid the implicit creation of a new list and copy of elements that is the default behaviour. Instead I'd rather have a lazy iteratable object on the original sequence. Well, in the end I wrote it myself but I was wondering if I missed sth in the library If I didn't is there a particular reason there isn't sth like that? I find it hard to believe that all slice needs have strictly copy semantics. It is a strict *shallow* copy. There is no copying of contents. That aside, you are right, hence itertools.islice as already mentioned. In the design of 3.0, I believe the idea was raised of making slices iterables in 3.0, just as was done for map, filter, and range. However, it would have been highly disruptive, and not save much space. Map and range create an unbounded number of new objects, rather than just a sequence of references to existing objects (or bytes or words for bytes and str slices). There is also the problem of virtual slices preventing garbage collection of the source sequence when it is not otherwise needed. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: IOError: [Errno 28] No space left on device
--- On Wed, 11/18/09, Grant Edwards inva...@invalid.invalid wrote: From: Grant Edwards inva...@invalid.invalid Subject: Re: IOError: [Errno 28] No space left on device To: python-list@python.org Date: Wednesday, November 18, 2009, 9:22 AM On 2009-11-18, hong zhang henryzhan...@yahoo.com wrote: Apparently the harddisk where you stored the file is full? It's not a real file, and takes up no space. I have plenty space see: $ df -l Filesystem 1K-blocks Used Available Use% Mounted on /dev/sda1 74027808 4910016 65357380 7% / That doesn't matter. /sys doesn't contain real files. It's an API to access kernel internals. but following is good. cont_tx = 1 for i in glob.glob('/sys/kernel/debug/ieee80211/phy*/iwlagn/data/continuous_tx'): with open(i, 'w') as f: print f, cont_tx Well, if that works, then what's your problem? But error comes from following, above is good. That is point here. def do_cont_tx( is_start): global cont_tx_started, stdscr if is_start == START and not cont_tx_started: cont_tx = 1 for i in glob.glob('/sys/kernel/debug/ieee80211/phy*/iwlagn/data/continuous_tx'): with open(i, 'w') as f: print f, cont_tx -- http://mail.python.org/mailman/listinfo/python-list
Re: IOError: [Errno 28] No space left on device
--- On Wed, 11/18/09, Diez B. Roggisch de...@nospam.web.de wrote: From: Diez B. Roggisch de...@nospam.web.de Subject: Re: IOError: [Errno 28] No space left on device To: python-list@python.org Date: Wednesday, November 18, 2009, 12:11 PM hong zhang wrote: --- On Wed, 11/18/09, Grant Edwards inva...@invalid.invalid wrote: From: Grant Edwards inva...@invalid.invalid Subject: Re: IOError: [Errno 28] No space left on device To: python-list@python.org Date: Wednesday, November 18, 2009, 9:22 AM On 2009-11-18, hong zhang henryzhan...@yahoo.com wrote: Apparently the harddisk where you stored the file is full? It's not a real file, and takes up no space. I have plenty space see: $ df -l Filesystem 1K-blocks Used Available Use% Mounted on /dev/sda1 74027808 4910016 65357380 7% / That doesn't matter. /sys doesn't contain real files. It's an API to access kernel internals. but following is good. cont_tx = 1 for i in glob.glob('/sys/kernel/debug/ieee80211/phy*/iwlagn/data/continuous_tx'): with open(i, 'w') as f: print f, cont_tx Well, if that works, then what's your problem? But error comes from following, above is good. That is point here. def do_cont_tx( is_start): global cont_tx_started, stdscr if is_start == START and not cont_tx_started: cont_tx = 1 for i in glob.glob('/sys/kernel/debug/ieee80211/phy*/iwlagn/data/continuous_tx'): with open(i, 'w') as f: print f, cont_tx -- cont_x -- doesn't work. So the above can't be the actual code. Sorry, -- is typo. -- http://mail.python.org/mailman/listinfo/python-list
Re: Minimally intrusive XML editing using Python
Thomas Lotze wrote: Chris Rebert wrote: Have you considered using an XML-specific diff tool such as: I'm afraid I'll have to fall back to using such a thing if I don't find a solution to what I actually want to do. I do realize that XML isn't primarily about its textual representation, so I guess I shouldn't be surprised if what I'm looking for doesn't exist. Still, it would be nice if it did... What's your real problem, or use case? Are you just concerned with diffing, or are others likely to read the xml, and want it formatted the way it already is? And how general do you need this tool to be? For example, if the only thing you're doing is modifying existing attributes or existing tags, the minimal change would be pretty unambiguous. But if you're adding tags, or adding content on what was an empty element, then the requirement gets fuzzy And finding an existing library for something fuzzy is unlikely. Sample input, change list, and desired output would be very useful. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Minimally intrusive XML editing using Python
On Wed, 18 Nov 2009 13:55:52 +0100, Thomas Lotze wrote: I wonder what Python XML library is best for writing a program that makes small modifications to an XML file in a minimally intrusive way. By that I mean that information the program doesn't recognize is kept, as are comments and whitespace, the order of attributes and even whitespace around attributes. In short, I want to be able to change an XML file while producing minimal textual diffs. Most libraries don't allow controlling the order of and the whitespace around attributes, so what's generally left to do is store snippets of original text along with the model objects and re-use that for writing the edited XML if the model wasn't modified by the program. Does a library exist that helps with this? Does any XML library at all allow structured access to the text representation of a tag with its attributes? Expat parsers have a CurrentByteIndex field, while SAX parsers have locators. You can use this to identify the portions of the input which need to be processed, and just copy everything else. One downside is that these only report either the beginning (Expat) or end (SAX) of the tag; you'll have to deduce the other side yourself. OTOH, diff is probably the wrong tool for the job. -- http://mail.python.org/mailman/listinfo/python-list
Re: python gui builders
On 2009-11-18, sturlamolden sturlamol...@yahoo.no wrote: GPL If it's an issue for your project, I suggest wxPython. It's cross-platform, fairly complete, and extensible. But the API is clunky compared to Qt. Dave Cook -- http://mail.python.org/mailman/listinfo/python-list
A Good Mailer
Hi; I need a good mailer that will enable me to mail email from web forms. Suggestions? TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list
Re: WindowsError is not available on linux?
In article mailman.599.1258510702.2873.python-l...@python.org, Peng Yu pengyu...@gmail.com wrote: It's not clear to me whether WindowsError is available on linux or not, after I read the document. Here's what I told a co-worker to do yesterday: if os.name == 'nt': DiskError = (OSError, WindowsError) else: DiskError = WindowsError try: disk_operation() except DiskError: logit() -- Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. --Brian W. Kernighan -- http://mail.python.org/mailman/listinfo/python-list
Re: IOError: [Errno 28] No space left on device
On 2009-11-18, Diez B. Roggisch de...@nospam.web.de wrote: hong zhang wrote: but following is good. cont_tx = 1 for i in glob.glob('/sys/kernel/debug/ieee80211/phy*/iwlagn/data/continuous_tx'): with open(i, 'w') as f: print f, cont_tx Well, if that works, then what's your problem? But error comes from following, above is good. That is point here. def do_cont_tx( is_start): global cont_tx_started, stdscr if is_start == START and not cont_tx_started: cont_tx = 1 for i in glob.glob('/sys/kernel/debug/ieee80211/phy*/iwlagn/data/continuous_tx'): with open(i, 'w') as f: print f, cont_tx -- cont_x -- doesn't work. So the above can't be the actual code. You never want to post the actual code you're running. That would make it too easy for people to help. -- Grant Edwards grante Yow! My mind is making at ashtrays in Dayton ... visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Language mavens: Is there a programming with if then else ENDIF syntax?
On Wed, Nov 18, 2009 at 4:15 AM, Steve Howell showel...@yahoo.com wrote: On the topic of switch statements and even-more-concise-then-we-have- already if/elif/else/end constructs, I have to say that Python does occasionally force you to write code like the code below. Maybe force is too strong a word, but Python lends itself to if/elif blocks like below, which get the job done just fine, but which are not syntactically pretty, due to the (el){0,1}if kind == duplication. There are often cases where if/elif statements are just a smell that you do not know how to do dictionary lookups, but if you converted the below code to use dictionary lookups, you would complicate the code almost as much as you abstracted the code, if not more, unless I am just being very naive. Anonymous methods would help to a certain degree. I am not saying I want either anonymous methods or switch statements, but the lack of either in a language leads to very procedural looking code when you use number-of-lines-of-code as a (possibly dubious) metric. Maybe this excerpt can be golfed down to something simpler, I would love to see it! if kind == 'dict': return dictionary_schema(ast) elif kind == 'list': method = dictionary_schema(ast) return lambda lst: map(method, lst) elif kind == 'attr': return ((lambda obj: getattr(obj, ast.field)), ast.field) elif kind == 'key': return (lambda obj: obj.get(ast.field), ast.field) elif kind == 'as': method, old_name = schema(ast.parent) return (method, ast.synonym) elif kind == 'call': method, old_name = schema(ast.parent) def call(obj): return method(obj)() return (call, old_name) elif kind == 'recurse': expr = ast.expr kind = expr.kind method, field_name = schema(ast.parent) if kind in ['attr', 'key']: new_method, new_field_name = schema(expr) field_name = new_field_name elif kind in ['dict', 'list']: new_method = schema(expr) else: raise Exception('unknown kind!') def recurse(obj): obj = method(obj) return new_method(obj) return (recurse, field_name) else: raise Exception('unknown kind!') This code is perhaps not a great example of your point. Every (el){0,1}if clause (other than the ones in the 'recurse' branch) end in return statements, so the el's are pointless. FWIW I might write it like so: class ASTthing: def processAST(self, ast, kind): try: method = getattr(self, 'do_' + kind) except AttributeError: raise Exception('unknown kind!') self.ast = ast return method() def do_dict(self): return dictionary_schema(self.ast) def do_list(self): method = dictionary_schema(self.ast) return lambda lst: map(method, lst) def do_attr(self): field_name = self.ast.field return lambda obj: getattr(obj, field_name), field_name def do_key(self): field_name = self.ast.field return lambda obj: obj.get(field_name), field_name def do_as(self): method, old_name = schema(self.ast.parent) return method, self.ast.synonym def do_call(self): method, old_name = schema(self.ast.parent) return lambda obj: method(obj)(), old_name def do_recurse(self): expr = self.ast.expr kind = expr.kind method, field_name = schema(self.ast.parent) if kind in 'attrkey': new_method, field_name = schema(expr) elif kind in 'dictlist': new_method = schema(expr) else: raise Exception('unknown kind!') def recurse(obj): obj = method(obj) return new_method(obj) return recurse, field_name IMO, that's more pythonic and less complicated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Language mavens: Is there a programming with if then else ENDIFsyntax?
The OP explicitly said no block delimiters. Your example uses {..}, and doesn't have endif. Just out of habit. I think that PHP, like C, lets you avoid the block deliminators so long as the block all fits on one line. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il -- http://mail.python.org/mailman/listinfo/python-list
Re: non-copy slices
Sth else that I noticed as I started using islice. The name is somewhat misleading. Having the slice part in the name I would expect it to imitate the functionality of normal slices. Random access, sub-slicing etc. However, it is only iteratable. Any particular reasons for that? My guess is that it's inside the itertools so it's meant only for iteration and not random access. However, as I told before the name implies the same functionality while the only thing they share is iteration. It's nothing in the library that completely imitates the slice without the copies, right? Cheers, Themis On Wed, Nov 18, 2009 at 6:49 PM, Terry Reedy tjre...@udel.edu wrote: tbour...@doc.ic.ac.uk wrote: Hi, I was looking for a facility similar to slices in python library that would avoid the implicit creation of a new list and copy of elements that is the default behaviour. Instead I'd rather have a lazy iteratable object on the original sequence. Well, in the end I wrote it myself but I was wondering if I missed sth in the library If I didn't is there a particular reason there isn't sth like that? I find it hard to believe that all slice needs have strictly copy semantics. It is a strict *shallow* copy. There is no copying of contents. That aside, you are right, hence itertools.islice as already mentioned. In the design of 3.0, I believe the idea was raised of making slices iterables in 3.0, just as was done for map, filter, and range. However, it would have been highly disruptive, and not save much space. Map and range create an unbounded number of new objects, rather than just a sequence of references to existing objects (or bytes or words for bytes and str slices). There is also the problem of virtual slices preventing garbage collection of the source sequence when it is not otherwise needed. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: WindowsError is not available on linux?
On Wed, Nov 18, 2009 at 2:53 PM, Aahz a...@pythoncraft.com wrote: In article mailman.599.1258510702.2873.python-l...@python.org, Peng Yu pengyu...@gmail.com wrote: It's not clear to me whether WindowsError is available on linux or not, after I read the document. Here's what I told a co-worker to do yesterday: if os.name == 'nt': DiskError = (OSError, WindowsError) else: DiskError = WindowsError try: disk_operation() except DiskError: logit() -- Shouldn't that be the other way? if os.name == 'nt': DiskError = OSError, WindowsError else : DiskError = OSError Aahz (a...@pythoncraft.com) * http://www.pythoncraft.com/ Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. --Brian W. Kernighan -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Using setup.py for an application, not a library module.
Most of the documentation for setup.py assumes you're packaging a library module. (Ref: http://docs.python.org/distutils/setupscript.html;) How do you properly package an application? What happens on setup.py install? Where does the application get installed? Where does the main program go? If I package and build my app, it packages properly, and unpacks and builds into Messager1.0/build/lib which is appropriate for a library, but not an application. Here's the setup file. distutils.core.setup( name='Messager', description=Baudot Teletype RSS and SMS program, version='1.0', author=John Nagle, author_email=na...@animats.com, packages=['messager'], requires=['pyserial', 'feedparser'] ) John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Re: WindowsError is not available on linux?
On 07:53 pm, a...@pythoncraft.com wrote: In article mailman.599.1258510702.2873.python-l...@python.org, Peng Yu pengyu...@gmail.com wrote: It's not clear to me whether WindowsError is available on linux or not, after I read the document. Here's what I told a co-worker to do yesterday: if os.name == 'nt': DiskError = (OSError, WindowsError) else: DiskError = WindowsError try: disk_operation() except DiskError: logit() This isn't necessary. WindowsError subclasses OSError. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: python gui builders
On 18 Nov, 07:51, sturlamolden sturlamol...@yahoo.no wrote: GPL PyQT is GPL for now, but Qt itself is available under the LGPL as is PySide. Eventualy PySide, which tracks the PyQT API, will supplant it and the issue will be moot. For now it can be a problem, but PyQT developer licenses are very afordable at only a few hundred dollars. If a commercial project can't aford that, it's got problems. Only you can know enough to make an informed decision. Wx does look more usable than last time I used it for a project and is a fine option too, for me though QT is the gold standard against all others are measured, and generaly found wanting. Simon Hibbs -- http://mail.python.org/mailman/listinfo/python-list
Re: IOError: [Errno 28] No space left on device
--- On Wed, 11/18/09, Grant Edwards inva...@invalid.invalid wrote: From: Grant Edwards inva...@invalid.invalid Subject: Re: IOError: [Errno 28] No space left on device To: python-list@python.org Date: Wednesday, November 18, 2009, 2:00 PM On 2009-11-18, Diez B. Roggisch de...@nospam.web.de wrote: hong zhang wrote: but following is good. cont_tx = 1 for i in glob.glob('/sys/kernel/debug/ieee80211/phy*/iwlagn/data/continuous_tx'): with open(i, 'w') as f: print f, cont_tx Well, if that works, then what's your problem? But error comes from following, above is good. That is point here. def do_cont_tx( is_start): global cont_tx_started, stdscr if is_start == START and not cont_tx_started: cont_tx = 1 for i in glob.glob('/sys/kernel/debug/ieee80211/phy*/iwlagn/data/continuous_tx'): with open(i, 'w') as f: print f, cont_tx -- cont_x -- doesn't work. So the above can't be the actual code. You never want to post the actual code you're running. That would make it too easy for people to help. -- It is typo. http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: WindowsError is not available on linux?
Dave Angel wrote: Worse, even if the exception cannot be thrown on a non-Windows environment, leaving it undefined makes it very awkward to write portable code. An except clause that can never happen in a particular environment is pretty innocent. Or somebody can use a base class for his except clause, to catch this error and other related ones. But it blows up if you explicitly use this exception. I think that needs documentation, at a minimum. WindowsError is a subclass of OSError that contains additional Windows specific error information. Just catch OSError and you are on the safe side. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: non-copy slices
tbour...@doc.ic.ac.uk wrote: Hi, I was looking for a facility similar to slices in python library that would avoid the implicit creation of a new list and copy of elements that is the default behaviour. Instead I'd rather have a lazy iteratable object on the original sequence. Well, in the end I wrote it myself but I was wondering if I missed sth in the library. If I didn't is there a particular reason there isn't sth like that? I find it hard to believe that all slice needs have strictly copy semantics. Cheers, Themis Two questions: 1) What is sth? and 2), What copy? Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] In [1]: class dummy(object): ...: pass ...: In [2]: a = dummy() In [3]: b = dummy() In [4]: c = dummy() In [5]: d = dummy() In [6]: e = dummy() In [7]: list1 = [a, b, c, d, e] In [8]: list1 Out[8]: [__main__.dummy object at 0x0130C510, __main__.dummy object at 0x013F1A50, __main__.dummy object at 0x00A854F0, __main__.dummy object at 0x00A7EF50, __main__.dummy object at 0x00A7E650] In [9]: list2 = list1[1:3] In [10]: list2 Out[10]: [__main__.dummy object at 0x013F1A50, __main__.dummy object at 0x00A854F0] In [11]: list2[0] is list1[1] Out[11]: *True* In [12]: list2[1] is list1[2] Out[12]: *True* No copying of items going on here. What do you get? ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: python gui builders
On 17 Nov, 23:25, Kevin Walzer k...@codebykevin.com wrote: On 11/17/09 4:25 PM, Tim Daneliuk wrote: +1 Tkinter for the simple stuff You can actually use Tkinter to do quite sophisticated GUI's that rival anything found in Qt or wx... Neither Tkinteror Wx have anything that come close to QGraphicsView, the Model-View-Delegate framework, the Phonon multimedia framework integration, QtSQL, QtXML, QtSVG, and the many other first grade components in Qt. You can substitute components from other frameworks, e.g. for database access, but then you lose the integration QtSQL has with the model-view-delegate features in other parts of the Qt world. Qt is much more than just a GUI framework, it's more of a rival to something like the MacOS development libraries, or the .NET framework in terms of the library facilities it offers. I think that's why Nokia bought into it. Qt provides them with a platform with the potential to rival the iPhone dev environment. Of course to take full advantage of it you need to invest in learning it all, which is non-trivial. It comes at a cost in time and potential lock-in. But the point is you can't just say Qt is just like Wx. Simon Hibbs -- http://mail.python.org/mailman/listinfo/python-list
Re: python gui builders
Simon Hibbs simon.hi...@gmail.com writes: I've had this problem for a few years. I've tried PythonCard, WxWidgets with WxDesigner, BoaConstructor, etc. None of them come anywhere close to PyQT/QTDesigner. For me, the killer feature missing from of all of the wx-based designers is that they require sizer based designs at all stages, not even permitting a fixed layout up front as a first draft. Either that or any case I've found permitting a fixed layout, then didn't permit turning that easily into a sizer-based layout. From an overall design perspective, that was the feature I found most intriguing in QTDesigner. I could randomly drop stuff around the window while doing an initial layout, which is especially helpful when you aren't quite sure yet how you want the layout to look. Then you can select groups of objects and apply the containers to provide for flexible layout. I absolutely prefer sizer-based layouts for a final implementation, but early in the design stages find it more helpful, and freeing, not to be as tied to the containers. With that said, for various reasons I still prefer wxPython to Qt, and at the moment, find wxFormBuilder the best fit for my own designs (even before the direct Python support, just using XRC). -- David -- http://mail.python.org/mailman/listinfo/python-list
Re: Language mavens: Is there a programming with if then else ENDIF syntax?
On Wed, 18 Nov 2009 09:33:38 +0200, Dotan Cohen wrote: Is there any particular reason why this might be a *bad* language- design idea? It is about as far from OO as one could get. Whether or not that is bad depends on the use case. That's crazy talk. IF...ENDIF is *syntax*, not a programming model. How is this hypothetical Python-like syntax not object oriented? class Parrot: def speak(self): if self.name is None: name = Polly else: name = self.name endif return %s wants a cracker! % name Syntax controls *how* you instruct the compiler, the programming model controls *what* you instruct the compiler to do. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: WindowsError is not available on linux?
Benjamin Kaplan wrote: On Wed, Nov 18, 2009 at 2:53 PM, Aahz a...@pythoncraft.com wrote: In article mailman.599.1258510702.2873.python-l...@python.org, Peng Yu pengyu...@gmail.com wrote: It's not clear to me whether WindowsError is available on linux or not, after I read the document. Here's what I told a co-worker to do yesterday: if os.name ='nt': DiskError =OSError, WindowsError) else: DiskError =indowsError try: disk_operation() except DiskError: logit() -- Shouldn't that be the other way? if os.name ='nt': DiskError =SError, WindowsError else : DiskError =SError Doesn't matter. It's not needed anyway, since WindowsError is derived from OSError. So just use OSError in the except clause. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Solved: Inserting Unicode text with MySQLdb in Python 2.4-2.5?
-- Forwarded message -- From: Keith Hughitt keith.hugh...@gmail.com To: python-list@python.org Date: Wed, 18 Nov 2009 06:09:11 -0800 (PST) Subject: Inserting Unicode text with MySQLdb in Python 2.4-2.5? Hi all, I ran into a problem recently when trying to add support for earlier versions of Python (2.4 and 2.5) to some database related code which uses MySQLdb, and was wondering if anyone has any suggestions. With later versions of Python (2.6), inserting Unicode is very simple, e.g.: # -*- coding: utf-8 -*- ... cursor.execute('''INSERT INTO `table` VALUES (0, 'Ångström'),...''') When the same code is run on earlier versions, however, the results is either garbled text (e.g. Ã or ? instead of Å in Python 2.5), or an exception being thrown (Python 2.4): UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 60: ordinal not in range(128) So far I've tried a number of different things, including: 1. Using Unicode strings (e.g. u\u212B) 2. Manually specifying the encoding using sys.setdefaultencoding ('utf-8') 3. Manually enabling Unicode support in MySQLdb (use_unicode=False, charset = utf8) ...but no combination of any of the above resulted in proper database content. To be certain that the issue was related to Python/MySQLdb and not MySQL itself, I manually inserted the text and it worked just fine. Furthermore, when working in a Python console, both print Å and print u\u212B display the correct output. Any ideas? The versions of the MySQLdb adapter tested were 1.2.1 (Python 2.4), and 1.2.2-10 (Python 2.5). Thanks! Keith Hello Keithm, Here is your answer... I run on Python2.5, this syntax works fine for me -- a piece of my code: getMaxID_Query = SELECT MAX(customerID) FROM customer; self.cursorMySQL.execute(getMaxID_Query) Try to use: instead of ''' . It will solve your problem. ThreaderSlash -- http://mail.python.org/mailman/listinfo/python-list
Re: python gui builders
Simon Hibbs wrote: On 18 Nov, 07:51, sturlamolden sturlamol...@yahoo.no wrote: GPL PyQT is GPL for now, but Qt itself is available under the LGPL as is PySide. Eventualy PySide, which tracks the PyQT API, will supplant it and the issue will be moot. For now it can be a problem, but PyQT developer licenses are very afordable at only a few hundred dollars. If a commercial project can't aford that, it's got problems. Only you can know enough to make an informed decision. Wx does look more usable than last time I used it for a project and is a fine option too, for me though QT is the gold standard against all others are measured, and generaly found wanting. Simon Hibbs Wouldn't it be nice if each fan of some form of GUI-package, would post it's code (and resulting images) for generating one or two standard GUI-forms ? Then everyone can judge the differences, and see what's simple and not so simple !! And of course I'm willing to contribute the wxPython (wrapped in some convenience procedures) for it. cheers, Stef -- http://mail.python.org/mailman/listinfo/python-list
Re: Using setup.py for an application, not a library module.
On Nov 18, 2009, at 3:53 PM, John Nagle wrote: Most of the documentation for setup.py assumes you're packaging a library module. (Ref: http://docs.python.org/distutils/setupscript.html ) How do you properly package an application? What happens on setup.py install? Where does the application get installed? Where does the main program go? If I package and build my app, it packages properly, and unpacks and builds into Messager1.0/build/lib which is appropriate for a library, but not an application. Here's the setup file. distutils.core.setup( name='Messager', description=Baudot Teletype RSS and SMS program, version='1.0', author=John Nagle, author_email=na...@animats.com, packages=['messager'], requires=['pyserial', 'feedparser'] ) Hi John, I'm not sure what part you find unpalatable other than lib being in the pathname. I recently wrote a setup.py for an app called Analysis. Under OS X, Linux and Windows it installs into the site-packages directory so I can run it like so: python C:\Python25\Lib\site-packages\analysis\main.py or: python /usr/local/lib/python2.6/dist-packages/analysis/main.py Now, packaging an application according to the expectations of the platform to provide a double-clickable icon will require something like py2exe or py2app. distutils doesn't provide a facility for that. DOes that give you an idea about what you were asking? bye Philip -- http://mail.python.org/mailman/listinfo/python-list
Re: A Good Mailer
On Wed, Nov 18, 2009 at 03:27:11PM -0400, Victor Subervi wrote: Hi; I need a good mailer that will enable me to mail email from web forms. smtplib Suggestions? silly example.. #!/usr/bin/env python import smtplib session = smtplib.SMTP(localhost) username = abc password = def session.login(username, password) # only if it requires auth subject = Hello, header = Subject: %s \r\nContent-type: text/html; charset=utf-8\r\n\r\n message = world! email_from = vic...@is.awesome email_to = [em...@myhost.com] session.sendmail(email_from, email_to, header+messages) HTH, Nick Stinemates TIA, Victor -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: using struct module on a file
On Wed, Nov 18, 2009 at 11:42 AM, Ulrich Eckhardt dooms...@knuut.de wrote: Hia! I need to read a file containing packed binary data. For that, I find the struct module pretty convenient. What I always need to do is reading a chunk of data from the file (either using calcsize() or a struct.Struct instance) and then parsing it with unpack(). For that, I repeatedly write utility functions that help me do just that, but I can't imagine that there is no better way for that. Questions: 0. Am I approaching this from the wrong direction? I'm not a programming noob, but rather new to Python still. 1. The struct module has pack_into() or unpack_from(), could I somehow combine that with a file? 2. Is there some easier way to read files? I know about array and xdrlib, but neither really fit my desires. 3. Failing all that, would you consider this a useful addition to the struct module, i.e. should I write a feature request? Thanks! Uli You might look at Construct: http://construct.wikispaces.com/ ~Simon -- http://mail.python.org/mailman/listinfo/python-list
Re: python gui builders
On 11/18/09 4:15 PM, Simon Hibbs wrote: On 17 Nov, 23:25, Kevin Walzerk...@codebykevin.com wrote: On 11/17/09 4:25 PM, Tim Daneliuk wrote: +1 Tkinter for the simple stuff You can actually use Tkinter to do quite sophisticated GUI's that rival anything found in Qt or wx... Neither Tkinteror Wx have anything that come close to QGraphicsView, the Model-View-Delegate framework, the Phonon multimedia framework integration, QtSQL, QtXML, QtSVG, and the many other first grade components in Qt. You can substitute components from other frameworks, e.g. for database access, but then you lose the integration QtSQL has with the model-view-delegate features in other parts of the Qt world. A few points of response: -I was focusing primarily on the UI bits, not the other parts of Qt. People tend to think that Tkinter only has labels, listboxes, buttons and menus: recent advances in Tk have greatly expanded and modernized the available widgets. There's also a rich econsystem of widget packages within Tk that can be wrapped in Tkinter. -Qt's support for things like SQL and XML make sense in a Pythonic context mainly if you're focusing on their integration with other parts of Qt. Python has many of these things just fine on its own, as you doubtless know. Qt is much more than just a GUI framework, it's more of a rival to something like the MacOS development libraries, or the .NET framework in terms of the library facilities it offers. I think that's why Nokia bought into it. Qt provides them with a platform with the potential to rival the iPhone dev environment. Of course, and I certainly wasn't claiming otherwise. Of course to take full advantage of it you need to invest in learning it all, which is non-trivial. It comes at a cost in time and potential lock-in. But the point is you can't just say Qt is just like Wx. wxWidgets (the C++ library) has support for a lot of things other than UI bits, as well. wxPython itself is mainly a GUI library because the additional features of wxWidgets in C++ are redundant in Python. --Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Using setup.py for an application, not a library module.
On 11/18/09 9:53 PM, John Nagle wrote: Most of the documentation for setup.py assumes you're packaging a library module. (Ref: http://docs.python.org/distutils/setupscript.html;) How do you properly package an application? What happens on setup.py install? Where does the application get installed? Where does the main program go? Usually, just package the lib and from your main program (e.g. the script that goes in /usr/bin, for instance), do just something like that: #!/usr/bin/python from mylib import main import sys sys.exit(main()) -- Alan Franzoni contact me at pub...@[mysurname].eu -- http://mail.python.org/mailman/listinfo/python-list
Re: Language mavens: Is there a programming with if then else ENDIF syntax?
On Wed, 18 Nov 2009 01:53:50 -0800, Steve Howell wrote: On Nov 18, 1:32 am, Chris Rebert c...@rebertia.com wrote: On Wed, Nov 18, 2009 at 1:15 AM, Steve Howell showel...@yahoo.com wrote: On the topic of switch statements and even-more-concise-then-we-have- already if/elif/else/end constructs, I have to say that Python does occasionally force you to write code like the code below. Maybe force is too strong a word, but Python lends itself to if/elif blocks like below, which get the job done just fine, but which are not syntactically pretty, due to the (el){0,1}if kind == duplication. There are often cases where if/elif statements are just a smell that you do not know how to do dictionary lookups, but if you converted the below code to use dictionary lookups, you would complicate the code almost as much as you abstracted the code, if not more, unless I am just being very naive. I'm gonna have to disagree and say using the dictionary dispatch technique would clean it up a good bit. Yes, it would entail creating several functions, but those functions could then be documented (vs. the currently opaque code blocks); and due to their separation and smaller length, they would be easier to understand and test than the given code. Additionally, the sheer length of the given code segment probably constitutes a code smell in and of itself for the function containing that code. If you introduce seven tiny little methods, aren't you increasing the length of the module by seven lines and introducing more complexity with the dispatch mechanism? (Actually, it's 14 lines more if you put a line of whitespace between your methods, and then you are also blurring an important cue that each of the seven code blocks all perform within the same context.) Dear me, the 1960s called, they want their controversy over structured programming back *wink* Yes, you increase the length of the module by having function headers. You also increase the length of the module by using meaningful names instead of calling everything a, b, c etc. We're not playing code golf, there's no reward for making unreadable code. The dispatch mechanism is no more complicated than a series of if...elif statements. In fact, you can replace an arbitrary number of if x == y statements with a *single* lookup: if x == 1: return 27 elif x == 2: return 14 elif x == 5: return 7 else: return -1 becomes the single line: return {1: 27, 2: 14, 5: 7}.get(x, -1) (although for more complicated examples, you would put the dict into its own line, or even lines). Dispatching isn't a panacea. You can't (easily) replace a series of if...elif statements where the conditions being tested aren't equality tests, e.g.: if 0 = x = 1: return 27 elif 1 x 1.5 or x == 2: return 14 elif ... is hard to turn into a dispatcher. But it's still a very useful technique when it applies. I do agree with your point that separate methods lead to easier unit testing. I'm a little more skeptical about the documentation/understanding argument, since code is often best understood within the context of surrounding code. That depends on the code. In particular, it depends on how coupled the code is. Ideally, you should have loosely coupled code, not highly coupled. If the code is loosely coupled, then there's no problem with understanding it in isolation. If the code is highly coupled, then it is hard to refactor it into a separate function, but that's a side-effect of the original problem, namely the high degree of coupling. As a general rule, if you need to know the context of the surrounding code to understand a function, you have too much coupling. I am also a bit skeptical of any coding technique that leads to lexical duplication like {'attr': process_attr, 'key': process_key, 'call': process_call}(ast); that is just replacing one smell with another. But how is that different from this? if condition(x, 'attr'): return process_attr(x)(ast) elif condition(x, 'key'): return process_key(x)(ast) elif ... Lexical duplication is one of the weakest code smells around, because it is so prone to false negatives. You often can't avoid referring to the same lexical element multiple times: def sinc(x): if x != 0: return sin(x)/x return 1 That's four references to x in a four line function. Is this a problem? No, of course not. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: New syntax for blocks
On Wed, 18 Nov 2009 18:28:11 +1300, greg wrote: r wrote: I think the syntax was chosen because the alternatives are even worse AND since assignment is SO common in programming, would you *really* rather type two chars instead of one? Smalltalk solved the problem by using a left-arrow character for assignment. But they had an unfair advantage in being able to use a non-standard character set on their custom-built machines. We should be able to do a lot better now using Unicode. We could even heal the vs != rift by using a real not-equal symbol! The problem isn't with the available characters, but with *typing* them. It is hard to enter arbitrary Unicode characters by the keyboard, which frankly boggles my mind. I don't know what the state of the art on Mac is these days, but in 1984s Macs had a standard keyboard layout that let you enter most available characters via the keyboard, using sensible mnemonics. E.g. on a US keyboard layout, you could get ≠ by holding down the Option key and typing =. For me, I had to: Click Start menu Utilities More Applications KCharSelect. Click through thirty-four(!) tables scanning by eye for the symbol I wanted. Click the ≠ character. Click To Clipboard. Go back to my editor window and paste. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Arcane question regarding white space, editors, and code collapsing
I work in TextMate a lot, which I generally love, but it's code collapsing confounds me. Essentially you have to indent blank lines to the proper level for the current block. Then it will collapse that section as one section. If you have simply a new line, it will see it as a break, and not collapse, though the python interpreter doesn't care- it only cares about lines of actual code. Is it... pythonic, then, to have these lines of tabs/spaces to support code collapsing? Is it proper, improper, or irrelevant? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Arcane question regarding white space, editors, and code collapsing
Wells we...@submute.net writes: Is it... pythonic, then, to have these lines of tabs/spaces to support code collapsing? Is it proper, improper, or irrelevant? It's quite improper (though syntactically null, in Python) to have trailing whitespace on lines. That includes blank lines. One major reason is that trailing whitespace causes spurious invisible differences between otherwise-identical lines when doing an automatic comparison, which is done quite a lot in collaboration and version control. Fix your text editor (which may entail switching to a better text editor) to respect blank lines and the conventions of the language. -- \ “Hey Homer! You're late for English!” “Pff! English, who needs | `\ that? I'm never going to England!” —Barney Homer, _The | _o__)Simpsons_ | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Language mavens: Is there a programming with if then else ENDIF syntax?
On Nov 18, 2:22 pm, Steven D'Aprano ste...@remove.this.cybersource.com.au wrote: On Wed, 18 Nov 2009 02:06:49 -0800, Steve Howell wrote: P.S. The underscores before the method names might look a little funny for inner methods, but it's the nature of the code..._dict and _list would lead to confusion with builtins, if not actual conflict. Then name them something sensible that tells what they do! The convention (which you break at your peril) is that functions are verbs, and classes are nouns. Even handle_dict is better than _dict -- the latter looks like you're calling a private mapping type. Do you verbify functions with no side effects? Do you prefer calculate_cosine(angle) to cosine(angle)? -- http://mail.python.org/mailman/listinfo/python-list
Writing a Carriage Return in Unicode
Hi! I am trying to write a UTF-8 file of UNICODE strings with a carriage return at the end of each line (code below). filOpen = codecs.open(c:\\temp\\unicode.txt,'w','utf-8') str1 = u'This is a test.' str2 = u'This is the second line.' str3 = u'This is the third line.' strCR = u\u240D filOpen.write(str1 + strCR) filOpen.write(str2 + strCR) filOpen.write(str3 + strCR) filOpen.close() The output looks like This is a test.âThis is the second line.âThis is the third line.â when opened in Wordpad as a UNICODE file. Thanks for your help!! -- http://mail.python.org/mailman/listinfo/python-list