Re: Problem with sys.path when embedding Python3 in C
En Mon, 22 Mar 2010 18:19:49 -0300, Krister Svanlund 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 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 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 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 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: 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 wrote: > En Mon, 22 Mar 2010 18:19:49 -0300, Krister Svanlund > 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 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. # 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 wrote: > On Mar 5, 10:01 am, BlueBird wrote: > > > > > > > On 3 mar, 20:35, Stefan Behnel 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
Re: individually updating unicodedata db?
2010/3/23 Gabriel Genellina : > En Mon, 22 Mar 2010 21:19:04 -0300, Vlastimil Brom > 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 wrote: > Omer Ihsan 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, 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" wrote: > En Mon, 22 Mar 2010 15:20:39 -0300, Pascal Chambon > 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): > > > 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() > > > Output: > > ERROR:root:An error > Traceback (most recent call last): > File "test_logging.py", line 32, in > 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 > 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 seco
Re: using message loop for hotkey capturing
Sorry about that, it is fixed now. On 3/23/10, Tim Golden 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 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 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 > 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 > 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 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 > > 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 > > 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 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 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 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 > > 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 > > 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 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=22&t=19225&sid=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 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 Golden 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 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 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 wrote: > On Mar 23, 3:12 pm, Tim Golden 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 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,"%s" % 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, 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 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,"%s" % stripped) Brilliant! That's just the type of clever solution I was looking for. Thank you! Malcolm - Original message - From: "Emile van Sebille" 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,"%s" % 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 wrote: > 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, 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: 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() 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 = '%s' ASXurl = 'http://www.asx.com.au/asx/markets/priceLookup.do? by=asxCodes&asxCodes=' 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,[newStoc
Re: Advice Criticism on Python App
On Tue, Mar 23, 2010 at 5:05 PM, 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: > 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 = '%s' ASXurl = 'http://www.asx.com.au/asx/markets/priceLookup.do? by=asxCodes&asxCodes=' 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 d&g) $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 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\James>cd C:\Python31 C:\Python31>python 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
Re: 'gcc' failed with exit status 1
JR, 24.03.2010 03:51: 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\James>cd C:\Python31 C:\Python31>python 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 Given that you're on Windows, this looks like a known bug in Cython: http://trac.cython.org/cython_trac/ticket/520 This is due to the lack of universal newline support in the codecs module, which has been fixed in the new Py2.6+ 'io' module. A patch for Cython that switches to the new 'io' module and works around this issue in older Python versions is available: http://hg.cython.org/cython-devel/raw-rev/751bdd38b55c That being said, the simplest way to work around this issue is to switch to Unix line endings in your source file. Most editors support this without problems. Stefan -- http://mail.python.org/mailman/listinfo/python-list