7000+ beautiful Russian women
7000+ beautiful Russian women http://groups.google.com/group/all-good-things/web/beautiful-girls-and-ladies -- http://mail.python.org/mailman/listinfo/python-list
Looking for someone proficient in Python to update a website.
Hello! I’m not sure if this is the right forum, but I am looking for someone proficient in Python software to update a website. I will pay well, and work in the Kansas City area. If this is not the correct way to find someone who can help, do you have any contacts in the Kansas City area who can assist? Please respond via email to [email protected] Sent from my iPhone -- https://mail.python.org/mailman/listinfo/python-list
RE: distutils and decorators
Benji York wrote: > Robert Brewer wrote: > > Actually, in this case we most definitely want to test > > 2.4's "@" syntax. The decorator in question is an aliaser, > > and therefore is one of the few > > decorators which must be implemented differently for the 2.3-style > > decoration and the 2.4-style. See the "expose" function at: > > http://www.cherrypy.org/file/trunk/cherrypy/__init__.py?rev=654 > > I extracted "expose" from the above URL and wrote this test > script (mind the wrapping): > ... > What am I missing? Nothing, apparently. Looks like I outfoxed myself with my own poor comments. Thanks for the correction! Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Will python never intend to support private, protected and public?
Title: RE: Will python never intend to support private, protected and public? Alex Martelli wrote: > I used to like [double-underscore private names], but as time > goes by have come to like it less and less; right now, > unless I have to respect existing coding standards, > I entirely avoid the double-underscore usage, > while single-underscores are OKish). Hear, hear. I've been seriously considering a ban on double-underscore names as part of the coding standard for CherryPy. And I am also glad you're back! I must say I opened several of your recent posts on topics which I would not otherwise have read. ;) Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: How to get listed on planet.python.org
Shane Hathaway wrote: > I've been writing Python-related articles on my weblog, and I thought > planet.python.org might be interested in including them. Does anyone > know how to submit a feed to the aggregator? > > http://hathawaymix.org/Weblog/rss20.xml?categories:list=Python I'm pretty sure you should just email [EMAIL PROTECTED] with your request. Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: sqlstring -- a library to build a SELECT statement
Title: RE: sqlstring -- a library to build a SELECT statement Tim Roberts wrote: "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > > > >An Example: > > > >>>> import sqlstring > >>>> model = sqlstring.TableFactory() > >>>> print model.person > >SELECT > >person.* > >FROM > >[person] person > > The [bracket] syntax is unique to Microsoft. > Everyone else, including Microsoft SQL Server, > uses "double quotes" to protect special characters > in identifiers. Except MySQL (at least 4.1), which uses backticks. http://dev.mysql.com/doc/refman/4.1/en/legal-names.html Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: How to add one month to datetime?
John W wrote: > I have been trying to figure out how to > easily add just one month to a datetime > object? ...I was wondering if there is > simple way of doing this with built in > datetime object? If you want the same day in the succeeding month, you can try: newdate = datetime.date(olddate.year, olddate.month + 1, olddate.day) ...but as you can see, that will run into problems quickly. See the "sane_date" function here: http://projects.amor.org/misc/browser/recur.py for a more robust solution, where: newdate = recur.sane_date(olddate.year, olddate.month + 1, olddate.day) will roll over any values which are out-of-bounds for their container. Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Python Framework that works with IIS/SQL Server?
[EMAIL PROTECTED] wrote: > I'd like to find a web framework that works with IIS and SQL Server on > Windows(I know-but I didn't make that decision). Anyhow, I've > looked at Turbogears, Django, subway and didn't see any evidence > that anyone had made these work in that configuration. > Any suggestions? Since TurboGears and Subway are built on top of CherryPy, they should be able to use the ASP/IIS WSGI gateway here: http://www.aminus.org/blogs/index.php/fumanchu/2005/05/26/wsgi_gateway_f or_asp_microsoft_iis ...and it seems there is some support for MS SQL Server in SQLObject, which both frameworks also use: http://sqlobject.org/SQLObject.html#ms-sql-server I use bare CherryPy with my own ORM, which handles SQL Server quite well: http://projects.amor.org/dejavu Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Reinvent no more forever
Ben Finney wrote: > I hold up all existing public source code repositories as evidence > against your prediction. Reinventing the wheel is distressingly > common, and a dependency tool isn't going to stop that. Is there ever a point at which one decides that "unusable dependency tools" are distressingly common, and cost more than reinvention? Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Iterators everywhere in Python 3000 (was: Why is dictionary.keys() a list and not a set?)
Title: Iterators everywhere in Python 3000 (was: Why is dictionary.keys() a list and not a set?) Alex Martelli wrote: > The typical reason I'm asking for .values() is because each > value is a count (e.g. of how many time the key has occurred) > and I want the total, so the typical idiom is sum(d.values()) > -- getting a result set would be an utter disaster, and should > I ever want it, set(d.values()) is absolutely trivial to code. > > Note that in both cases I don't need a LIST, just an ITERATOR, > so itervalues would do just as well (and probably faster) > except it looks more cluttered and by a tiny margin less > readable -- "the sum of the values" rolls off the tongue, > "the sum of the itervalues" doesn't!-) So, the direction > of change for Python 3000, when backwards compatibility > can be broken, is to return iterators rather than lists. > At that time, should you ever want a list, you'll say so > explicitly, as you do now when you want a set, i.e. > list(d.values()) I'd just like to throw in my anecdotal opinion regarding interfaces based on iterators. I wrote Dejavu, a pure-Python ORM, starting at about Python 2.3. I thought iterators were a Pretty Neat Idea, and used/generated iterators "all the way down": SQL results were iterated over, ORM Units were created and yielded to a StorageManager interface, which yielded them to a Sandbox interface, which yielded them to the caller. It worked wonderfully! But it was a nightmare to use. Yes, half the calls were "for thing in recall(cls, expr):", but the half that were not (slicing, popping, len, and most of all: sort) required "list(things)" or "[x for x in things]" to be written again and again. It seems trivial until you've done it many, many times. When one of my users prompted me to switch back to lists for the public interface, I jumped at the idea, and have been much happier since then as an end-user of my own library. I still have a top-level "xrecall" method, for those times when I really *need* an iterator (4.5% of the time in my current apps), and I use iterators "behind the scenes" still to support that. It would be even worse for Python: Dejavu might require a half-dozen list() calls in any given module. Some Python 3000 code could require hundreds. Because I wrote Dejavu in Python, I could separate the public, list-like interface from the internal, iterative ones pretty easily. Python can't do that for itself; if dict.values became an iterator, then a huge swath of end-user code, and even the stdlib, would be affected, with no interface layer in-between to call list() for you. [I wonder how the PyPy folks feel about "iterators everywhere"...?] Given my experience with Dejavu, I'd rather not see Python 3000 move to using iterators with abandon. IMO, it fixes a poor interface (iter) for 5% of code by introducing a poor interface (list) for 50% of code. Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Lambda as declarative idiom (was RE: what is lambda used for in real code?)
Steven Bethard wrote: > * Rewritable with existing functions > Mainly these are examples of code that can benefit from using the > functions available in the operator module, especially > operator.itemgetter and operator.attrgetter (available in 2.4) > ... > * Rewritable with list comprehensions/generator expressions > Lambdas in map or filter expressions can often be replaced by an > appropriate list comprehension or generator expression (in Python 2.3/2.4) > ... > So, those are my thoughts on how lambdas are "really" used. > If others out there have real-life code that uses lambdas > in interesting ways, feel free to share them here! Admittedly, I use lambdas in a unique way; I turn them into SQL statements. But it points out what lambdas could become: a generic declarative idiom. You might notice that operator.add, for example, is not optimized for ints and strings like BINARY_ADD is (have a gander at ceval.c); instead, operator.add uses the "slow" PyNumber_Add. But your rewrites using operator.add are much faster than the equivalent lambdas, most likely due to the function-call overhead. Wouldn't it be great if we could eval a lambda once, optimizing it as much as possible (using techniques like attrgetter, and possibly type annotations), and then let it run over large data sets? In the case of "lambda x: x + 3", we could use a type annotation to restrict the values of x to ints, and then take advantage of a compiler-side optimized int + int, evaluated once, rather than on each call. Lambdas would be much easier to optimize than full-blown functions (especially since most operations within lambdas do not produce side-effects). I know; pipe dream. But that's what *I* use lambdas for (even if I have to transform Python bytecode into another language to do it at the moment ;). Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Frameworks for "Non-Content Oriented Web Apps"
[EMAIL PROTECTED] wrote: > Let me make an attemp at defining "Non-Content > Oriented Web Applications". > > A "Non-Content Oriented Web Application": > (1) will be accessed from web browser(obviously). Clear enough. > (2) will be developed using 'W3C' and other open > standards(STRICTLY, to ensure compatibility and > portablity). This is getting better IMO. But we're still at the point where exclusively following open standards ensures in-compatibility and non-portability. Meh. > (3) will expose some kind of functionality to the user, > not just some document to read. If I were to rephrase that, I would say "serves dynamic pages" as opposed to "static". > (4) functionality can be very simple to very complex. Which usually means a multitude of tools, depending on "how complex". The big issue with leaving this question so generic is that the answers are legion. So I'll just keep it short and make my own shameless plug: try Cation for the Web interface and Dejavu for the data layer, both developed by yours truly. ;) http://www.aminus.org/rbre/python or... svn://casadeamor.com/cation/trunk svn://casadeamor.com/dejavu/trunk Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Lambda as declarative idiom
Michael Spencer wrote:
> Roman Suzi wrote:
>
> > Maybe this is too outlandish, but I see lambdas as a
> "quote" mechanism,
> > which presents a possibility to postpone (precisely
> control, delegate)
> > evaluation. That is, an ovehead for lambda must be much
> lower but at the
> > same time visible to the programmer:
> >
> > d = a + (lambda x, y: x+ y)(3, 4)
> [...]
>
> I believe that this "possibility to postpone" divides into
> two related but separate concepts: controlling the moment
> of evaluation, and assembling the arguments required at
> that moment. They are both species of 'eval', but
> managing arguments is more specialized, because it includes
> possibly renaming parameters, assigning default values,
> processing positional and keyword arguments, and, perhaps
> in the future dealing with argument types.
Yes, but the "moment of evaluation" is more complex than just
"postponing". In a declarative construct, you probably also want global
variables to be bound early, so that the expression does not depend upon
*any* free variables. Ditto for closures. A more realistic example:
term = input("Enter the amount to add")
e = expr(x): x + term
...MUCH code passes, maybe even a new process or thread...
d = a + e(3)
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: Bug in handling of single underscore identifiers?
Tom Blackwell wrote:
> Today I installed the 'mechanoid' package from sourceforge, but the
> self-test failed. On looking into it, I noticed odd behaviour in the
> handling of single underscore module names. Importing into the
> current namespace with 'from' seems to work, but accessing members of
> the imported module only works if the imported name is qualified by
> the containing module name.
>
> For example:
> >>> from mechanoid import _mechanoid_Common
> >>> from _mechanoid_Common import Common
> Traceback (most recent call last):
> File "", line 1, in ?
> ImportError: No module named _mechanoid_Common
> >>> from mechanoid._mechanoid_Common import Common
> **succeeds**
> >>> _mechanoid_Common
> 'mechanoid\_mechanoid_Common.pyc'>
>
> Is this a bug or a feature? The language reference section 2.3.2
> 'Reserved classes of identifiers' indicates that identifiers starting
> with a single underscore are not imported by "from module import *".
> However I can't find any indication that "from module import _name"
> should work this way.
I don't think this has anything to do with the underscore. The import
statement doesn't reference module globals; instead, it uses its own
mechanism to find the module you specify:
>>> from os import path
>>> path.sys
>>> from path import sys
Traceback (most recent call last):
File "", line 1, in ?
ImportError: No module named path
In your example ("from _mechanoid_Common import Common"), import can't
find any module named "_mechanoid_Common" in site-packages, PYTHONPATH,
or other known sources.
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: Pre/Postconditions with decorators
Stephen Thorne wrote:
> On 6 Jan 2005 13:33:42 -0800, Rittersporn
> <[EMAIL PROTECTED]> wrote:
> > @condition("number>0 and number<2","result>=0")
> > def sqrt(number):
> > import math
> > return math.sqrt(number)
> >
> > @condition("list(seq) is not None","sum(seq)==result")
> > def my_sum(seq):
> > tmp=0
> > for element in seq:
> > tmp+=element
> > return tmp
> >
> > print sqrt(1.2)
> > print my_sum([1,2,3])
>
> I think it would be nicer to have the pre and post conditions
> being compilable.
Me too.
> @condition((list(seq) is not None for seq in args), (sum(seq)==result
> for ((seq,), result) in (args, result))
>
> or something silly like that.
Ian Bicking was just talking about @require decorators:
http://blog.ianbicking.org/already-under-our-noses.html
@require(int, int)
def gcd(a, b):
...
If we made a "checker" module for such things in the stdlib, we could
write most of that:
from checker import *
@args((list, itemsnotNone, ))
@returns((any, ))
def my_sum(seq):
tmp=0
for element in seq:
tmp+=element
return tmp
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: DOS problem (simple fix??)
Gavin Bauer wrote:
> My DOS window (running in windows ME) closes the second it finishes
> running my programs. As you can imagine, this makes it hard to see the
> results. I've gotten in the habit of putting raw_input("Press enter to
> exit") at the end of every program, and in addition to being pain in
> the butt, it often fails to work. Being new to programming in general,
> I make more mistakes than most people. My programs often have errors
> before they get to my raw_input command. They then display the error
> and immediately close. It is naturally a lot easier to fix an error
> when you know what the error is. This makes debugging even more
> annoying than it ordinarily would be, if you can imagine that. I've
> heard that it should be a simple preference fix, but I've asked around
> and no one seems to know how.
>
> Thank you, and please make all answers simple enough to be understood
> by a highschool student and his father :) .
Even after all the IPO hype, the map integration, and the Suggest beta,
Google is STILL your friend:
http://www.google.com/search?q=windows+console+remain+open
In other words, use the /k switch to cmd.exe
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: Display Function Code Body?
Haibao Tang wrote:
> Hail Python pals! I played with the R (http://r-project.cran.org) last
> night to do some statistics and it has an interactive session too, and
> I found a feature that is quite useful.
>
> I found by actually typing a function name, the R gives you a
> code body output.
>
> > f1 = function(x){x*x}
> > f1
> function(x){x*x}
...
> What I would like to do is to write a function like disp(),
> when typed, it can give you the code infomation.
>
> >>> disp(f1)
>
> def f1(x):
> return x*x
>
You can do this with lambdas with my LambdaDecompiler inside:
http://www.aminus.org/rbre/dejavu/codewalk.py
If you want to extend it to full functions, be my guest. ;)
There's also a commercial decompiler out there called "decompyle", and
they even have a web service. http://www.crazy-compilers.com/decompyle/
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: switching an instance variable between a property and a normal value
Steven Bethard wrote: > I'd like to be able to have an instance variable that can > sometimes be > accessed as a property, and sometimes as a regular value, > e.g. something > like: ... > py> c.x is c.x # I'd like this to be False You'd like 'c.x is c.x' to be FALSE? You can't be serious. Must be a typo. If you want C._x to return something other than the property descriptor, you can. Grab the sample code for Property from http://users.rcn.com/python/download/Descriptor.htm#properties and modify the __get__ method: def __get__(self, obj, objtype=None): if obj is None: return self# Return whatever you like here if self.fget is None: raise AttributeError, "unreadable attribute" return self.fget(obj) That might be one way to get what you want. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Exception report library
Ian Bicking wrote: > I've been using one of several systems to catch unexpected exceptions > and log them (e.g., write to a file, display on web page, email me, > etc). But many are built into a particular system, or have an > interesting but incomplete set of features. E.g., many web > frameworks have exception reporters (and the stdlib includes cgitb), > but I want to handle non-web exceptions in the same way as exceptions > from web requests, and that's not generally easy. ... > I feel like there must be something out there, since every Python > programmer has to deal with this sort of thing to some degree...? I feel that way, too, but haven't found it. I broke my webapp framework out of my ORM late last year, and quickly realized how small the core framework really is (22k, versus 250k for the web bits). Features like the logging handler could be provided as separate modules, rather than built into the Application object, and I've been meaning to get around to that. If we could put our many heads together, I think this would be doable for the stdlib. Here are the pieces of the framework, by the way, which might also benefit from some standardization (I was thinking about them all at once): 1. Thread-safe application state 2. Logging (+ exception handling) 3. Configuration data (reading from various sources) 4. Registry of Workers for getting things done on a schedule, possibly recurring 5. Registry of startup/shutdown functions 6. Registry of active user interfaces I think the first three are all good candidates for a standard. If we had a standard, thread-safe Application object, the rest could be registerable plugins for that. You'd basically register callbacks for app.startup and .shutdown methods to iterate over. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: switching an instance variable between a property and a normal value
Steven Bethard wrote:
> I'm playing around with a mapping type that uses setdefault
> as suggested
> in http://www.python.org/moin/Python3_2e0Suggestions. The
> default value
> for a missing key is either a simple value, or a value
> generated from a
> function. If it's generated from the function, it should be
> generated
> new each time so that, for example, if the default is an empty list,
> d[1] and d[2] don't access the same list. This is why 'c.x is c.x'
> should be False if I'm using the function.
>
> The best option I guess is to rewrite this with a
> _getdefault() function instead of a property:
>
> But I was hoping to avoid having two separate attributes (self._value
> and self._func) when only one should have a value at any given time.
It seems to me like you were using the property as a glorified flag.
Just use a flag.
ftypes = ('BuiltinFunctionType', 'BuiltinMethodType',
'FunctionType', 'GeneratorType', 'LambdaType',
'MethodType', 'UnboundMethodType',)
class D(dict):
def __init__(self):
self._default = None
self._call_default = False
def __getitem__(self, key):
if not key in self:
if self._call_default:
self[key] = self._default()
else:
self[key] = self._default
return dict.__getitem__(self, key)
def setdefaultvalue(self, value):
self._default = value
self._call_default = isinstance(value, ftypes)
...or:
def setdefaultvalue(self, value, call_callables=True):
self._default = value
self._call_default = callable(value) and call_callables
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: Exception report library
Ian Bicking wrote: > I've been using one of several systems to catch unexpected > exceptions and log them (e.g., write to a file, display on > web page, email me, etc). But many are built into a > particular system, or have an interesting but incomplete > set of features... > I feel like there must be something out there, since every Python > programmer has to deal with this sort of thing to some degree...? And I replied: > I feel that way, too, but haven't found it...If we could put our > many heads together, I think this would be doable for the stdlib. Ian: > I'm not optimistic about a good exception handler in the standard > library; development slows down a lot at that point, and it's not a > reasonable candidate until it is designed and used Sure; I understand it's a long process, and should start independently. Me again: > Here are the pieces of the framework, by the way, which might also > benefit from some standardization: > >1. Thread-safe application state >2. Logging (+ exception handling) >3. Configuration data (reading from various sources) >4. Registry of Workers for getting things done on a schedule, > possibly recurring >5. Registry of startup/shutdown functions >6. Registry of active user interfaces > > I think the first three are all good candidates for a standard. > If we had a standard, thread-safe Application object, the rest > could be registerable plugins for that. You'd basically register > callbacks for app.startup and .shutdown methods to iterate over. Ian: > Hmm... I'm confused by these bits. Are you talking about > libraries for other parts of a web framework, besides exception > handling? If so, you might want to look into WSGI... Those are the bits I pulled out as specifically non-web-specific, which could be used for any kind of app (and tend to get rewritten for every framework). If your app is single-process, multi-threaded, it needs a state manager so two threads don't load or destroy global resources simultaneously. Most apps need logging and uncaught exception handling (as you noticed). Etcetera. One way to meet these needs once-and-for-all would be to have a (eventually standard) library for them, where you could mix and match the pieces you needed. So, you could write WSGI consumers of them, but they wouldn't be WSGI-specific in my mind. If they were, they'd just add to the "several systems" you were lamenting... ;) Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: there's a socket.sendall(), so why no socket.recvall()?
Irmen de Jong wrote: > Subject says it all; > there's a socket.sendall(), so why no socket.recvall()? Good question! Something like: # Receive reply. data = [] while True: try: chunk = conn.recv(8192) except Exception, x: if x.args[0] != 10035: raise x else: if chunk == '': break data.append(chunk) If you call .makefile() and then .read() the _fileobject, you get the same behavior (only better). Adding recvall would just duplicate that, I think. But that's desirable IMO. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Writing huge Sets() to disk
Martin MOKREJŠ wrote: > I have sets.Set() objects having up to 20E20 items, > each is composed of up to 20 characters. Keeping > them in memory on !GB machine put's me quickly into swap. > I don't want to use dictionary approach, as I don't see a sense > to store None as a value. The items in a set are unique. > > How can I write them efficiently to disk? got shelve*? Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] * the "shelve" module in the standard library, that is. -- http://mail.python.org/mailman/listinfo/python-list
RE: Writing huge Sets() to disk
Martin MOKREJŠ wrote: > Robert Brewer wrote: > > Martin MOKREJŠ wrote: > > > >> I have sets.Set() objects having up to 20E20 items, > >>each is composed of up to 20 characters. Keeping > >>them in memory on !GB machine put's me quickly into swap. > >>I don't want to use dictionary approach, as I don't see a sense > >>to store None as a value. The items in a set are unique. > >> > >> How can I write them efficiently to disk? > > > > > > got shelve*? > > I know about shelve, but doesn't it work like a dictionary? > Why should I use shelve for this? Then it's faster to use > bsddb directly and use string as a key and None as a value, I'd guess. If you're using Python 2.3, then a sets.Set *is* implemented with a dictionary, with None values. It simply has some extra methods to make it behave like a set. In addition, the Set class already has builtin methods for pickling and unpickling. So it's probably faster to use bsddb directly, but why not find out by trying 2 lines of code that uses shelve? The time-consuming part of your quest is writing the timed test suite that will indicate which route will be fastest, which you'll have to do regardless. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Uploading files
Peter Mott wrote: > If you upload a file using the cgi module is there any > way to discover the file name that the user submitted > as well as the file data? I've googled till I squint > but I can't find anything. Working example (for ASP, which uses BinaryRead to get the request stream): contentLength = int(env['CONTENT_LENGTH']) content, size = request.BinaryRead(contentLength) content = StringIO.StringIO(content) form = cgi.FieldStorage(content, None, "", env, True) content.close() for key in form: value = form[key] try: filename = value.filename except AttributeError: filename = None if filename: # Store filename, filedata as a tuple. self.requestParams[key] = (filename, value.value) else: for subValue in form.getlist(key): self.requestParams[key] = subValue Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: why are people still using classic classes?
Simon Wittber wrote: > Is there a legitimate use for classic classes that I am not aware of? As was pointed out to me when I asked on this list just a short while ago ;) classic classes can be faster. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: module on files & directories
Sara Fwd wrote: > > Can anybody help me find a module or a function that > > looks in a directory and defines whether the objects > > in there are files or directories? and Simon Brunning replied: > See os.path.isfile() and os.path.isdir() - > <http://docs.python.org/lib/module-os.path.html>. I suspect you will also want to look at os.walk() eventually: for root, dirs, files in os.walk(path): for dir in dirs: do_something_with(dir) Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: python to mssql
Brane wrote: > can someone please give me some info regarding subject http://sourceforge.net/projects/mysql-python Ask a broad question... Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: simultaneous multiple requests to very simple database
Eric S. Johansson wrote: > I have an application where I need a very simple database, > effectively a very large dictionary. The very large > dictionary must be accessed from multiple processes > simultaneously. I need to be able to lock records within > the very large dictionary when records are written to. Just to clarify, you want shared-read until a write, at which point you want to lock just the item being written? Or would page or table locking be acceptable at that point? Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: generator expressions: performance anomaly?
Jeremy Bowers wrote: > On Tue, 18 Jan 2005 14:05:15 +, Antoon Pardon wrote: > > I don't see how generating byte code for a = 9; when seeing the > > expression a = 3 + 6, would be a problem for non-functional > > languages. > > Ultimately, the use is fairly limited; I can't imagine the > execution time saved would reach the time of implementation > for weeks after a release, even aggregating across all Python > use in the world, and "real time gained" (i.e., time useful > to a human) would probably never add up to the > implementation time. So why bother? That's a horrid trade off > when there are so many other real gains to be had. Especially since you can already do it explicitly with Raymond Hettinger's cookbook recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Solutions for data storage?
Leif K-Brooks wrote: > My ideal solution would be an object database (or object-relational > mapper, I guess) which provided total transparency in all but a few > places, built-in indexing, built-in features for handling schema > changes, the ability to create attributes which are required to be > unique among other instances, and built-in querying with > pretty syntax. Thanks; I'll add unique indexing to the feature list for Dejavu. Should be about 15 lines of code. :) Try svn://casadeamor.com/dejavu/trunk if you want a truly Pythonic query syntax. Wait a couple of days, and I'll have version 1.3 ready and online at http://www.aminus.org/rbre/python -- lots of changes from 1.2.6 which is there now, but at least you can read old docs online now without svn. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Accessing MDB files on Windows
Jorge Luiz Godoy Filho wrote: > What is the best way to deal with MDB files? I was thinking on using > ODBC... I'll need to read and write some information to it. The load > won't be so high, but there might be a lot of data. > > Any advices? Will my approach work? I'm not a Windows guy... :-) Use ADO unless you need to support older versions of Windows. It'll be a lot faster and cleaner than ODBC. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: RuntimeError: dictionary changed size during iteration
Roman Suzi wrote: > I think, the behaviour below is misfeature: > > >>> [e for e in vars()] > Traceback (most recent call last): > File "", line 1, in ? > RuntimeError: dictionary changed size during iteration > >>> e = None > >>> [e for e in vars()] > ['e', '__builtins__', 'rlcompleter', '__file__', '_[1]', > 'atexit', '__name__', > 'readline', '__doc__'] But not unexpected, since vars() returns a dictionary, and binding 'e' changes that dictionary while you are iterating over it. Try either: [e for e in vars().keys()] or e = None [e for e in vars()] or the generator expression if you have Python 2.4. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Solutions for data storage?
Leif K-Brooks wrote: > Robert Brewer wrote: > > Try svn://casadeamor.com/dejavu/trunk if you want a truly > Pythonic query > > syntax. Wait a couple of days, and I'll have version 1.3 ready and > > online at http://www.aminus.org/rbre/python -- lots of changes from > > 1.2.6 which is there now, but at least you can read old > docs online now > > without svn. > > Thanks a lot for the reply. I've skimmed the documentation (very > well-written, by the well), and I really like the looks of what I've > seen so far. I'm a bit confused about where sandboxes get created, > though; in a Web application, would I give each request a > sandbox of its > own, or create one for the entire application, or what? Correct; in a Web application, each request should get its own sandbox. Here's a sample mod_python request.py script, where "cation" is my webapp framework, and "mcontrol" is the name of the app itself, which possesses a Dejavu arena object. from cation.html.uimodpython import UserInterfaceModPython import mcontrol def handler(req): ui = UserInterfaceModPython(mcontrol.application) ui.sandbox = mcontrol.arena.new_sandbox() ui.request(req) ui.sandbox.flush_all() return ui.status_code Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] P.S. I've finally tested postgres, mysql, and sqlite on both Debian Linux and Windows 2k, and made the final updates. So the 1.3 release should be _very_ soon. -- http://mail.python.org/mailman/listinfo/python-list
QOTW from Ryan Tomayko
http://naeblis.cx/rtomayko/2005/01/20/getters-setters-fuxors "...Many people coming to Python can't believe no one uses IDEs. The automatic assumption is that Python is for old grey beards who are comfortable with vi and Emacs and refuse to accept breakthroughs in programming productivity like IDEs. Then they write a little Python code and realize that an IDE would just get in their way." FuManChu -- http://mail.python.org/mailman/listinfo/python-list
Dejavu 1.3, a Python ORM
The Dejavu Object-Relational Mapper (version 1.3) is now available and in the public domain. Get it at svn://casadeamor.com/dejavu/trunk or http://www.aminus.org/rbre/python/. Dejavu is an Object-Relational Mapper for Python applications. It is designed to provide the "Model" third of an MVC application. Dejavu avoids making decisions in the framework which are better left to developers, and avoids forcing developers to make decisions which are better left to deployers. In particular, deployers are allowed to mix and match storage mechanisms, including how and when to cache objects in memory, making it easier for deployers to tune applications to their particular environment. Dejavu provides: MODELING LAYER 1. A base Unit class for persisting objects to storage. 2. A base Unit Property class for persistent object attributes. 3. ID Sequencers. 4. Associations between Unit classes. 5. Unit Engines, Rules, and Collections. 6. Aggregation and analysis tools. APPLICATION LAYER 1. Expressions: pure Python Unit queries. This is perhaps the most appealing feature of Dejavu. However, since it uses bytecode hacks, Dejavu only runs on CPython. 2. Sandboxes, which serve as Identity Maps and per-connection caches. Unit objects are "memorized" and "recalled" from a Sandbox, using Expressions. 3. An Arena class for application-level data. STORAGE LAYER 1. A base StorageManager class and specification. Unlike many ORMs, Dejavu does not require you to have complete control of the back end. 2. Specific StorageManagers for: a. Microsoft SQL Server/MSDE via ADO. b. Microsoft Access (Jet) via ADO. c. PostgreSQL. d. MySQL. e. SQLite. f. ODBC databases (not complete, and probably never will be). g. Shelve to dbm. Major changes from 1.2: 1. Support for PostgreSQL, MySQL, and SQLite. 2. New db module which abstracts common DB StorageManager code. 3. Full support for decimal and fixedpoint. 4. zoo_fixture.py brings common tests to all StorageManagers. Dejavu welcomes your use and feedback as an application developer. Dejavu also welcomes framework developers. New code for additional Storage Managers, analysis tools, or other portions will be gladly reviewed for inclusion in future releases. Drop me an email if you feel so inclined. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Python Scripting
Ali Polatel wrote: > I want to ask you a question about python scripting. > I want to know if I can design web-pages with python Yes. > or at least write html files with python. Yes. > and if I write html files with python and some CGI scripts > and upload them to the web-page .. does the people who view > those pages have to have python interpreters in their computers? No. > Another question is ... I am writing a bot for a chess server > in python and this bot should update a web-page when it gets > some commands from the server. How can i make a programme update > a web-page? If the file is local: open(filename, 'w').write(content) If the file is remote and you need to upload it via ftp, check out the ftplib module in the standard library, for starters. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: I want update one record using ADO,but I can't ,why?
nightmarch wrote: > I want update one record ,but I can't ,why? > > code like following: > > ##- > import win32com.client as wc > > def main(): > conn = wc.Dispatch(r'ADODB.Connection') > rs = wc.Dispatch(r'ADODB.Recordset') > connStr = "Provider=MSDAORA.1;Password=jmpower;User > ID=jmpower;Data Source=jmgis_agps3;Persist Security Info=True" > tblName = r'wjtmp' > > conn.Open(connStr ) > > rs.Open( tblName, conn, wc.constants.adOpenKeyset, > wc.constants.adLockOptimistic ) > > if rs.Supports( wc.constants.adUpdate ): > rs.Fields.Item(0).Value = 11 > rs.Update() > else: > print "recordset can't update" > > rs.Close() > conn.Close() > > if __name__ == '__main__': > main() > ##- You almost give us enough information to help out ,but you don't quite ,why? What happens when you run the above? Is there any output? Error message? Does your update affect the membership of the record in the keyset? http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/ htm/mdconkeysetcursors.asp Why are you using keysets at all? Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: I want update one record using ADO,but I can't ,why?
nightmarch wrote: > Sorry, I mean this code line " rs.Supports( wc.constants.adUpdate ) " > got False result, So I can't update one record,i.e. I can't execute > this code "rs.Fields.Item(0).Value = 11". > > And , if code is written like this: > > ##conn.Open(connStr ) >rs.Open( tblName, conn, wc.constants.adOpenKeyset, > wc.constants.adLockOptimistic ) > >rs.Fields.Item(0).Value = 11 >s.Update() > ##>code- > > I got error msg like following: > > ## self._oleobj_.Invoke(*(args + (value,) + defArgs)) > com_error: (-2147352567, '\xb7\xa2\xc9\xfa\xd2\xe2\xcd\xe2\xa1\xa3', > (0, 'ADODB.Field', 'Current Recordset does not support updating. This > may be a limitation of the provider, or of the selected locktype.', > 'C:\\WINNT\\HELP\\ADO210.CHM', 0, -2146825037), None) > ##>errorMsg Well, without knowing your entire Oracle setup, I'm not sure how far one can get. My only thought is to try a full SELECT statement instead of just the tablename, and preface the tablename with the schema, something like: "select * from %s.%s;" % (schema, tblName) It's possible the trailing semicolon is important to close the statement. The next thing to check would be permissions. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Best python postgres module?
Roland Heiber wrote: > i recently migrated from mysql to postgresql and did use > severel python > postgres-modules. All do what they are designed for, so > which one would > you use? psycopg, pygresql, pypgsql? psycopg seems to be the best > solution for heavy traffic/multiple connections i have no real > testing environment, so any advice which one to use for different > usecases would be nice. If your "use cases" involve cross-platform development (i.e. Linux and Windows), pypgsql seems to fit the bill nicely. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: variable declaration
AlexanderZatvornitskiy wrote: > I'am novice in python, and I find one very bad thing (from my > point of view) in > language. There is no keyword or syntax to declare variable, > like 'var' in > Pascal, or special syntax in C. It can cause very ugly > errors,like this: > > epsilon=0 > S=0 > while epsilon<10: > S=S+epsilon > epselon=epsilon+1 > print S > > It will print zero, and it is not easy to find such a bug! > > Even Visual Basic have 'Option Explicit' keyword! May be, > python also have such > a feature, I just don't know about it? The feature is called "pychecker", and, although it isn't included in the standard distribution, it's readily available: http://pychecker.sourceforge.net/ Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: variable declaration
Alex Martelli wrote: > If Python doesn't fit YOUR brain, for example because your brain is > ossified around a craving for the declaration of variables, > then, unless > you're specifically studying a new language just for personal growth > purposes, I think you might well be better off with a language that > DOES, at least until and unless your brain changes by other means. *shudder* Once a VB coder, always a VB coder? Whatever your first shop uses, you're stuck with for life? Again, I say *shudder*. Bah. Nothing teaches you a new language like having your job depend upon it. People who study languages merely for "personal growth" learn 50% of the syntax and 1% of the concepts, and then fritter that learning away on inconsequential newsgroups the world over. Alex Z, keep using and learning Python. Let it change your brain. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: variable declaration
Alex Martelli wrote: > > Robert Brewer <[EMAIL PROTECTED]> wrote: > > > Bah. Nothing teaches you a new language like having your > job depend upon > > it. People who study languages merely for "personal growth" > learn 50% of > > the syntax and 1% of the concepts, and then fritter that > learning away > > on inconsequential newsgroups the world over. > > I disagree. I studied Python, even though it had nothing to > do with my > job, just with the idea of using it on hobby projects; yet I believe I > can reasonably claim to have learned more than 50% of the > syntax and 1% > of the concepts, even though you might claim that, whatever percentage > it may be, it's "frittered away on inconsequential newsgroups". You are an exceptional person, Alex. ;) Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Python AST Sprint
Timothy Fitz wrote: > I am interested in helping Python, however my knowledge of Abstract > Syntax Trees is lacking. Where should I turn to educate myself? Any > books or websites would be appreciated. Follow the links and advice in this python-dev thread: http://marc.free.net.ph/thread/20050104.014254.b2978a88.en.html#20050104 .014254.b2978a88 That should hold you until the sprint ;) Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Converting a string to a function pointer
Håkan Persson wrote: > I am trying to "convert" a string into a function pointer. > Suppose I have the following: > > from a import a > from b import b > from c import c > > funcString = GetFunctionAsString() > > and funcString is a string that contains either "a", "b" or "c". > How can I simply call the correct function? > I have tried using getattr() but I don't know what the first (object) > argument should be in this case. If you want to avoid typing all of the "import" statements, use something like my public-domain xray module (http://www.aminus.org/rbre/python/xray.py) and then write: import xray funcString = GetFunctionAsString() func = xray.functions(funcString) func() Dotted-package names work with that module, by the way. The benefit is that you can then import any function in any module. The curse is that you can then import any function in any module. ;) Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Persistence design [was: RE: OT: why are LAMP sites slow?]
Jack Diederich wrote:
> *ding*ding*ding* The biggest mistake I've made most
> frequently is using
> a database in applications. YAGNI. Using a database at all has it's
> own overhead. Using a database badly is deadly. Most sites would
> benefit from ripping out the database and doing something simpler.
> Refactoring a database on a live system is a giant pain in the ass,
> simpler file-based approaches make incremental updates easier.
>
> The Wikipedia example has been thrown around, I haven't looked at the
> code either; except for search why would they need a database to
> look up an individual WikiWord? Going to the database
> requires reading
> an index when pickle.load(open('words/W/WikiWord')) would
> seem sufficient.
>
...
>
> If there is interest I'll follow up with some details on my own LAMP
> software which does live reports on gigs of data and - you
> guessed it -
> I regret it is database backed. That story also involves why
> I started
> using Python (the prototype was in PHP).
I'd be interested, if only selfishly to hear more potential use cases
for *my* projects. ;)
One of my goals for Dejavu* (my ORM) is to abstract persistence to the
point that you can easily test your actual, live dataset against many
potential storage mechanisms (i.e. multiple DB's, but also shelve,
etc.). I need to finish the migration tools, but it's well on the way.
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
* http://www.aminus.org/rbre/python
--
http://mail.python.org/mailman/listinfo/python-list
RE: Python Processes for Win32
[EMAIL PROTECTED] wrote: > I have a daemon type script (daemon.py -- we'll say) that I would like > to have run continuously. I'd like to be able to do something like > this: > > daemon.py start > > ... and then to have it stop I'd like to do this: > > daemon.py stop > > I am having a hard time googling for a clue as to how to accomplish > this. If anyone can point me in the right direction, I'd really > appreciate it. Write a Windows service (natively, see http://www.python.org/windows/win32 or using py2exe, see http://starship.python.net/crew/theller/py2exe/). Then use: net start daemonsvc net stop daemonsvc Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: bad generator performance
Johannes Ahl mann wrote: > i am in the process of profiling an application and noticed how much > time my depth first generator for walking a tree data structure took. > > i wrote the same thing as a recursive function producing an array, and > this non-generator version is nearly 10 times faster! > > any ideas why this is, what i did wrong... > for some reason the generator version appears as being called > much more > often than the recursive one. no idea why that is, but the data is > definitely identical! > > here the output from the python profiler and the respective code: > > ### snip ### > > ncalls tottime percall cumtime percall filename:lineno(function) > 94209/81910.5600.0000.5900.000 > :71(depthFirstIterator2) > 4095/10.0600.0000.0800.080 :62(depthFirstIterator1) > > ### snip ### > > def depthFirstIterator1(self, depth = 0): > ret = [[self, True, depth]] > > if self.isFolder(): > for c in self.children: > ret = ret + c.depthFirstIterator(depth = depth + 1) > > return ret + [[self, False, depth]] > > def depthFirstIterator2(self, depth = 0): > yield [self, True, depth] > > if self.isFolder(): > for c in self.children: > for y in c.depthFirstIterator(depth = depth + 1): > yield y > > yield [self, False, depth] > > ### snip ### > > i'd appreciate any comments or explanations why the generator might be > so much slower, as i had just decided to use generators more > frequently > and in the respective PEP they are praised as generally fast. Um. Under my definition of "recursion", you haven't really removed recursion in the generator version. That is, you're still calling the depthFirstIterator method upon each iteration--you've just changed from list-concatenation to yielding instead, which trades off list-management overhead for closure-maintenance overhead. A truly non-recursive implementation would probably exist outside of whatever class you've got this method in, and would keep its own pointer to the current node as it traversed the tree. Hope that helps, Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: unittest: collecting tests from many modules?
"Jorgen Grahn" wrote: > I have a set of tests in different modules: test_foo.py, > test_bar.py and so on. All of these use the simplest > possible internal layout: a number of classes containing > test*() methods, and the good old lines at the end: > >> > >> if __name__ == "__main__": > >> unittest.main() > >> > This is great, because each of the modules are runnable, > and I can select classes or tests to run on the commandline > if I want to. However, running all the tests from e.g. > a Makefile is not that fun; I don't get a single pass/fail > summary across the modules. > > What's the best way of creating a test.py which > - aggregates the tests from all the test_*.py modules? > - doesn't require me to enumerate all the test classes in test.py > (forcing each module to define test_foo.theSuite or > someting would be OK though) > - retains the ability to select tests and verbosity (-q, > -v) from the > command line? I missed the first post somehow; hope this gets in the conversation in the right place. Anyway, use normal os.walk() calls to gather the files which start with "test_"; then use the TestLoader.loadTestsFromName method to instruct unittest to test them as a group. If you want a working example, see the CherryPy test loader at: http://www.cherrypy.org/file/trunk/cherrypy/test/test.py (In that example, I overrode loadTestsFromName in a subclass, in order to be less verbose in exactly the way I wanted, but the default works just as well). Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Debugger Confusion
Rex Eastbourne wrote: > I'm a little confused about which debugging utilities do what, and > which I should use for my Python code. I'd like to be able to step > through my code, insert breakpoints, etc. I haven't been able to do > this yet (I'm using Emacs on Windows). I have seen references to GDB, > GUD, PDB, and others. Which ones do I need? 1. At the point you would like to start the debugger, insert the following 2 lines: import pdb pdb.set_trace() 2. Run your script from the command line. 3. When your script executes the above lines, the pdb debugger will start up, and give you a prompt. Type 'h' at the prompt (and hit 'enter'), and you'll be shown a list of pdb commands. 's' to step through your code, 'c' to continue processing (and stop the debugger, essentially). The prompt is interactive, so you can inspect program variables as you like. Start with that, and come back if you have any more questions. :) Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Yet Another Python Web Programming Question
Daniel Bickett wrote: > I neglected to mention an important fact, and that is the fact that I > am limited to Apache, which elminates several suggestions (that are > appreciated none-the-less). Do you have access to mod_python, mod_rewrite, FastCGI, or SCGI? Then CherryPy 2.1 is still a great option for you with Apache: http://www.cherrypy.org/wiki/WSGIServers http://www.cherrypy.org/wiki/BehindApache Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Yet Another Python Web Programming Question
Paul Boddie wrote: > "Robert Brewer" <[EMAIL PROTECTED]> wrote in message > news:<[EMAIL PROTECTED]>... > > Daniel Bickett wrote: > > > I neglected to mention an important fact, and that is the > > > fact that I am limited to Apache, which elminates several > > > suggestions (that are appreciated none-the-less). > > > > Do you have access to mod_python, mod_rewrite, FastCGI, or > > SCGI? Then CherryPy 2.1 is still a great option for you with > > Apache: > > http://www.cherrypy.org/wiki/WSGIServers > > http://www.cherrypy.org/wiki/BehindApache > > According to the "quick facts" page "CherryPy powered web > applications are in fact stand-alone Python applications embedding > their own multi-threaded web server", suggesting that if the hosting > environment is "limited to Apache" and if this can also be taken to > mean that the environment doesn't permit long-running server processes > apart from Apache, then CherryPy isn't likely to be suitable. Thanks for pointing that out; that page was out of date, and has now been corrected: http://www.cherrypy.org/wiki/CherryPyQuickFacts . CherryPy 2.1 apps can be deployed using Apache (via mod_python) or IIS (via ASP) as the webserver *without* running the webserver built into CherryPy. In fact, CherryPy should work with any WSGI-capable webserver, and be deployable in a wide variety of hosting environments with no changes to your application code. Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: ANN: CherryPy-2.1.0-beta released
Damjan wrote: > > I am happy to announce the first beta release of CherryPy-2.1 > ... > > unicode decoding/encoding, > > This especially interesting to me. > Is CherryPy completelly unicode (and UTF-8) ready? > The thing that frustrates me about quixote2 is that it has a lot of > assumptions that text is a str object in the latin1 encoding. > I succeded to patch quixote to be usable but that may not be enough. > > My quixote application works with unicode objects all the > time, and the only place I want UTF-8 is when the content > is sent to the client... (or when its stored in a database > or file which I handle myself fine). Encoding is a snap in CherryPy 2.1. Write your application using unicode objects, then have all output converted to UTF-8 by simply writing in your config file: encodingFilter.on = True To use a different encoding, write: encodingFilter.encoding = "ascii" Encoding is restricted to a limited set of MIME types; 'text/html' is the default list. To change that, use the config entry: encodingFilter.mimeTypeList = ['text/html', 'text/plain'] All of these configuration entries are specifiable per-path, so different portions of your site can use different encoding schemes. Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: WSGI-server in the standard distro?
> Having a HTTP 1.0/1.1-compliant production-grade > WSGI-only server in the distro would be sweet :-) > > I might be demanding a bit much here, but still ... To "demand" it might be a bit much, but to "expect" it...? ;) I don't think anyone's going to drop what they're doing and go code such a server because it's been demanded; even if they did, it would need a long-ish period of time in which it was tested by the community in production scenarios. However, since our hypothetical server is not yet in the standard library, who would use it in production? Catch-22. An alternative would be to allow one or more of the servers which have been written for CherryPy or Django to see some use "in the wild", and have each go through its own series of bugfixes and performance improvements, driven by direct need. When they have done so, we can compare them and drop one into the standard library with far fewer unknowns. I'm obviously biased (being on the CherryPy team), but I think the "winner" will be Peter Hunt's WSGI server for CherryPy. It was designed from the beginning to be framework-agnostic; that is, there's nothing CherryPy-specific in the module. Peter has said multiple times that he'd like it to become the standard WSGI server, and that his desire is for other frameworks to adopt it wholesale. Django should certainly grab it right away; performance-wise, it beats the pants off the reference server that comes with wsgiref (which is what they based their WSGI server on). If there are any licensing or other issues keeping django from using the CherryPy WSGI server, swing by irc://irc.oftc.net/cherrypy and we'll get them worked out in a hurry. Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Multiple (threaded?) connections to BaseHTTPServer
Adam Atlas wrote: > Is there any built-in way for BaseHTTPServer to handle multiple > connections at once, e.g. with threads? If not, can this existing > module be easily extended to do this, or will I have to do lower-level > socket things (and probably thus have to write my own HTTP code)? Do you *really* want to reinvent that wheel? ;) I'd suggest you start with a threaded HTTP server from one of Python's many web frameworks. Since I hack on CherryPy, I'll link you to its liberally-licensed PooledThreadServer: http://www.cherrypy.org/file/trunk/cherrypy/_cphttpserver.py Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Multiple (threaded?) connections to BaseHTTPServer
Adam Atlas wrote: > Never mind... I've found a workable solution: > http://mail.python.org/pipermail/python-list/2001-August/062214.html > > Robert, thanks, I'll still check that out for any future projects; but > for my current purpose, it seems overkill. But I don't know for sure; > assuming BaseHTTPServer is good enough for my current needs aside from > its lack of threading, does PooledThreadedServer have any advantages > over the method I linked above? The biggest difference (and you can decide whether it's an advantage for your environment or not) is that the ThreadingMixin starts a new thread for each request, while CherryPy's PooledThreadedServer uses a thread pool. That is, you start some number of threads (say, 10) when you start the server, and those threads serve all requests as they are able. The big advantage I was secretly hoping for was that you'd read up on CherryPy and discover it already does what you want. ;) Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: CGI File Uploads and Progress Bars
Doug Helm wrote:
> I'm writing a CGI to handle very large file uploads.
> I would like to include a progress bar.
> ...I need to know not only the number of
> bytes received, but also the total number of
> incoming bytes. Here's the heart of the code:
>
> while afcommon.True:
> lstrData = lobjIncomingFile.file.read(afcommon.OneMeg)
> if not lstrData:
> break
> lobjFile.write(lstrData)
> llngBytes += long(len(lstrData))
> lobjFile.close()
>
> Assume that lobjIncomingFile is actually a file-type
> element coming from CGI.FieldStorage. It's already
> been tested to ensure that it is a file-type element.
> Also, assume that I've already opened a file on the
> server, referred to by lobjFile (so lobjFile is the
> target of the incoming data).
I took a cursory look through the cgi module (and am trying to remember
what we did for CherryPy*). It seems that, at the time you run the above
code, the uploaded file has already been completely read from the client
and placed into a temporary file. That is, lobjIncomingFile.file.read
does not read from the HTTP request body; it reads from a temporary file
instead.
> If this were a client application opening a file,
> I would just do the following:
>
> import os
> print os.stat('myfile.dat')[6]
>
> But, of course, this isn't a local file. In fact,
> it's not really a file at all.
In fact, it is a file, just a temporary one. See
cgi.FieldStorage.makefile().
> So, bottom line: Does anyone know how to get the
> size of the incoming file data without reading the
> whole thing into a string? Can I do something with
> content_header?
Sure. Subclass cgi.FieldStorage, and override make_file to provide your
own file-like object that you can monitor as its "write" method is
called (see read_binary for the actual upload r/w code). The existing
FieldStorage class places the file size (gleaned from the Content-Length
request header) into self.length.
Robert Brewer
System Architect
Amor Ministries
[EMAIL PROTECTED]
* See CherryPy's
--
http://mail.python.org/mailman/listinfo/python-list
distutils and decorators
We're trying to get CherryPy 2.1 RC 1 out the door, but setup.py is
giving us some problems. In our test suite, we want to test a decorator
that we provide. Of course, decorators won't work in Python 2.3, so I
put the actual decorated functions into a separate module, and import it
into the test suite only when running Python 2.4:
if sys.hexversion > 0x020400A2:
from cp_decorator_tests import Exposing, ExposingNewStyle
Now "setup.py install" is complaining when run under Python 2.3, since
it tries to byte-compile every .py file. Output from a second install
run:
C:\Python23\Lib\site-packages\cptrunk>python setup.py install
running install
running build
running build_py
running install_lib
byte-compiling
C:\Python23\Lib\site-packages\cherrypy\test\cp_decorator_tests.py to
cp_decorator_tests.pyc
File
"C:\Python23\Lib\site-packages\cherrypy\test\cp_decorator_tests.py",
line 4
@cherrypy.expose("1")
^
SyntaxError: invalid syntax
running install_data
1. Is there some way to tell setup to skip the byte-compiling on that
single file, or
2. Is there some way to only ship cp_decorator_tests.py if you're
running 2.4, or
3. Is there some better way to optionally test decorators, like using
eval, or
4. other...?
Robert Brewer
System Architect
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: distutils and decorators
Title: RE: distutils and decorators I wrote: > We're trying to get CherryPy 2.1 RC 1 out the door, but setup.py is > giving us some problems. > In our test suite, we want to test a decorator > that we provide. Of course, decorators won't work in Python 2.3 and Benji York replied: > More accurately, the special "@" decorator syntax doesn't work in 2.3. > I would propose that you *do not* want to test the syntax (that's what > the Python test suite is for), but instead test the functionality of the > decorator. Therefore I'd switch to 2.3 compatible syntax instead. Actually, in this case we most definitely want to test 2.4's "@" syntax. The decorator in question is an aliaser, and therefore is one of the few decorators which must be implemented differently for the 2.3-style decoration and the 2.4-style. See the "expose" function at: http://www.cherrypy.org/file/trunk/cherrypy/__init__.py?rev=654 Robert Brewer System Architect Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Making dynamic data available via ODBC with Python
Erwin S. Andreasen wrote: > I have a Python application server that manages several different data > sets, permits various reports to be run on them and the data to be > downloaded as tab-delimetered files, all via a web interface. > > I'd like to explore the possibilities of making the data directly > available in Windows applications (such as Excel, where it would very > nice to directly do pivot tables from the live data) via ODBC. Hi, Erwin, I give my users Excel documents within a web app. They perform a query to get the subset of data they want to play with, then see that in an HTML table, with a link to "get it in Excel format". [If the dataset is huge, they're prompted to preview only, say, the first 10 rows.] When they request the Excel format, they get the same data (the HTML table!), with a Content-type of "application/vnd.ms-excel" and no frills; both IE and Firefox will use Excel to open it. Works wonderfully. Let me know if you need more details. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Python and version control
Peter Hansen wrote: > Carl wrote: > > What is the ultimate version control tool for Python if you > > are working in a Windows environment? > > I never liked coupling the two together like that. Instead > I use tools like TortoiseCVS or (now) TortoiseSVN with a > Subversion repository. These things let you access revision > control features from context (right-button) menus right in > Windows Explorer, as you browse the file system. Seconded. Bob -- http://mail.python.org/mailman/listinfo/python-list
RE: Help with embedding fully qualified script name
Kamilche wrote: > To avoid pathname headaches, I've taken to including the following 3 > lines at the top of every script that will be double-clicked: > > import os, sys > pathname, scriptname = os.path.split(sys.argv[0]) > pathname = os.path.abspath(pathname) > os.chdir(pathname) Putting the sys.argv call in a main block would make it more future-proof (for the day when your script becomes a library ;): import os pathname = os.path.normpath(os.path.dirname(__file__)) # application code goes here if __name__ == '__main__': import sys pathname = os.path.normpath(os.path.dirname(sys.argv[0])) Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: customizing metaclass constructed classes
Robin Becker wrote:
> I have a set of classes for database access which are
> constructed using a
> special metaclass and base class.
>
> so in the base module
>
> #base.py
> class M(type):
> def __init__(cls, name, bases, dict):
>super(M, cls).__init__(name, bases, dict)
>for f in dict['_fieldDefs']:
>#create special property based on the field def
>
>
> class A(object):
> __metaclass__ = M
> _fieldDefs = []
>
> #base methods
> ..
>
> in the database module we use the above
> eg
>
> #database.py
> class C(A):
>_fieldDefs =[
> IntColumn('id',primaryKey=1,allowNull=0),
> TextColumn('name',allowNull=0,size=50),
> TextColumn('description',allowNull=1,size=50),
> ]
>
> Now to my question: can I change the definition of the client
> class C at run
> time? I want to do something like add another element to C's
> _fieldDefs and then
> get it to go through the construction phase provided by M.
> It's clearly
> pointless for me to try something like
>
> from database import C
> C._fieldDefs.append()
>
> as C is constructed by the import.
> I either have to delay C's construction or reconstruct it.
>
> Would something like this do?
>
> def reconstruct():
> import database
> class C(database.C):
>_fieldDefs = database.C._fieldDefs+[..]
> database.C = C
>
> Is there a better way to do this which preserves more of C's
> original identity?
> I suppose I want to call the metaclass initialization again,
> but can't see a way to do that.
You *are* using a language with callable functions, right? ;)
#base.py
def create_special_property(cls, f):
# create special property based on f
class M(type):
def __init__(cls, name, bases, dict):
super(M, cls).__init__(name, bases, dict)
for f in dict['_fieldDefs']:
create_special_property(cls, f)
#database.py
class C(A):
_fieldDefs =[
IntColumn('id',primaryKey=1,allowNull=0),
TextColumn('name',allowNull=0,size=50),
TextColumn('description',allowNull=1,size=50),
]
base.create_special_property(C, DateColumn('start_date'))
Slightly off-topic: if you really want to make it pretty, add a custom
descriptor so you can write:
class C(A):
id = IntColumn(primaryKey=1,allowNull=0)
name = TextColumn(allowNull=0,size=50)
description = TextColumn(allowNull=1,size=50)
See UnitProperty (the descriptor), MetaUnit (the metaclass), and Unit
(the domain object) in http://www.aminus.org/rbre/dejavu/__init__.py for
an implementation of mine which you can steal in toto (because it's
public domain).
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: replacing ASP/VBScript with Python
Peter Maas wrote: > I have inherited an extremely messy ASP/VBScript application which > is a pain for me to support. Now the customer is thinking about a > redesign. I'd like to rewrite the whole thing in Python but the app > has to meet some conditions like > > - IIS frontend > - MSSQL db server > - Win32 authentication > - No 'ugly' URLs like http://server/cgi-bin/frontend.cgi?main.py > - Performance: intranet with ~ 1000 users None of those sound like a problem. > My personal preferences: > > - I'd rather do this in plain Python than using e.g. Zope because I >fear the additional complexity of handling Zope and make it seam- >lessly work with IIS. I had the same fear. :) > - I'd like to do session handling in Python because ASP's session >object is quite limited and some of the ASP app's mess is caused >by trying to use it for compound data type storage. OTOH I could >pickle Python objects to a string and store that in an ASP session. > In the meantime I have searched the internet and found plenty of options: > > - plain cgi with fastcgi and mod_rewrite for IIS to transform the URL > - quixote cgi with fastcgi and mod_rewrite > - Webware + wkcgi > - Python ASP (registering Python with Pywin32 as ASP language) > - mxODBC + SQL ODBC driver > - pyADO + SQL MDAC driver > > I'm now confident that it is doable and keen on finding out. The usual > question: what is the one and best way to do it? ;) Python ASP (pywin32), but put as little code as possible into the ASP--make it just a stub to call the real Python app. That app will be running persistently in the background, which should obviate most of the need for session support. That's been my experience, anyway. Here's an example (from http://www.aminus.org/rbre/cation/html/admin/ASP.html): <[EMAIL PROTECTED]> <% from cation.html.uiasp import UserInterfaceASP from cation import catapp ui = UserInterfaceASP(catapp) ui.request(Request, Response) %> The only downside is that ASP expects a physical file for every URL, so you'll either have lots of dumb copies of the stub, or a single dispatcher (and the ugly URL's you wanted to avoid). With a little planning, you can have the stubs auto-generated. Database side: try them all and see which is best with your dataset. ;) Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: replacing ASP/VBScript with Python
Peter Maas wrote: > Robert Brewer schrieb: > >>I'm now confident that it is doable and keen on finding > out. The usual > >>question: what is the one and best way to do it? ;) > > > > > > Python ASP (pywin32), but put as little code as possible into the > > ASP--make it just a stub to call the real Python app. That > app will be > > running persistently in the background, which should > obviate most of the > > need for session support. That's been my experience, anyway. > > Sounds reasonable. How do ASP-Python and IIS work together? > Is the Python- > Interpreter loaded each time a Python-ASP is called? No, you get a persistent process (that's what I meant by "running persistently"). Be careful using the Low or Medium "Application Protection" settings, as your app may mix with other applications in the same IIS process. Sometimes, that's what you want (two apps built using the same framework can then share framework modules if you use Low or Medium). On the other hand, the High setting lowers performance. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
"Best" way to SIGHUP spamd from web page?
I'd like to be able to restart spamd (the SpamAssassin daemon) from a web page, so that it will reload its system config files. Currently, I'm only worried about Debian; my SA is from the testing (Sarge) distro, and I'm running Apache 1.3. I don't have any other signals to send, or commands, and no dynamic values other than the pid (which I can read just fine from /var/run/spamd.pid). Basically, there are half-a-dozen different ways to get this to happen, but all of them spend 3/4 of their documentation saying "DON'T EVER DO THIS". I'm just wondering if anyone has recommendations for whose advice to ignore first. ;) Detailed explanations of your choice would be much appreciated, of course. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Calling a function from module question.
JRCondon wrote: > Sean, if you are asking what I think you are asking (I don't > think name hiding is the issue), you can use > > from module_name import * Sshh! We're obviously going to great lengths to not tell him about *. ;) Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: "Best" way to SIGHUP spamd from web page?
[EMAIL PROTECTED] wrote: > Webmin (webmin.com) has a command shell module (cgi over > https?). Isn't this an example of a secure way to run > commands via the internet? Yes, if I wanted to write my app in Perl 5. ;) But as far as I can tell, that relies heavily on Perl's taint-checking, which isn't available in Python. I ended up writing a daemon (running as root) which simply listens on a local socket; when it receives any message, it HUPs spamd. Ugly but effective. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: recommended way of generating HTML from Python
Michele Simionato wrote:
> The problem is a problem of standardization, indeed.
> There are plenty of recipes to do the same job, I just
> would like to use a blessed one (I am teaching a Python
> course and I do not know what to recommend to my students).
Wouldn't we *all* like all of our problems worked out for us. ;)
> class HTMLTag(object):
> [wonderful code snipped]
That's a reasonable start, and you have some fun magic in there, but I think
you're going to hit a wall of complexity Real Soon Now--elements without a
separate closing tag, safe attribute quoting, and general usability pressures
will start to bite you. I note also what Kent said about separation, and the
desire to "hand things off to a web designer".
In my own work, I tried to meet both of these concerns with a single Assembly
class, which you can see at http://www.aminus.org/rbre/cation/html/assembly.py.
At its most basic, it is nothing more than a namespace plus a template. I think
it solves the separation issue nicely by allowing the template to be loaded
from a file, whether that file be HTML from a designer, HTML "bulding blocks"
which a developer might supply, or even CSS, or an email template. But it also
allows for useful subclassing, for code generation. Here's an example: the
subclass for "hidden input" elements:
class HiddenElement(Assembly):
"""An Assembly for generating HTML elements
Usage:
output = assembly.HiddenElement(app).assemble_all(key)
"""
templateText = u''
def assemble_all(self, name, value):
return self.assemble({u'name': html.quote(name),
u'value': html.quote(value)})
The "assemble_all" method allows the developer to focus on the important bits
(name and value) and forget the implementation details. Check out the TableRows
class for a more complex example, whereby an HTML table can be built
incrementally, inline with the data access logic.
Now, getting into usability concerns (that framework and library authors tend
to obsess over ;) may be too advanced for your class at the moment. But that's
why recipes are recipes, not standard library modules: they're often biased
toward quick and dirty scripting, not usable, maintainable edifices.
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: Problematic behavior of the import statement when several modulefiles have the same name.
Xif wrote:
> Here's a problem with relative imports:
>
> Suppose I have a package called some_package (in a separate directory
> included in the PYTHONPATH, with an __init__.py file etc.)
>
> This package has a module inside the directory, called "database", and
> therefore residing in the file some_package/database.py.
>
> Now, what if there's another module, for example inside the
> site-packages directory, with the same file name (i.e. database.py)?
>
> We have a problem. Since although these modules have
> different absolute
> names ("some_package.database" for the first module, and just
> "database" for the second), when I try to do
>
> import database
>
> from inside some_package, it first of all tries to find the matching
> file in the some_package directory (i.e. do a relative import). Since
> it first checks the some_package directory, and finds database.py
> there,
>
> import database
>
> in fact imports the module with the absolute name
> some_package.database.
>
> This is problemat on two levels:
>
> 1) It is surprising and undesirable that "import database" in effect
> may do two completely different things ("import some_package.database"
> or "import database") depending on an external, unpredictable factor:
> the existence of a database.py file inside the some_package directory.
>
> 2) It effectively prevents you from naming a module inside a package
> with the same name of any module in the "root" PYTHONPATH directories.
> In my example, there's no sane way I can see of having
> some_package.database if there's already a database module
> (database.py
> file) in any PYTHONPATH directory.
>
> Are my observations correct? Is there something I ignored? Should
> this be posted somewhere else?
Short answer: don't use relative imports:
from some_package import database
http://docs.python.org/ref/import.html
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: hotshot ??
Charles Hartman wrote:
> (I asked this a day or two ago; if there was an answer, I missed it.
> Anybody using hotshot?)
>
>
> I've used profile before, but wanted to get more information so I
> thought I'd try hotshot instead. It works fine when used like
> profile.
> But when I run it using this line,
> prof = hotshot.Profile('ScanHot.prof', lineevents=1)
> though it runs all right, when I try to load the resulting
> file I get
> this:
>
> >>> hs = hotshot.stats.load("ScanHot.prof")
> Traceback (most recent call last):
>File "", line 1, in ?
>File
> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
> python2.3/hotshot/stats.py", line 12, in load
> return StatsLoader(filename).load()
>File
> "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/
> python2.3/hotshot/stats.py", line 51, in load
> assert not self._stack
> AssertionError
>
> --which I don't understand. (The program is a GUI one using wxPython
> 2.5, running from within the WingIDE on a Mac under OS
> 10.3.8, if any
> of that makes a difference. Nothing there prevents hotshot
> from loading
> a file that's been made without the lineevents=1 argument.)
Sounds like you're hitting a known bug:
http://sourceforge.net/tracker/index.php?func=detail&aid=900092&group_id
=5470&atid=105470
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: Itertools wishlists
Steven Bethard wrote: > Ville Vainio wrote: > > A simpler API: > > > > def flatten(sequence, atomic_test = lambda o: > isinstance(o,basestring)): > > """ don't recurse into iterables if atomic_test -> True """ > > Yes, this is also the API I would have suggested. Simple, > but flexible enough to handle the odd cases with the occasional > user-defined iterable non-containers. If there are two or three common atomic_test's they could also be placed into itertools globals (with better names, of course ;): def is_string(item): return isinstance(item, basestring) def flatten(seq, atomic_test = is_string): ... Perhaps atomic_test could allow a tuple or list of tests and combine them...? Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: How to create datetime object from DbiDate (win32.odbc)?
Frank Millman wrote: > I am using odbc from win32 extensions to connect to MS SQL Server. I > use mx.DateTime to handle dates. When I select a datetime column from > the database, odbc returns something called a DbiDate object. I cannot > find out any information on this type, but mx can convert it to a > mx.DateTime object using DateTimeFrom(), which is really all that I > need. > > I am looking into changing from mx.DateTime to using the builtin > datetime type, but I cannot figure out how to convert a DbiDate object > to a datetime object. > > First prize would be to have a datetime constructor that takes a > DbiDate object as input, in the same way that mx does, but this does > not seem to exist. Try: datetime.datetime.utcfromtimestamp(int(value)) I gave up on dbiDates completely, however, (since their range is so limited) and use strings instead. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] No virus found in this outgoing message, because: 1) it's plain text, and 2) doesn't have an attachment. Checked by Common-Sense Anti-Virus, Version: 0.0.001 -- http://mail.python.org/mailman/listinfo/python-list
RE: A way to wait Python event
Diez B. Roggisch wrote: > > I tried to launch "python.exe test.py" in another program. After the > > launch the console was showed and exited on Windows. I want the > > console stay there. Is there a Python statement to wait an > event loop > > like Tcl's "after forever"? > ... > Apart from that, there might be some hidden "keep this damn > window open > after the executed progam terminated"-checkbox. Happy hunting. http://www.google.com/search?q=windows+console+remain+open Use the /k switch to cmd.exe Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: RotatingFileHandler
Kamus of Kadizhar wrote:
> I'm having a problem with logging. I have an older app that used the
> RotatingFileHandler before it became part of the main distribution (I
> guess in 2.3).
>
> It worked fine then. Now I get:
>
> [EMAIL PROTECTED] bin]# ./mplayer.py file://test.avi
> //test.avi
> Traceback (most recent call last):
> File "./mplayer.py", line 40, in ?
> logFile.emit(movieName)
> File
> "/usr/src/build/394694-i386/install/usr/lib/python2.3/logging/
> handlers.py", line 102, in emit
> File
> "/usr/src/build/394694-i386/install/usr/lib/python2.3/logging/
> __init__.py", line 567, in format
> File
> "/usr/src/build/394694-i386/install/usr/lib/python2.3/logging/
> __init__.py", line 362, in format
> AttributeError: 'str' object has no attribute 'getMessage'
>
> The offending snippet of code is:
>
>logFile =
> logging.handlers.RotatingFileHandler('/var/log/user/movies2.lo
> g','a',2000,4)
>logFile.emit(movieName)
Making a quick run-through of the logging module, it looks like you need
to have a Formatter object added to your Handler:
filename = '/var/log/user/movies2.log'
logFile = logging.handlers.RotatingFileHandler(filename,'a',2000,4)
formatter = logging.Formatter()
logFile.setFormatter(formatter)
...then you can call emit.
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: question on regular expressions
Darren Dale wrote:
> I'm stuck. I'm trying to make this:
>
> file://C:%5Cfolder1%5Cfolder2%5Cmydoc1.pdf,file://C
> %5Cfolderx%5Cfoldery%5Cmydoc2.pdf
>
> (no linebreaks) look like this:
>
> ./mydoc1.pdf,./mydoc2.pdf
Regular expressions are much easier to write when you only have to worry
about single characters. So the first step might be to replace all of
the %5C's with \:
>>> a
'file://C:%5Cfolder1%5Cfolder2%5Cmydoc1.pdf,file://C%5Cfolderx%5Cfoldery
%5Cmydoc2.pdf'
>>> a = a.replace("%5C", "\\")
>>> a
'file://C:\\folder1\\folder2\\mydoc1.pdf,file://C\\folderx\\foldery\\myd
oc2.pdf'
Then you can use something like:
>>> re.findall(r"([^\\]*\.[^,]*)(?:,|$)", a)
['mydoc1.pdf', 'mydoc2.pdf']
...or Sean Ross' suggestion about urllib.
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: type cmp add
Zora Honey wrote: > I've just discovered operator overloading via defining a > class's special > methods and I think it's swell, or would be if I could figure out two > things: > > In order say, add things, I need to do some type checking. For a+b to > work, both must be instances of the same class. I can check to see if > they are instances using if type(a)==types.InstanceType, but I don't > know how determine which class it is in an instance of. (This must > somehow be possible because if I do "print a" without having > overloaded > __str__, I get <__main__.C instance at 0x815b9ec> telling me it's an > instance of class C). a.__class__ > Also, how to I make an instance of a class from within the class? I > want c = a + b to return a new instance of value a + b > without changing > a or b. When I define the __add__ method, I have access to self and > other, whose properties I can change at will, but how do I get a fresh > instance of the class that I am writing? self.__class__() Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: [Python-Help] (fwd)
Alfred Canoy wrote:
> I'm just new to programming and would like to ask for help..
>
> Build a module that contains three functions that do the following:
>
> a.. Compute the average of a list of numbers
> b.. Finds the statistical median value of a list of numbers
> c.. Finds the mode of a list of numbers
>
> Can you please give me clue how I should start solving the
> following problem
> below? Here's the source code that I did so far:
>
> # compute the average of a list of numbers:
> # Keeps asking for numbers until 0 is entered
> # Prints the average value
>
> count = 0
> sum = 0
> number = 1
>
> print 'Enter 0 to exit the loop'
> while number != 0:
> number = input ('Enter a number: ')
> count = count + 1
> sum = sum + number
> count = count -1
> print ' The average is:', sum/count
Looks good to me (well, I'd write the loop differently, but...). What is
happening that you dislike?
>>> count = sum = 0
>>> number = 1
>>> while number != 0:
... number = input('Enter a number: ')
... count += 1
... sum += number
...
[Enters 3, 5, and 7]
>>> sum, count
(15, 4)
>>> count -= 1
>>> sum/count
5
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: Mean, median, and mode
(now that we have a meaningful subject line)
Alfred Canoy wrote:
> >> I'm just new to programming and would like to ask for help..
> >>
> >> Build a module that contains three functions that do the following:
> >>
> >> a.. Compute the average of a list of numbers
> >> b.. Finds the statistical median value of a list of numbers
> >> c.. Finds the mode of a list of numbers
> >>
> >> Can you please give me clue how I should start solving the
> >> following problem
> >> below? Here's the source code that I did so far:
> >>
> >> # compute the average of a list of numbers:
> >> # Keeps asking for numbers until 0 is entered
> >> # Prints the average value
> >>
> >> count = 0
> >> sum = 0
> >> number = 1
> >>
> >> print 'Enter 0 to exit the loop'
> >> while number != 0:
> >> number = input ('Enter a number: ')
> >> count = count + 1
> >> sum = sum + number
> >> count = count -1
> >> print ' The average is:', sum/count
For the mode, you might build a dictionary:
freq = {}
while number != 0:
number = input ('Enter a number: ')
count = count + 1
sum = sum + number
try:
freq[number] += 1
except KeyError:
freq[number] = 1
...then you can check for the largest value in that dictionary:
max = 0
mode = None
for k, v in freq.iteritems():
if v > max:
max = v
mode = k
I leave the rest in your capable hands... ;) Including the case where
two numbers occur in equal frequencies. ;;)
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: Linguistic challenge: name this program
Andre Roberge wrote: > In 1981, Richard Pattis wrote a delightful little book titled "Karel > the Robot, a Gentle Introduction to the Art of Programming." Pattis's > "Karel the Robot" was named after the author Karel Capek, who > popularized the word "robot" in his play "Rossum's Universal Robots". > Pattis's approach was to introduce a robot who could follow 5 basic > instructions and be taught to accomplish tasks of increasing > complexity. > > A few years ago, a first implementation of "Karel the Robot" in Python > was created and called PyKarel. A second, newer implementation is > called Guido van Robot (GvR for short), and is available at > gvr.sourceforge.net. Work is currently underway by the developpers of > GvR to produce a new-and-improved version. > > I have been working on my own (better ;-) version (sometimes > collaborating with the GvR folks) in order to learn Python. It is now > 90% finished. It is meant to be a complete environment to learn about > programming concepts, from simple sequences of instruction to OOP. > > Given the origin of Pattis's name (Rossum's Universal Robot) and the > name of Python's BDFL, I find it difficult to think of a better name > than Guido van Robot to name a programming environment in which one > uses Python to teach a robot new tricks! (Hat's off to Steve Howell > for this one). Yet, I want a "clever" name for my version. > > Any suggestions? RUR? Perhaps http://jerz.setonhill.edu/resources/RUR/ might give you more ideas. FuManChu -- http://mail.python.org/mailman/listinfo/python-list
RE: Mean, median, and mode
Josiah Carlson wrote: > [EMAIL PROTECTED] (Sean McIlroy) wrote: > > > > >>> median = lambda x: (max(x)-min(x))/2 > > That is /not/ the median in the general case. > > median = lambda x: x.sort() or x[len(x)//2] That...is a really sneaky use of null return values. I like. :) Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: better regular expression?
Vivek wrote: > I am trying to construct a regular expression using the re module that > matches for > 1. my hostname > 2. absolute from the root URLs including just "/" > 3. relative URLs. > > Basically I want the attern to not match for URLs that are not on my > host. Far easier would be grabbing the URL's and then using urlparse.urlparse() on them. Relative paths should be combined with the base scheme://location/path. When you want to see if they are on your host, just use .startswith(). If you're worried about ../, make the paths concrete (os paths) and call os.path.normpath before comparing them. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: regex for url paramter
Andreas Volz wrote:
> I try to extract a http target from a URL that is given as parameter.
> urlparse couldn't really help me. I tried it like this
>
> url="http://www.example.com/example.html?url=http://www.exampl
> e.org/exa
> mple.html"
>
> p = re.compile( '.*url=')
> url = p.sub( '', url)
> print url
> > http://www.example.org/example.html
>
> This works, but if there're more parameters it doesn't work:
>
> url2="http://www.example.com/example.html?url=http://www.examp
> le.org/exa
> mple.html¶m=1"
>
> p = re.compile( '.*url=')
> url2 = p.sub( '', url2)
> print url2
> > http://www.example.org/example.html¶m=1
>
> I played with regex to find one that matches also second case with
> multible parameters. I think it's easy, but I don't know how
> to do. Can you help me?
I'd go back to urlparse if I were you.
>>> import urlparse
>>>
url="http://www.example.com/example.html?url=http://www.example.org/exam
ple.html"
>>> urlparse.urlparse(url)
('http', 'www.example.com', '/example.html', '',
'url=http://www.example.org/example.html', '')
>>> query = urlparse.urlparse(url)[4]
>>> params = [p.split("=", 1) for p in query.split("&")]
>>> params
[['url', 'http://www.example.org/example.html']]
>>> urlparse.urlparse(params[0][1])
('http', 'www.example.org', '/example.html', '', '', '')
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: Help with generators outside of loops.
Christopher J. Bottaro wrote: > I have a generator that works like this: > > for row in obj.ExecSQLQuery(sql, args): > # process the row > > Now there are some querys that run where I know the result > will only be a > single row. Is there anyway to get that single row from the generator > without having to use it in a for loop? I want to do > something like this: > > row = obj.ExecSQLQuery(sql, args)[0] > > But I'm guessing that you can't index into a generator as if > it is a list. row = obj.ExecSQLQuery(sql, args).next() Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Possible to insert variables into regular expressions?
Chris Lasher wrote: > I would like to create a set of very similar regular expression. In > my initial thought, I'd hoped to create a regular expression with a > variable inside of it that I could simply pass a string into by > defining this variable elsewhere in my module/function/class where I > compile the regular expression, thus making for an easy > substitution. And Steven Bethard replied: > Can you use the %-formatting operations? This is what I normally do > with a situation like this. It means you have to compile a > new regular expression for each different value you substitute > into the expression, but that's to be expected anyway when you're > trying to check several different regular expressions... > > >>> import re ... > >>> expr = r'(\w*%s\w*)' > >>> re.compile(expr % r'oo').findall(s) > ['Wood', 'Looking'] > >>> re.compile(expr % r'ou').findall(s) > ['You', 'Yourself', 'Through', 'You', 'Your'] Just make sure you use re.escape, in case your interpolated string has regex-sensitive chars. re.compile(expr % re.escape(r'oo')).findall(s) Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Tibia 0.1 DOM-based website editor
Cross-posted here to encourage comments/discussion. I know there's a big feature or two I'm missing out on ;) Suggestions welcome. Tibia is an in-browser editor for web pages. It allows you to quickly and easily modify the content of your web pages. It allows you to directly view, edit, and save files on your webserver. It also allows you to upload files from your local filesystem to your webserver, and then edit those documents. It also allows you to grab web pages from other websites and save them on your server, and then edit _those_. Stick the single tibia.tba file on your webserver (assuming Python is installed) and you're off and editing files in the same folder or below. Admins can edit any element; non-admins can edit any element for which admins give them permission. You should probably have IE6 or Firefox; IE has limitations. If you want to test it with another recent browser (it's all DOM-based), feel free and let me know what breaks: [EMAIL PROTECTED] Ditto for other webserver/OS/Python versions. You can also fill out complete bug reports or feature requests at http://www.casadeamor.com/FogBugz. Tibia is public domain. Download: http://www.aminus.org/rbre/tibia/tibia.tba Subversion: svn://casadeamor.com/tibia/trunk Help: http://www.aminus.org/rbre/tibia/tibia.html Demo: http://www.aminus.org/rbre/tibia/demo/tibia.tba Log in as an admin with iwethey/yammer. Log in as a guest with guest/guest. Please don't break my little home webserver ;) Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Tibia 0.1 DOM-based website editor
Gabriel Cooper wrote: > Robert Brewer wrote: > > >[...] > >Tibia is an in-browser editor for web pages. It allows you to quickly > >and easily modify the content of your web pages. > >[...] > > > I couldn't get it to work using Firefox on Red Hat Fedora > Core 2. From > what I garnered from the help you're supposed to be able to > double-click > on any page element with a big block-border around it, right? If so, > nothing happened for me. :( I assume you're using the demo? My copy of Firefox has an error browser under Tools->Javascript Console. Does the double-click report any error there? Make sure you clear the list before trying, since errors from all other webpages gt dumped in the same list. Thanks for the feedback! Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: tibia error in apache2
>From tibia log file:
2004-12-10 16:05:56,322 ERROR None: GET frameset
Traceback (most recent call last):
File "C:\PYTHON23\lib\site-packages\tibia.py", line 997, in __init__
self.username = self.username.split("\\")[-1]
AttributeError: 'NoneType' object has no attribute 'split'
2004-12-10 16:05:57,102 ERROR None: GET logo
Traceback (most recent call last):
File "C:\PYTHON23\lib\site-packages\tibia.py", line 997, in __init__
self.username = self.username.split("\\")[-1]
AttributeError: 'NoneType' object has no attribute 'split'
2004-12-10 16:05:57,102 ERROR None: GET logo
Traceback (most recent call last):
File "C:\PYTHON23\lib\site-packages\tibia.py", line 997, in __init__
self.username = self.username.split("\\")[-1]
AttributeError: 'NoneType' object has no attribute 'split'
You need to use some sort of authentication with Tibia, or it can't tell
who's an admin and who's not. The demo uses Basic Auth. Add something like
the following to your .conf for the tibia folder:
AuthType Basic
AuthName "Tibia"
AuthUserFile D:\htdocs\tibia\passwords
Require valid-user
...and then use htpasswd to create the passwords file.
I will look into ways to use Tibia without auth, for intranets, perhaps.
Thanks!
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: Blank ASP pages
ElCapitan wrote: > Gordon McMillan wrote: > > Jason S. Nadler wrote: > > > > > My server is spitting out blank .asp pages which use python. If > Python is > > > not declared, the asp pages work fine. > > > I just yesterday stepped up to Python 1.52 and the new win32all > > > After the install, the blanks started appearing. > > > All the paths look fine in registry. > > > Any clues? > > > > You've asked before, and got no replies, so it's safe to say > > this is not a common problem among the asp users. So you'll > > need to go into more detail. > > > > What's a "blank page"? One with nothing between > > and ? What does view -> source show you in a > > browser? > > > > Can you tell (from logs or whatever) that the Python scripts > > are getting run? > > > > Have you tried setting the debug flag on the components and > > running with the Trace Collector? > > I have same exact problem and get the sourcecode right back > (asp source > code) when i right click page and view source code. Not sure what > server they are using this is not in my company. I've run into this a couple of times. Often, setting the default ASP language to Python is the trick. Internet Services Manager->Site->Folder->Properties->Configuration->App Options->Default ASP Language. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: CGI zombies with Apache 1.3 on Linux
Erik Max Francis wrote: > Robert Brewer wrote: > > > I've Googled extensively, but can't figure out what might > be causing my > > Python CGI app to zombie (yes, Tibia, the one I just > announced ;). The > > cgi bit looks like this: > > Zombies are caused by forking a subprocess and the parent not > waiting on > it. Does your system (sometimes) spin off a subprocess? That's what I can't figure out. The app serves web pages via CGI, and calls .read and .write on files in the same directory. It also calls urllib.urlopen once in a while, and uses PIL's Image.open and .save. Oh, and os.walk. Other than that, it's all text processing. The subprocesses are children of apache processes (when I use "ps axf"). There's also a "[sh] " process sitting around which is a child of apache. Any ideas? Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: CGI zombies with Apache 1.3 on Linux
I wrote: > I've Googled extensively, but can't figure out what might be > causing my Python CGI app to zombie (yes, Tibia, the one I > just announced ;). Never mind for now. I think it was a mistake in my httpd.conf. My TransferLog didn't pipe to the correct handler, which meant access & error events weren't being logged, which I *think* caused the children's parents to wait forever if there was an unhandled exception. I'll be back if it happens again. ;) Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Tibia 0.1 DOM-based website editor
Fuzzyman wrote: > Interesting. > > I couldn't get the demo to work either by the way. A 404 error on the > tba file. Bah. You must've looked after I switched fom .tba to .py Try http://www.aminus.org/rbre/tibia/demo/tibia.py > This is *similar* t oa project I'm about to release, Jalopy. Jalopy is > a collaborative website tool - allowing a team of people to work on a > website together. It uses Kupu as an online WYSIWYG HTML editor. (I > assume tibia uses something similar ? if not you should integrate Kupu > !). Similar, but with important differences. Although Tibia makes use of Javascript to manipulate the DOM, its goals and audience are different. Tibia: 1. ...is a single file, to reduce deployment cost: download (wget), edit httpd.conf or IIS conf (if you're not already mapping .py to CGI), write a tibia.conf if you don't want the defaults. Install PIL if desired, which is a one-liner on Debian and an installer on Win*. So Kupu's right out. So is the jalopy approach: "login_tools, configobj, caseless, listquote, dateutils, dataenc, pathutils and cgiutils" is far too many dependencies when you're shooting for zero/one ;). 2. ...combines *both* WYSIWYG and source code access, at the same time. Your typing is performed in a plain-'ol textarea, which avoids all of the "where is my cursor?" problems with WYSIWYG-only when used on complex pages. However, as you type, your changes are reflected in real time in the source document. I need an Undo button, though. /pops off and adds a new feature request 3. ...handles complex, preexistent web pages produced by others. Have your web page laid out by a pro, then give access to individual elements to your "content providers" as needed. Using the web grabber and upload tools, you can stop FTP'ing web pages to your colo completely. It doesn't appear to me from the Kupu demos that they can handle anything complex...but I could be wrong. I'd like to see a page like Plone's home page being edited by Kupu. You can see it in Tibia at the demo: http://www.aminus.org/rbre/tibia/demo/tibia.py?page=www.plone.org.html > You can see a jalopy demo at > http://www.voidspace.org.uk/cgi-bin/jalopydemo/jalopy.py > > I'm not *sure* if that is the latest version - but I think so. I've > nearly finished the docs and will do a release. It looks good! I like some of the tools Kupu provides (and in fact, stole the idea for my simplistic B, I, U buttons after seeing Kupu for the first time a few weeks ago). I'm a bit unclear on exactly where Kupu stops and Jalopy starts, though. You might want to make that more clear in the help file...maybe a one-liner like "Kupu does X, Y, and Z, and Jalopy adds A, B, and C". I'm looking forward to your release (with uploads! ;). Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Tibia 0.1 DOM-based website editor
Richie Hindle wrote: > [Robert] > > Tibia is an in-browser editor for web pages. It allows you > to quickly > > and easily modify the content of your web pages. It allows you to > > directly view, edit, and save files on your webserver. > > Very impressive! I ran into a couple of difficulties but > otherwise it's a great tool. Thanks! We're starting to use it already in-house. > I had to hard-code a username - does it require you to use HTTP > authentication before it will work? If so, it would be good if you > mentioned that in the documentation. Currently, it requires you to use *some* form of authentication. I'm working on a way to get around that for intranet deployers who don't care (but _should_, but hey, it's their loss). If you set up your own site, you also need to have somebody in the Admin group if you want to get any editing done. > It also erased my HTML file when I tried to save my changes. > 8-) I'll try to track that one down if I get the chance. Sorry about that. Tibia switches between three modes: web, upload, and server. The initial release had an ugly pattern where you would open a webpage, switch to server mode (without realizing it) by clicking the "server" flyout button and then hit save--and get nothing saved because you thought you were still in "web mode". I changed the events a bit in recent releases so that doesn't happen anymore; you only change to server mode when you actually load a file from the server. Numerous other buglets fixed over the weekend. Thanks for the feedback, all! Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Suggestion for "syntax error": ++i, --i
Terry Reedy wrote: > "Petr Prikryl" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > > >Summary: In my opinion, the C-like prefix > >increment and decrement operators (++i and --i) > > You could propose to the author of Pychecker that he include, > if possible, an option to check for and warn about '++', '--'. +1 FuManChu -- http://mail.python.org/mailman/listinfo/python-list
RE: Iteration within re.sub()?
Bryant Huang wrote:
> Is it possible to perform iteration within the re.sub() function call?
>
> For example, if I have a string like:
>
> str = "abbababbabbaaa"
>
> and I want to replace all b's with an integer that increments from 0,
> could I do that with re.sub()?
>
> Replacing b's with 0's is trivial:
>
> i = 0
> pat = re.compile("b")
> print pat.sub(`i`, str)
>
> Now, how can I increment i in each replacement? Is this
> possible? Like,
> using a lambda function, for example? Or do I use a different re
> function altogether?
>
> I use this trivial [ab]* language for simplicity, but I have a real
> problem where I need to match a more complex regex and replace it with
> an incrementing integer.
It's possible. Here's a quick, ugly version, which:
1. Uses a function for the "repl" arg of re.sub().
2. Uses a list to get around i being local inside of sub(). You could
just as well use the global statement.
3. Starts i[0] at -1. You could also use itertools.count or range to
good effect.
PythonWin 2.3.2 (#49, Oct 2 2003, 20:02:00) [MSC v.1200 32 bit (Intel)]
on win32.
>>> import re
>>> s = "abbababbabbaaa"
>>> i[0] = -1
>>> def sub(match):
... i[0] += 1
... return str(i[0])
...
>>> re.sub("b", sub, s)
'a01a2a34a56aaa'
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: PythonWin Not Updating
Chris wrote: > I'm working on a program in PythonWin. The problem I'm > running into is that after I make a code change, > PythonWin doesn't always see it. Has anyone else > had this problem? "See it" in the interactive session? Use reload(): http://docs.python.org/lib/built-in-funcs.html Otherwise, you'll have to explain a bit more--that's my best guess as to what your issue is. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Dejavu 1.2.6, a Python ORM
The Dejavu Object-Relational Mapper (version 1.2.6) is now available and in the public domain. Get it at svn://casadeamor.com/dejavu/trunk. Dejavu is an Object-Relational Mapper for Python applications. It is designed to provide the "Model" third of an MVC application. Dejavu avoids making decisions in the framework which are better left to developers, and avoids forcing developers to make decisions which are better left to deployers. In particular, deployers are allowed to mix and match storage mechanisms, including how and when to cache objects in memory, making it easier for deployers to tune applications to their particular environment. Dejavu provides: MODELING LAYER 1. A subclassable Unit class for persisting objects to storage. 2. A base Unit Property class for declaring persistent object attributes. 3. ID Sequencers. 4. Associations between Unit classes. 5. Unit Engines, Rules, and Collections. 6. Aggregation and analysis tools. APPLICATION LAYER 1. Expressions: pure Python Unit queries. This is perhaps the most appealing feature of Dejavu. However, since it uses bytecode hacks, Dejavu only runs on CPython. 2. Sandboxes, which serve as Identity Maps and per-connection caches. Unit objects are "memorized" and "recalled" from a Sandbox, using Expressions. 3. An Arena class for application-level data. STORAGE LAYER 1. A subclassable StorageManager class and specification. Unlike many ORMs, Dejavu does not require you to have complete control of your back end. 2. Specific StorageManagers for: a. Microsoft SQL Server via ADO. b. Microsoft Access (Jet) via ADO. c. ODBC databases (not complete = broken) d. Shelve to dbm. e. Future versions of Dejavu will support PostgreSQL, MySQL, and SQLite. Others are being considered. Dejavu welcomes your use and feedback as an application developer. Dejavu also welcomes framework developers. New code for additional Storage Managers, analysis tools, will be gladly reviewed for inclusion in future releases. Drop me an email if you feel so inclined. Robert Brewer MIS Amor Ministries [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
RE: Why no list heritable type?
James Stroud wrote: > The thread "why not arrays" got me thinking. I would really > like to inherit > from a list so that I can add methods based on its contents, > say if I filled > it with a type of object and wanted to iterate over all > objects. I have built > a wrapper around a list like this for general use: > > class list_of_objects: > def __init__(self): > self.data = [] > def __len__(self): > return len(self.data) > etc ... > > Then it can be heritable and I can add or override methods. > Why aren't built > in lists and dictionaries real heritable types that can save > this kind of patchwork? They are since Python 2.2 (IIRC): class mylist(list): def mymethod(self): self.x = 5 ...etc. What problems are you running into? FuManChu -- http://mail.python.org/mailman/listinfo/python-list
RE: Cool object trick
Alex Stapleton wrote:
> you can't do
>
> var = "varA"
> obj = struct(varA = "Hello")
> print obj.var
>
> and expect it to say Hello to you.
Did you mean "print obj.varA"? I can't think of any use case for the way
you wrote it, so I'm naively guessing you've got a typo. Feel free to
correct me. ;)
>>> class struct(object):
... def __init__(self, **kwargs):
... self.__dict__.update(kwargs)
...
>>> var = "varA"
>>> obj = struct(**{str(var): "Hello"})
>>> print obj.varA
Hello
Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list
RE: Troubleshooting: re.finditer() creates object even when nomatch found
Chris Lasher wrote: > That's odd that there's no built-in method to do this. It seems like > it would be a common task. Is there any way to request a feature like > this from the RE module keepers, whomever they may be? The best way to request such a feature would be to write a patch. ;) FuManChu -- http://mail.python.org/mailman/listinfo/python-list
