ANN: Pylint bug day, 2nd edition
Hi everyone we'll hold the next `pylint bugs day`_ on april 16th 2010 (friday). If some of you want to come and work with us in our `Paris office`_, you'll be much welcome. Else you can still join us on jabber / irc: * jabber: chat room pub...@jabber.logilab.org * irc: #public on irc://irc.logilab.org See you then! .. _pylint bugs day: https://www.logilab.net/elo/blogentry/18781 .. _paris office: http://www.logilab.fr/contact -- Alexandre Fayolle LOGILAB, Paris (France) Formations Python, CubicWeb, Debian : http://www.logilab.fr/formations Développement logiciel sur mesure : http://www.logilab.fr/services Informatique scientifique: http://www.logilab.fr/science -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations/
Re: Castrated traceback in sys.exc_info()
En Mon, 22 Mar 2010 15:20:39 -0300, Pascal Chambon chambon.pas...@wanadoo.fr escribió: Allright, here is more concretely the problem : ERROR:root:An error Traceback (most recent call last): File C:/Users/Pakal/Desktop/aaa.py, line 7, in c return d() File C:/Users/Pakal/Desktop/aaa.py, line 11, in d def d(): raise ValueError ValueError As you see, the traceback only starts from function c, which handles the exception. It doesn't show main(), a() and b(), which might however be (and are, in my case) critical to diagnose the severity of the problem (since many different paths would lead to calling c()). So the question is : is that possible to enforce, by a way or another, the retrieval of the FULL traceback at exception raising point, instead of that incomplete one ? Thanks for bringing this topic! I learned a lot trying to understand what happens. The exception traceback (what sys.exc_info()[2] returns) is *not* a complete stack trace. The sys module documentation is wrong [1] when it says ...encapsulates the call stack at the point where the exception originally occurred. The Language Reference is more clear [2]: Traceback objects represent a stack trace of an exception. A traceback object is created when an exception occurs. When the search for an exception handler unwinds the execution stack, at each unwound level a traceback object is inserted in front of the current traceback. When an exception handler is entered, the stack trace is made available to the program. That is, a traceback holds only the *forward* part of the stack: the frames already exited when looking for an exception handler. Frames going from the program starting point up to the current execution point are *not* included. Conceptually, it's like having two lists: stack and traceback. The complete stack trace is always stack+traceback. At each step (when unwinding the stack, looking for a frame able to handle the current exception) an item is popped from the top of the stack (last item) and inserted at the head of the traceback. The traceback holds the forward path (from the current execution point, to the frame where the exception was actually raised). It's a linked list, its tb_next attribute holds a reference to the next item; None marks the last one. The back path (going from the current execution point to its caller and all the way to the program entry point) is a linked list of frames; the f_back attribute points to the previous one, or None. In order to show a complete stack trace, one should combine both. The traceback module contains several useful functions: extract_stack() + extract_tb() are a starting point. The simplest way I could find to make the logging module report a complete stack is to monkey patch logging.Formatter.formatException so it uses format_exception() and format_stack() combined (in fact it is simpler than the current implementation using a StringIO object): code import logging import traceback def formatException(self, ei): Format and return the specified exception information as a string. This implementation builds the complete stack trace, combining traceback.format_exception and traceback.format_stack. lines = traceback.format_exception(*ei) if ei[2]: lines[1:1] = traceback.format_stack(ei[2].tb_frame.f_back) return ''.join(lines) # monkey patch the logging module logging.Formatter.formatException = formatException def a(): return b() def b(): return c() def c(): try: return d() except: logging.exception(An error) raise def d(): raise ValueError def main(): a() main() /code Output: ERROR:root:An error Traceback (most recent call last): File test_logging.py, line 32, in module main() File test_logging.py, line 30, in main a() File test_logging.py, line 19, in a def a(): return b() File test_logging.py, line 20, in b def b(): return c() File test_logging.py, line 23, in c return d() File test_logging.py, line 27, in d def d(): raise ValueError ValueError Traceback (most recent call last): File test_logging.py, line 32, in module main() File test_logging.py, line 30, in main a() File test_logging.py, line 19, in a def a(): return b() File test_logging.py, line 20, in b def b(): return c() File test_logging.py, line 23, in c return d() File test_logging.py, line 27, in d def d(): raise ValueError ValueError Note that both tracebacks are identical: the first comes from the patched logging module, the second is the standard Python one. [1] http://docs.python.org/library/sys.html#sys.exc_info [2] http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: GC is very expensive: am I doing something wrong?
On Mon, 22 Mar 2010 22:05:40 -0700, Paul Rubin wrote: Antoine Pitrou solip...@pitrou.net writes: Orders of magnitude worse, in any case, sounds very exaggerated. The worst case can lose orders of magnitude if a lot of values hash to the same bucket. Well, perhaps one order of magnitude. for i in xrange(100): ... n = 32*i+1 ... assert hash(2**n) == hash(2) ... d1 = dict.fromkeys(xrange(100)) d2 = dict.fromkeys([2**(32*i+1) for i in xrange(100)]) from timeit import Timer setup = from __main__ import d1, d2 t1 = Timer(for k in d1.keys(): x = d1[k], setup) t2 = Timer(for k in d2.keys(): x = d2[k], setup) min(t1.repeat(number=1000, repeat=5)) 0.026707887649536133 min(t2.repeat(number=1000, repeat=5)) 0.33103203773498535 -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with sys.path when embedding Python3 in C
En Mon, 22 Mar 2010 18:19:49 -0300, Krister Svanlund krister.svanl...@gmail.com escribió: Hi, I've recently begun experimenting with embedding python and i got a small problem. The following line here is the ugly-hack I had to do to make it work, nothing else I know of makes it possible to import modules from startup directory. So my question is: Is there a prettier way to do this? The startup directory is not included in the module search path - neither in your embedded version, nor in the standard interpreter (it's only included when running in interactive mode). PyRun_SimpleString(import sys\nsys.path.append(\\)); If you really want the current directory in sys.path, use the getcwd function to obtain it. But make sure this is what you want - the directory containing the executable might be a better choice (at least more predictable). Note that Python already provides lots of ways to add directories to sys.path (the default search path (see site.py), per-user site directories (see PEP370), .pth files, the PYTHONPATH and PYTHONHOME environment variables, the Windows registry, other ways I forgot...) So I'd ask why do you want to add a non-standard one. In C code, you can alter the initial search path by setting Py_SetProgramName and Py_SetPythonHome. And you may even completely replace getpathp.c source file with your own. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: individually updating unicodedata db?
En Mon, 22 Mar 2010 21:19:04 -0300, Vlastimil Brom vlastimil.b...@gmail.com escribió: I guess, I am stuck here, as I use the precompiled version supplied in the windows installer and can't compile python from source to obtain the needed unicodedata.pyd. You can recompile Python from source, on Windows, using the free Microsoft® Visual C++® 2008 Express Edition. http://www.microsoft.com/express/Windows/ Fetch the required dependencies using Tools\buildbot\external.bat, and then execute PCbuild\env.bat and build.bat. See readme.txt in that directory for details. It should build cleanly. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: logging: local functions == loss of lineno
On Mar 20, 8:36 am, Peter Otten __pete...@web.de wrote: Jean-Michel Pichavant wrote: You are still accessing the private attribute of the modulelogging. Just reading it is a significantly more conservative approach than setting it to an object with an unusual notion of equality ;) My previous remark was misleading, in fact there's nothing you can do about it. How about replacinglogging._srcfile with fixname(logging.__file__)? _srcfile is not meant to be used elsewhere than in theloggingmodule itself. However, I don't wanna sound like I'm rejecting this solution, 1st the OP is satisified with it and since this solution is working, it is still more helpful than anyone noticing that you've accessed a private attribute (some will successfully argue that python allows to do so). Yeah, I had hoped that I could get away without drawing the consenting adults wildcard... At the very begining of this thread I've provided a complete different approach, instead of using the builtin 'filename' and 'lineno' field of thelogging, use custom fileds with the extra parameter. It has also some drawbacks but could be a possible alternative. Having two filename/lineno sets ist likely to confuse. Peter Guys, Sorry I'm a little late to this discussion. I could add a _findCaller function to the module (not part of the public API, but replaceable by someone who really needs to) which does the heavy lifting, and Logger.findCaller just calls it. Then those who need to can implement their own strategy, without needing to jump through hoops. Does that approach sound helpful? Regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
Re: StringChain -- a data structure for managing large sequences of chunks of bytes
My apologies; I left out the heading on the last of the four structures in the benchmark results. Here are those results again with the missing heading (Stringy) inserted: Regards, Zooko - Hide quoted text - On Sun, Mar 21, 2010 at 11:09 PM, Zooko O'Whielacronx zoo...@gmail.com wrote: impl: StringChain task: _accumulate_then_one_gulp 1 best: 2.694e+00 5 best: 2.742e+00 10 best: 2.310e+00 50 best: 2.040e+00 100 best: 1.988e+00 500 best: 2.193e+00 task: _alternate_str 1 best: 6.509e+00 5 best: 4.559e+00 10 best: 4.308e+00 50 best: 4.070e+00 100 best: 3.991e+00 500 best: 4.000e+00 impl: SimplerStringChain task: _accumulate_then_one_gulp 1 best: 1.407e+00 5 best: 2.317e+00 10 best: 2.012e+00 50 best: 1.902e+00 100 best: 1.897e+00 500 best: 2.104e+00 task: _alternate_str 1 best: 4.888e+00 5 best: 5.198e+00 10 best: 1.750e+01 50 best: 6.233e+01 100 best: 1.134e+02 500 best: 7.599e+02 impl: StringIOy task: _accumulate_then_one_gulp 1 best: 4.196e+00 5 best: 5.522e+00 10 best: 4.499e+00 50 best: 3.756e+00 100 best: 4.176e+00 500 best: 5.414e+00 task: _alternate_str 1 best: 5.484e+00 5 best: 7.863e+00 10 best: 2.126e+01 50 best: 6.972e+01 100 best: 1.219e+02 500 best: 9.463e+02 impl: Stringy - Hide quoted text - task: _accumulate_then_one_gulp 1 best: 1.502e+00 5 best: 1.420e+01 10 best: 2.245e+01 50 best: 8.577e+01 100 best: 2.295e+02 500 best: 1.326e+03 task: _alternate_str 1 best: 3.290e+00 5 best: 4.220e+00 10 best: 1.665e+01 50 best: 6.281e+01 100 best: 1.127e+02 500 best: 7.626e+02 -- http://mail.python.org/mailman/listinfo/python-list
Re: GC is very expensive: am I doing something wrong?
Steven D'Aprano ste...@remove.this.cybersource.com.au writes: Well, perhaps one order of magnitude. for i in xrange(100): ... n = 32*i+1 ... assert hash(2**n) == hash(2) Try with much more than 100 items (you might want to construct the entries a little more intricately to avoid such big numbers). The point is that access becomes O(N) instead of O(1). See: http://www.cs.rice.edu/~scrosby/hash/ for the consequences. http://cr.yp.to/critbit.html discusses the issue a little more. -- http://mail.python.org/mailman/listinfo/python-list
Re: GC is very expensive: am I doing something wrong?
Steven D'Aprano wrote: On Mon, 22 Mar 2010 22:05:40 -0700, Paul Rubin wrote: Antoine Pitrou solip...@pitrou.net writes: Orders of magnitude worse, in any case, sounds very exaggerated. The worst case can lose orders of magnitude if a lot of values hash to the same bucket. Well, perhaps one order of magnitude. for i in xrange(100): ... n = 32*i+1 ... assert hash(2**n) == hash(2) ... d1 = dict.fromkeys(xrange(100)) d2 = dict.fromkeys([2**(32*i+1) for i in xrange(100)]) from timeit import Timer setup = from __main__ import d1, d2 t1 = Timer(for k in d1.keys(): x = d1[k], setup) t2 = Timer(for k in d2.keys(): x = d2[k], setup) min(t1.repeat(number=1000, repeat=5)) 0.026707887649536133 min(t2.repeat(number=1000, repeat=5)) 0.33103203773498535 But the ratio grows with the number of collisions: $ python extrapolate.py 10 0.00120401382446 0.00753307342529 ratio: 6.25663366337 100 0.00542402267456 0.316139936447 ratio: 58.2851428571 1000 0.00553417205811 3.36690688133 ratio: 608.384930209 $ cat extrapolate.py from timeit import Timer class Item(object): def __init__(self, value, hash=None): self.value = value self.hash = value if hash is None else hash def __eq__(self, other): return self.value == other.value def __hash__(self): return self.hash setup = from __main__ import d bench = for k in d: x = d[k] for n, number in (10,100), (100,100), (1000,10): print n d1 = dict.fromkeys(Item(i) for i in xrange(n)) d2 = dict.fromkeys(Item(i, 0) for i in xrange(n)) ab = [] for d in d1, d2: t = Timer(bench, setup) ab.append(min(t.repeat(number=number, repeat=3))) print ab[-1] print ratio:, ab[1]/ab[0] print See also http://xkcd.com/605/ Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: How to automate accessor definition?
John Posner a écrit : On 3/22/2010 11:44 AM, Bruno Desthuilliers wrote: snip Another (better IMHO) solution is to use a plain property, and store the computed value as an implementation attribute : @property def foo(self): cached = self.__dict__.get('_foo_cache') if cached is None: self._foo_cache = cached = self._some_time_consuming_operation() return cached There's no need to access __dict__ directly. Nope, inded. I guess I wrote it that way to make clear that we were looking for an instance attribute (as a sequel of my previous writing on attribute lookup rules). I believe this is equivalent (and clearer): @property def foo(self): try: cached = self._foo_cache except AttributeError: self._foo_cache = cached = self._time_consuming_op() return cached This is functionally _almost_ equivalent - won't work the same if there's a class attribute _foo_cache, which might or not be a good thing !-) Will possibly be a bit faster after the first access - IIRC setting up an error handler is by itself cheaper than doing a couple attribute access and a method call - but I'd timeit before worrying about it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with sys.path when embedding Python3 in C
On Tue, Mar 23, 2010 at 8:07 AM, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: En Mon, 22 Mar 2010 18:19:49 -0300, Krister Svanlund krister.svanl...@gmail.com escribió: Hi, I've recently begun experimenting with embedding python and i got a small problem. The following line here is the ugly-hack I had to do to make it work, nothing else I know of makes it possible to import modules from startup directory. So my question is: Is there a prettier way to do this? The startup directory is not included in the module search path - neither in your embedded version, nor in the standard interpreter (it's only included when running in interactive mode). PyRun_SimpleString(import sys\nsys.path.append(\\)); If you really want the current directory in sys.path, use the getcwd function to obtain it. But make sure this is what you want - the directory containing the executable might be a better choice (at least more predictable). Note that Python already provides lots of ways to add directories to sys.path (the default search path (see site.py), per-user site directories (see PEP370), .pth files, the PYTHONPATH and PYTHONHOME environment variables, the Windows registry, other ways I forgot...) So I'd ask why do you want to add a non-standard one. In C code, you can alter the initial search path by setting Py_SetProgramName and Py_SetPythonHome. And you may even completely replace getpathp.c source file with your own. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list The thing is that I want the application to be able to import modules I've written, but yeah, the applications directory is what I want rather than the cwd. I have tried Py_SetProgramName but haven't gotten it to work or cause any change at all to the import behaviour. Could you possibly provide som sort of example? -- http://mail.python.org/mailman/listinfo/python-list
Re: GC is very expensive: am I doing something wrong?
Paul Rubin, 23.03.2010 06:05: Antoine Pitrou writes: Orders of magnitude worse, in any case, sounds very exaggerated. The worst case can lose orders of magnitude if a lot of values hash to the same bucket. While this is theoretically true, and it's good to be aware of this possibility, common string hash functions make it so rare in practice that a hash table will almost always outperform a trie for exact lookups. If it happens, it will either show up clearly enough in benchmarks or not be worth bothering. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: GC is very expensive: am I doing something wrong?
Stefan Behnel stefan...@behnel.de writes: While this is theoretically true, and it's good to be aware of this possibility, common string hash functions make it so rare in practice that a hash table will almost always outperform a trie for exact lookups. If it happens, it will either show up clearly enough in benchmarks or not be worth bothering. It is unlikely to happen by accident. You might care that it can happen on purpose. See: http://www.cs.rice.edu/~scrosby/hash/ that I cited in another post. The article shows some sample attacks on Python cgi's. -- http://mail.python.org/mailman/listinfo/python-list
How to find the best solution ?
I have a text and would like to split the text into smaller parts, say into 100 characters each. But if the 100th character is not a blank ( but word) this must be less than 100 character.That means the word itself can not be split. These smaller parts must contains only whole( not split) words. I was thinking about RegEx but do not know how to find the correct Regular Expression. Can anyone help? Thanks L. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to find the best solution ?
On 23/03/2010 10:48, Johny wrote: I have a text and would like to split the text into smaller parts, say into 100 characters each. But if the 100th character is not a blank ( but word) this must be less than 100 character.That means the word itself can not be split. These smaller parts must contains only whole( not split) words. I was thinking about RegEx but do not know how to find the correct Regular Expression. Can anyone help? Thanks L. Have a look at the textwrap module TJG -- http://mail.python.org/mailman/listinfo/python-list
Some silly code for Easter holiday
This program simulates some colored balls moving around, changing color according to certain rules. I think the most interesting is perhaps to not look at this code but just try to run it and figure out the color changing rules from observing the effect (extra mystery: why I wrote this). Sort of like an Easter holiday mystery. code # Py3 # Copyright 2010 Alf P. Steinbach import tkinter as tk from collections import namedtuple import random Point = namedtuple( Point, x, y ) Size= namedtuple( Size, x, y ) RGB = namedtuple( RGB, r, g, b ) def generator( g ): assert isinstance( g, type( (i for i in ()) ) ) return g def tk_internal_bbox_from( bbox: tuple ): return ((bbox[0], bbox[1], bbox[2]+2, bbox[3]+2)) def tk_new_ellipse( canvas, bbox: tuple, **kwargs ): return canvas.create_oval( tk_internal_bbox_from( bbox ), **kwargs ) class TkTimer: def __init__( self, widget, msecs: int, action, start_running: bool = True ): self._widget = widget self._msecs = msecs self._action = action self._id = None if start_running: self.start() def start( self ): self._id = self._widget.after( self._msecs, self._on_timer ) def stop( self ): id = self._id; self._id = None self._widget.after_cancel( id ) # Try to cancel last event. def _on_timer( self ): if self._id is not None: self._action() self.start() class TkEllipse: def __init__( self, canvas, bbox: tuple, **kwargs ): self._canvas = canvas self._id = tk_new_ellipse( canvas, bbox, **kwargs ) @property # id def id( self ): return self._id @property # fill def fill( self ): return self._canvas.itemcget( self._id, fill ) @fill.setter def fill( self, color_representation: str ): self._canvas.itemconfigure( self._id, fill = color_representation ) @property # internal_bbox def internal_bbox( self ): return tuple( self._canvas.coords( self._id ) ) @property # position def position( self ): bbox = self.internal_bbox return Point( bbox[0], bbox[1] ) @position.setter def position( self, new_pos: Point ): bbox = self.internal_bbox (dx, dy) = (new_pos.x - bbox[0], new_pos.y - bbox[1]) self._canvas.move( self._id, dx, dy ) #assert self.position == new_pos class Color: def __init__( self, rgb_or_name ): if isinstance( rgb_or_name, RGB ): name = None rgb = rgb_or_name else: assert isinstance( rgb_or_name, str ) name = rgb_or_name rgb = None self._name = name self._rgb = rgb @property def representation( self ): if self._name is not None: return self._name else: rgb = self._rgb return #{:02X}{:02X}{:02X}.format( rgb.r, rgb.g, rgb.b ) def __str__( self ):return self.representation def __hash__( self ): return hash( self.representation ) class Rectangle: def __init__( self, width : int, height : int, upper_left : Point = Point( 0, 0 ) ): self._left = upper_left.x self._right = upper_left.x + width self._top = upper_left.y self._bottom = upper_left.y + height @property # left def left( self ): return self._left @property # top def top( self ):return self._top @property # right def right( self ): return self._right @property # bottom def bottom( self ): return self._bottom @property # width def width( self ): return self._right - self._left @property # height def height( self ): return self._bottom - self._top @property # size def size( self ): return Size( self.width, self.height ) class Ball: def __init__( self, color : Color, position: Point = Point( 0, 0 ), velocity: Point = Point( 0, 0 ) ): self.color = color self.position = position self.velocity = velocity def squared_distance_to( self, other ): p1 = self.position p2 = other.position return (p2.x - p1.x)**2 + (p2.y - p1.y)**2 class BallSim: def __init__( self, rect: Rectangle, n_balls : int = 1 ): def random_pos(): return Point( random.randrange( rect.left, rect.right ), random.randrange( rect.top, rect.bottom ) ) def random_velocity(): return Point( random.randint( -10, 10 ), random.randint( -10, 10 ) ) def balls( color ): return generator( Ball( color,
Re: short-circuiting any/all ?
kj wrote: Arguably, Knuth's premature optimization is the root of all evil applies even to readability (e.g. what's the point of making code optimally readable if one is going to change it completely next day?) The guy who will change it will have to read it. The only waste would be if the code would never be read again. If there were the equivalent of a profiler for code clutter, I guess I could relax my readability standards a bit... ~K Don't relax, just keep up :o) JM -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Pylint bug day, 2nd edition
On Monday 22 March 2010 18:38:07 Alexandre Fayolle wrote: .. _pylint bugs day: https://www.logilab.net/elo/blogentry/18781 Correct link is : http://www.logilab.org/blogentry/18781 Sorry for the inconvenience. -- Alexandre Fayolle LOGILAB, Paris (France) Formations Python, CubicWeb, Debian : http://www.logilab.fr/formations Développement logiciel sur mesure : http://www.logilab.fr/services Informatique scientifique: http://www.logilab.fr/science -- http://mail.python.org/mailman/listinfo/python-list
Re: SOAP 1.2 Python client ?
On 5 mar, 13:19, lbolla lbo...@gmail.com wrote: On Mar 5, 10:01 am, BlueBird p...@freehackers.org wrote: On 3 mar, 20:35, Stefan Behnel stefan...@behnel.de wrote: BlueBird, 03.03.2010 17:32: I am looking for aSOAP1.2 python client. To my surprise, it seems that this does not exist. Does anybody know about this ? SOAPmay be an overly bloated protocol, but it's certainly not black magic. It's not hard to do manually if you really need to: http://effbot.org/zone/element-soap.htm But this requires a goog knowloedge ofSOAP, in order to parse everything correctly. The reason I want to use a ready-made client is that I have about zero knowledge aboutSOAP, and even more in the differences betweenSOAP1.1 and 1.2 . cheers, Philippe I use a thin custom-made python wrapper around gSoap[1], which is tens of times faster than ZSI. I looked at gSoap and the solution seemed really nice. They can generate C that I can call with ctypes. The only problem is that I am working on a closed source software and their licensing cost for close source were too expensive for my company. After much much digging, we found out the problem and managed to solve it with SUDS. When calling a .NET service, you should not reference the soap envelope spec with 'http://schemas.xmlsoap.org/soap/ envelope/' but with 'http://schemas.xmlsoap.org/soap/envelope' . The .NET server implementation seems to be very picky about the last / . Yeah for SUDS and oh for .NET cheers, Philippe -- http://mail.python.org/mailman/listinfo/python-list
jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-
jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs application manager usa jobs for non us citizens on http://jobsinusa-net.blogspot.com/ jobs in usa for foreigners jobs in usa hotels jobs in usa for uk citizens usa jobs usa jobs in afghanistan usa jobs
Re: individually updating unicodedata db?
2010/3/23 Gabriel Genellina gagsl-...@yahoo.com.ar: En Mon, 22 Mar 2010 21:19:04 -0300, Vlastimil Brom vlastimil.b...@gmail.com escribió: I guess, I am stuck here, as I use the precompiled version supplied in the windows installer and can't compile python from source to obtain the needed unicodedata.pyd. You can recompile Python from source, on Windows, using the free Microsoft® Visual C++® 2008 Express Edition. http://www.microsoft.com/express/Windows/ Fetch the required dependencies using Tools\buildbot\external.bat, and then execute PCbuild\env.bat and build.bat. See readme.txt in that directory for details. It should build cleanly. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list Thanks for the hints; i probably screwed some steps up in some way, but the result seem to be working for the most part; I'll try to summarise it just for the record (also hoping to get further suggestions): I used the official source tarball for python 2.6.5 from: http://www.python.org/download/ In the unpacked sources, I edited the file: ...\Python-2.6.5-src\Tools\unicode\makeunicodedata.py import re # added ... # UNIDATA_VERSION = 5.1.0 # changed to: UNIDATA_VERSION = 5.2.0 Furthermore the following text files were copied to the same directory like makeunicodedata.py CompositionExclusions-3.2.0.txt EastAsianWidth-3.2.0.txt UnicodeData-3.2.0.txt UnicodeData.txt EastAsianWidth.txt CompositionExclusions.txt from http://unicode.org/Public/3.2-Update/ and http://unicode.org/Public/5.2.0/ucd/ furthermore there are some files in the subdirectories needed: ...\Python-2.6.5-src\Tools\unicode\Objects\unicodetype_db.h ...\Python-2.6.5-src\Tools\unicode\Modules\unicodedata_db.h ...\Python-2.6.5-src\Tools\unicode\Modules\unicodename_db.h After running makeunicodedata.py, the above headers are recreated from the new unicode database and can be copied to the original locations in the source ...\Python-2.6.5-src\Objects\unicodetype_db.h ...\Python-2.6.5-src\Modules\unicodedata_db.h ...\Python-2.6.5-src\Modules\unicodename_db.h (while keeping the backups) Trying to run ...\Python-2.6.5-src\Tools\buildbot\external.bat and other bat files, I got quite a few path mismatches resulting in file ... not found errors; However, I was able to just open the solution file in Visual C++ 2008 Express: C:\install\Python-2.6.5-src\PCbuild\pcbuild.sln set the build configuration to release and try to build the sources. There were some errors in particular modules (which might be due to my mistakes or ommissions, as this maybe shouldn't happen normally), but the wanted ...\Python-2.6.5-src\PCbuild\unicodedata.pyd was generated and can be used in the original python installation: C:\Python26\DLLs\unicodedata.pyd the newly added characters, cf.: http://www.unicode.org/Public/UNIDATA/DerivedAge.txt seem to be available ⅐ (dec.: 8528) (hex.: 0x2150) # ⅐ VULGAR FRACTION ONE SEVENTH (Number, Other) (dec.: 68352) (hex.: 0x10b00) # AVESTAN LETTER A (Letter, Other) but some are not present; I noticed this for the new CJK block - CJK Unified Ideographs Extension C (U+2A700..U+2B73F). Probably this new range isn't taken into account for some reason. All in all, I am happy to have the current version of the unicode database available; I somehow expected this to be more complicated, but on the other hand I can't believe this is the standard way of preparing the built versions (with all the copying,checking and and replacing the files); it might be possible, that the actual distribution is built using some different tools (the trivial missing import in makeunicodedata.py would be found immediately, I guess). I also wanted to ask, whether the missing characters might be a result of my error in updating the unicode database, or could it be a problem with the makeunicodedata.py itself? Thanks in advance and sorry for this long post. vbr -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 2.6.5
Thank you everyone for all the work that went into this update, but there may be a small problem with the Windows x86 installer. I've built and used python 2.6.5 on linux without any apparent problems, but the Windows x86 binary installer stops after compiling a few python source files. I've tried the Windows x86 installer on two differently configured Windows XP PCs (SP3 with patches), but I get the following errors during the advanced compiling of python source files: There is a problem with this Windows Installer package. A program run as part of the setup did not finish as expected. Contact your support personnel or package vendor. Python 2.6.5 Installer ended prematurely ... The md5sum of the Windows x86 installer matched the published value. I did not try not using the advanced option. I reinstalled python 2.6.4 on both of the PCs without any problems and used the advanced compile option. Is anyone else having trouble with the 2.6.5 Windows x86 installer? Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: device identification
On Mar 23, 9:22 am, Tim Roberts t...@probo.com wrote: Omer Ihsan omrih...@gmail.com wrote: i have installed pyusb now and run the sample usbenum.pyi have 3 usb ports on my PC but the results show 6 outputs to dev.filename..they are numbers like 001 or 005 etc and they changed when i plugged in devices...(i am no good with the usb standards)i just want to identify each device/port... what parameter in the example would help me You can't identify the ports.[1] What good would it do you? The ports on your PC are not numbered. You certainly CAN identify the devices, by their VID and PID (or idVendor and idProduct). You identify by function, not by location. When you plug in a USB drive, you don't want to worry about where it's plugged in. === [1]: OK, technically, it is not impossible to identify the port numbers, but it is quite tedious. You need to chase through the sysfs expansion of your buses hub/port tree and find a match for your device. It's not worth the trouble. -- Tim Roberts, t...@probo.com Providenza Boekelheide, Inc. VID and PID is fair enough. now what i want is that i have a threaded code that threads two functions to run at the same time. i want each function to run seperate devices. the problem is if it doesnt identify the attached devices it might run the code on a single device which isnt what is required. how will i be able to run a code on a device of my choice???you can leave away the threading part for now. -- http://mail.python.org/mailman/listinfo/python-list
Re: RELEASED Python 2.6.5
I just downloaded the installer and tested it on my win xp machine. The installer worked fine. -- Allan Davis Member of NetBeans Dream Team http://wiki.netbeans.org/NetBeansDreamTeam Lead Developer, nbPython http://wiki.netbeans.org/Python http://codesnakes.blogspot.com (my blog) Co-Chair, CajunJUG http://www.cajunjug.org On Tue, Mar 23, 2010 at 9:38 AM, pe...@psantoro.net wrote: Thank you everyone for all the work that went into this update, but there may be a small problem with the Windows x86 installer. I've built and used python 2.6.5 on linux without any apparent problems, but the Windows x86 binary installer stops after compiling a few python source files. I've tried the Windows x86 installer on two differently configured Windows XP PCs (SP3 with patches), but I get the following errors during the advanced compiling of python source files: There is a problem with this Windows Installer package. A program run as part of the setup did not finish as expected. Contact your support personnel or package vendor. Python 2.6.5 Installer ended prematurely ... The md5sum of the Windows x86 installer matched the published value. I did not try not using the advanced option. I reinstalled python 2.6.4 on both of the PCs without any problems and used the advanced compile option. Is anyone else having trouble with the 2.6.5 Windows x86 installer? Peter -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: GC is very expensive: am I doing something wrong?
Le Tue, 23 Mar 2010 02:57:56 -0700, Paul Rubin a écrit : It is unlikely to happen by accident. You might care that it can happen on purpose. See: http://www.cs.rice.edu/~scrosby/hash/ that I cited in another post. The article shows some sample attacks on Python cgi's. Certainly interesting in a purely academic point of view, but in real life if you want to cause a denial of service by overwhelming a server, there are far more obvious options than trying to guess the server's use of hash tables and trying to cause lots of collisions in them. -- http://mail.python.org/mailman/listinfo/python-list
Python is cool!!
I have been learning Python, and it is amazing I am using the tutorial that comes with the official distribution. At the end my goal is to develop applied mathematic in engineering applications to be published on the Web, specially on app. oriented to simulations and control systems, I was about to start learning Java but I found Python which seems easier to learn that Java. Would it be easy to integrate Python in Web pages with HTML? I have read many info on Internet saying it is, and I hope so Any opinion -- http://mail.python.org/mailman/listinfo/python-list
using message loop for hotkey capturing
Hi all, but mainly Tim Golden: Tim, I am using your wonderful message loop for keyboard input, the one on your site that you pointed me to a few months ago. It has been working perfectly as long as I had only one dictionary of keys mapping to one dictionary of functions, but now I want two of each. My program has different modes, which may have varying keystrokes, and I also have some global keystrokes which are the same across all modes, like exiting or switching modes. I cannot figure out how to make the message loop look in two dictionaries at onc. I tried using an if, saying that if action_to_take was not set in the mode-specific dictionary then look at the global dictionary, but it is like it is never looking in the global dictionary at all. I get no syntax errors or problems when running the program, so it has to be something in my logic. Go to http://www.gateway2somewhere.com/sw/main.pyw to see what I mean; the problem code is near the very bottom of the file. Thanks for any suggestions. Oh, please note that I indent one space per indentation level. -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is cool!!
On 23/03/2010 16:55, Jose Manuel wrote: I have been learning Python, and it is amazing I am using the tutorial that comes with the official distribution. At the end my goal is to develop applied mathematic in engineering applications to be published on the Web, specially on app. oriented to simulations and control systems, I was about to start learning Java but I found Python which seems easier to learn that Java. Would it be easy to integrate Python in Web pages with HTML? I have read many info on Internet saying it is, and I hope so You probably want to be looking at IronPython and Silverlight. In fact, the prolific Michael Foord has already produced an example of this, which gives you the Python tutorial online! http://trypython.org TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: using message loop for hotkey capturing
On 23/03/2010 17:01, Alex Hall wrote: Hi all, but mainly Tim Golden: Tim, I am using your wonderful message loop for keyboard input, the one on your site that you pointed me to a few months ago. It has been working perfectly as long as I had only one dictionary of keys mapping to one dictionary of functions, but now I want two of each. My program has different modes, which may have varying keystrokes, and I also have some global keystrokes which are the same across all modes, like exiting or switching modes. I cannot figure out how to make the message loop look in two dictionaries at onc. I tried using an if, saying that if action_to_take was not set in the mode-specific dictionary then look at the global dictionary, but it is like it is never looking in the global dictionary at all. I get no syntax errors or problems when running the program, so it has to be something in my logic. Go to http://www.gateway2somewhere.com/sw/main.pyw Happy to look, Alex, but that link's giving me a 404 at the moment TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Castrated traceback in sys.exc_info()
On Mar 23, 6:12 am, Gabriel Genellina gagsl-...@yahoo.com.ar wrote: En Mon, 22 Mar 2010 15:20:39 -0300, Pascal Chambon chambon.pas...@wanadoo.fr escribi�: Allright, here is more concretely the problem : ERROR:root:An error Traceback (most recent call last): File C:/Users/Pakal/Desktop/aaa.py, line 7, in c return d() File C:/Users/Pakal/Desktop/aaa.py, line 11, in d def d(): raise ValueError ValueError As you see, the traceback only starts from function c, which handles the exception. It doesn't show main(), a() and b(), which might however be (and are, in my case) critical to diagnose the severity of the problem (since many different paths would lead to calling c()). So the question is : is that possible to enforce, by a way or another, the retrieval of the FULL traceback at exception raising point, instead of that incomplete one ? Thanks for bringing this topic! I learned a lot trying to understand what happens. The exception traceback (what sys.exc_info()[2] returns) is *not* a complete stack trace. The sys module documentation is wrong [1] when it says ...encapsulates the call stack at the point where the exception originally occurred. The Language Reference is more clear [2]: Traceback objects represent a stack trace of an exception. A traceback object is created when an exception occurs. When the search for an exception handler unwinds the execution stack, at each unwound level a traceback object is inserted in front of the current traceback. When an exception handler is entered, the stack trace is made available to the program. That is, a traceback holds only the *forward* part of the stack: the frames already exited when looking for an exception handler. Frames going from the program starting point up to the current execution point are *not* included. Conceptually, it's like having two lists: stack and traceback. The complete stack trace is always stack+traceback. At each step (when unwinding the stack, looking for a frame able to handle the current exception) an item is popped from the top of the stack (last item) and inserted at the head of the traceback. The traceback holds the forward path (from the current execution point, to the frame where the exception was actually raised). It's a linked list, its tb_next attribute holds a reference to the next item; None marks the last one. The back path (going from the current execution point to its caller and all the way to the program entry point) is a linked list of frames; the f_back attribute points to the previous one, or None. In order to show a complete stack trace, one should combine both. The traceback module contains several useful functions: extract_stack() + extract_tb() are a starting point. The simplest way I could find to make theloggingmodule report a complete stack is to monkey patch logging.Formatter.formatException so it uses format_exception() and format_stack() combined (in fact it is simpler than the current implementation using a StringIO object): code importlogging import traceback def formatException(self, ei): Format and return the specified exception information as a string. This implementation builds the complete stack trace, combining traceback.format_exception and traceback.format_stack. lines = traceback.format_exception(*ei) if ei[2]: lines[1:1] = traceback.format_stack(ei[2].tb_frame.f_back) return ''.join(lines) # monkey patch theloggingmodulelogging.Formatter.formatException = formatException def a(): return b() def b(): return c() def c(): try: return d() except: logging.exception(An error) raise def d(): raise ValueError def main(): a() main() /code Output: ERROR:root:An error Traceback (most recent call last): File test_logging.py, line 32, in module main() File test_logging.py, line 30, in main a() File test_logging.py, line 19, in a def a(): return b() File test_logging.py, line 20, in b def b(): return c() File test_logging.py, line 23, in c return d() File test_logging.py, line 27, in d def d(): raise ValueError ValueError Traceback (most recent call last): File test_logging.py, line 32, in module main() File test_logging.py, line 30, in main a() File test_logging.py, line 19, in a def a(): return b() File test_logging.py, line 20, in b def b(): return c() File test_logging.py, line 23, in c return d() File test_logging.py, line 27, in d def d(): raise ValueError ValueError Note that both tracebacks are identical: the first comes from the patched loggingmodule, the second is the standard Python one. [1]http://docs.python.org/library/sys.html#sys.exc_info [2]
Re: using message loop for hotkey capturing
Sorry about that, it is fixed now. On 3/23/10, Tim Golden m...@timgolden.me.uk wrote: On 23/03/2010 17:01, Alex Hall wrote: Hi all, but mainly Tim Golden: Tim, I am using your wonderful message loop for keyboard input, the one on your site that you pointed me to a few months ago. It has been working perfectly as long as I had only one dictionary of keys mapping to one dictionary of functions, but now I want two of each. My program has different modes, which may have varying keystrokes, and I also have some global keystrokes which are the same across all modes, like exiting or switching modes. I cannot figure out how to make the message loop look in two dictionaries at onc. I tried using an if, saying that if action_to_take was not set in the mode-specific dictionary then look at the global dictionary, but it is like it is never looking in the global dictionary at all. I get no syntax errors or problems when running the program, so it has to be something in my logic. Go to http://www.gateway2somewhere.com/sw/main.pyw Happy to look, Alex, but that link's giving me a 404 at the moment TJG -- http://mail.python.org/mailman/listinfo/python-list -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap -- http://mail.python.org/mailman/listinfo/python-list
Re: How to find the best solution ?
Johny wrote: I have a text and would like to split the text into smaller parts, say into 100 characters each. But if the 100th character is not a blank ( but word) this must be less than 100 character.That means the word itself can not be split. These smaller parts must contains only whole( not split) words. I was thinking about RegEx but do not know how to find the correct Regular Expression. While I suspect you can come close with a regular expression: import re, random size = 100 r = re.compile(r'.{1,%i}\b' % size) # generate a random text string with a mix of word-lengths words = ['a', 'an', 'the', 'four', 'fives', 'sixsix'] data = ' '.join(random.choice(words) for _ in range(200)) # for each chunk of 100 characters (or fewer # if on a word-boundary), do something for bit in r.finditer(data): chunk = bit.group(0) print %i: [%s] % (len(chunk), chunk) it may have an EOF fencepost error, so you might have to clean up the last item. My simple test seemed to show it worked without cleanup though. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Unicode blues in Python3
I know that unicode is the way to go in Python 3.1, but it is getting in my way right now in my Unix scripts. How do I write a chr(253) to a file? #nntst2.py import sys,codecs mychar=chr(253) print(sys.stdout.encoding) print(mychar) ./nntst2.py ISO8859-1 ý ./nntst2.py nnout2 Traceback (most recent call last): File ./nntst2.py, line 5, in module print(mychar) UnicodeEncodeError: 'ascii' codec can't encode character '\xfd' in position 0: ordinal not in range(128) cat nnout2 ascii ..Oh great! ok lets try this: #nntst3.py import sys,codecs mychar=chr(253) print(sys.stdout.encoding) print(mychar.encode('latin1')) ./nntst3.py ISO8859-1 b'\xfd' ./nntst3.py nnout3 cat nnout3 ascii b'\xfd' ..Eh... not what I want really. #nntst4.py import sys,codecs mychar=chr(253) print(sys.stdout.encoding) sys.stdout=codecs.getwriter(latin1)(sys.stdout) print(mychar) ./nntst4.py ISO8859-1 Traceback (most recent call last): File ./nntst4.py, line 6, in module print(mychar) File Python-3.1.2/Lib/codecs.py, line 356, in write self.stream.write(data) TypeError: must be str, not bytes ..OK, this is not working either. Is there any way to write a value 253 to standard output? -- http://mail.python.org/mailman/listinfo/python-list
Re: using message loop for hotkey capturing
Alex Hall wrote: Hi all, but mainly Tim Golden: Tim, I am using your wonderful message loop for keyboard input, the one on your site that you pointed me to a few months ago. It has been working perfectly as long as I had only one dictionary of keys mapping to one dictionary of functions, but now I want two of each. My program has different modes, which may have varying keystrokes, and I also have some global keystrokes which are the same across all modes, like exiting or switching modes. I cannot figure out how to make the message loop look in two dictionaries at onc. I tried using an if, saying that if action_to_take was not set in the mode-specific dictionary then look at the global dictionary, but it is like it is never looking in the global dictionary at all. I get no syntax errors or problems when running the program, so it has to be something in my logic. Go to http://www.gateway2somewhere.com/sw/main.pyw to see what I mean; the problem code is near the very bottom of the file. Thanks for any suggestions. Oh, please note that I indent one space per indentation level. msg.wParam gives an int, but the keys of globalFuncs are 'g1', etc, not ints. Incidentally, you might want to change: if(not action_to_take): to: if action_to_take is None: in case any of the values happen to be 0 (if not now, then possibly at some time in the future). -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode blues in Python3
On Tuesday 23 March 2010 10:33:33 nn wrote: I know that unicode is the way to go in Python 3.1, but it is getting in my way right now in my Unix scripts. How do I write a chr(253) to a file? #nntst2.py import sys,codecs mychar=chr(253) print(sys.stdout.encoding) print(mychar) The following code works for me: $ cat nnout5.py #!/usr/bin/python3.1 import sys mychar = chr(253) sys.stdout.write(mychar) $ echo $(cat nnout) ý Can I ask why you're using print() in the first place, rather than writing directly to a file? Python 3.x, AFAIK, distinguishes between text and binary files and will let you specify the encoding you want for strings you write. Hope that helps, Rami ./nntst2.py ISO8859-1 ý ./nntst2.py nnout2 Traceback (most recent call last): File ./nntst2.py, line 5, in module print(mychar) UnicodeEncodeError: 'ascii' codec can't encode character '\xfd' in position 0: ordinal not in range(128) cat nnout2 ascii ..Oh great! ok lets try this: #nntst3.py import sys,codecs mychar=chr(253) print(sys.stdout.encoding) print(mychar.encode('latin1')) ./nntst3.py ISO8859-1 b'\xfd' ./nntst3.py nnout3 cat nnout3 ascii b'\xfd' ..Eh... not what I want really. #nntst4.py import sys,codecs mychar=chr(253) print(sys.stdout.encoding) sys.stdout=codecs.getwriter(latin1)(sys.stdout) print(mychar) ./nntst4.py ISO8859-1 Traceback (most recent call last): File ./nntst4.py, line 6, in module print(mychar) File Python-3.1.2/Lib/codecs.py, line 356, in write self.stream.write(data) TypeError: must be str, not bytes ..OK, this is not working either. Is there any way to write a value 253 to standard output? Rami Chowdhury Ninety percent of everything is crap. -- Sturgeon's Law 408-597-7068 (US) / 07875-841-046 (UK) / 01819-245544 (BD) -- http://mail.python.org/mailman/listinfo/python-list
Re: using message loop for hotkey capturing
On 3/23/10, MRAB pyt...@mrabarnett.plus.com wrote: Alex Hall wrote: Hi all, but mainly Tim Golden: Tim, I am using your wonderful message loop for keyboard input, the one on your site that you pointed me to a few months ago. It has been working perfectly as long as I had only one dictionary of keys mapping to one dictionary of functions, but now I want two of each. My program has different modes, which may have varying keystrokes, and I also have some global keystrokes which are the same across all modes, like exiting or switching modes. I cannot figure out how to make the message loop look in two dictionaries at onc. I tried using an if, saying that if action_to_take was not set in the mode-specific dictionary then look at the global dictionary, but it is like it is never looking in the global dictionary at all. I get no syntax errors or problems when running the program, so it has to be something in my logic. Go to http://www.gateway2somewhere.com/sw/main.pyw to see what I mean; the problem code is near the very bottom of the file. Thanks for any suggestions. Oh, please note that I indent one space per indentation level. msg.wParam gives an int, but the keys of globalFuncs are 'g1', etc, not ints. That did it. I originally used 1-4 like I did for the mode dictionaries, not realizing that the ints were so important; I figured they were just keys in the dictionary and that they could be anything, it was just easier to use ints. Now, I have changed my globals to 20-23 and everything seems to be going well. Thanks!! Incidentally, you might want to change: if(not action_to_take): to: if action_to_take is None: in case any of the values happen to be 0 (if not now, then possibly at some time in the future). Sorry, could you explain why you suggested this? I do not follow. Because of the if statement if action_to_take:, I figured it was saying if action_to_take was successfully set or something else having a boolean value. Guess not? -- http://mail.python.org/mailman/listinfo/python-list -- Have a great day, Alex (msg sent from GMail website) mehg...@gmail.com; http://www.facebook.com/mehgcap -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode blues in Python3
Rami Chowdhury wrote: On Tuesday 23 March 2010 10:33:33 nn wrote: I know that unicode is the way to go in Python 3.1, but it is getting in my way right now in my Unix scripts. How do I write a chr(253) to a file? #nntst2.py import sys,codecs mychar=chr(253) print(sys.stdout.encoding) print(mychar) The following code works for me: $ cat nnout5.py #!/usr/bin/python3.1 import sys mychar = chr(253) sys.stdout.write(mychar) $ echo $(cat nnout) ý Can I ask why you're using print() in the first place, rather than writing directly to a file? Python 3.x, AFAIK, distinguishes between text and binary files and will let you specify the encoding you want for strings you write. Hope that helps, Rami ./nntst2.py ISO8859-1 ý ./nntst2.py nnout2 Traceback (most recent call last): File ./nntst2.py, line 5, in module print(mychar) UnicodeEncodeError: 'ascii' codec can't encode character '\xfd' in position 0: ordinal not in range(128) cat nnout2 ascii ..Oh great! ok lets try this: #nntst3.py import sys,codecs mychar=chr(253) print(sys.stdout.encoding) print(mychar.encode('latin1')) ./nntst3.py ISO8859-1 b'\xfd' ./nntst3.py nnout3 cat nnout3 ascii b'\xfd' ..Eh... not what I want really. #nntst4.py import sys,codecs mychar=chr(253) print(sys.stdout.encoding) sys.stdout=codecs.getwriter(latin1)(sys.stdout) print(mychar) ./nntst4.py ISO8859-1 Traceback (most recent call last): File ./nntst4.py, line 6, in module print(mychar) File Python-3.1.2/Lib/codecs.py, line 356, in write self.stream.write(data) TypeError: must be str, not bytes ..OK, this is not working either. Is there any way to write a value 253 to standard output? #nntst5.py import sys mychar=chr(253) sys.stdout.write(mychar) ./nntst5.py nnout5 Traceback (most recent call last): File ./nntst5.py, line 4, in module sys.stdout.write(mychar) UnicodeEncodeError: 'ascii' codec can't encode character '\xfd' in position 0: ordinal not in range(128) equivalent to print. I use print so I can do tests and debug runs to the screen or pipe it to some other tool and then configure the production bash script to write the final output to a file of my choosing. -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode blues in Python3
nn wrote: I know that unicode is the way to go in Python 3.1, but it is getting in my way right now in my Unix scripts. How do I write a chr(253) to a file? Python3 make a distinction between bytes and string(i.e., unicode) types, and you are still thinking in the Python2 mode that does *NOT* make such a distinction. What you appear to want is to write a particular byte to a file -- so use the bytes type and a file open in binary mode: b=bytes([253]) f = open(abc, 'wb') f.write(b) 1 f.close() On unix (at least), the od program can verify the contents is correct: od abc -d 000 253 001 Hope that helps. Gary Herron #nntst2.py import sys,codecs mychar=chr(253) print(sys.stdout.encoding) print(mychar) ./nntst2.py ISO8859-1 ý ./nntst2.py nnout2 Traceback (most recent call last): File ./nntst2.py, line 5, in module print(mychar) UnicodeEncodeError: 'ascii' codec can't encode character '\xfd' in position 0: ordinal not in range(128) cat nnout2 ascii ..Oh great! ok lets try this: #nntst3.py import sys,codecs mychar=chr(253) print(sys.stdout.encoding) print(mychar.encode('latin1')) ./nntst3.py ISO8859-1 b'\xfd' ./nntst3.py nnout3 cat nnout3 ascii b'\xfd' ..Eh... not what I want really. #nntst4.py import sys,codecs mychar=chr(253) print(sys.stdout.encoding) sys.stdout=codecs.getwriter(latin1)(sys.stdout) print(mychar) ./nntst4.py ISO8859-1 Traceback (most recent call last): File ./nntst4.py, line 6, in module print(mychar) File Python-3.1.2/Lib/codecs.py, line 356, in write self.stream.write(data) TypeError: must be str, not bytes ..OK, this is not working either. Is there any way to write a value 253 to standard output? -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode blues in Python3
Gary Herron wrote: nn wrote: I know that unicode is the way to go in Python 3.1, but it is getting in my way right now in my Unix scripts. How do I write a chr(253) to a file? Python3 make a distinction between bytes and string(i.e., unicode) types, and you are still thinking in the Python2 mode that does *NOT* make such a distinction. What you appear to want is to write a particular byte to a file -- so use the bytes type and a file open in binary mode: b=bytes([253]) f = open(abc, 'wb') f.write(b) 1 f.close() On unix (at least), the od program can verify the contents is correct: od abc -d 000 253 001 Hope that helps. Gary Herron #nntst2.py import sys,codecs mychar=chr(253) print(sys.stdout.encoding) print(mychar) ./nntst2.py ISO8859-1 ý ./nntst2.py nnout2 Traceback (most recent call last): File ./nntst2.py, line 5, in module print(mychar) UnicodeEncodeError: 'ascii' codec can't encode character '\xfd' in position 0: ordinal not in range(128) cat nnout2 ascii ..Oh great! ok lets try this: #nntst3.py import sys,codecs mychar=chr(253) print(sys.stdout.encoding) print(mychar.encode('latin1')) ./nntst3.py ISO8859-1 b'\xfd' ./nntst3.py nnout3 cat nnout3 ascii b'\xfd' ..Eh... not what I want really. #nntst4.py import sys,codecs mychar=chr(253) print(sys.stdout.encoding) sys.stdout=codecs.getwriter(latin1)(sys.stdout) print(mychar) ./nntst4.py ISO8859-1 Traceback (most recent call last): File ./nntst4.py, line 6, in module print(mychar) File Python-3.1.2/Lib/codecs.py, line 356, in write self.stream.write(data) TypeError: must be str, not bytes ..OK, this is not working either. Is there any way to write a value 253 to standard output? Actually what I want is to write a particular byte to standard output, and I want this to work regardless of where that output gets sent to. I am aware that I could do open('nnout','w',encoding='latin1').write(mychar) but I am porting a python2 program and don't want to rewrite everything that uses that script. -- http://mail.python.org/mailman/listinfo/python-list
DRUNK MOM AND BOY... HOT CLIP.....
DRUNK MOM AND BOY... HOT CLIP. http://123sex4u.blogspot.com/ http://123sex4u.blogspot.com/ http://123sex4u.blogspot.com/ http://123sex4u.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: using message loop for hotkey capturing
Alex Hall wrote: On 3/23/10, MRAB pyt...@mrabarnett.plus.com wrote: [snip] Incidentally, you might want to change: if(not action_to_take): to: if action_to_take is None: in case any of the values happen to be 0 (if not now, then possibly at some time in the future). Sorry, could you explain why you suggested this? I do not follow. Because of the if statement if action_to_take:, I figured it was saying if action_to_take was successfully set or something else having a boolean value. Guess not? The code: globalFuncs.get (msg.wParam) returns None if the key isn't in the dict. 'if' and 'while' statements treat other objects than just True as True, in fact anything for which bool() returns True. For example: bool(100) returns True bool([1, 2, 3]) returns True bool('some text') returns True but: bool(0) returns False bool([]) returns False bool('') returns False bool(None) returns False I also just noticed that you don't give action_to_take a default value before checking whether it's a hotkey. Suppose that msg.message == win32con.WM_HOTKEY was False: if msg.message == win32con.WM_HOTKEY: action_to_take=globalFuncs.get (msg.wParam) if(not action_to_take): It would get to if(not action_to_take): and either find that action_to_take wasn't defined, or use the value from the previous pass through the loop. -- http://mail.python.org/mailman/listinfo/python-list
Miracles of the devil and beat of the revolution of religious reform
Follow what god revealed to the Almighty Peace be upon you Those who wish to familiarized themselves after you click on the link please wait a little until it opens the link Miracles of the devil and beat of the revolution of religious reform http://www.ushaaqallah.com/forum/viewtopic.php?f=22t=19225sid=49b706e316461bcd768accfb7ccf031c Peace be upon you -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode blues in Python3
nn, 23.03.2010 19:46: Actually what I want is to write a particular byte to standard output, and I want this to work regardless of where that output gets sent to. I am aware that I could do open('nnout','w',encoding='latin1').write(mychar) but I am porting a python2 program and don't want to rewrite everything that uses that script. Are you writing text or binary data to stdout? Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is cool!!
On Tue, Mar 23, 2010 at 1:07 PM, Tim Golden m...@timgolden.me.uk wrote: On 23/03/2010 16:55, Jose Manuel wrote: I have been learning Python, and it is amazing I am using the tutorial that comes with the official distribution. At the end my goal is to develop applied mathematic in engineering applications to be published on the Web, specially on app. oriented to simulations and control systems, I was about to start learning Java but I found Python which seems easier to learn that Java. Would it be easy to integrate Python in Web pages with HTML? I have read many info on Internet saying it is, and I hope so You probably want to be looking at IronPython and Silverlight. In fact, the prolific Michael Foord has already produced an example of this, which gives you the Python tutorial online! http://trypython.org TJG Granted that I know next to nothing about webwork, but is there a reason why you recommended a competing, nonstandard technology rather than simply pointing him towards more standards compliant tools that exist to do exactly what he asked for? Seems a bit dodgy to advocate a closed solution when the alternative has 100% market share. Geremy Condra -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is cool!!
On 23/03/2010 20:04, geremy condra wrote: On Tue, Mar 23, 2010 at 1:07 PM, Tim Goldenm...@timgolden.me.uk wrote: On 23/03/2010 16:55, Jose Manuel wrote: Would it be easy to integrate Python in Web pages with HTML? I have read many info on Internet saying it is, and I hope so You probably want to be looking at IronPython and Silverlight. In fact, the prolific Michael Foord has already produced an example of this, which gives you the Python tutorial online! http://trypython.org TJG Granted that I know next to nothing about webwork, but is there a reason why you recommended a competing, nonstandard technology rather than simply pointing him towards more standards compliant tools that exist to do exactly what he asked for? Seems a bit dodgy to advocate a closed solution when the alternative has 100% market share. I can't say I thought *very* hard before sending that but... The OP asked for integrate Python in Web Pages with HTML which I understood -- perhaps wrongly -- to mean: run Python in the browser. The only two ways I'm aware of doing that in Python are the undersupported Python-as-IE-scripting-language and IronPython/Silverlight. Now I look again, I realise that he may have meant simply: Python as a server-side toolset with possible support for Javascript. In which case, of course, my answer was not so applicable. TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode blues in Python3
Stefan Behnel wrote: nn, 23.03.2010 19:46: Actually what I want is to write a particular byte to standard output, and I want this to work regardless of where that output gets sent to. I am aware that I could do open('nnout','w',encoding='latin1').write(mychar) but I am porting a python2 program and don't want to rewrite everything that uses that script. Are you writing text or binary data to stdout? Stefan latin1 charset text. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is cool!!
Jose Manuel wrote: Would it be easy to integrate Python in Web pages with HTML? I have read many info on Internet saying it is, and I hope so Django is, among several other similar projects and frameworks, very popular for generating web apps in Python. I have only used Django and it works very well. -- http://mail.python.org/mailman/listinfo/python-list
Re: Castrated traceback in sys.exc_info()
Gabriel Genellina a écrit : En Mon, 22 Mar 2010 15:20:39 -0300, Pascal Chambon chambon.pas...@wanadoo.fr escribió: Allright, here is more concretely the problem : ERROR:root:An error Traceback (most recent call last): File C:/Users/Pakal/Desktop/aaa.py, line 7, in c return d() File C:/Users/Pakal/Desktop/aaa.py, line 11, in d def d(): raise ValueError ValueError As you see, the traceback only starts from function c, which handles the exception. It doesn't show main(), a() and b(), which might however be (and are, in my case) critical to diagnose the severity of the problem (since many different paths would lead to calling c()). So the question is : is that possible to enforce, by a way or another, the retrieval of the FULL traceback at exception raising point, instead of that incomplete one ? Thanks for bringing this topic! I learned a lot trying to understand what happens. The exception traceback (what sys.exc_info()[2] returns) is *not* a complete stack trace. The sys module documentation is wrong [1] when it says ...encapsulates the call stack at the point where the exception originally occurred. The Language Reference is more clear [2]: Traceback objects represent a stack trace of an exception. A traceback object is created when an exception occurs. When the search for an exception handler unwinds the execution stack, at each unwound level a traceback object is inserted in front of the current traceback. When an exception handler is entered, the stack trace is made available to the program. That is, a traceback holds only the *forward* part of the stack: the frames already exited when looking for an exception handler. Frames going from the program starting point up to the current execution point are *not* included. Conceptually, it's like having two lists: stack and traceback. The complete stack trace is always stack+traceback. At each step (when unwinding the stack, looking for a frame able to handle the current exception) an item is popped from the top of the stack (last item) and inserted at the head of the traceback. The traceback holds the forward path (from the current execution point, to the frame where the exception was actually raised). It's a linked list, its tb_next attribute holds a reference to the next item; None marks the last one. The back path (going from the current execution point to its caller and all the way to the program entry point) is a linked list of frames; the f_back attribute points to the previous one, or None. In order to show a complete stack trace, one should combine both. The traceback module contains several useful functions: extract_stack() + extract_tb() are a starting point. The simplest way I could find to make the logging module report a complete stack is to monkey patch logging.Formatter.formatException so it uses format_exception() and format_stack() combined (in fact it is simpler than the current implementation using a StringIO object): Good point, there is clearly a distinction between stack trace and exception traceback that I didn't know (actually, it seems no one makes it in computer literature). Good catch, Gabriel. There should be no need to monkey-patch the logging module - it's better if I include the change in the module itself. The only remaining question is that of backward compatibility, but I can do this for Python 2.7/3.2 only so that won't be an issue. It's probably a good idea to log an issue on the bug tracker, though, so we have some history for the change - do you want to do that, or shall I? Regards, Vinay Sajip Well having it fixed in logging would be great, but that kind of information is good to have in other circumstances, so shouldn't we rather advocate the availability of this stack trace part in exc_info too ? This way, people like me who consider frames as black magic wouldn't need to meet complex stuffs as traceback.format_stack(ei[2].tb_frame.f_back :p Should I open an issue for this evolution of exceptiuon handling, or should we content ourselves of this hacking of frame stck ? Regards, Pascal -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is cool!!
On Mar 23, 3:12 pm, Tim Golden m...@timgolden.me.uk wrote: I can't say I thought *very* hard before sending that but... The OP asked for integrate Python in Web Pages with HTML which I understood -- perhaps wrongly -- to mean: run Python in the browser. The only two ways I'm aware of doing that in Python are the undersupported Python-as-IE-scripting-language and IronPython/Silverlight. If I had to run Python in a browser, the first thing I would do is turn to Pyjamas: http://pyjs.org/ Regards, Pat -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is cool!!
There is a project PyWhip (renamed as PyKata) which aims for the same purpose. Google AppEmgine + Django does the trick for that. May be you can take an inspiration or two from there especially because all code is open to/for you. ~l0nwlf On Wed, Mar 24, 2010 at 2:54 AM, Patrick Maupin pmau...@gmail.com wrote: On Mar 23, 3:12 pm, Tim Golden m...@timgolden.me.uk wrote: I can't say I thought *very* hard before sending that but... The OP asked for integrate Python in Web Pages with HTML which I understood -- perhaps wrongly -- to mean: run Python in the browser. The only two ways I'm aware of doing that in Python are the undersupported Python-as-IE-scripting-language and IronPython/Silverlight. If I had to run Python in a browser, the first thing I would do is turn to Pyjamas: http://pyjs.org/ Regards, Pat -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Pythonic way to trim and keep leading and trailing whitespace
I'm looking for a pythonic way to trim and keep leading whitespace in a string. Use case: I have a bunch of text strings with various amounts of leading and trailing whitespace (spaces and tabs). I want to grab the leading and trailing whitespace, save it, surround the remaining text with html tags, and then add back the leading and trailing whitespace. The only solution I can think of is regex, and that makes me think of the 2 proverbial problems that come with that :) Is there a 'better' solution than regex for this scenario? (Seems like this would be a common type of string processing). Thanks, Malcolm -- http://mail.python.org/mailman/listinfo/python-list
Re: Python is cool!!
On Tue, Mar 23, 2010 at 4:50 PM, Shashwat Anand anand.shash...@gmail.com wrote: There is a project PyWhip (renamed as PyKata) which aims for the same purpose. Google AppEmgine + Django does the trick for that. May be you can take an inspiration or two from there especially because all code is open to/for you. But, if I understand PyWhip/PyKata after glancing at the project page, it doesn't actually run code in the browser... Regards, Pat -- http://mail.python.org/mailman/listinfo/python-list
Posting to https
I am trying to obtain data on a https site, but everytime I try to access the data that is behind the logon screen, I get the logon page instead. I was able to successfully do a test problem: import sys, urllib2, urllib zipcode = 48103 url = 'http://www.wunderground.com/cgi-bin/findweather/getForecast' data = urllib.urlencode([('query', zipcode)]) req = urllib2.Request(url) fd = urllib2.urlopen(req, data) while 1: data = fd.read(1024) if not len(data): break sys.stdout.write(data) which performed as I expected. However, for the url 'https://secure.umcu.org/cgi-bin/mcw000.cgi?MCWSTART' with data = ... {'HBUSERNAME':username,'PASSWORD':password} I was sent just the logon screen. Am I missing something important that has to do with interaction with javascript, https, or cgi, or something completely different? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonic way to trim and keep leading and trailing whitespace
On 3/23/2010 3:09 PM pyt...@bdurham.com said... I'm looking for a pythonic way to trim and keep leading whitespace in a string. Use case: I have a bunch of text strings with various amounts of leading and trailing whitespace (spaces and tabs). I want to grab the leading and trailing whitespace, save it, surround the remaining text with html tags, and then add back the leading and trailing whitespace. I'd do it this way: target = ' spam and eggs ' stripped = target.strip() replaced = target.replace(stripped,html%s/html % stripped) HTH, Emile The only solution I can think of is regex, and that makes me think of the 2 proverbial problems that come with that :) Is there a 'better' solution than regex for this scenario? (Seems like this would be a common type of string processing). Thanks, Malcolm -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonic way to trim and keep leading and trailing whitespace
As far as I know, I don't think there is anything that strips it and returns the material that was stripped. Regex's would be your best bet. Daniel On Tue, Mar 23, 2010 at 6:09 PM, pyt...@bdurham.com wrote: I'm looking for a pythonic way to trim and keep leading whitespace in a string. Use case: I have a bunch of text strings with various amounts of leading and trailing whitespace (spaces and tabs). I want to grab the leading and trailing whitespace, save it, surround the remaining text with html tags, and then add back the leading and trailing whitespace. The only solution I can think of is regex, and that makes me think of the 2 proverbial problems that come with that :) Is there a 'better' solution than regex for this scenario? (Seems like this would be a common type of string processing). Thanks, Malcolm -- http://mail.python.org/mailman/listinfo/python-list -- ~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode blues in Python3
nn wrote: Stefan Behnel wrote: nn, 23.03.2010 19:46: Actually what I want is to write a particular byte to standard output, and I want this to work regardless of where that output gets sent to. I am aware that I could do open('nnout','w',encoding='latin1').write(mychar) but I am porting a python2 program and don't want to rewrite everything that uses that script. Are you writing text or binary data to stdout? Stefan latin1 charset text. Are you sure about that? If you carefully reconsider, could you come to the conclusion that you are not writing text at all, but binary data? If it really was text that you write, why do you need to use U+00FD (LATIN SMALL LETTER Y WITH ACUTE). To my knowledge, that character is really infrequently used in practice. So that you try to write it strongly suggests that it is not actually text what you are writing. Also, your formulation suggests the same: Is there any way to write a value 253 to standard output? If you would really be writing text, you'd ask Is there any way to write 'ý' to standard output? Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Castrated traceback in sys.exc_info()
On Mar 23, 8:49 pm, Pascal Chambon chambon.pas...@wanadoo.fr wrote: Should I open an issue for this evolution of exceptiuon handling, or should we content ourselves of this hacking of frame stck ? Possibly worth raising an issue (not logging-related), but perhaps it's worth seeing if this has come up before creating the issue. Regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonic way to trim and keep leading and trailing whitespace
Emile, target = 'spam and eggs ' stripped = target.strip() replaced = target.replace(stripped,html%s/html % stripped) Brilliant! That's just the type of clever solution I was looking for. Thank you! Malcolm - Original message - From: Emile van Sebille em...@fenx.com To: python-list@python.org Date: Tue, 23 Mar 2010 15:34:48 -0700 Subject: Re: Pythonic way to trim and keep leading and trailing whitespace On 3/23/2010 3:09 PM pyt...@bdurham.com said... I'm looking for a pythonic way to trim and keep leading whitespace in a string. Use case: I have a bunch of text strings with various amounts of leading and trailing whitespace (spaces and tabs). I want to grab the leading and trailing whitespace, save it, surround the remaining text with html tags, and then add back the leading and trailing whitespace. I'd do it this way: target = ' spam and eggs ' stripped = target.strip() replaced = target.replace(stripped,html%s/html % stripped) HTH, Emile The only solution I can think of is regex, and that makes me think of the 2 proverbial problems that come with that :) Is there a 'better' solution than regex for this scenario? (Seems like this would be a common type of string processing). Thanks, Malcolm -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonic way to trim and keep leading and trailing whitespace
regex is not goto that you should always avoid using it. It have its own use-case, here regex solution is intuitive although @emile have done this for you via string manpulation. On Wed, Mar 24, 2010 at 4:09 AM, Daniel Chiquito daniel.chiqu...@gmail.comwrote: As far as I know, I don't think there is anything that strips it and returns the material that was stripped. Regex's would be your best bet. Daniel On Tue, Mar 23, 2010 at 6:09 PM, pyt...@bdurham.com wrote: I'm looking for a pythonic way to trim and keep leading whitespace in a string. Use case: I have a bunch of text strings with various amounts of leading and trailing whitespace (spaces and tabs). I want to grab the leading and trailing whitespace, save it, surround the remaining text with html tags, and then add back the leading and trailing whitespace. The only solution I can think of is regex, and that makes me think of the 2 proverbial problems that come with that :) Is there a 'better' solution than regex for this scenario? (Seems like this would be a common type of string processing). Thanks, Malcolm -- http://mail.python.org/mailman/listinfo/python-list -- ~ -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonic way to trim and keep leading and trailing whitespace
pyt...@bdurham.com wrote: I'm looking for a pythonic way to trim and keep leading whitespace in a string. Use case: I have a bunch of text strings with various amounts of leading and trailing whitespace (spaces and tabs). I want to grab the leading and trailing whitespace, save it, surround the remaining text with html tags, and then add back the leading and trailing whitespace. The only solution I can think of is regex, and that makes me think of the 2 proverbial problems that come with that :) Just in case you're okay with a regexp solution, you can use s = \t\tabc def import re r = re.compile(r'^(\s*)(.*?)(\s*)$') m = re.match(s) m.groups() ('\t\t', 'abc def', ' ') leading, text, trailing = m.groups() While Emile's solution works nicely for your particular use-case, in the event you need to discern between leading/trailing whitespace, the above makes it pretty easy. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonic way to trim and keep leading and trailing whitespace
On 03/23/10 23:38, Tim Chase wrote: cut Just in case you're okay with a regexp solution, you can use s = \t\tabc def import re r = re.compile(r'^(\s*)(.*?)(\s*)$') m = re.match(s) m.groups() ('\t\t', 'abc def', ' ') leading, text, trailing = m.groups() cut Ahhh regex, the hammer, Swiss Army Knife, cable tie, duct tape, superglue and soldering iron, all wrapped in one*. Mastery of it will enable you to drive the nails in your coffin at an incomparable speed. :-) *Yes I was a sysadmin, why do you ask? -- mph -- http://mail.python.org/mailman/listinfo/python-list
Advice Criticism on Python App
I have made a Python App(really script) that will check a stocks current values from a website save that data to a SQLite 3 database. I am looking for any suggestions criticisms on what I should do better or anything at all but mainly in these areas: [QUOTE] - Correct Python Layout of code - Correct error checking: Am I catching all my errors or are my exceptions not specific enough? Should I be using more try excepts inside my functions? - Are there any areas where huge errors, bugs etc could occur that I have not compensated for? - I am also looking for suggestions on how to write a function better, so if you think that function is really bad should be rewritten completely or something I would really like to hear it. - Anything else that you see - Is python meant to be used in the way I have used it? To make a 'semi detailed' app?[/QUOTE] Any advice criticism would be really helpful. App: [CODE] *Stock Data Builder* Algorithm: - Search website for stock - Get website HTML source code - Search code for target stock data(price,dividends,etc..) - Add data to text file import sys import os import sqlite3 import datetime import time import urllib2 ### Global Variables ### menu = ***Stock Program*** \n\n1. Add a Stock to track \n2. Get Todays Tracking Data \n3. Exit \nEnter decision: target = 'th scope=row class=rowa href=/asx/research/ companyInfo.do?by=asxCodeasxCode=%s%s/a' ASXurl = 'http://www.asx.com.au/asx/markets/priceLookup.do? by=asxCodesasxCodes=' class stock: code = purchasePrice= 0 purchaseQuantity = 0 price= [] # list of recent prices recentBid= [] # list of recent bids for stock recentOffer = [] # list of recent offers for stock stockVol = [] # list of stock quantity available on market def __init__(self): Default Constructor self.code = self.purchasePrice= 0 self.purchaseQuantity = 0 def constructor(self, stockCode, purPrice, purQuant): Constructor self.code = stockCode self.purchasePrice= purPrice self.purchaseQuantity = purQuant def setData(self, stockCode, purPrice, purQuant, priceList, reBidList, reOffList, popList): Defines implements the objects' public variables self.code = stockCode self.purchasePrice= purPrice self.purchaseQuantity = purQuant self.price= priceList self.recentBid= reBidList self.recentOffer = reOffList self.stockVol = popList self.printStats() def updateData(self, priceEle, bidEle, offerEle, populEle): Adds data to stock object's lists self.price.append(priceEle) self.recentBid.append(bidEle) self.recentOffer.append(offerEle) self.stockVol.append(populEle) def printStats(self): Output Stock attributes print(Stock Code: +self.code) print(Stock Purchase Price: +str(self.purchasePrice)) print(Stock Quantity Owned: +str(self.purchaseQuantity)) print(***Initial Investment Value: +str(self.purchasePrice*self.purchaseQuantity)) if not(len(self.price) = 0): print(Stock Current Price: +str(self.price[-1])) print(Recent Bid: +str(self.recentBid[-1])) print(Recent Offer: +str(self.recentOffer[-1])) print(Total Stock Volume in market: +str(self.stockVol[-1])) print(***Present Investment Value: +str(self.price[-1]*self.purchaseQuantity)) print(\n) ### Functions ### def connectDatabase(dbLocation, dbName, tableName): Establish Return connection to SQLite Database try: if not (os.path.exists(dbLocation)): os.mkdir(dbLocation) # create folder/dir os.chdir(dbLocation)# change directory focus to dbLocation conn = sqlite3.connect(dbLocation+dbName) cur = conn.cursor() try: createTableQ = CREATE TABLE IF NOT EXISTS +tableName + (code varchar PRIMARY KEY, purchase_price float, purchase_quantity float, purchase_date varchar); cur.execute(createTableQ) conn.commit() except: pass return conn except IOError or OSError: print Connection to database failed return False def retrieveStockDatabase(conn, tableName): Read SQLite3 database extract stock data into StockList stockList = [] stockQuery = select recent_price, recent_offer, recent_bid, stock_volume from ? ; cur = conn.cursor() cur.execute(select code, purchase_price, purchase_quantity from +tableName+;) for row in cur.fetchall(): newStock = stock() newStock.code = row[0] newStock.purchasePrice= row[1] newStock.purchaseQuantity = row[2] cur.execute(stockQuery,[newStock.code])
Re: Advice Criticism on Python App
On Tue, Mar 23, 2010 at 5:05 PM, Jimbo nill...@yahoo.com wrote: I have made a Python App(really script) that will check a stocks current values from a website save that data to a SQLite 3 database. I am looking for any suggestions criticisms on what I should do better or anything at all but mainly in these areas: snip Any advice criticism would be really helpful. Complying with Python naming conventions would be one place to start: * Class names should be in StudlyCaps (so class Stock, not class stock). * Constants should be in UPPERCASE_WITH_UNDERSCORES. * Most other names should be words_separated_by_underscores, not camelCaseLikeThis; FWIW, I'm not a fan of this part of the guideline personally. Also, conditions don't need parentheses around them. So: if (decision == 1): #WRONG! harder to read, extra syntactic noise if decision == 1: #RIGHT For many more style details, see PEP 8 -- Style Guide for Python Code: http://www.python.org/dev/peps/pep-0008/ Additionally, the return 0 in main() serves no purpose; the return value isn't used as the exit code for the program. You can either eliminate the line entirely or use plain return if you want the extra clarity. Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Advice Criticism on Python App
Jimbo wrote: I have made a Python App(really script) that will check a stocks current values from a website save that data to a SQLite 3 database. I am looking for any suggestions criticisms on what I should do better or anything at all but mainly in these areas: [QUOTE] - Correct Python Layout of code - Correct error checking: Am I catching all my errors or are my exceptions not specific enough? Should I be using more try excepts inside my functions? - Are there any areas where huge errors, bugs etc could occur that I have not compensated for? - I am also looking for suggestions on how to write a function better, so if you think that function is really bad should be rewritten completely or something I would really like to hear it. - Anything else that you see - Is python meant to be used in the way I have used it? To make a 'semi detailed' app?[/QUOTE] Any advice criticism would be really helpful. App: [CODE] *Stock Data Builder* Algorithm: - Search website for stock - Get website HTML source code - Search code for target stock data(price,dividends,etc..) - Add data to text file import sys import os import sqlite3 import datetime import time import urllib2 ### Global Variables ### menu = ***Stock Program*** \n\n1. Add a Stock to track \n2. Get Todays Tracking Data \n3. Exit \nEnter decision: target = 'th scope=row class=rowa href=/asx/research/ companyInfo.do?by=asxCodeasxCode=%s%s/a' ASXurl = 'http://www.asx.com.au/asx/markets/priceLookup.do? by=asxCodesasxCodes=' class stock: code = purchasePrice= 0 purchaseQuantity = 0 price= [] # list of recent prices recentBid= [] # list of recent bids for stock recentOffer = [] # list of recent offers for stock stockVol = [] # list of stock quantity available on market This will be variables belonging to the class itself, not instances of it. def __init__(self): Default Constructor self.code = self.purchasePrice= 0 self.purchaseQuantity = 0 def constructor(self, stockCode, purPrice, purQuant): Constructor self.code = stockCode self.purchasePrice= purPrice self.purchaseQuantity = purQuant def setData(self, stockCode, purPrice, purQuant, priceList, reBidList, reOffList, popList): Defines implements the objects' public variables self.code = stockCode self.purchasePrice= purPrice self.purchaseQuantity = purQuant self.price= priceList self.recentBid= reBidList self.recentOffer = reOffList self.stockVol = popList self.printStats() def updateData(self, priceEle, bidEle, offerEle, populEle): Adds data to stock object's lists self.price.append(priceEle) self.recentBid.append(bidEle) self.recentOffer.append(offerEle) self.stockVol.append(populEle) def printStats(self): Output Stock attributes print(Stock Code: +self.code) In Python 2 'print' is a statement, so it doesn't need its arguments to be enclosed in (). You could also use Python's string formatting: print Stock Code: %s % self.code print(Stock Purchase Price: +str(self.purchasePrice)) print(Stock Quantity Owned: +str(self.purchaseQuantity)) print(***Initial Investment Value: +str(self.purchasePrice*self.purchaseQuantity)) if not(len(self.price) = 0): 'not' has a lower priority than '=', and this can be simplified anyway: if len(self.price) 0: or even: if self.price: because empty containers (eg lists) are treated as False, non-empty ones as True, by 'if' and 'while' statements. print(Stock Current Price: +str(self.price[-1])) print(Recent Bid: +str(self.recentBid[-1])) print(Recent Offer: +str(self.recentOffer[-1])) print(Total Stock Volume in market: +str(self.stockVol[-1])) print(***Present Investment Value: +str(self.price[-1]*self.purchaseQuantity)) print(\n) ### Functions ### def connectDatabase(dbLocation, dbName, tableName): Establish Return connection to SQLite Database try: if not (os.path.exists(dbLocation)): os.mkdir(dbLocation) # create folder/dir os.chdir(dbLocation)# change directory focus to dbLocation It's normally easier to use absolute paths instead of changing the current directory. conn = sqlite3.connect(dbLocation+dbName) It's better to join paths using os.path.join() because that will insert any directory separators for you. cur = conn.cursor() try: createTableQ = CREATE TABLE IF NOT EXISTS +tableName + (code varchar PRIMARY KEY, purchase_price float, purchase_quantity float, purchase_date varchar); cur.execute(createTableQ)
Hello,everybody,the good shoping place,the new year approaching, click in. Let's facelift bar! ===== HTTP://loveshopping.us ====
Hello,everybody,the good shoping place,the new year approaching, click in. Let's facelift bar! = HTTP://loveshopping.us Air jordan(1-24)shoes $33 UGG BOOT $50 Nike shox(R4,NZ,OZ,TL1,TL2,TL3) $35 Handbags(Coach lv fendi dg) $35 Tshirts (Polo ,ed hardy,lacoste) $16 Jean(True Religion,ed hardy,coogi) $30 Sunglasses(Oakey,coach,gucci,Armaini) $16 New era cap $15 Bikini (Ed hardy,polo) $25 FREE SHIPPING -- http://mail.python.org/mailman/listinfo/python-list
Re: GC is very expensive: am I doing something wrong?
Antoine Pitrou solip...@pitrou.net writes: See: http://www.cs.rice.edu/~scrosby/hash/ ... Certainly interesting in a purely academic point of view, but in real life if you want to cause a denial of service by overwhelming a server, there are far more obvious options than trying to guess the server's use of hash tables and trying to cause lots of collisions in them. If you look at the very low bandwidth used in some of those hashtable attacks, it's hard to see any other somewhat-generic attack that's comparably effective. Usually we think of DOS as involving massive botnets and the like, not a dribble of a few hundred characters per second. -- http://mail.python.org/mailman/listinfo/python-list
'gcc' failed with exit status 1
Hello All, I was hoping I could get some help with this issue with getting Cython to work. Earlier I had an issue that said unable to find vcvarsall.bat and it turns out there is an active bug report that covers that issue (I have a 64 bit windows system). I still hadn't installed 3.1.2, so I did that tonight and now I have the issue below. Any thoughts on what I am doing wrong? Microsoft Windows [Version 6.1.7600] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Users\Jamescd C:\Python31 C:\Python31python setup.py build_ext --inplace running build_ext cythoning hello.pyx to hello.c Error converting Pyrex file to C: ... def say_hello_to(name): ^ C:\Python31\hello.pyx:1:23: Unrecognized character building 'hello' extension C:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall -IC:\Python31\include - IC:\Pytho n31\PC -c hello.c -o build\temp.win-amd64-3.1\Release\hello.o hello.c:1:2: #error Do not use this file, it is the result of a failed Cython co mpilation. error: command 'gcc' failed with exit status 1 C:\Python31 -- http://mail.python.org/mailman/listinfo/python-list
Re: Unicode blues in Python3
On Tue, 23 Mar 2010 11:46:33 -0700, nn wrote: Actually what I want is to write a particular byte to standard output, and I want this to work regardless of where that output gets sent to. What do you mean work? Do you mean display a particular glyph or something else? In bash: $ echo -e \0101 # octal 101 = decimal 65 A $ echo -e \0375 # decimal 253 � but if I change the terminal encoding, I get this: $ echo -e \0375 ý Or this: $ echo -e \0375 ² depending on which encoding I use. I think your question is malformed. You need to work out what behaviour you actually want, before you can ask for help on how to get it. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
[issue8196] sqlit3.paramstyle reported as 'qmark'
Gerhard Häring g...@ghaering.de added the comment: I said qmark vs numeric. I. e. vs: execute(UPDATE authors set name = :1, email = :2, comment = :3 WHERE id = :4, (form.name, form.email, form.text, form.id)) The sqlite3 module will always support both paramstyles qmark and named, simply because that is what the underlying SQLite engine supports. What paramstyle says is mostly important for third-party software that works across multiple DB-API compliant database modules. paramstyle enables them to use database supported parameter binding. In reality, though, there will hardly be a wrapper for DB-API modules that does *not* need to special-case anything depending on the underlying database. So they will hardly ever rely only on the paramstyle and threadsafety parameters. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8196 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8207] test_pep277 fails on OS X
Ned Deily n...@acm.org added the comment: Also this failure on py3k: == ERROR: test_normalize (test.test_pep277.UnicodeFileTests) -- Traceback (most recent call last): File /private/tmp/pp3/usr/local/lib/python3.2/test/test_pep277.py, line 119, in test_normalize os.stat(name) OSError: [Errno 2] No such file or directory: '@test_42408_tmp/\u2002\u2002\u2002A' -- -- versions: +Python 3.2 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8207 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue1544339] _ctypes fails to build on Solaris x86 32-bit (Sun compiler)
Nick nick_bo...@fastmail.fm added the comment: Martin, the patch is for libffi included in ctypes 1.0.2. This is python 2.4 (required for plone/zope) so python 2.5/2.6 etc is not a possibility. ctypes 1.0.2 compiles with this patch but then core dumps anyway during tests so false hope. It appears to me that no-one is maintaining this separate ctypes code-base anymore so I'll have to ditch dependencies that use it (Shapely) unfortunately. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue1544339 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8207] test_pep277 fails on OS X
Florent Xicluna florent.xicl...@gmail.com added the comment: This patch should fix it... HFS Plus uses a variant of Normal Form D in which U+2000 through U+2FFF, U+F900 through U+FAFF, and U+2F800 through U+2FAFF are not decomposed. rant I believed there was only one Unicode... But obviously the Apple's Unicode is something different. /rant -- assignee: - flox components: +Macintosh, Unicode keywords: +patch nosy: +michael.foord priority: - normal resolution: - accepted stage: - patch review Added file: http://bugs.python.org/file16627/issue8207_pep277_for_os_x.diff ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8207 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8209] OptionParser keyword arg 'epilog' not mentioned in the docs
New submission from Senthil Kumaran orsent...@gmail.com: I was looking for some option in optparse module which will allow me to add custom help text after the generated help. Realized that OptionParser class has a keyword argument 'epilog' for the same purpose. But this is not been explained in the documentation, other keyword args are covered. -- assignee: orsenthil components: Documentation messages: 101565 nosy: orsenthil priority: normal severity: normal status: open title: OptionParser keyword arg 'epilog' not mentioned in the docs versions: Python 2.6, Python 2.7, Python 3.1, Python 3.2 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8209 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8209] OptionParser keyword arg 'epilog' not mentioned in the docs
Senthil Kumaran orsent...@gmail.com added the comment: Fixed in revision 79329. -- resolution: - fixed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8209 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8207] test_pep277 fails on OS X
Marc-Andre Lemburg m...@egenix.com added the comment: Florent Xicluna wrote: Florent Xicluna florent.xicl...@gmail.com added the comment: This patch should fix it... HFS Plus uses a variant of Normal Form D in which U+2000 through U+2FFF, U+F900 through U+FAFF, and U+2F800 through U+2FAFF are not decomposed. Could you provide a reference link for this quote ? It's rather strange that those ranges are not decomposed, since they do contain combining code points. -- nosy: +lemburg ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8207 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8207] test_pep277 fails on OS X
Ned Deily n...@acm.org added the comment: Actually, the file system in question is what Apple calls a HFSX case-sensitive (see http://developer.apple.com/mac/library/technotes/tn/tn1150.html#HFSX). On a typical OS X system, you could encounter any combination of HFS+ case-insensitive, HFSX case-insensitive, HFSX case-sensitive file systems, along with other usual suspects, like NFS or SMB. I'll note again the warning in r33595. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8207 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8209] OptionParser keyword arg 'epilog' not mentioned in the docs
Senthil Kumaran orsent...@gmail.com added the comment: merged into release26-maint branch - 79331 -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8209 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8207] test_pep277 fails on OS X
Florent Xicluna florent.xicl...@gmail.com added the comment: Could you provide a reference link for this quote ? I put the link in the patch: http://developer.apple.com/mac/library/qa/qa2001/qa1173.html -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8207 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8207] test_pep277 fails on OS X
Ned Deily n...@acm.org added the comment: With the patch for trunk, the test no longer fails on the given file system. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8207 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue6352] Compiler warning in unicodeobject.c
STINNER Victor victor.stin...@haypocalc.com added the comment: Apparently this was never backported to 3.1. done: r79335 (py3k). -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue6352 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue7668] test_httpservers fails with non-ascii path
Florent Xicluna florent.xicl...@gmail.com added the comment: Fixed with r79297 -- priority: - normal resolution: - fixed stage: needs patch - committed/rejected status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue7668 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue7880] sysconfig does not like symlinks
Changes by Florent Xicluna florent.xicl...@gmail.com: -- status: pending - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue7880 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8133] test_imp fails on OS X; filename normalization issue.
Changes by Florent Xicluna florent.xicl...@gmail.com: -- status: pending - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8133 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8205] test_multiprocessing failure
Florent Xicluna florent.xicl...@gmail.com added the comment: Fixed with r79310. -- resolution: - fixed stage: needs patch - committed/rejected status: open - closed ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8205 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8158] documentation of 'optparse' module incomplete
R. David Murray rdmur...@bitdance.com added the comment: Senthil documented epilog in issue 8209. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8158 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8209] OptionParser keyword arg 'epilog' not mentioned in the docs
R. David Murray rdmur...@bitdance.com added the comment: See also issue 8158. -- nosy: +r.david.murray ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8209 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8210] rev 78820 causes problems on Solaris (Python 2.6)
New submission from Attila Nagy nagy.att...@yahoo.com: The check-in http://svn.python.org/view?view=revrevision=78820 causes problems on Solaris (SXCE 125, ksh, Studio 12). configure output: [...] checking for --with-pydebug... no ./configure: test: unknown operator == test on Solaris does not accept ==. = works okay. -- components: Build messages: 101577 nosy: attila severity: normal status: open title: rev 78820 causes problems on Solaris (Python 2.6) versions: Python 2.6 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8210 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8211] configure: ignore AC_PROG_CC hardcoded CFLAGS
New submission from STINNER Victor victor.stin...@haypocalc.com: configure.in uses AC_PROG_CC, extract of the autoconf manual: (http://www.delorie.com/gnu/docs/autoconf/autoconf_64.html) If using the GNU C compiler, set shell variable GCC to `yes'. If output variable CFLAGS was not already set, set it to `-g -O2' for the GNU C compiler (`-O2' on systems where GCC does not accept `-g'), or `-g' for other compilers. Python does already set the optimization level in its OPT variable: for gcc, it uses -O3 by default, and not -O option (in this case, gcc disables all optimisations, it's like -O0) if --with-pydebug is used. Because of AC_PROG_CC, Python is compiled with -O2 even if --with-pydebug is used, which is bad because it's harder to debug an optimized program: most variable are unavailable (gcc prints optimized out). Another problem is that AC_PROG_CC eats user CFLAGS. It's not possible to specify: ./configure CFLAGS=myflags. On the autoconf mailing list, I saw a simple trick: Save CFLAGS before you call AC_PROG_CC, and restore it after, if you don't want -g -O2. Attached patch implements that. Results: * ./configure: CFLAGS=$(BASECFLAGS) $(OPT) $(EXTRA_CFLAGS) * ./configure --with-pdebug CFLAGS=-O0: CFLAGS=$(BASECFLAGS) -O0 $(OPT) $(EXTRA_CFLAGS) It works :-) -- components: Build files: configure_cflags.patch keywords: patch messages: 101578 nosy: haypo severity: normal status: open title: configure: ignore AC_PROG_CC hardcoded CFLAGS versions: Python 2.6, Python 2.7, Python 3.1, Python 3.2 Added file: http://bugs.python.org/file16628/configure_cflags.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8211 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue4999] multiprocessing.Queue does not order objects
Stefan Praszalowicz deubeul...@gmail.com added the comment: I just got surprised by this, and I agree that updating the doc would be nice, because as of now, it states quite explicitly that the Queue and JoinableQueue types are multi-producer, multi-consumer FIFO queues. -- nosy: +Stefan.P type: - behavior ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue4999 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8212] A tp_dealloc of a subclassed class cannot resurrect an object
New submission from Kristján Valur Jónsson krist...@ccpgames.com: The tp_dealloc of a type can chose to resurrect an object. the subtype_dealloc() in typeobject.c does this when it calls the tp_del() member and it has increased the refcount. The problem is, that if you subclass a custom C object, and that C object's tp_dealloc() chooses to resurrect a dying object, that doesn't go well with subtype_dealloc(). After calling basedealloc() (line 1002 in typeobject.c), the object's type is decrefed. But if the object was resurrected by basedealloc() this shouldn't have been done. The object will be alive, but the type will be missing a reference. This will cause a crash later. This could be fixable if we knew somehow after calling basedealloc() if the object were still alive. But we cannot check self because it may have died. The only way out of this conundrum that I can see is to change the signature of tp_dealloc() to return a flag, whether it did actually delete the object or not. Of course, I see no easy way around not clearing the slots, but the clearing of the dict could be postponed until after the call to basedealloc(). Since tp_dealloc _can_ resurrect objects (subtype_dealloc does it), subclassing such objects should work, and not crash the interpreter if the base class' dp_dealloc() decides to do so. No suggested -- messages: 101580 nosy: krisvale severity: normal status: open title: A tp_dealloc of a subclassed class cannot resurrect an object type: crash versions: Python 2.7 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8212 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8210] rev 78820 causes problems on Solaris (Python 2.6)
Changes by Brian Curtin cur...@acm.org: -- nosy: +benjamin.peterson priority: - normal stage: - needs patch type: - behavior ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8210 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8188] Unified hash for numeric types.
Mark Dickinson dicki...@gmail.com added the comment: Another update, partly to address comments raised by Guido on Rietveld. I'll upload these changes to Rietveld later today. - rename sys._hash_info to sys.hash_info and make it public rather than private (it still needs docs somewhere) - add some explanatory comments to long_hash; remove an outdated comment - fix missing error check (in previous patch) in slot_tp_hash. slot_tp_hash also now always raises a TypeError if __hash__ returns a non-integer; this is a change from current behaviour, which allows small floats to be returned by __hash__, but not large floats (where large means 2**31 or 2**63 in absolute value, depending on the system). I'm assuming this was unintentional (the docs specify that __hash__ should return an integer). - simplify specification of hash function slightly: for nonnegative x it simply computes the reduction of x; previously it computed 1 + reduction of (x-1) for positive values. This extra +-1 doesn't really add anything of value, and makes it slightly more complicated and error-prone to write your own hash function. -- Added file: http://bugs.python.org/file16629/numeric_hash4.patch ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8188 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8202] sys.argv[0] and python -m package
Nick Coghlan ncogh...@gmail.com added the comment: I realised today that this behaviour is actually the case for any execution of a module inside a package with -m (i.e. any __init__ modules execute before sys.argv and __main__ are fully configured). As I recall, I used a bit of a hack to get main.c to implement -m correctly by piggybacking on the existing -c semantics. I'll find the hack and replace it with some proper '-c' or '-m' logic. -- ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8202 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue7279] decimal.py: == and != comparisons involving NaNs
Mark Dickinson dicki...@gmail.com added the comment: Re-opening to address a couple of points that came out of the python-dev discussion: (1) As Stefan pointed out on python-dev, equality and inequality comparisons involving signaling nans should signal (order comparisons already do). IEEE 754 is fairly clear on this. From section 6.2: Signaling NaNs shall be reserved operands that, under default exception handling, signal the invalid operation exception (see 7.2) for every general-computational and signaling-computational operation except for the conversions described in 5.12. (Comparisons fall under 'signaling-computational operations, in section 5.6 of the standard.) I propose to fix this for 2.7 and 3.2. (2) Currently hash(Decimal(nan)) raises a TypeError. I can see no good reason for this at all; it's possible to hash float nans and to put them in sets and dictionaries. I propose to remove this restriction for 2.7 and 3.2. I think hash(Decimal(snan)) should also succeed: *computational* operations on signaling nans should signal, but I don't think that putting a signaling nan into a dict, or checking for its presence in a list, counts as a computational operation for this purpose. -- assignee: - mark.dickinson priority: - high status: closed - open ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue7279 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8213] Python 3 ignored PYTHONUNBUFFERED and -u
New submission from Noam Yorav-Raphael noamr...@gmail.com: Hello, Python 3.1 ignored the PYTHONUNBUFFERED environment variable and the '-u' switch (which do the same thing): stdout remains buffered even when the flag is raised. To reproduce, run: python3 -u -c 'import time, sys; sys.stdout.write(a); time.sleep(1); sys.stdout.write(\n)' You can see that it first waits a second and then 'a' is printed. I'm using Ubuntu 9.10. Tested this on both the 3.1.1 installed and svn checkout (revision 79345). This follows a bug report: https://bugs.launchpad.net/dreampie/+bug/545012 which was reported on win32, so the problem is there too. -- components: IO messages: 101584 nosy: noam severity: normal status: open title: Python 3 ignored PYTHONUNBUFFERED and -u type: behavior versions: Python 3.1 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8213 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8212] A tp_dealloc of a subclassed class cannot resurrect an object
Antoine Pitrou pit...@free.fr added the comment: Indeed. The io module has had to circumvent this and uses the following snippet when resurrecting an instance of a subclass of one of its types (see iobase_dealloc() in Modules/_io/iobase.c): /* When called from a heap type's dealloc, the type will be decref'ed on return (see e.g. subtype_dealloc in typeobject.c). */ if (PyType_HasFeature(Py_TYPE(self), Py_TPFLAGS_HEAPTYPE)) Py_INCREF(Py_TYPE(self)); return; I agree it would be nice to have an automatic way of handling this. I don't see an obvious solution, though. -- components: +Interpreter Core nosy: +benjamin.peterson, pitrou priority: - normal stage: - needs patch type: crash - feature request versions: +Python 3.2 ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8212 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8213] Python 3 ignored PYTHONUNBUFFERED and -u
STINNER Victor victor.stin...@haypocalc.com added the comment: -u is not ignored, but use line buffering: see issue #4705 and commit r68977. -- nosy: +haypo ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8213 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8213] Python 3 ignored PYTHONUNBUFFERED and -u
Changes by STINNER Victor victor.stin...@haypocalc.com: -- nosy: +pitrou ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8213 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8213] Python 3 ignored PYTHONUNBUFFERED and -u
Antoine Pitrou pit...@free.fr added the comment: In the current state of affaires this is more of a documentation issue. Python 3 doesn't support totally unbuffered text I/O (and standard streams are open in text mode). What `-u` and PYTHONUNBUFFERED do is that the binary layer of standard streams is unbuffered, but the text layer is still line-buffered (if in a tty). python --help gives you an accurate description: -u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u' Also, you can try out: python3 -u -c 'import time, sys; sys.stdout.buffer.write(bb); time.sleep(1); sys.stdout.buffer.write(b\n)' To explicitly flush the text layer, you can use the flush() method. -- priority: - normal ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8213 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com
[issue8213] Python 3 ignored PYTHONUNBUFFERED and -u
Changes by Antoine Pitrou pit...@free.fr: -- assignee: - georg.brandl components: +Documentation -IO nosy: +georg.brandl ___ Python tracker rep...@bugs.python.org http://bugs.python.org/issue8213 ___ ___ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com